Project

General

Profile

Download (28.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Functions for dealing with CDM entities from the package model.common
5
 *
6
 * @copyright
7
 *   (C) 2007-2012 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 */
18

    
19
/**
20
 * @defgroup compose Compose functions
21
 * @{
22
 * Functions which are composing Drupal render arays
23
 *
24
 * The cdm_dataportal module needs to compose rather complex render arrays from
25
 * the data returned by the CDM REST service. The compose functions are
26
 * responsible for creating the render arrays.
27
 *
28
 * All these functions are also implementations of the compose_hook()
29
 * which is used in the proxy_content() function.
30
 * @}
31
 */
32

    
33

    
34
/**
35
 * Composes an HTML element class attribute value composed of
36
 * the short-name of the cdm class and the uuid of the entity.
37
 * This class attribute should be used wherever an cdm-entity is rendered.
38
 *
39
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
40
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
41
 * Taxon uuid is added also as taxon_uuid:<uuid>
42
 *
43
 * These according class selectors in css must be escaped, eg:
44
 *    .cdm\:TextData
45
 *
46
 * @param $cdm_entity
47
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
48
 */
49
function html_class_attribute_ref($cdm_entity) {
50

    
51
  $attributes = '';
52
  if (is_cdm_entity($cdm_entity)) {
53
    // Entities
54
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
55
    switch ($cdm_entity->class){
56
      case 'Taxon':
57
        if(isset($cdm_entity->sec->uuid)){
58
          $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
59
        }
60
        break;
61
    }
62
  } elseif (isset($cdm_entity->class)) {
63
    // DTOs
64
    if(isset_not_empty($cdm_entity->type) && isset_not_empty($cdm_entity->uuid)){
65
        $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
66
    }
67
    // additional data of specific DTOs
68
    switch ($cdm_entity->class){
69
      case 'TaxonNodeDto':
70
        $attributes .= "taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
71
      break;
72
    }
73
  }
74

    
75
  return $attributes;
76
}
77

    
78

    
79
/**
80
 * Compose an render array from a CDM Marker object.
81
 *
82
 * compose_hook() implementation
83
 *
84
 * @param object $marker
85
 *   CDM instance of type Marker
86
 * @return array
87
 *   A drupal render array
88
 *
89
 * @ingroup compose
90
 */
91
function compose_cdm_marker($marker) {
92
  $label = $marker->markerType->representation_L10n . ': ' . (($marker->flag !== TRUE ? t('yes') : t('no')));
93
  return markup_to_render_array('<span class="' . html_class_attribute_ref($marker) . '">' . $label . '</span>');
94
}
95

    
96
/**
97
 * Checks if the given $cdm_entitiy has a marker the type references by the
98
 * $marker_type_uuid and returns TRUE if a matching marker has been found.
99
 *
100
 * @param object $cdm_entitiy A CDM Entity
101
 * @param string $marker_type_uuid
102
 */
103
function cdm_entity_has_marker($cdm_entitiy, $marker_type_uuid) {
104
  if(isset($cdm_entitiy->markers[0]) && !is_uuid($marker_type_uuid)){
105
    foreach ($cdm_entitiy->markers as $marker) {
106
      if(isset($marker->markerType) && $marker->markerType->uuid == $marker_type_uuid){
107
        return TRUE;
108
      }
109
    }
110
  }
111
  return FALSE;
112
}
113

    
114
/**
115
 * Sorts an array of CDM IdentifiableSource instances by 1. by the
116
 * author teams family names and 2. by the publication date.
117
 *
118
 * @param array $sources
119
 *    The array of CDM IdentifiableSource instances
120
 * @return array
121
 *  An array of drupal render arrays
122
 */
123
function oder_and_render_original_sources($sources){
124
    $sort_array = array();
125
    foreach ($sources as $source) {
126

    
127
      $order_key = '';
128

    
129
      // find the familynames
130
      if(isset($source->citation->uuid) && !isset($source->citation->authorship)){
131
        $authorteam = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $source->citation->uuid);
132

    
133
        $persons = array();
134
        if($authorteam->class == 'Team'){
135
          if(isset($authorteam->teamMembers)){
136
            $persons = $authorteam->teamMembers;
137
          }
138
        } else {
139
          $persons[] = $authorteam;
140
        }
141

    
142
        foreach($persons as $person){
143
          if(!empty($person->lastname)){
144
            $order_key .= $person->lastname;
145
          } else {
146
            $order_key .= $person->titleCache;
147
          }
148
        }
149
        if(empty($order_key)){
150
          $order_key = $authorteam->titleCache;
151
        }
152

    
153
      }
154
      $order_key = str_pad($order_key, 50);
155

    
156
      // add publication date to the key
157
      if(isset($source->citation->datePublished)){
158
        $order_key .= '_' . timePeriodAsOrderKey($source->citation->datePublished);
159
      } else {
160
        $order_key .= '_' . "0000";
161
      }
162

    
163
      // padd key until unique
164
      while(array_key_exists($order_key, $sort_array)){
165
        $order_key .= "_";
166
      }
167

    
168
      $sort_array[$order_key] = render_original_source($source);
169
    }
170
    ksort($sort_array);
171
    return array_values ($sort_array);
172
}
173

    
174
/**
175
 * Compare callback to be used in usort to sort image sources of CDM OriginalSource instances.
176
 *
177
 * TODO the compare strategy implemented in oder_and_render_original_sources() is probably better but is not taking the
178
 * originalName into account.
179
 *
180
 * @param $a
181
 * @param $b
182
 */
183
function compare_original_sources($a, $b){
184

    
185
  $a_string = '';
186
  if(isset($a->citation->titleCache)) {
187
    $a_string = $a->citation->titleCache;
188
  }
189
  if((isset($a->nameUsedInSource))){
190
    $a_string .= $a->nameUsedInSource->titleCache;
191
  } elseif (isset($a->originalNameString)){
192
    $a_string .= $a->originalNameString;
193
  }
194

    
195
  $b_string = '';
196
  if(isset($b->citation->titleCache)) {
197
    $b_string = $b->citation->titleCache;
198
  };
199
  if((isset($b->nameUsedInSource))){
200
    $b_string .= $b->nameUsedInSource->titleCache;
201
  } elseif (isset($b->originalNameString)){
202
    $b_string .= $b->originalNameString;
203
  }
204

    
205
  if ($a_string == $b_string) {
206
    return 0;
207
  }
208
  return ($a_string < $b_string) ? -1 : 1;
209
}
210

    
211
/**
212
 * Compare callback to be used in usort to sort image sources of CDM Media instances.
213
 *
214
 * @param $a
215
 * @param $b
216
 */
217
function compare_text_data($a, $b) {
218

    
219
  if ($a->multilanguageText_L10n->text == $b->multilanguageText_L10n->text) {
220
    return 0;
221
  }
222
  return ($a->multilanguageText_L10n->text < $b->multilanguageText_L10n->text) ? -1 : 1;
223
}
224

    
225
/**
226
 * Provides an explanatory text on the statistical values representation as generated by statistical_values()
227
 *
228
 * @return string
229
 *     the text
230
 */
231
  function statistical_values_explanation(){
232
    return t("A single or the first number in square brackets denotes sample size");
233
  }
234

    
235
/**
236
 * Creates an array suitable to be used in statistical_values()
237
 * The min max structure is suitable for being used in the context
238
 * of GatheringEvents and StatisticalMeasures (see render_quantitative_statistics()).
239
 *
240
 * The order of the items is important for the display and must not be changed.
241
 *
242
 * @return array
243
 */
244
function statistical_values_array() {
245

    
246
  $min_max = [
247
    'ExactValue' => NULL,
248
    'Min' => NULL,
249
    'TypicalLowerBoundary' => NULL,
250
    'TypicalUpperBoundary' => NULL,
251
    'Max' => NULL,
252
    'SampleSize' => NULL,
253
    'Average' => NULL,
254
    'Variance' => NULL,
255
    'StandardDeviation' => NULL
256
  ];
257
  return $min_max;
258
}
259

    
260
/**
261
 * Creates markup from a min max array.
262
 *
263
 * NOTE: use  statistical_values_array() to create an appropriate array
264
 *
265
 * Internally Min will be translated to TypicalLowerBoundary if no such value is present.
266
 * The same also accounts for Max and TypicalUpperBoundary.
267
 *
268
 * For further details see #3742, #8766
269
 *
270
 * @param $stat_vals_arr
271
 *  the statistical values array as produced by statistical_values_array()
272
 * @param $unit
273
 *  Defaults to no unit
274
 * @return string
275
 */
276
function statistical_values($stat_vals_arr, $unit = '') {
277

    
278
  static $xbar_equals = 'x&#772;='; // x&#772; is x-bar (http://www.personal.psu.edu/ejp10/blogs/gotunicode/2010/03/dealing-with-x-bar-x-and-p-hat.html)
279

    
280
  $exact_markup = '';
281
  $min_max_markup = '';
282
  $other_vals_array = [];
283

    
284
  // --- sanitize values
285
  if(statistical_values_num_equals($stat_vals_arr, 'Min', 'TypicalLowerBoundary')){
286
    $stat_vals_arr['Min'] = NULL;
287
  }
288

    
289
  if(statistical_values_num_equals($stat_vals_arr, 'Max', 'TypicalUpperBoundary')){
290
    $stat_vals_arr['Max'] = NULL;
291
  }
292

    
293
  if($stat_vals_arr['TypicalLowerBoundary'] === null && $stat_vals_arr['Min'] !== null){
294
    $stat_vals_arr['TypicalLowerBoundary'] = $stat_vals_arr['Min'];
295
    $stat_vals_arr['Min'] = NULL;
296
  }
297

    
298
  if($stat_vals_arr['TypicalUpperBoundary'] === null && $stat_vals_arr['Max']  !== null){
299
    $stat_vals_arr['TypicalUpperBoundary'] = $stat_vals_arr['Max'];
300
    $stat_vals_arr['Max'] = NULL;
301
  }
302

    
303
  if (statistical_values_num_equals($stat_vals_arr, 'TypicalUpperBoundary', 'TypicalLowerBoundary')) {
304
    $stat_vals_arr['Average'] = $stat_vals_arr['TypicalUpperBoundary'];
305
    $stat_vals_arr['TypicalLowerBoundary'] = NULL;
306
    $stat_vals_arr['TypicalUpperBoundary'] = NULL;
307
  }
308

    
309
  // --- check for inconsistent cases, eg. only Max and average given
310
  if ($stat_vals_arr['TypicalLowerBoundary'] === NULL && $stat_vals_arr['TypicalUpperBoundary']  !== null) {
311
    // min missing
312
    $stat_vals_arr['TypicalLowerBoundary'] = '?';
313
  }
314
  if ($stat_vals_arr['TypicalLowerBoundary'] !== null && $stat_vals_arr['TypicalUpperBoundary'] === NULL) {
315
    // max missing
316
    $stat_vals_arr['TypicalUpperBoundary'] = '?';
317
  }
318

    
319
  if(statistical_values_is_numeric($stat_vals_arr['Average']) && statistical_values_is_numeric($stat_vals_arr['TypicalUpperBoundary']) && statistical_values_is_numeric($stat_vals_arr['TypicalLowerBoundary'])) {
320
    statistical_values_adjust_significant_figures($stat_vals_arr['Average'], $stat_vals_arr['TypicalLowerBoundary'], $stat_vals_arr['TypicalUpperBoundary']);
321
  }
322

    
323
  foreach ($stat_vals_arr as $key => $statistical_val) {
324

    
325
    if ($statistical_val !== NULL) {
326
      if ($statistical_val == '?') {
327
        $val_markup = $statistical_val;
328
      }
329
      else {
330
        if (is_numeric($statistical_val->_value)) {
331
          $val_markup = '<span class="'
332
            . html_class_attribute_ref($statistical_val) . ' '
333
            . (isset($statistical_val->type) ? $statistical_val->type->termType : '') . ' ' . $key . '" title="' . $key . '">'
334
            . $statistical_val->_value . '</span>';
335

    
336
        }
337
        else {
338
          $val_markup = NULL;
339
        }
340
      }
341

    
342
      if ($val_markup) {
343
        switch ($key) {
344
          case 'ExactValue':
345
            $exact_markup = $val_markup;
346
            break;
347
          // ---- min_max_element
348
          case 'Min':
349
            $min_max_markup .= "($val_markup&ndash;)";
350
            break;
351
          case 'Max':
352
            $min_max_markup .= "(&ndash;$val_markup)";
353
            break;
354
          case 'TypicalLowerBoundary':
355
            $min_max_markup .= "$val_markup";
356
            break;
357
          case 'TypicalUpperBoundary':
358
            $min_max_markup .= "&ndash;$val_markup";
359
            break;
360
          // ---- other values
361
          case 'SampleSize':
362
            $other_vals_array[$key] = $val_markup;
363
            break;
364
          case 'Average':
365
            $other_vals_array[$key] = $xbar_equals . $val_markup;
366
            break;
367
          case 'Variance':
368
            $other_vals_array[$key] = 'σ²=' . $val_markup;
369
            break;
370
          case 'StandardDeviation':
371
            $other_vals_array[$key] = 'σ=' . $val_markup;
372
            break;
373
        }
374
      }
375
    }
376
  }
377

    
378
  $full_markup = $exact_markup . ($exact_markup ? ' ' : '') . $min_max_markup;
379

    
380
  if(!$full_markup && !empty($other_vals_array['Average'])){
381
    // this could be the case in which we only have one value for Average
382
    // this trivial case needs to be displayed a simpler way
383
    $full_markup = str_replace($xbar_equals, '' , $other_vals_array['Average']);
384
    unset($other_vals_array['Average']);
385
  }
386
  if($unit){
387
    $full_markup .= ' ' . $unit;
388
  }
389
  if(count($other_vals_array)){
390
    $full_markup .= ' [' . join(';', $other_vals_array) . ']';
391
  }
392

    
393
  return $full_markup;
394
}
395

    
396
/**
397
 * Calculates the required precision for the target value to be significantly different from min and may and rounds it.
398
 *
399
 * @param $target
400
 *    The statistical value to be rounded to the least significant precision
401
 * @param $min
402
 *    The lower bound to calculate the least significant precision
403
 * @param $max
404
 *    The upper bound to calculate the least significant precision
405
 * @param int $threshold
406
 *    Per default 1, but can be set to any other value > 0 and < 1 to define
407
 *    another threshold for the transition to the next precision level.
408
 *    E.g. A value of 0.5 will cause values > 50 and <= 500 to be shown with
409
 *    a precision of 2, whereas with a threshold of 1 the values > 10 and <= 100
410
 *    will be shown with a precision of 2 figures
411
 */
412
function statistical_values_adjust_significant_figures(&$target, $min,  $max, $threshold = 1){
413

    
414
  $precision = 1;
415
  if($min->_value !== $max->_value){
416
    $precision = floor(log10(abs($max->_value - $min->_value) * (1 / $threshold)));
417
    // increase precision by one
418
    $precision += $precision < 0 ? - 1 : 1;
419
  }
420

    
421
  $target->_value = sigFig($target->_value, $precision);
422
}
423

    
424
/**
425
 * based on an idea taken from https://stackoverflow.com/questions/37618679/format-number-to-n-significant-digits-in-php#answer-48283297
426
 *
427
 * @param $value
428
 * @param $digits
429
 *
430
 * @return float|string
431
 */
432
function sigFig($value, $digits, $round_only = true)
433
{
434
  if ($value == 0) {
435
    $decimalPlaces = $digits - 1;
436
  } elseif ($value < 0) {
437
    $decimalPlaces = $digits - floor(log10($value * -1)) - 1;
438
  } else {
439
    $decimalPlaces = $digits - floor(log10($value)) - 1;
440
  }
441

    
442
  $answer = ($decimalPlaces > 0) && !$round_only ?
443
    number_format($value, $decimalPlaces) : round($value, abs($decimalPlaces));
444
  return $answer;
445
}
446

    
447

    
448

    
449
/**
450
 * Used internally in statistical_values() do determine numerically equality of stat_vals_arr values
451
 *
452
 * @param $stat_vals_arr
453
 * @param $key1
454
 * @param $key2
455
 *
456
 * @return bool
457
 */
458
function statistical_values_num_equals($stat_vals_arr, $key1, $key2){
459

    
460
  return $stat_vals_arr[$key1] !== NULL && $stat_vals_arr[$key2] !== NULL && $stat_vals_arr[$key1]->_value == $stat_vals_arr[$key2]->_value && is_numeric($stat_vals_arr[$key1]->_value);
461
}
462

    
463
function statistical_values_is_numeric($stat_val){
464
  return $stat_val !== null && is_numeric($stat_val->_value);
465
}
466

    
467
/**
468
 * Creates min max markup to represent a min-average-max measure optionally with an error value.
469
 *
470
 * The fields that are taken into account are:
471
 * - field_base_name = min
472
 * - field_base_nameMax = max
473
 * - field_base_nameText = free text
474
 * - field_base_nameError = error value
475
 *
476
 * @param $object
477
 *    The object having min max measurement fields e.g.: GatheringEvent
478
 * @param string $field_base_name
479
 *    The base name for all measurement fields. This name is at the same time the full name of the
480
 *    min value.
481
 * @return string
482
 *   The markup for the min max
483
 *
484
 * @see statistical_values()
485
 */
486
function statistical_values_from_gathering_event($object, $field_base_name)
487
{
488
  static $default_unit = 'm';
489

    
490
  $field_name = $field_base_name . 'Text';
491
  if (isset_not_empty($object->$field_name)) {
492
    // Freetext overrides all other data
493
    $min_max_markup = ' ' . $object->$field_name;
494
  } else {
495
    // create markup for the atomized min max data
496
    $min_max_array = statistical_values_array();
497
    if (isset_numerical($object->$field_base_name)) {
498
      $min_max_array['TypicalLowerBoundary'] = new stdClass();
499
      $min_max_array['TypicalLowerBoundary']->_value = $object->$field_base_name;
500
    }
501
    $field_name = $field_base_name . 'Max';
502
    if (isset_numerical($object->$field_name)) {
503
      $min_max_array['TypicalUpperBoundary'] = new stdClass();
504
      $min_max_array['TypicalUpperBoundary']->_value = $object->$field_name;
505
    } else {
506
      $min_max_array['Average'] = $min_max_array['TypicalLowerBoundary'];
507
      $min_max_array['TypicalLowerBoundary'] = null;
508
    }
509
    $min_max_markup = statistical_values($min_max_array, $default_unit);
510
  }
511

    
512
  return $min_max_markup;
513
}
514

    
515
// TODO  move below code into new file: agent.inc
516

    
517
/*
518
 * Compose an render array from a CDM TaxonNodeAgentRelation object as Taxon Expert.
519
 *
520
 * compose_hook() implementation
521
 *
522
 * @param object $taxon_node_agent_relation
523
 *   CDM instance of type TaxonNodeAgentRelation
524
 * @return array
525
 *   A drupal render array
526
 *
527
 * @ingroup compose
528
 */
529
function compose_cdm_taxon_expert($taxon_node_agent_relation) {
530

    
531
  $agent_details = null;
532

    
533
  $label_suffix = ':';
534

    
535
  if($taxon_node_agent_relation->class == 'DefaultPagerImpl'){
536
    // oops this is a pager
537
    // this situation will occur when this compose is executed
538
    // through the proxy_content() method
539
    $taxon_node_agent_relation = $taxon_node_agent_relation->records[0];
540

    
541
  }
542

    
543
  if(is_object($taxon_node_agent_relation->agent)) {
544
    $agent_details = compose_cdm_team_or_person_base($taxon_node_agent_relation->agent);
545
    // all data will be added to the groups of the agent_details render array
546
    $groups = &$agent_details[0]['#groups'];
547

    
548
    @_description_list_group_add($groups, t('Role'). $label_suffix, $taxon_node_agent_relation->type->representation_L10n);
549

    
550
    $family_tnars = cdm_ws_fetch_all(CDM_WS_PORTAL_AGENT . '/' . $taxon_node_agent_relation->agent->uuid . '/taxonNodeAgentRelations', array("rank"=>"Familia"));
551

    
552
    $taxa_markup = array(
553
      '#theme_wrappers' => array('container'),
554
      '#attributes' => array('class' => array('managed_taxa')),
555
      '#wrapper_attributes' => array('class' => 'sublist-container')
556
      );
557
    foreach($family_tnars as $tnar){
558
      if(is_object($tnar->taxonNode->taxon)){
559
        $taxa_markup[$tnar->taxonNode->taxon->titleCache] = markup_to_render_array(render_taxon_or_name($tnar->taxonNode->taxon, url(path_to_taxon($tnar->taxonNode->taxon->uuid))));
560
      }
561
    }
562
    ksort($taxa_markup);
563

    
564
    @_description_list_group_add($groups, t('Families'). $label_suffix, array($taxa_markup));
565

    
566
  }
567

    
568
  return $agent_details;
569
}
570

    
571

    
572
/*
573
 * Compose an render array from a CDM TeamOrPersonBase object.
574
 *
575
 * compose_hook() implementation
576
 *
577
 * TODO: currently mainly implemented for Agent, add Team details
578
 *
579
 * @param object $team_or_person
580
 *   CDM instance of type TeamOrPersonBase
581
 * @return array
582
 *   A drupal render array
583
 *
584
 * @ingroup compose
585
 */
586
function compose_cdm_team_or_person_base($team_or_person, $data = array()) {
587

    
588
  $groups = array();
589

    
590
  $label_suffix = ':';
591

    
592
  // $weight = 0;
593
  if($team_or_person){
594

    
595
    if(is_object($team_or_person->lifespan)){
596
      // ToDo render as date* - date† ?
597
      @_description_list_group_add($groups, t('Lifespan'). $label_suffix, timePeriodToString($team_or_person->lifespan) /*, '' , $weight++ */);
598
    }
599

    
600
    // nomenclaturalTitle
601
    @_description_list_group_add($groups, "Nomenclatural Title". $label_suffix, $team_or_person->nomenclaturalTitle);
602
    // collectorTitle
603
    @_description_list_group_add($groups, "Collector Title". $label_suffix, $team_or_person->collectorTitle);
604

    
605
    // institutionalMemberships
606
    if(is_array($team_or_person->institutionalMemberships)){
607

    
608
      $institutes_ra =  array();
609
      foreach($team_or_person->institutionalMemberships as $membership) {
610
        $membership_groups = array();
611
        @_description_list_group_add($membership_groups, t('Department'). $label_suffix, $membership->department);
612
        @_description_list_group_add($membership_groups, t('Role'). $label_suffix, $membership->role);
613
        if(is_object($membership->period)){
614
          @_description_list_group_add($membership_groups, t('Period'). $label_suffix, timePeriodToString($membership->period));
615
        }
616
        if(is_object($membership->institute->contact)){
617
          $institute_contact_details = compose_cdm_contact($membership->institute->contact, $membership->institute->titleCache);
618
          if(is_array($institute_contact_details[0]['#groups'])){
619
            $membership_groups = array_merge($membership_groups, $institute_contact_details[0]['#groups']);
620
          }
621
        }
622
        if(count($membership_groups) > 0){
623
          $institutes_ra[]  = array(
624
            '#title' => $membership->institute->titleCache,
625
            '#theme' => 'description_list',
626
            '#groups' => $membership_groups,
627
            '#attributes' => array('class' => html_class_attribute_ref($membership)),
628
            '#wrapper_attributes' => array('class' => 'sublist-container')
629
          );
630
        } else {
631
          // no further details for the membership, display the title
632
          $institutes_ra[] = markup_to_render_array('<h3>' . $membership->institute->titleCache . '</h3>');
633
        }
634

    
635
      }
636

    
637
      $label = count($institutes_ra) > 1 ? t('Institutes'):  t('Institute');
638
      @_description_list_group_add($groups, $label. $label_suffix, $institutes_ra /*, '' , $weight++ */);
639
    }
640

    
641

    
642
    // Contact
643
    $agent_contact_details = compose_cdm_contact($team_or_person->contact, $team_or_person->titleCache);
644
    if(is_array($agent_contact_details[0]['#groups'])){
645
      $groups = array_merge($groups, $agent_contact_details[0]['#groups']);
646
    }
647

    
648
    // additional data
649
    foreach($data as $key=>$value){
650
      @_description_list_group_add($sub_dl_groups, t('@key', array('@key' => $key)), $value /*, '' , $weight++ */);
651
    }
652

    
653
  }
654

    
655
  $team_or_person_details = array(
656
    '#title' => $team_or_person->titleCache,
657
    '#theme' => 'description_list',
658
    '#groups' => $groups,
659
    '#attributes' => array('class' => html_class_attribute_ref($team_or_person)),
660
  );
661
  return array($team_or_person_details);
662
}
663

    
664

    
665
/*
666
 * Compose an render array from a CDM Contact object.
667
 *
668
 * compose_hook() implementation
669
 *
670
 * TODO: currently mainly implemented for Agent, add Team details
671
 *
672
 * @param object $contact
673
 *   CDM instance of type Contact
674
 * @param $title
675
 *   The title for the description list header
676
 * @param $weight
677
 *   Optional weight for the description list entries
678
 * @return array
679
 *   A drupal render array
680
 *
681
 * @ingroup compose
682
 */
683
function compose_cdm_contact($contact, $title, $weight = 0)
684
{
685

    
686
  $groups = array();
687

    
688
  $contact_details = null;
689

    
690
  $label_suffix = ':';
691

    
692
  $contact_field_names_map = array(
693
    'emailAddresses' => t('Email'),
694
    'urls' => t('Urls'),
695
    'phoneNumbers' => t('Phone'),
696
    'faxNumbers' => t('Fax'),
697
  );
698

    
699
  // Contact
700
  if(is_object($contact)){
701
    if(isset($contact->addresses)){
702
      // TODO ....
703
      // $sub_groups = array();
704
      // foreach($contact->addresses as $address){
705
      //   @_description_list_group_add($sub_groups, $label, $contact->$fieldName, '', $weight++);
706
      // }
707
    }
708
    foreach($contact_field_names_map as $fieldName => $label){
709
      if(is_array($contact->$fieldName)){
710
        @_description_list_group_add($groups, $label . $label_suffix, $contact->$fieldName, '', $weight++);
711
      }
712
    }
713
    $contact_details = array(
714
      '#title' => $title,
715
      '#theme' => 'description_list',
716
      '#groups' => $groups
717
    );
718

    
719

    
720
  } else if(is_string($title)) {
721
    // if the contact entity is empty but the title is given anyway
722
    // we are only adding the title, using the description_list
723
    // structure is not possible since it would be empty due to
724
    // missing group data
725
    $contact_details = array('#markup' => '<h3>' . $title . '</h3>');
726
  }
727

    
728
  return array($contact_details);
729

    
730
}
731

    
732
function visible_extensions_sorted($cdm_entity) {
733

    
734
  $visible_extensions_sorted = [];
735
  $extension_types_visible = variable_get(EXTENSION_TYPES_VISIBLE, unserialize(EXTENSION_TYPES_VISIBLE_DEFAULT));
736
  if (isset($cdm_entity->extensions)) {
737
    foreach ($cdm_entity->extensions as $ext) {
738
      if (array_search($ext->type->uuid, $extension_types_visible)) {
739
        if (!array_key_exists($ext->type->uuid, $visible_extensions_sorted)) {
740
          $visible_extensions_sorted[$ext->type->uuid] = [];
741
        }
742
        $visible_extensions_sorted[$ext->type->uuid][] = $ext;
743
      }
744
    }
745
  }
746
  return $visible_extensions_sorted;
747
}
748

    
749
/**
750
 * Compose an render array from a CDM Extension objects.
751
 *
752
 * @param $extensions
753
 *    An array of CDM Extension objects
754
 * @return array
755
 *   A render array containing the fields of the supplied $sequence
756
 *
757
 * @ingroup compose
758
 */
759
function compose_extensions($extensions)
760
{
761
  $render_array= null;
762
  $extensions_by_type = array();
763
  foreach ($extensions as $extension) {
764
    if (@is_string($extension->value)) {
765
      if (!isset($extensions_by_type[$extension->type->representation_L10n])) {
766
        $extensions_by_type[$extension->type->representation_L10n] = array();
767
      }
768
      $extensions_by_type[$extension->type->representation_L10n][] = markup_to_render_array($extension->value);
769
    }
770
  }
771

    
772
  if (count($extensions_by_type)) {
773
    $sub_dl_groups = array();
774
    foreach ($extensions_by_type as $type_label => $text_list) {
775
      @_description_list_group_add($sub_dl_groups, $type_label . ':', $text_list);
776
    }
777
    $render_array = array(
778
      array('#theme' => 'description_list', '#groups' => $sub_dl_groups)
779
    );
780
    return $render_array;
781
  }
782
  return $render_array;
783
}
784

    
785
/**
786
 * Compose an render array from a CDM Identifier objects.
787
 *
788
 * @param $extensions
789
 *    An array of CDM Identifier objects
790
 * @return array
791
 *   A render array containing the fields of the supplied $sequence
792
 *
793
 * @ingroup compose
794
 */
795
function compose_identifiers($identifiers){
796

    
797
  $render_array = [];
798
  //     // urn:lsid:ipni.org:authors:20009164-1 UUID_IDENTIFIER_TYPE_LSID
799
  foreach($identifiers as $identifier){
800
    if($identifier->identifier){
801
      $render_array[] = markup_to_render_array('<span class="label">' . $identifier->type->representation_L10n . ':</span> ' . $identifier->identifier, null, '<span class="'. html_class_attribute_ref($identifier) . '">', '</span>');
802
    }
803
  }
804

    
805
  return $render_array;
806

    
807
}
808

    
809
function formatParams($params) {
810
    $paramString = null;
811
    if (is_array($params)){
812
        $keys =array_keys($params);
813
        $paramString = '';
814
        foreach ($keys as $k ){
815
            if ($k != 'pageNumber' && $k != 'pageSize'){
816
                $paramString .= ' -'.$k.'='.urlencode($params[$k]);
817
            }
818
        }
819
    }
820
    return $paramString;
821
}
822

    
823
function formatWSParams($params) {
824
  $paramString = null;
825
    if (is_array($params)){
826
        $keys =array_keys($params);
827
        $paramString = '';
828
        foreach ($keys as $k ){
829
            if ($k != 'pageNumber' && $k != 'pageSize'){
830
                $paramString .= '&'.$k.'='.urlencode($params[$k]);
831
            }
832
        }
833
    }
834
    return $paramString;
835
}
836

    
837
/**
838
 *
839
 * @param $cdm_entity
840
 *
841
 * @return string the markup
842
 */
843
function render_cdm_entity_link($cdm_entity) {
844

    
845
  switch ($cdm_entity->class) {
846
    case 'TaxonDescription':
847
    case 'NameDescription':
848
    case 'SpecimenDescription':
849
      $link =  '<span class="' . html_class_attribute_ref($cdm_entity) . '">' . $cdm_entity->titleCache . '</span> ' . icon_link(path_to_description($cdm_entity->uuid));
850
      break;
851
    default:
852
      $link = '<span class="error">UNSUPPORTED CDM ENTITY TYPE</span>';
853
  }
854
  return $link;
855
}
856

    
857
/**
858
 * @param $point
859
 * @param bool $do_link_to_geohack
860
 * @param string $geohack_link_pagename
861
 *
862
 * @return string
863
 */
864
function render_point($point, $do_link_to_geohack = true, $geohack_link_pagename = ''){
865
  if(!isset($point->sexagesimalString)){
866
    return '';
867
  }
868
  $markup = $point->sexagesimalString;
869
  if($do_link_to_geohack) {
870
    // see https://www.mediawiki.org/wiki/GeoHack
871
    $geohack_url = sprintf(
872
      "https://geohack.toolforge.org/geohack.php?language=en&params=%f;%f&pagename=%s",
873
      $point->latitude,
874
      $point->longitude,
875
      $geohack_link_pagename);
876
    $markup = l($markup, $geohack_url, ['attributes' => ['target' => 'geohack']]);
877
  }
878
  if(isset($point->errorRadius) && $point->errorRadius){
879
    $markup .= ' +/-' . $point->errorRadius . ' m';
880
  }
881
  if(isset($point->referenceSystem) && $point->referenceSystem){
882
    $refsystem = '(' . $point->referenceSystem->representation_L10n . ')';
883
    $markup = str_replace($refsystem, '', $markup);
884
    $markup .= ' ' . $refsystem;
885
  }
886
  return $markup;
887
}
888

    
889
/**
890
 * Creates an icon which links to the given path
891
 *
892
 * @param $path
893
 *
894
 * @param string $fragment
895
 *   The URL fragment to link to
896
 * @param bool $superscript
897
 *   If TRUE, the Icon will be be displayed in superscript position. Default is TRUE.
898
 *
899
 * @return string
900
 */
901
function icon_link($path, $fragment = '', $superscript = FALSE) {
902
  if($superscript){
903
    $attributes = ['class' => ['superscript']];
904
  } else {
905
    $attributes = [];
906
  }
907
  $icon_link = l(custom_icon_font_markup('icon-interal-link-alt-solid', $attributes), $path, ['html' => TRUE, 'fragment' => $fragment] );
908
  return $icon_link;
909
}
910

    
911
/**
912
 * Determine if a variable is set and is not NULL an is not empty.
913
 *
914
 * @param $var
915
 *  The variable to test
916
 *
917
 * @return bool
918
 *  True if the variable is set and is not NULL an is not empty.
919
 */
920
function isset_not_empty(&$var, $numerical_non_zero = FALSE){
921
  if (!isset($var)){
922
    return false;
923
  }
924
  if(is_numeric($var)) {
925
    if($numerical_non_zero){
926
      return $var;
927
    } else {
928
      true;
929
    };
930
  } else if(is_array($var)){
931
    return count($var) > 0;
932
  }else if(is_string($var)){
933
    return !!trim($var);
934
  } else {
935
    return !!$var;
936
  }
937
}
938

    
939
function isset_numerical(&$var){
940
  if (!isset($var)){
941
    return false;
942
  }
943
  return is_numeric($var);
944
}
945

    
946
function normalize_to_class_attribute($string){
947
  $string = strtolower($string);
948
  $string = preg_replace('/\s/', '_', $string);
949
  $string = preg_replace('/[^a-z0-9\-_]/', '', $string);
950
  return $string;
951
}
(2-2/15)