Project

General

Profile

Download (28.5 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
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
54
  } elseif (isset($cdm_entity->class)) {
55
    switch ($cdm_entity->class){
56
      case 'TypedEntityReference':
57
      case 'TaggedEntityReference':
58
      case 'TypeDesignationDTO':
59
        $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
60
      break;
61
      case 'TaxonNodeDto':
62
        $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
63
      break;
64
      case 'Taxon':
65
        if(isset($cdm_entity->sec->uuid)){
66
        $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
67
      }
68
      break;
69
    }
70
  }
71

    
72
  return $attributes;
73
}
74

    
75

    
76
/**
77
 * Compose an render array from a CDM Marker object.
78
 *
79
 * compose_hook() implementation
80
 *
81
 * @param object $marker
82
 *   CDM instance of type Marker
83
 * @return array
84
 *   A drupal render array
85
 *
86
 * @ingroup compose
87
 */
88
function compose_cdm_marker($marker) {
89

    
90
  $render_array = array(
91
      // ---- generic
92
      //  these entries should be common to all cdm enitiy render arrays
93
      '#theme' => 'cdm_marker', // TODO   add alternative theme funcitons: 'cdm_marker_' . marker.type.label
94
      '#attributes' => array('class' => html_class_attribute_ref($marker)),
95

    
96
      // ---- individual
97
      '#label' => $marker->markerType->representation_L10n . ': ' . (($marker->flag !== TRUE ? t('yes') : t('no'))),
98
  );
99

    
100
  return $render_array;
101
}
102

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

    
121
/**
122
 * Sorts an array of CDM IdentifiableSource instances by 1. by the
123
 * author teams family names and 2. by the publication date.
124
 *
125
 * @param array $sources
126
 *    The array of CDM IdentifiableSource instances
127
 * @return array
128
 *  An array of drupal render arrays
129
 */
130
function oder_and_render_original_sources($sources){
131
    $sort_array = array();
132
    foreach ($sources as $source) {
133

    
134
      $order_key = '';
135

    
136
      // find the familynames
137
      if(isset($source->citation->uuid) && !isset($source->citation->authorship)){
138
        $authorteam = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $source->citation->uuid);
139

    
140
        $persons = array();
141
        if($authorteam->class == 'Team'){
142
          if(isset($authorteam->teamMembers)){
143
            $persons = $authorteam->teamMembers;
144
          }
145
        } else {
146
          $persons[] = $authorteam;
147
        }
148

    
149
        foreach($persons as $person){
150
          if(!empty($person->lastname)){
151
            $order_key .= $person->lastname;
152
          } else {
153
            $order_key .= $person->titleCache;
154
          }
155
        }
156
        if(empty($order_key)){
157
          $order_key = $authorteam->titleCache;
158
        }
159

    
160
      }
161
      $order_key = str_pad($order_key, 50);
162

    
163
      // add publication date to the key
164
      if(isset($source->citation->datePublished)){
165
        $order_key .= '_' . timePeriodAsOrderKey($source->citation->datePublished);
166
      } else {
167
        $order_key .= '_' . "0000";
168
      }
169

    
170
      // padd key until unique
171
      while(array_key_exists($order_key, $sort_array)){
172
        $order_key .= "_";
173
      }
174

    
175
      $sort_array[$order_key] = render_original_source($source);
176
    }
177
    ksort($sort_array);
178
    return array_values ($sort_array);
179
}
180

    
181
/**
182
 * Compare callback to be used in usort to sort image sources of CDM OriginalSource instances.
183
 *
184
 * TODO the compare strategy implemented in oder_and_render_original_sources() is probably better but is not taking the
185
 * originalName into account.
186
 *
187
 * @param $a
188
 * @param $b
189
 */
190
function compare_original_sources($a, $b){
191

    
192
  $a_string = '';
193
  if(isset($a->citation->titleCache)) {
194
    $a_string = $a->citation->titleCache;
195
  }
196
  if((isset($a->nameUsedInSource))){
197
    $a_string .= $a->nameUsedInSource->titleCache;
198
  } elseif (isset($a->originalNameString)){
199
    $a_string .= $a->originalNameString;
200
  }
201

    
202
  $b_string = '';
203
  if(isset($b->citation->titleCache)) {
204
    $b_string = $b->citation->titleCache;
205
  };
206
  if((isset($b->nameUsedInSource))){
207
    $b_string .= $b->nameUsedInSource->titleCache;
208
  } elseif (isset($b->originalNameString)){
209
    $b_string .= $b->originalNameString;
210
  }
211

    
212
  if ($a_string == $b_string) {
213
    return 0;
214
  }
215
  return ($a_string < $b_string) ? -1 : 1;
216
}
217

    
218
/**
219
 * Compare callback to be used in usort to sort image sources of CDM Media instances.
220
 *
221
 * @param $a
222
 * @param $b
223
 */
224
function compare_text_data($a, $b) {
225

    
226
  if ($a->multilanguageText_L10n->text == $b->multilanguageText_L10n->text) {
227
    return 0;
228
  }
229
  return ($a->multilanguageText_L10n->text < $b->multilanguageText_L10n->text) ? -1 : 1;
230
}
231

    
232
/**
233
 * Provides an explanatory text on the statistical values representation as generated by statistical_values()
234
 *
235
 * @return string
236
 *     the text
237
 */
238
  function statistical_values_explanation(){
239
    return t("A single or the first number in square brackets denotes sample size");
240
  }
241

    
242
/**
243
 * Creates an array suitable to be used in statistical_values()
244
 * The min max structure is suitable for being used in the context
245
 * of GatheringEvents and StatisticalMeasures (see render_quantitative_statistics()).
246
 *
247
 * The order of the items is important for the display and must not be changed.
248
 *
249
 * @return array
250
 */
251
function statistical_values_array() {
252

    
253
  $min_max = [
254
    'ExactValue' => NULL,
255
    'Min' => NULL,
256
    'TypicalLowerBoundary' => NULL,
257
    'TypicalUpperBoundary' => NULL,
258
    'Max' => NULL,
259
    'SampleSize' => NULL,
260
    'Average' => NULL,
261
    'Variance' => NULL,
262
    'StandardDeviation' => NULL
263
  ];
264
  return $min_max;
265
}
266

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

    
285
  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)
286

    
287
  $exact_markup = '';
288
  $min_max_markup = '';
289
  $other_vals_array = [];
290

    
291
  // --- sanitize values
292
  if(statistical_values_num_equals($stat_vals_arr, 'Min', 'TypicalLowerBoundary')){
293
    $stat_vals_arr['Min'] = NULL;
294
  }
295

    
296
  if(statistical_values_num_equals($stat_vals_arr, 'Max', 'TypicalUpperBoundary')){
297
    $stat_vals_arr['Max'] = NULL;
298
  }
299

    
300
  if($stat_vals_arr['TypicalLowerBoundary'] === null && $stat_vals_arr['Min'] !== null){
301
    $stat_vals_arr['TypicalLowerBoundary'] = $stat_vals_arr['Min'];
302
    $stat_vals_arr['Min'] = NULL;
303
  }
304

    
305
  if($stat_vals_arr['TypicalUpperBoundary'] === null && $stat_vals_arr['Max']  !== null){
306
    $stat_vals_arr['TypicalUpperBoundary'] = $stat_vals_arr['Max'];
307
    $stat_vals_arr['Max'] = NULL;
308
  }
309

    
310
  if (statistical_values_num_equals($stat_vals_arr, 'TypicalUpperBoundary', 'TypicalLowerBoundary')) {
311
    $stat_vals_arr['Average'] = $stat_vals_arr['TypicalUpperBoundary'];
312
    $stat_vals_arr['TypicalLowerBoundary'] = NULL;
313
    $stat_vals_arr['TypicalUpperBoundary'] = NULL;
314
  }
315

    
316
  // --- check for inconsistent cases, eg. only Max and average given
317
  if ($stat_vals_arr['TypicalLowerBoundary'] === NULL && $stat_vals_arr['TypicalUpperBoundary']  !== null) {
318
    // min missing
319
    $stat_vals_arr['TypicalLowerBoundary'] = '?';
320
  }
321
  if ($stat_vals_arr['TypicalLowerBoundary'] !== null && $stat_vals_arr['TypicalUpperBoundary'] === NULL) {
322
    // max missing
323
    $stat_vals_arr['TypicalUpperBoundary'] = '?';
324
  }
325

    
326
  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'])) {
327
    statistical_values_adjust_significant_figures($stat_vals_arr['Average'], $stat_vals_arr['TypicalLowerBoundary'], $stat_vals_arr['TypicalUpperBoundary']);
328
  }
329

    
330
  foreach ($stat_vals_arr as $key => $statistical_val) {
331

    
332
    if ($statistical_val !== NULL) {
333
      if ($statistical_val == '?') {
334
        $val_markup = $statistical_val;
335
      }
336
      else {
337
        if (is_numeric($statistical_val->_value)) {
338
          $val_markup = '<span class="'
339
            . html_class_attribute_ref($statistical_val) . ' '
340
            . (isset($statistical_val->type) ? $statistical_val->type->termType : '') . ' ' . $key . '" title="' . $key . '">'
341
            . $statistical_val->_value . '</span>';
342

    
343
        }
344
        else {
345
          $val_markup = NULL;
346
        }
347
      }
348

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

    
385
  $full_markup = $exact_markup . ($exact_markup ? ' ' : '') . $min_max_markup;
386

    
387
  if(!$full_markup && !empty($other_vals_array['Average'])){
388
    // this could be the case in which we only have one value for Average
389
    // this trivial case needs to be displayed a simpler way
390
    $full_markup = str_replace($xbar_equals, '' , $other_vals_array['Average']);
391
    unset($other_vals_array['Average']);
392
  }
393
  if($unit){
394
    $full_markup .= ' ' . $unit;
395
  }
396
  if(count($other_vals_array)){
397
    $full_markup .= ' [' . join(';', $other_vals_array) . ']';
398
  }
399

    
400
  return $full_markup;
401
}
402

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

    
421
  $precision = 1;
422
  if($min->_value !== $max->_value){
423
    $precision = floor(log10(abs($max->_value - $min->_value) * (1 / $threshold)));
424
    // increase precision by one
425
    $precision += $precision < 0 ? - 1 : 1;
426
  }
427

    
428
  $target->_value = sigFig($target->_value, $precision);
429
}
430

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

    
449
  $answer = ($decimalPlaces > 0) && !$round_only ?
450
    number_format($value, $decimalPlaces) : round($value, abs($decimalPlaces));
451
  return $answer;
452
}
453

    
454

    
455

    
456
/**
457
 * Used internally in statistical_values() do determine numerically equality of stat_vals_arr values
458
 *
459
 * @param $stat_vals_arr
460
 * @param $key1
461
 * @param $key2
462
 *
463
 * @return bool
464
 */
465
function statistical_values_num_equals($stat_vals_arr, $key1, $key2){
466

    
467
  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);
468
}
469

    
470
function statistical_values_is_numeric($stat_val){
471
  return $stat_val !== null && is_numeric($stat_val->_value);
472
}
473

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

    
497
  $field_name = $field_base_name . 'Text';
498
  if (@is_string($object->$field_name)) {
499
    // Freetext overrides all other data
500
    $min_max_markup = ' ' . $object->$field_name;
501
  } else {
502
    // create markup for the atomized min max data
503
    $min_max_array = statistical_values_array();
504
    if (@is_numeric($object->$field_base_name)) {
505
      $min_max_array['Min'] = new stdClass();
506
      $min_max_array['Min']->_value = $object->$field_base_name;
507
    }
508
    $field_name = $field_base_name . 'Max';
509
    if (@is_numeric($object->$field_name)) {
510
      $min_max_array['Max'] = new stdClass();
511
      $min_max_array['Max']->_value = $object->$field_name;
512
    }
513
    $min_max_markup = statistical_values($min_max_array, $default_unit);
514
  }
515

    
516
  return $min_max_markup;
517
}
518

    
519
// TODO  move below code into new file: agent.inc
520

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

    
535
  $agent_details = null;
536

    
537
  $label_suffix = ':';
538

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

    
545
  }
546

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

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

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

    
556
    $taxa_markup = array(
557
      '#theme_wrappers' => array('container'),
558
      '#attributes' => array('class' => array('managed_taxa')),
559
      '#wrapper_attributes' => array('class' => 'sublist-container')
560
      );
561
    foreach($family_tnars as $tnar){
562
      if(is_object($tnar->taxonNode->taxon)){
563
        $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))));
564
      }
565
    }
566
    ksort($taxa_markup);
567

    
568
    @_description_list_group_add($groups, t('Families'). $label_suffix, array($taxa_markup));
569

    
570
  }
571

    
572
  return $agent_details;
573
}
574

    
575

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

    
592
  $groups = array();
593

    
594
  $label_suffix = ':';
595

    
596
  // $weight = 0;
597
  if($team_or_person){
598

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

    
604
    // nomenclaturalTitle
605
    @_description_list_group_add($groups, "Nomenclatural Title". $label_suffix, $team_or_person->nomenclaturalTitle);
606
    // collectorTitle
607
    @_description_list_group_add($groups, "Collector Title". $label_suffix, $team_or_person->collectorTitle);
608

    
609
    // institutionalMemberships
610
    if(is_array($team_or_person->institutionalMemberships)){
611

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

    
639
      }
640

    
641
      $label = count($institutes_ra) > 1 ? t('Institutes'):  t('Institute');
642
      @_description_list_group_add($groups, $label. $label_suffix, $institutes_ra /*, '' , $weight++ */);
643
    }
644

    
645

    
646
    // Contact
647
    $agent_contact_details = compose_cdm_contact($team_or_person->contact, $team_or_person->titleCache);
648
    if(is_array($agent_contact_details[0]['#groups'])){
649
      $groups = array_merge($groups, $agent_contact_details[0]['#groups']);
650
    }
651

    
652
    // additional data
653
    foreach($data as $key=>$value){
654
      @_description_list_group_add($sub_dl_groups, t('@key', array('@key' => $key)), $value /*, '' , $weight++ */);
655
    }
656

    
657
  }
658

    
659
  $team_or_person_details = array(
660
    '#title' => $team_or_person->titleCache,
661
    '#theme' => 'description_list',
662
    '#groups' => $groups,
663
    '#attributes' => array('class' => html_class_attribute_ref($team_or_person)),
664
  );
665
  return array($team_or_person_details);
666
}
667

    
668

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

    
690
  $groups = array();
691

    
692
  $contact_details = null;
693

    
694
  $label_suffix = ':';
695

    
696
  $contact_field_names_map = array(
697
    'emailAddresses' => t('Email'),
698
    'urls' => t('Urls'),
699
    'phoneNumbers' => t('Phone'),
700
    'faxNumbers' => t('Fax'),
701
  );
702

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

    
723

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

    
732
  return array($contact_details);
733

    
734
}
735

    
736
function visible_extensions_sorted($cdm_entity) {
737

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

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

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

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

    
801
  $render_array = [];
802
  //     // urn:lsid:ipni.org:authors:20009164-1 UUID_IDENTIFIER_TYPE_LSID
803
  foreach($identifiers as $identifier){
804
    if($identifier->identifier){
805
      $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>');
806
    }
807
  }
808

    
809
  return $render_array;
810

    
811
}
812

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

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

    
841
/**
842
 *
843
 * @param $cdm_entity
844
 *
845
 * @return string the markup
846
 */
847
function render_cdm_entity_link($cdm_entity) {
848

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

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

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

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

    
936
}
(2-2/15)