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
    $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 (isset_not_empty($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 (isset_numerical($object->$field_base_name)) {
505
      $min_max_array['TypicalLowerBoundary'] = new stdClass();
506
      $min_max_array['TypicalLowerBoundary']->_value = $object->$field_base_name;
507
    }
508
    $field_name = $field_base_name . 'Max';
509
    if (isset_numerical($object->$field_name)) {
510
      $min_max_array['TypicalUpperBoundary'] = new stdClass();
511
      $min_max_array['TypicalUpperBoundary']->_value = $object->$field_name;
512
    } else {
513
      $min_max_array['Average'] = $min_max_array['TypicalLowerBoundary'];
514
      $min_max_array['TypicalLowerBoundary'] = null;
515
    }
516
    $min_max_markup = statistical_values($min_max_array, $default_unit);
517
  }
518

    
519
  return $min_max_markup;
520
}
521

    
522
// TODO  move below code into new file: agent.inc
523

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

    
538
  $agent_details = null;
539

    
540
  $label_suffix = ':';
541

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

    
548
  }
549

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

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

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

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

    
571
    @_description_list_group_add($groups, t('Families'). $label_suffix, array($taxa_markup));
572

    
573
  }
574

    
575
  return $agent_details;
576
}
577

    
578

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

    
595
  $groups = array();
596

    
597
  $label_suffix = ':';
598

    
599
  // $weight = 0;
600
  if($team_or_person){
601

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

    
607
    // nomenclaturalTitle
608
    @_description_list_group_add($groups, "Nomenclatural Title". $label_suffix, $team_or_person->nomenclaturalTitle);
609
    // collectorTitle
610
    @_description_list_group_add($groups, "Collector Title". $label_suffix, $team_or_person->collectorTitle);
611

    
612
    // institutionalMemberships
613
    if(is_array($team_or_person->institutionalMemberships)){
614

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

    
642
      }
643

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

    
648

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

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

    
660
  }
661

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

    
671

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

    
693
  $groups = array();
694

    
695
  $contact_details = null;
696

    
697
  $label_suffix = ':';
698

    
699
  $contact_field_names_map = array(
700
    'emailAddresses' => t('Email'),
701
    'urls' => t('Urls'),
702
    'phoneNumbers' => t('Phone'),
703
    'faxNumbers' => t('Fax'),
704
  );
705

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

    
726

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

    
735
  return array($contact_details);
736

    
737
}
738

    
739
function visible_extensions_sorted($cdm_entity) {
740

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

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

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

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

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

    
812
  return $render_array;
813

    
814
}
815

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

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

    
844
/**
845
 *
846
 * @param $cdm_entity
847
 *
848
 * @return string the markup
849
 */
850
function render_cdm_entity_link($cdm_entity) {
851

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

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

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

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

    
946
function isset_numerical(&$var){
947
  if (!isset($var)){
948
    return false;
949
  }
950
  return is_numeric($var);
951
}
952

    
(2-2/15)