Project

General

Profile

Download (29 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

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

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

    
103
  return $render_array;
104
}
105

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

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

    
137
      $order_key = '';
138

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

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

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

    
163
      }
164
      $order_key = str_pad($order_key, 50);
165

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

    
173
      // padd key until unique
174
      while(array_key_exists($order_key, $sort_array)){
175
        $order_key .= "_";
176
      }
177

    
178
      $sort_array[$order_key] = render_original_source($source);
179
    }
180
    ksort($sort_array);
181
    return array_values ($sort_array);
182
}
183

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

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

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

    
215
  if ($a_string == $b_string) {
216
    return 0;
217
  }
218
  return ($a_string < $b_string) ? -1 : 1;
219
}
220

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

    
229
  if ($a->multilanguageText_L10n->text == $b->multilanguageText_L10n->text) {
230
    return 0;
231
  }
232
  return ($a->multilanguageText_L10n->text < $b->multilanguageText_L10n->text) ? -1 : 1;
233
}
234

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

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

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

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

    
288
  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)
289

    
290
  $exact_markup = '';
291
  $min_max_markup = '';
292
  $other_vals_array = [];
293

    
294
  // --- sanitize values
295
  if(statistical_values_num_equals($stat_vals_arr, 'Min', 'TypicalLowerBoundary')){
296
    $stat_vals_arr['Min'] = NULL;
297
  }
298

    
299
  if(statistical_values_num_equals($stat_vals_arr, 'Max', 'TypicalUpperBoundary')){
300
    $stat_vals_arr['Max'] = NULL;
301
  }
302

    
303
  if($stat_vals_arr['TypicalLowerBoundary'] === null && $stat_vals_arr['Min'] !== null){
304
    $stat_vals_arr['TypicalLowerBoundary'] = $stat_vals_arr['Min'];
305
    $stat_vals_arr['Min'] = NULL;
306
  }
307

    
308
  if($stat_vals_arr['TypicalUpperBoundary'] === null && $stat_vals_arr['Max']  !== null){
309
    $stat_vals_arr['TypicalUpperBoundary'] = $stat_vals_arr['Max'];
310
    $stat_vals_arr['Max'] = NULL;
311
  }
312

    
313
  if (statistical_values_num_equals($stat_vals_arr, 'TypicalUpperBoundary', 'TypicalLowerBoundary')) {
314
    $stat_vals_arr['Average'] = $stat_vals_arr['TypicalUpperBoundary'];
315
    $stat_vals_arr['TypicalLowerBoundary'] = NULL;
316
    $stat_vals_arr['TypicalUpperBoundary'] = NULL;
317
  }
318

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

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

    
333
  foreach ($stat_vals_arr as $key => $statistical_val) {
334

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

    
346
        }
347
        else {
348
          $val_markup = NULL;
349
        }
350
      }
351

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

    
388
  $full_markup = $exact_markup . ($exact_markup ? ' ' : '') . $min_max_markup;
389

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

    
403
  return $full_markup;
404
}
405

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

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

    
431
  $target->_value = sigFig($target->_value, $precision);
432
}
433

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

    
452
  $answer = ($decimalPlaces > 0) && !$round_only ?
453
    number_format($value, $decimalPlaces) : round($value, abs($decimalPlaces));
454
  return $answer;
455
}
456

    
457

    
458

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

    
470
  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);
471
}
472

    
473
function statistical_values_is_numeric($stat_val){
474
  return $stat_val !== null && is_numeric($stat_val->_value);
475
}
476

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

    
500
  $field_name = $field_base_name . 'Text';
501
  if (isset_not_empty($object->$field_name)) {
502
    // Freetext overrides all other data
503
    $min_max_markup = ' ' . $object->$field_name;
504
  } else {
505
    // create markup for the atomized min max data
506
    $min_max_array = statistical_values_array();
507
    if (isset_numerical($object->$field_base_name)) {
508
      $min_max_array['TypicalLowerBoundary'] = new stdClass();
509
      $min_max_array['TypicalLowerBoundary']->_value = $object->$field_base_name;
510
    }
511
    $field_name = $field_base_name . 'Max';
512
    if (isset_numerical($object->$field_name)) {
513
      $min_max_array['TypicalUpperBoundary'] = new stdClass();
514
      $min_max_array['TypicalUpperBoundary']->_value = $object->$field_name;
515
    } else {
516
      $min_max_array['Average'] = $min_max_array['TypicalLowerBoundary'];
517
      $min_max_array['TypicalLowerBoundary'] = null;
518
    }
519
    $min_max_markup = statistical_values($min_max_array, $default_unit);
520
  }
521

    
522
  return $min_max_markup;
523
}
524

    
525
// TODO  move below code into new file: agent.inc
526

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

    
541
  $agent_details = null;
542

    
543
  $label_suffix = ':';
544

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

    
551
  }
552

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

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

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

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

    
574
    @_description_list_group_add($groups, t('Families'). $label_suffix, array($taxa_markup));
575

    
576
  }
577

    
578
  return $agent_details;
579
}
580

    
581

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

    
598
  $groups = array();
599

    
600
  $label_suffix = ':';
601

    
602
  // $weight = 0;
603
  if($team_or_person){
604

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

    
610
    // nomenclaturalTitle
611
    @_description_list_group_add($groups, "Nomenclatural Title". $label_suffix, $team_or_person->nomenclaturalTitle);
612
    // collectorTitle
613
    @_description_list_group_add($groups, "Collector Title". $label_suffix, $team_or_person->collectorTitle);
614

    
615
    // institutionalMemberships
616
    if(is_array($team_or_person->institutionalMemberships)){
617

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

    
645
      }
646

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

    
651

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

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

    
663
  }
664

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

    
674

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

    
696
  $groups = array();
697

    
698
  $contact_details = null;
699

    
700
  $label_suffix = ':';
701

    
702
  $contact_field_names_map = array(
703
    'emailAddresses' => t('Email'),
704
    'urls' => t('Urls'),
705
    'phoneNumbers' => t('Phone'),
706
    'faxNumbers' => t('Fax'),
707
  );
708

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

    
729

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

    
738
  return array($contact_details);
739

    
740
}
741

    
742
function visible_extensions_sorted($cdm_entity) {
743

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

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

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

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

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

    
815
  return $render_array;
816

    
817
}
818

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

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

    
847
/**
848
 *
849
 * @param $cdm_entity
850
 *
851
 * @return string the markup
852
 */
853
function render_cdm_entity_link($cdm_entity) {
854

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

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

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

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

    
949
function isset_numerical(&$var){
950
  if (!isset($var)){
951
    return false;
952
  }
953
  return is_numeric($var);
954
}
955

    
(2-2/15)