Project

General

Profile

Download (88.5 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

    
3
const BIBLIOGRAPHY_FOOTNOTE_KEY = PSEUDO_FEATURE_BIBLIOGRAPHY;
4

    
5

    
6
/**
7
 * Returns the localized representations of the modifiers hold by the
8
 * supplied cdm instance concatenated into one string.
9
 *
10
 * @param object $is_modifieable
11
 *   cdm instance of an class implementing the interface IModifieable:
12
 *   DescriptionElementBase, StateDate, State
13
 *
14
 * @return String
15
 *   localized representations of the modifiers hold by the
16
 *   supplied cdm instance concatenated into one string
17
 */
18
function cdm_modifiers_representations($is_modifieable, $glue = ', ') {
19
  $modifiers_strings = array();
20
  if (isset($is_modifieable->modifiers)) {
21
    foreach ($is_modifieable->modifiers as $modifier) {
22
      $modifiers_strings[] = cdm_term_representation($modifier);
23
    }
24
  }
25
  return implode(', ', $modifiers_strings);
26
}
27

    
28
/**
29
 * Filters the given set of description elements and prefers computed elements over others.
30
 *
31
 * Computed description elements
32
 * are identified by the MarkerType.COMPUTED()
33
 *
34
 * If the given set contains at least one computed element only
35
 * the computed elements are returned.
36
 *
37
 * @param array $description_elements
38
 *   An array of CDM DescriptionElementBase instances
39
 *
40
 * @return array
41
 *   only the computed description elements otherwise all others.
42
 *
43
 * @deprecated this is replaced by the cdmlib DistributionUtil class!!!
44
 */
45
function cdm_description_elements_prefer_computed($description_elements){
46

    
47
  $computed_elements = array();
48
  $other_elements = array();
49

    
50
  if (!empty($description_elements)) {
51
    foreach ($description_elements as $element) {
52
      if (cdm_entity_has_marker($element, UUID_MARKERTYPE_COMPUTED)) {
53
        $computed_elements[] = $element;
54
      }
55
      else {
56
        $other_elements[] = $element;
57
      }
58
    }
59
  }
60

    
61
  if (count($computed_elements) > 0) {
62
    return $computed_elements;
63
  }
64
  else {
65
    return $other_elements;
66
  }
67
}
68

    
69
/**
70
 * Creates a query parameter array based on the setting stored in the drupal variable CDM_DISTRIBUTION_FILTER.
71
 *
72
 * @return array
73
 *   An array with distribution filter query parameters
74
 */
75
function cdm_distribution_filter_query() {
76
  $cdm_distribution_filter = get_array_variable_merged(CDM_DISTRIBUTION_FILTER, CDM_DISTRIBUTION_FILTER_DEFAULT);
77
  $query = array();
78

    
79
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
80
  if($feature_block_settings['sort_elements'] == SORT_HIERARCHICAL){
81
    $query['distributionOrder'] = 'AREA_ORDER';
82
  }
83

    
84
  $query['recipe'] = variable_get(DISTRIBUTION_CONDENSED_RECIPE, DISTRIBUTION_CONDENSED_RECIPE_DEFAULT);
85

    
86

    
87

    
88
  if ($cdm_distribution_filter['filter_rules']['statusOrderPreference']) {
89
    $query['statusOrderPreference'] = 1;
90
  }
91
  if ($cdm_distribution_filter['filter_rules']['subAreaPreference']) {
92
    $query['subAreaPreference'] = 1;
93
  }
94
  if (is_array($cdm_distribution_filter['hiddenAreaMarkerType']) && count($cdm_distribution_filter['hiddenAreaMarkerType']) > 0) {
95
    $query['hiddenAreaMarkerType'] = '';
96
    foreach ($cdm_distribution_filter['hiddenAreaMarkerType'] as $marker_type => $enabled) {
97
      if ($enabled) {
98
        $query['hiddenAreaMarkerType'] .= ($query['hiddenAreaMarkerType'] ? ',' : '') . $marker_type;
99
      }
100
    }
101
  }
102

    
103
  return $query;
104
}
105

    
106
/**
107
 * Merge the fields 'annotations', 'markers', 'sources', 'media' from the source CDM DescriptionElement into  the target.
108
 *
109
 * @param object $target
110
 *   The source CDM DescriptionElement
111
 * @param object $source
112
 *   The target CDM DescriptionElement
113
 */
114
function cdm_merge_description_elements($target, $source) {
115
  static $fields_to_merge = array('annotations', 'markers', 'sources', 'media');
116

    
117
  foreach ($fields_to_merge as $field) {
118
    if (is_array($source->$field)) {
119
      if (!is_array($target->$field)) {
120
        $target->$field = $source->$field;
121
      }
122
      else {
123
        $target->$field = array_merge($target->$field, $source->$field);
124
      }
125
    }
126
  }
127
}
128

    
129
/**
130
 * Adds an entry to the end of the table of content items list
131
 *
132
 * The  table of content items are crated internally by calling
133
 * toc_list_item() the resulting item is added to the statically cached
134
 * list of toc elements
135
 *
136
 * @param string $label
137
 *   The label of toc entry
138
 * @param $class_attribute_suffix
139
 *   The suffix to be appended to the class attribute prefix:
140
 *   "feature-toc-item-"
141
 * @param string $fragment
142
 *   Optional parameter to define a url fragment different from the $label,
143
 *   if the $fragment is not defined the $label will be used
144
 * @param boolean $as_first_element
145
 *   Place the new item as fist one. This parameter is ignored when $weight is
146
 *   being set
147
 * @param integer $weight
148
 *   Defines the weight for the ordering the item in the toc list.
149
 *   The item will be placed at the end if weigth is NULL.
150
 *
151
 * @throws \Exception re-throws exception from theme()
152
 */
153
function cdm_toc_list_add_item($label, $class_attribute_suffix, $fragment = NULL, $as_first_element = FALSE, $weight = null) {
154

    
155
  $toc_list_items = &cdm_toc_list();
156

    
157
  if (!$fragment) {
158
    $fragment = $label;
159
  }
160
  $fragment = generalizeString($fragment);
161

    
162
  $class_attributes = 'feature-toc-item-' . $class_attribute_suffix;
163

    
164
  $new_item = toc_list_item(
165
    theme(
166
      'cdm_feature_name',
167
      array('feature_name' => $label)),
168
      array('class' => $class_attributes),
169
      $fragment
170
    );
171

    
172
  if ($weight === null && $as_first_element) {
173
    reset($toc_list_items);
174
    $weight = key($toc_list_items); // returns null for empty arrays
175
    $weight = $weight !== null ? $weight - FEATURE_BLOCK_WEIGHT_INCREMENT : 0;
176
  }
177
  else if($weight === null) {
178
      end($toc_list_items);
179
      $weight = key($toc_list_items); // returns null for empty arrays
180
      $weight = $weight !== null ? $weight + FEATURE_BLOCK_WEIGHT_INCREMENT : 0;
181
  }
182
  $toc_list_items[$weight] = $new_item;
183
  ksort($toc_list_items); // sort so that the last element has always the highest weight
184

    
185
}
186

    
187
/**
188
 * Returns the statically cached table of content items as render array.
189
 *
190
 * @see cdm_toc_list_add_item()
191
 *
192
 * @return array
193
 *   a render array of table of content items suitable for theme_item_list()
194
 */
195
function &cdm_toc_list(){
196

    
197
  $toc_list_items = &drupal_static('toc_list_items', array());
198

    
199
  return $toc_list_items;
200
}
201

    
202
/**
203
 * Prepares an empty Drupal block for displaying description elements of a
204
 * specific CDM Feature.
205
 *
206
 * The block can also be used for pseudo Features like a bibliography. Pseudo
207
 * features are derived from other data on the fly and so not exist as such in
208
 * the cdm data. For pseudo features the $feature can be created using
209
 * make_pseudo_feature().
210
 *
211
 * @param $feature_name
212
 *   A label describing the feature, usually the localized feature
213
 *   representation.
214
 * @param object $feature
215
 *   The CDM Feature for which the block is created.
216
 *
217
 * @return object
218
 *   A Drupal block object
219
 *
220
 * @throws \Exception re-throws exception from theme()
221
 */
222
function feature_block($feature_name, $feature) {
223
  $block = new stdclass();
224
  $block->module = 'cdm_dataportal';
225
  $block->region = NULL;
226
  $class_attribute = html_class_attribute_ref($feature);
227
  $block_delta = $feature->class !== 'PseudoFeature' ? $feature_name : $feature->label;
228
  $block->delta = generalizeString($block_delta);
229
  $block->subject = '<a name="' . $block->delta . '"></a><span class="' . $class_attribute . '">'
230
    . theme('cdm_feature_name', array('feature_name' => $feature_name))
231
    . '</span>';
232
  $block->module = "cdm_dataportal-feature";
233
  $block->content = '';
234
  return $block;
235
}
236

    
237

    
238
/**
239
 * Returns a list of a specific type of IdentificationKeys.
240
 *
241
 * The list can be restricted by a taxon.
242
 *
243
 * @param string $type
244
 *   The simple name of the cdm class implementing the interface
245
 *   IdentificationKey, valid values are:
246
 *   PolytomousKey, MediaKey, MultiAccessKey.
247
 * @param string $taxonUuid
248
 *   If given this parameter restrict the listed keys to those which have
249
 *   the taxon identified be this uuid in scope.
250
 *
251
 * @return array
252
 *   List with identification keys.
253
 */
254
function _list_IdentificationKeys($type, $taxonUuid = NULL, $pageSize = NULL, $pageNumber = NULL) {
255
  if (!$type) {
256
    drupal_set_message(t('Type parameter is missing'), 'error');
257
    return;
258
  }
259
  $cdm_ws_base_path = NULL;
260
  switch ($type) {
261
    case "PolytomousKey":
262
      $cdm_ws_base_path = CDM_WS_POLYTOMOUSKEY;
263
      break;
264

    
265
    case "MediaKey":
266
      $cdm_ws_base_path = CDM_WS_MEDIAKEY;
267
      break;
268

    
269
    case "MultiAccessKey":
270
      $cdm_ws_base_path = CDM_WS_MULTIACCESSKEY;
271
      break;
272

    
273
  }
274

    
275
  if (!$cdm_ws_base_path) {
276
    drupal_set_message(t('Type parameter is not valid: ') . $type, 'error');
277
  }
278

    
279
  $queryParameters = '';
280
  if (is_numeric($pageSize)) {
281
    $queryParameters = "pageSize=" . $pageSize;
282
  }
283
  else {
284
    $queryParameters = "pageSize=0";
285
  }
286

    
287
  if (is_numeric($pageNumber)) {
288
    $queryParameters = "pageNumber=" . $pageNumber;
289
  }
290
  else {
291
    $queryParameters = "pageNumber=0";
292
  }
293
  $queryParameters = NULL;
294
  if ($taxonUuid) {
295
    $queryParameters = "findByTaxonomicScope=$taxonUuid";
296
  }
297
  $pager = cdm_ws_get($cdm_ws_base_path, NULL, $queryParameters);
298

    
299
  if (!$pager || $pager->count == 0) {
300
    return array();
301
  }
302
  return $pager->records;
303
}
304

    
305

    
306
/**
307
 * Creates a list item for a table of content, suitable as data element for a themed list
308
 *
309
 * @see theme_list()
310
 *
311
 * @param $label
312
 * @param $http_request_params
313
 * @param $attributes
314
 * @return array
315
 */
316
function toc_list_item($label, $attributes = array(), $fragment = null) {
317

    
318
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
319
  $http_request_params = drupal_static('http_request_params', drupal_get_query_parameters());
320

    
321
  $item =  array(
322
    'data' => l(
323
      $label,
324
      $_GET['q'],
325
      array(
326
        'attributes' => array('class' => array('toc')),
327
        'fragment' => generalizeString($label),
328
        'query' => $http_request_params,
329
      )
330
    ),
331
  );
332
  $item['attributes'] = $attributes;
333
  return $item;
334
}
335

    
336
/**
337
 * Creates the footnotes for the given CDM instance.
338
 *
339
 * Footnotes are created for annotations and original sources whereas the resulting footnote keys depend on the
340
 * parameters $footnote_list_key_suggestion and $is_bibliography_aware, see parameter $footnote_list_key_suggestion
341
 * for more details.
342
 *
343
 * possible keys for
344
 *     - annotation footnotes:
345
 *       - $footnote_list_key_suggestion
346
 *       - RenderHints::getFootnoteListKey().'-annotations'
347
 *     - original source footnotes
348
 *       - "BIBLIOGRAPHY" (when !$is_bibliography_aware && bibliography_settings['enabled'] == 1 )
349
 *       - "BIBLIOGRAPHY-$footnote_list_key_suggestion" (when !$is_bibliography_aware && bibliography_settings['enabled'] == 0 )
350
 *       - $footnote_list_key_suggestion (when $is_bibliography_aware)
351
 *
352
 * @param $description_element
353
 *   A CDM DescriptionElement instance
354
 * @param string $separator
355
 *   Optional parameter. The separator string to concatenate the footnote ids, default is ','
356
 * @param $footnote_list_key_suggestion string
357
 *    Optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be determined by the nested
358
 *    method calls by calling RenderHints::getFootnoteListKey(). NOTE: the footnote key for annotations will be set to
359
 *    RenderHints::getFootnoteListKey().'-annotations'.
360
 * @param bool $do_link_to_reference
361
 *    Create a link to the reference pages for sources when TRUE.
362
 * @param bool $do_link_to_name_used_in_source
363
 *    Create a link to the name pages for name in source when TRUE.
364
 * @param bool $is_bibliography_aware
365
 *    Put source references into the bibliography when this param is TRUE.
366
 *
367
 * @return String
368
 *   The foot note keys
369
 *
370
 * @throws \Exception re-throw exception from theme()
371
 * @see cdm_entities_annotations_footnotekeys()
372
 *    For original sources the $footnote_list_key_suggestion will be overwritten by bibliography_footnote_list_key() when
373
 *    $is_bibliography_aware is set TRUE.
374
 * @$original_source_footnote_tag
375
 *    null will cause bibliography_footnote_list_key to use the default
376
 */
377
function cdm_create_footnotes(
378
    $description_element,
379
    $separator = ',',
380
    $footnote_list_key_suggestion = null,
381
    $do_link_to_reference = FALSE,
382
    $do_link_to_name_used_in_source = FALSE,
383
    $is_bibliography_aware = FALSE
384
  ){
385

    
386
  $sources = cdm_entity_sources_sorted($description_element);
387

    
388
  // Annotations as footnotes.
389
  $footnote_keys = cdm_entity_annotations_as_footnotekeys($description_element, $footnote_list_key_suggestion);
390

    
391
  // Source references as footnotes.
392
  if($is_bibliography_aware){
393
    $bibliography_settings = get_bibliography_settings();
394
    $sources_footnote_list_key = bibliography_footnote_list_key($footnote_list_key_suggestion);
395
    $original_source_footnote_tag = $bibliography_settings['enabled'] == 1 ? 'div' : null; // null will cause bibliography_footnote_list_key to use the default
396
  } else {
397
    $sources_footnote_list_key = $footnote_list_key_suggestion;
398
    if(!$sources_footnote_list_key) {
399
      RenderHints::getFootnoteListKey();
400
    }
401
    $original_source_footnote_tag = NULL;
402
  }
403

    
404
  foreach ($sources as $source) {
405
    if (_is_original_source_type($source)) {
406
      $fn_key = FootnoteManager::addNewFootnote(
407
        $sources_footnote_list_key,
408
        render_original_source(
409
          $source,
410
          $do_link_to_reference,
411
          $do_link_to_name_used_in_source
412
        ),
413
        $original_source_footnote_tag
414
      );
415
      // Ensure uniqueness of the footnote keys.
416
      cdm_add_footnote_to_array($footnote_keys, $fn_key);
417
    }
418
  }
419
  // Sort and render footnote keys.
420
  asort($footnote_keys);
421
  return footnote_keys_to_markup($footnote_keys, $separator);
422
}
423

    
424
/**
425
 * Creates markup for an array of foot note keys
426
 *
427
 * @param array $footnote_keys
428
 * @param string $separator
429
 *
430
 * @return string
431
 */
432
function footnote_keys_to_markup(array $footnote_keys, $separator) {
433

    
434
  $footnotes_markup = '';
435
  foreach ($footnote_keys as $foot_note_key) {
436
    try {
437
      $footnotes_markup .= cdm_footnote_key($foot_note_key, ($footnotes_markup ? $separator : ''));
438
    } catch (Exception $e) {
439
      drupal_set_message("Exception: " . $e->getMessage(), 'error');
440
    }
441
  }
442
  return $footnotes_markup;
443
}
444

    
445

    
446
/**
447
 * Compare callback to be used in usort() to sort render arrays produced by
448
 * compose_description_element().
449
 *
450
 * @param $a
451
 * @param $b
452
 *
453
 * @return int Returns < 0 if $a['#value'].$a['#value-suffix'] from is less than
454
 * $b['#value'].$b['#value-suffix'], > 0 if it is greater than $b['#value'].$b['#value-suffix'],
455
 * and 0 if they are equal.
456
 */
457
function compare_description_element_render_arrays($a, $b){
458
  if ($a['#value'].$a['#value-suffix'] == $b['#value'].$b['#value-suffix']) {
459
    return 0;
460
  }
461
  return ($a['#value'].$a['#value-suffix'] < $b['#value'].$b['#value-suffix']) ? -1 : 1;
462

    
463
}
464

    
465

    
466
/**
467
 * @param $element
468
 * @param $feature_block_settings
469
 * @param $element_markup
470
 * @param $footnote_list_key_suggestion
471
 * @param bool $prepend_feature_label
472
 *
473
 * @return array|null
474
 */
475
function compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label = FALSE)
476
{
477

    
478
  $render_array = array(
479
    '#type' => 'html_tag',
480
    '#tag' => cdm_feature_block_element_tag_name($feature_block_settings),
481

    
482
    '#attributes' => array(
483
      'class' => array(
484
        'DescriptionElement',
485
        'DescriptionElement-' . $element->class,
486
        html_class_attribute_ref($element)
487
      )
488
    ),
489

    
490
    '#value' => '',
491
    '#value_suffix' => NULL
492

    
493
  );
494

    
495
  $annotations_and_sources = handle_annotations_and_sources(
496
    $element,
497
    handle_annotations_and_sources_config($feature_block_settings),
498
    $element_markup,
499
    $footnote_list_key_suggestion
500
  );
501

    
502
  $timescope_markup = '';
503
  if(isset($element->timeperiod)){
504
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, true);
505
  }
506

    
507
  // handle the special case were the TextData is used as container for original source with name
508
  // used in source information without any text stored in it.
509
  $names_used_in_source_markup = '';
510
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
511
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
512
    // remove all <span class="nameUsedInSource">...</span> from all source_references
513
    // these are expected to be at the end of the strings
514
    $pattern = '/ <span class="nameUsedInSource">.*$/';
515
    foreach( $annotations_and_sources['source_references'] as &$source_reference){
516
      $source_reference = preg_replace($pattern , '', $source_reference);
517
    }
518
  }
519

    
520
  $source_references_markup = '';
521
  if (!empty($annotations_and_sources['source_references'])) {
522
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
523
  }
524

    
525
  $feature_label = '';
526
  if ($prepend_feature_label) {
527
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
528
  }
529
  $content_markup = $names_used_in_source_markup . $element_markup . $timescope_markup . $source_references_markup;
530

    
531
  if(!$content_markup && $feature_block_settings['sources_as_content'] !== 1){
532
    // no textual content? So skip this element completely, even if there could be an footnote key
533
    // see #4379
534
    return null;
535
  }
536

    
537
    $render_array['#value'] = $feature_label . $content_markup;
538
    $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
539
  return $render_array;
540
}
541

    
542
/**
543
 * Creates a handle_annotations_and_sources configuration array from feature_block_settings.
544
 *
545
 * The handle_annotations_and_sources configuration array is meant to be used for the
546
 * method handle_annotations_and_sources().
547
 *
548
 * @param $feature_block_settings array
549
 *
550
 * @return array
551
 *   The configuration array for handle_annotations_and_sources()
552
 */
553
function handle_annotations_and_sources_config($feature_block_settings){
554

    
555
  $config = $feature_block_settings;
556
  unset($config['sources_as_content_to_bibliography']);
557
  $config['add_footnote_keys'] = 0;
558
  if($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
559
    $config['add_footnote_keys'] = 1;
560
  }
561
  $config['bibliography_aware'] = 1;
562

    
563
  return $config;
564
}
565

    
566
/**
567
 * @param $entity
568
 * @param $config array
569
 *   An associative array to configure the display of the annotations and
570
 *   sources. The array has the following keys
571
 *   - sources_as_content
572
 *   - link_to_name_used_in_source
573
 *   - link_to_reference
574
 *   - add_footnote_keys
575
 *   - bibliography_aware
576
 *   Valid values are 1 or 0.
577
 * @param $inline_text_prefix
578
 *   Only used to decide if the source references should be enclosed in
579
 *   brackets or not when displayed inline. This text will not be included into
580
 *   the response.
581
 * @param $footnote_list_key_suggestion string
582
 *    optional parameter. If this paramter is left empty (null, 0, "") the
583
 *   footnote key will be determined by the nested method calls by calling
584
 *   RenderHints::getFootnoteListKey(). NOTE: the footnore key for annotations
585
 *   will be set to RenderHints::getFootnoteListKey().'-annotations'. @return
586
 *   array an associative array with the following elements:
587
 *   - foot_note_keys: all footnote keys as markup
588
 *   - source_references: an array of the source references citations
589
 *   - names used in source: an associative array of the names in source,
590
 *        the name in source strings are de-duplicated
591
 *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
592
 *
593
 * @throws \Exception
594
 *
595
 * @see cdm_entities_annotations_footnotekeys()
596
 */
597
  function handle_annotations_and_sources($entity, $config, $inline_text_prefix, $footnote_list_key_suggestion) {
598

    
599
    $annotations_and_sources = array(
600
      'foot_note_keys' => NULL,
601
      'source_references' => [],
602
      'names_used_in_source' => []
603
    );
604

    
605
    // some entity types only have single sources:
606
    $sources = cdm_entity_sources_sorted($entity);
607

    
608
    if ($config['sources_as_content'] == 1) {
609
      foreach ($sources as $source) {
610
        if (_is_original_source_type($source)) {
611
          $reference_citation = render_original_source(
612
            $source,
613
            $config['link_to_reference'] == 1,
614
            $config['link_to_name_used_in_source'] == 1
615
          );
616

    
617
          if ($reference_citation) {
618
            if (empty($inline_text_prefix)) {
619
              $annotations_and_sources['source_references'][] = $reference_citation;
620
            } else {
621
              $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
622
            }
623
          }
624

    
625
          // also put the name in source into the array, these are already included in the $reference_citation but are
626
          // still required to be available separately in some contexts.
627
          $name_in_source_render_array = compose_name_in_source(
628
            $source,
629
            $config['link_to_name_used_in_source'] == 1
630
          );
631

    
632
          if (!empty($name_in_source_render_array)) {
633
            $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
634
          }
635
        }
636
      } // END of loop over sources
637

    
638
      // annotations footnotes separate from sources
639
      $annotations_and_sources['foot_note_keys'] = footnote_keys_to_markup(
640
        cdm_entity_annotations_as_footnotekeys($entity, $footnote_list_key_suggestion), ', '
641
      );
642

    
643
    } // END of references inline
644

    
645
    // footnotes for sources and annotations or put into into bibliography if requested ...
646
    if ($config['add_footnote_keys'] == 1) {
647
        $annotations_and_sources['foot_note_keys'] = cdm_create_footnotes(
648
          $entity, ',',
649
          $footnote_list_key_suggestion,
650
          $config['link_to_reference'] == 1,
651
          $config['link_to_name_used_in_source'] == 1,
652
          !empty($config['bibliography_aware'])
653
        );
654
    }
655

    
656
    return $annotations_and_sources;
657
  }
658

    
659
/**
660
 * Get the source or the sources from a cdm entity and return them ordered by see compare_original_sources()
661
 * (Some entity types only have single sources)
662
 * @param $entity
663
 *
664
 * @return array
665
 */
666
function cdm_entity_sources_sorted($entity) {
667
  if (isset($entity->source) && is_object($entity->source)) {
668
    $sources = [$entity->source];
669
  }
670
  else if (isset($entity->sources)) {
671
    $sources = $entity->sources;
672
  }
673
  else {
674
    $sources = [];
675
  }
676
  usort($sources, 'compare_original_sources');
677
  return $sources;
678
}
679

    
680

    
681
/**
682
   * This method determines the footnote key for original sources to be shown in the bibliography block
683
   *
684
   * The footnote key depends on the value of the 'enabled' value of the bibliography_settings
685
   *    - enabled == 1 -> "BIBLIOGRAPHY"
686
   *    - enabled == 0 -> "BIBLIOGRAPHY-$key_suggestion"
687
   *
688
   * @see get_bibliography_settings() and @see constant BIBLIOGRAPHY_FOOTNOTE_KEY
689
   *
690
   * @param $key_suggestion string
691
   *    optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be retrieved by
692
   *    calling RenderHints::getFootnoteListKey().
693

    
694
   *
695
   * @return string
696
   *  the footnote_list_key
697
   */
698
  function bibliography_footnote_list_key($key_suggestion = null) {
699
    if(!$key_suggestion){
700
      $key_suggestion = RenderHints::getFootnoteListKey();
701
    }
702
    $bibliography_settings = get_bibliography_settings();
703
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? BIBLIOGRAPHY_FOOTNOTE_KEY : BIBLIOGRAPHY_FOOTNOTE_KEY . '-' . $key_suggestion;
704
    return $footnote_list_key;
705
  }
706

    
707
/**
708
 * Provides the according tag name for the description element markup which
709
 * fits the  $feature_block_settings['as_list'] value
710
 *
711
 * @param $feature_block_settings
712
 *   A feature_block_settings array, for details, please see
713
 *   get_feature_block_settings($feature_uuid = 'DEFAULT')
714
 *
715
 * @return mixed|string
716
 */
717
  function cdm_feature_block_element_tag_name($feature_block_settings){
718
    switch ($feature_block_settings['as_list']){
719
      case 'ul':
720
      case 'ol':
721
        return 'li';
722
      case 'div':
723
        if(isset($feature_block_settings['element_tag'])){
724
          return $feature_block_settings['element_tag'];
725
        }
726
        return 'span';
727
      case 'dl':
728
        return 'dd';
729
      default:
730
        return 'div'; // should never happen, throw error instead?
731
    }
732
  }
733

    
734

    
735
/* ==================== COMPOSE FUNCTIONS =============== */
736

    
737
  /**
738
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
739
   *
740
   * The taxon profile consists of drupal block elements, one for the description elements
741
   * of a specific feature. The structure is defined by specific FeatureTree.
742
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
743
   *
744
   * The merged nodes can be obtained by making use of the
745
   * function cdm_ws_descriptions_by_featuretree().
746
   *
747
   * @see cdm_ws_descriptions_by_featuretree()
748
   *
749
   * @param $mergedFeatureNodes
750
   *
751
   * @param $taxon
752
   *
753
   * @return array
754
   *  A Drupal render array containing feature blocks and the table of content
755
   *
756
   * @ingroup compose
757
   */
758
  function make_feature_block_list($mergedFeatureNodes, $taxon) {
759

    
760
    $block_list = array();
761

    
762
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
763

    
764
    $use_description_features = array(UUID_USE);
765

    
766

    
767
    RenderHints::pushToRenderStack('feature_block');
768
    // Create a drupal block for each feature
769
    $block_weight = - FEATURE_BLOCK_WEIGHT_INCREMENT;
770
    foreach ($mergedFeatureNodes as $feature_node) {
771

    
772
      $block_weight = $block_weight + FEATURE_BLOCK_WEIGHT_INCREMENT;
773

    
774
      if ((isset($feature_node->descriptionElements['#type']) ||
775
          has_feature_node_description_elements($feature_node)) && $feature_node->term->uuid != UUID_IMAGE) { // skip empty or suppressed features
776

    
777
        RenderHints::pushToRenderStack($feature_node->term->uuid);
778
          
779
        $feature_name = cdm_term_representation($feature_node->term, 'Unnamed Feature');
780
        $feature_block_settings = get_feature_block_settings($feature_node->term->uuid);
781
        
782

    
783
        $block = feature_block($feature_name, $feature_node->term);
784
        $block->content = array();
785
        $block_content_is_empty = TRUE;
786

    
787
        if(array_search($feature_node->term->uuid, $use_description_features) !== false) {
788
          // do not show features which belong to the UseDescriptions, these are
789
          // handled by compose_feature_block_items_use_records() where the according descriptions are
790
          // fetched again separately.
791
          // UseDescriptions are a special feature introduced for palmweb
792
          continue;
793
        }
794

    
795
        /*
796
         * Content/DISTRIBUTION.
797
         */
798
        if ($feature_node->term->uuid == UUID_DISTRIBUTION) {
799
          $block = compose_feature_block_distribution($taxon, $feature_node->descriptionElements, $feature_node->term);
800
          $block_content_is_empty = FALSE;
801
        }
802

    
803
        /*
804
         * Content/COMMON_NAME.
805
         */
806
        else if ($feature_node->term->uuid == UUID_COMMON_NAME) {
807
          $common_names_render_array = compose_feature_block_items_feature_common_name($feature_node->descriptionElements, $feature_node->term);
808
          $block->content[] = $common_names_render_array;
809
          $block_content_is_empty = FALSE;
810
        }
811

    
812
        /*
813
         * Content/Use Description (Use + UseRecord)
814
         */
815
        else if ($feature_node->term->uuid == UUID_USE_RECORD) {
816
          $block->content[] = cdm_block_use_description_content($taxon->uuid, $feature_node->term);
817
          $block_content_is_empty = FALSE;
818
        }
819

    
820
        /*
821
         * Content/ALL OTHER FEATURES.
822
         */
823
        else {
824

    
825
          $media_list = array();
826
          $elements_render_array = array();
827
          $child_elements_render_array = null;
828

    
829
          if (isset($feature_node->descriptionElements[0])) {
830
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements, $feature_node->term);
831
          }
832

    
833
          // Content/ALL OTHER FEATURES/Subordinate Features
834
          // subordinate features are printed inline in one floating text,
835
          // it is expected hat subordinate features can "contain" TextData,
836
          // Qualitative- and Qualitative- DescriptionElements
837
          if (isset($feature_node->childNodes[0])) {
838
            $child_elements_render_array = compose_feature_block_items_nested($feature_node, $media_list, $feature_block_settings);
839
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
840
          }
841
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
842
          if(!$block_content_is_empty){
843
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $feature_node->term, $feature_block_settings['glue']);
844
            $block->content[] = compose_feature_media_gallery($feature_node, $media_list, $gallery_settings);
845
            /*
846
             * Footnotes for the feature block
847
             */
848
            $block->content[] = markup_to_render_array(cdm_footnotes(PSEUDO_FEATURE_BIBLIOGRAPHY . '-' . $feature_node->term->uuid));
849
            $block->content[] = markup_to_render_array(cdm_footnotes($feature_node->term->uuid));
850
            $block->content[] = markup_to_render_array(cdm_annotation_footnotes($feature_node->term->uuid));
851
          }
852
        } // END all other features
853

    
854
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
855
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
856

    
857
        if(!$block_content_is_empty){ // skip empty block content
858
          $block_list[$block_weight] = $block;
859
          cdm_toc_list_add_item(cdm_term_representation($feature_node->term), $feature_node->term->uuid, null, FALSE, $block_weight);
860
        } // END: skip empty block content
861
      } // END: skip empty or suppressed features
862
      RenderHints::popFromRenderStack();
863
    } // END: creating a block per feature
864

    
865
    RenderHints::popFromRenderStack();
866

    
867
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
868

    
869
    ksort($block_list);
870

    
871
    return  $block_list;
872
  }
873

    
874
/**
875
 * Creates a render array of description elements  held by child nodes of the given feature node.
876
 *
877
 * This function is called recursively!
878
 *
879
 * @param $feature_node
880
 *   The feature node.
881
 * @param array $media_list
882
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
883
 * @param $feature_block_settings
884
 *   The feature block settings.
885
 * @param $main_feature
886
 *  Only used internally in recursive calls.
887
 *
888
 * @return array
889
 *  A Drupal render array
890
 *
891
 * @ingroup compose
892
 */
893
function compose_feature_block_items_nested($feature_node, &$media_list, $feature_block_settings, $main_feature = NULL)
894
{
895

    
896
  if(!$main_feature){
897
    $main_feature = $feature_node->term;
898
  }
899
  /*
900
   * TODO should be configurable, options; YES, NO, AUTOMATIC
901
   * (automatic will only place the label if the first word of the description element text is not the same)
902
   */
903
  $prepend_feature_label = false;
904

    
905
  $render_arrays = array();
906
  foreach ($feature_node->childNodes as $child_node) {
907
    if (isset($child_node->descriptionElements[0])) {
908
      foreach ($child_node->descriptionElements as $element) {
909

    
910
        if (isset($element->media[0])) {
911
          // Append media of subordinate elements to list of main
912
          // feature.
913
          $media_list = array_merge($media_list, $element->media);
914
        }
915

    
916
        $child_node_element = null;
917
        switch ($element->class) {
918
          case 'TextData':
919
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
920
            break;
921
          case 'CategoricalData':
922
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
923
            break;
924
          case 'QuantitativeData':
925
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
926

    
927
        }
928
        if (is_array($child_node_element)) {
929
          $render_arrays[] = $child_node_element;
930
        }
931
      }
932
    }
933

    
934
    if(isset($child_node->childNodes[0])){
935
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
936
    }
937
  }
938

    
939
  return $render_arrays;
940
}
941

    
942
  /**
943
   *
944
   * @param $feature_node
945
   *  The merged feature three node which potentially contains media in its description elements.
946
   * @param $media_list
947
   *    Additional media to be merged witht the media contained in the nodes description elements
948
   * @param $gallery_settings
949
   * @return array
950
   *
951
   * @ingroup compose
952
   */
953
  function compose_feature_media_gallery($feature_node, $media_list, $gallery_settings) {
954

    
955
    if (isset($feature_node->descriptionElements)) {
956
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
957
    }
958

    
959
    $captionElements = array('title', 'rights');
960

    
961
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
962
      $gallery = compose_cdm_media_gallerie(array(
963
        'mediaList' => $media_list,
964
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $feature_node->term->uuid,
965
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
966
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
967
        'captionElements' => $captionElements,
968
      ));
969
      return markup_to_render_array($gallery);
970
    }
971

    
972
    return markup_to_render_array('');
973
  }
974

    
975
  /**
976
   * Composes the distribution feature block for a taxon
977
   *
978
   * @param $taxon
979
   * @param $descriptionElements
980
   *   an associative array with two elements:
981
   *   - '#type': must be 'DTO'
982
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
983
   * @param $feature
984
   *
985
   * @return array
986
   *  A drupal render array
987
   *
988
   * @ingroup compose
989
   */
990
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
991
    $text_data_glue = '';
992
    $text_data_sortOutArray = FALSE;
993
    $text_data_enclosingTag = 'ul';
994
    $text_data_out_array = array();
995

    
996
    $distributionElements = NULL;
997
    $distribution_info_dto = NULL;
998
    $distribution_sortOutArray = FALSE;
999

    
1000
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1001

    
1002
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
1003
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
1004
      $distribution_glue = '';
1005
      $distribution_enclosingTag = 'dl';
1006
    } else {
1007
      $distribution_glue = '';
1008
      $distribution_enclosingTag = 'ul';
1009
    }
1010

    
1011
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
1012
      // skip the DISTRIBUTION section if there is no DTO type element
1013
      return array(); // FIXME is it ok to return an empty array?
1014
    }
1015

    
1016
    $block = feature_block(
1017
      cdm_term_representation($feature, 'Unnamed Feature'),
1018
      $feature
1019
    );
1020
    $block->content = array();
1021

    
1022
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
1023
    if (isset($descriptionElements['TextData'])) {
1024
      // --- TextData
1025
      foreach ($descriptionElements['TextData'] as $text_data_element) {
1026
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1027
        $repr = drupal_render($text_data_render_array);
1028

    
1029
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
1030
          $text_data_out_array[] = $repr;
1031
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
1032
          // not work since this array contains html attributes with uuids
1033
          // and what is about cases like the bibliography where
1034
          // any content can be prefixed with some foot-note anchors?
1035
          $text_data_sortOutArray = TRUE;
1036
          $text_data_glue = '<br/> ';
1037
          $text_data_enclosingTag = 'p';
1038
        }
1039
      }
1040
    }
1041

    
1042

    
1043
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1044
      $block->content[] = compose_feature_block_wrap_elements(
1045
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1046
      );
1047
    }
1048

    
1049
    // --- Distribution map
1050
    $distribution_map_query_parameters = NULL;
1051

    
1052
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
1053
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
1054
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
1055
      )
1056
    {
1057
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
1058
    }
1059
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
1060
    $block->content[] = $map_render_element;
1061

    
1062
    $dto_out_array = array();
1063

    
1064
    // --- Condensed Distribution
1065
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
1066
      $condensed_distribution_markup = '<p class="condensed_distribution">';
1067

    
1068
      $isFirst = true;
1069
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
1070
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
1071
          if(!$isFirst){
1072
            $condensed_distribution_markup .= ' ';
1073
          }
1074
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
1075
          . $cdItem->areaStatusLabel . '</span>';
1076
          $isFirst = false;
1077
        }
1078
      }
1079

    
1080
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
1081
        if(!$isFirst){
1082
          $condensed_distribution_markup .= ' ';
1083
        }
1084
        $isFirst = TRUE;
1085
        $condensed_distribution_markup .= '[';
1086
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
1087
          if (!$isFirst) {
1088
            $condensed_distribution_markup .= ' ';
1089
          }
1090
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
1091
            . $cdItem->areaStatusLabel . '</span>';
1092
          $isFirst = false;
1093
        }
1094
        $condensed_distribution_markup .= ']';
1095
      }
1096

    
1097
      $condensed_distribution_markup .= '&nbsp;' . l(
1098
          font_awesome_icon_markup(
1099
            'fa-info-circle',
1100
            array(
1101
              'alt'=>'help',
1102
              'class' => array('superscript')
1103
            )
1104
          ),
1105
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
1106
          array('html' => TRUE));
1107
      $condensed_distribution_markup .= '</p>';
1108
      $dto_out_array[] = $condensed_distribution_markup;
1109
    }
1110

    
1111
    // --- tree or list
1112
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1113
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1114

    
1115
      // --- tree
1116
      if (is_object($distribution_info_dto->tree)) {
1117
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
1118
        $dto_out_array[] = $distribution_tree_render_array;
1119
      }
1120

    
1121
      // --- sorted element list
1122
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
1123
        foreach ($distribution_info_dto->elements as $descriptionElement) {
1124
          if (is_object($descriptionElement->area)) {
1125
            $sortKey = $descriptionElement->area->representation_L10n;
1126
            $distributionElements[$sortKey] = $descriptionElement;
1127
          }
1128
        }
1129
        ksort($distributionElements);
1130
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
1131
        $dto_out_array[] = $distribution_element_render_array;
1132

    
1133
      }
1134
      //
1135
      $block->content[] = compose_feature_block_wrap_elements(
1136
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1137
      );
1138
    }
1139

    
1140
    // --- TextData at the bottom
1141
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1142
      $block->content[] = compose_feature_block_wrap_elements(
1143
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1144
      );
1145
    }
1146

    
1147
    $block->content[] = markup_to_render_array(cdm_footnotes('BIBLIOGRAPHY-' . UUID_DISTRIBUTION));
1148
    $block->content[] = markup_to_render_array(cdm_footnotes(UUID_DISTRIBUTION));
1149
    $block->content[] = markup_to_render_array(cdm_annotation_footnotes(UUID_DISTRIBUTION));
1150

    
1151
    return $block;
1152
  }
1153

    
1154

    
1155
  /**
1156
   * Composes a drupal render array for single CDM TextData description element.
1157
   *
1158
   * @param $element
1159
   *    The CDM TextData description element.
1160
   *  @param $feature_uuid
1161
   * @param bool $prepend_feature_label
1162
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1163
   *
1164
   * @return array
1165
   *   A drupal render array with the following elements being used:
1166
   *    - #tag: either 'div', 'li', ...
1167
   *    ⁻ #attributes: class attributes
1168
   *    - #value_prefix: (optionally) contains footnote anchors
1169
   *    - #value: contains the textual content
1170
   *    - #value_suffix: (optionally) contains footnote keys
1171
   *
1172
   * @ingroup compose
1173
   */
1174
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
1175

    
1176
    $footnote_list_key_suggestion = $feature_uuid;
1177

    
1178
    $element_markup = '';
1179
    if (isset($element->multilanguageText_L10n->text)) {
1180
      // TODO replacement of \n by <br> should be configurable
1181
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
1182
    }
1183

    
1184
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1185

    
1186
    return $render_array;
1187
  }
1188

    
1189

    
1190
/**
1191
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
1192
 *
1193
 * @param $element
1194
 *  The CDM TaxonInteraction entity
1195
 *
1196
 * @return
1197
 *  A drupal render array
1198
 *
1199
 * @ingroup compose
1200
 */
1201
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
1202

    
1203
  $out = '';
1204

    
1205

    
1206
  if (isset($element->description_L10n)) {
1207
    $out .=  ' ' . $element->description_L10n;
1208
  }
1209

    
1210
  if(isset($element->taxon2)){
1211
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1212
  }
1213

    
1214
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1215

    
1216
  return $render_array;
1217
}
1218

    
1219

    
1220
/**
1221
 * Renders a single instance of the type IndividualsAssociations.
1222
 *
1223
 * @param $element
1224
 *   The CDM IndividualsAssociations entity.
1225
 * @param $feature_block_settings
1226
 *
1227
 * @return array
1228
 *   Drupal render array
1229
 *
1230
 * @ingroup compose
1231
 */
1232
function compose_description_element_individuals_association($element, $feature_block_settings) {
1233

    
1234
  $out = '';
1235

    
1236
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1237

    
1238
  if (isset($element->description_L10n)) {
1239
    $out .=  ' ' . $element->description_L10n;
1240
  }
1241

    
1242
  $out .= drupal_render($render_array);
1243

    
1244
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1245

    
1246
  return $render_array;
1247
}
1248

    
1249
/**
1250
 * Renders a single instance of the type CategoricalData.
1251
 *
1252
 * @param $element
1253
 *  The CDM CategoricalData entity
1254
 *
1255
 * @param $feature_block_settings
1256
 *
1257
 * @param bool $prepend_feature_label
1258
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1259
 *
1260
 * @return array
1261
 *   a drupal render array for given CategoricalData element
1262
 *
1263
 * @ingroup compose
1264
 */
1265
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1266

    
1267
  $state_data_markup = render_state_data($element);
1268

    
1269
  $render_array = compose_description_element($element, $feature_block_settings, $state_data_markup, $element->feature->uuid, $prepend_feature_label);
1270

    
1271
  return $render_array;
1272
}
1273

    
1274
/**
1275
 * @param $element
1276
 *
1277
 * @return string
1278
 * the markup
1279
 */
1280
function render_state_data($element) {
1281

    
1282
  $state_data_items = [];
1283

    
1284
  $out = '';
1285

    
1286
  if (isset($element->stateData)) {
1287
    foreach ($element->stateData as $state_data) {
1288

    
1289
      $state = NULL;
1290

    
1291
      if (isset($state_data->state)) {
1292
        $state = cdm_term_representation($state_data->state);
1293

    
1294
          $sample_count = 0;
1295
          if (isset($state_data->count)) {
1296
            $sample_count = $state_data->count;
1297
            $state .= ' [' . $state_data->count . ']';
1298
          }
1299
    
1300
          if (isset($state_data->modifyingText_L10n)) {
1301
            $state .= ' ' . $state_data->modifyingText_L10n;
1302
          }
1303
    
1304
          $modifiers_strings = cdm_modifiers_representations($state_data);
1305
          $state_data_markup = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1306
          // we could use strip_tags() to reduce the markup to text for the key but this is expensive
1307
          $sort_key = str_pad($sample_count, 6, '0', STR_PAD_LEFT) . '_' . $state_data_markup;
1308
          $state_data_items[$sort_key] = $state_data_markup;
1309
      }
1310

    
1311
    }
1312
    krsort($state_data_items);
1313
    $out = '<span class="' . html_class_attribute_ref($element) . '">' . join(', ', $state_data_items) .  '</span>';
1314
  }
1315
  return $out;
1316
}
1317

    
1318

    
1319
/**
1320
 * Theme function to render CDM DescriptionElements of the type QuantitativeData.
1321
 *
1322
 * The function renders the statisticalValues contained in the QuantitativeData
1323
 * entity according to the following scheme:
1324
 *
1325
 * (ExtremeMin)-Min-Average-Max-(ExtremeMax)
1326
 *
1327
 * All modifiers of these values are appended.
1328
 *
1329
 * If the QuantitativeData is containing more statisticalValues with further
1330
 * statisticalValue types, these additional measures will be appended to the
1331
 * above string separated by whitespace.
1332
 *
1333
 * Special cases;
1334
 * 1. Min==Max: this will be interpreted as Average
1335
 *
1336
 * @param $element
1337
 *  The CDM QuantitativeData entity
1338
 *
1339
 * @param $feature_block_settings
1340
 *
1341
 * @param bool $prepend_feature_label
1342
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1343
 *
1344
 *
1345
 * @return array
1346
 *   drupal render array for the given QuantitativeData element
1347
 *
1348
 * @ingroup compose
1349
 */
1350
function compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1351
  /*
1352
   * - statisticalValues
1353
   *   - value
1354
   *   - modifiers
1355
   *   - type
1356
   * - unit->representation_L10n
1357
   * - modifyingText
1358
   * - modifiers
1359
   * - sources
1360
   */
1361

    
1362
  $out = render_quantitative_statistics($element);
1363

    
1364
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid, $prepend_feature_label);
1365

    
1366
  return $render_array;
1367
}
1368

    
1369
/**
1370
 * Composes the HTML for quantitative statistics
1371
 * @param $element
1372
 *
1373
 * @return string
1374
 */
1375
function render_quantitative_statistics($element) {
1376

    
1377
  $out = '';
1378
  $type_representation = NULL;
1379
  $min_max = statistical_values_array();
1380
  $sample_size_markup = null;
1381

    
1382
  if (isset($element->statisticalValues)) {
1383
    $out = '<span class=\"' . html_class_attribute_ref($element) . '\">';
1384
    $other_values_markup = [];
1385
    foreach ($element->statisticalValues as $statistical_val) {
1386

    
1387
      // compile the full value string which also may contain modifiers
1388
      if (isset($statistical_val->value)) {
1389
        $statistical_val->_value = $statistical_val->value;
1390
      }
1391
      $val_modifiers_strings = cdm_modifiers_representations($statistical_val);
1392
      if ($val_modifiers_strings) {
1393
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1394
      }
1395

    
1396
      // either put into min max array or into $other_values
1397
      // for generic output to be appended to 'min-max' string
1398
      if (array_key_exists(statistical_measure_term2min_max_key($statistical_val->type), $min_max)) {
1399
        $min_max[statistical_measure_term2min_max_key($statistical_val->type)] = $statistical_val;
1400
      }
1401
      else {
1402
        drupal_set_message("Unsupported statistical value type: " . $statistical_val->type->uuid, "error");
1403
      }
1404
    } // end of loop over statisticalValues
1405

    
1406
    // create markup
1407
    $unit = null;
1408
    if (isset($element->unit)) {
1409
      $unit = ' <span class="unit" title="'
1410
        . cdm_term_representation($element->unit) . '">'
1411
        . cdm_term_representation_abbreviated($element->unit)
1412
        . '</span>';
1413
    }
1414
    $min_max_markup = statistical_values($min_max, $unit);
1415
    $out .= $min_max_markup . '</span>';
1416
  }
1417

    
1418
  if($sample_size_markup){
1419
    $out .= ' ' . $sample_size_markup;
1420

    
1421
  }
1422

    
1423
  // modifiers of the description element itself
1424
  $modifier_string = cdm_modifiers_representations($element);
1425
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1426
  if (isset($element->modifyingText_L10n)) {
1427
    $out = $element->modifyingText_L10n . ' ' . $out;
1428
  }
1429
  return $out;
1430
}
1431

    
1432
function statistical_measure_term2min_max_key($term){
1433
  static $uuid2key = [
1434
    UUID_STATISTICALMEASURE_MIN => 'Min',
1435
    UUID_STATISTICALMEASURE_MAX => 'Max',
1436
    UUID_STATISTICALMEASURE_AVERAGE => 'Average',
1437
    UUID_STATISTICALMEASURE_SAMPLESIZE => 'SampleSize',
1438
    UUID_STATISTICALMEASURE_VARIANCE => 'Variance',
1439
    UUID_STATISTICALMEASURE_TYPICALLOWERBOUNDARY => 'TypicalLowerBoundary',
1440
    UUID_STATISTICALMEASURE_TYPICALUPPERBOUNDARY => 'TypicalUpperBoundary',
1441
    UUID_STATISTICALMEASURE_STANDARDDEVIATION => 'StandardDeviation',
1442
    UUID_STATISTICALMEASURE_EXACTVALUE => 'ExactValue',
1443
    UUID_STATISTICALMEASURE_STATISTICALMEASUREUNKNOWNDATA => 'StatisticalMeasureUnknownData'
1444
  ];
1445
  return $uuid2key[$term->uuid];
1446
}
1447

    
1448

    
1449
/**
1450
 * Wraps the render array for the given feature into an enclosing html tag.
1451
 *
1452
 * Optionally the elements can be sorted and glued together by a separator string.
1453
 *
1454
 * @param array $description_element_render_arrays
1455
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1456
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1457
 * @param  $feature :
1458
 *  The feature to which the elements given in $elements are belonging to.
1459
 * @param string $glue :
1460
 *  Defaults to empty string.
1461
 * @param bool $sort
1462
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1463
 *
1464
 * @return array
1465
 *    A Drupal render array
1466
 *
1467
 * @ingroup compose
1468
 */
1469
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1470
  {
1471

    
1472
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1473
    $enclosing_tag = $feature_block_settings['as_list'];
1474

    
1475
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1476
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1477
    }
1478

    
1479
    $is_first = true;
1480
    foreach($description_element_render_arrays as &$element_render_array){
1481
      if(!is_array($element_render_array)){
1482
        $element_render_array = markup_to_render_array($element_render_array);
1483
      }
1484
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1485

    
1486
      // add the glue!
1487
      if(!$is_first) {
1488
        if (isset($element_render_array['#value'])) {
1489
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1490
        } elseif (isset($element_render_array['#markup'])) {
1491
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1492
        }
1493
      }
1494
      $is_first = false;
1495
    }
1496

    
1497
    $render_array['elements']['children'] = $description_element_render_arrays;
1498

    
1499
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1500
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1501

    
1502
    return $render_array;
1503
  }
1504

    
1505

    
1506
  /* compose nameInSource or originalNameString as markup
1507
   *
1508
   * @param $source
1509
   * @param $do_link_to_name_used_in_source
1510
   * @param $suppress_for_shown_taxon
1511
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1512
   *    for which the taxon page is being created, Defaults to TRUE
1513
   *
1514
   * @return array
1515
   *    A Drupal render array with an additional element, the render array is empty
1516
   *    if the source had no name in source information
1517
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1518
   *
1519
   * @ingroup compose
1520
   */
1521
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1522

    
1523
    $plaintext = NULL;
1524
    $markup = NULL;
1525
    $name_in_source_render_array = array();
1526

    
1527
    static $taxon_page_accepted_name = '';
1528
    $taxon_uuid = get_current_taxon_uuid();
1529
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1530

    
1531
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1532
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1533
    }
1534

    
1535
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1536
      // it is a DescriptionElementSource !
1537
      $plaintext = $source->nameUsedInSource->titleCache;
1538
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1539
        return $name_in_source_render_array; // SKIP this name
1540
      }
1541
      $markup = render_taxon_or_name($source->nameUsedInSource);
1542
      if ($do_link_to_name_used_in_source) {
1543
        $markup = l(
1544
          $markup,
1545
          path_to_name($source->nameUsedInSource->uuid),
1546
          array(
1547
            'attributes' => array(),
1548
            'absolute' => TRUE,
1549
            'html' => TRUE,
1550
          ));
1551
      }
1552
    }
1553
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1554
      // the name used in source can not be expressed as valid taxon name,
1555
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1556
      // field
1557
      // using the originalNameString as key to avoid duplicate entries
1558
      $plaintext = $source->originalNameString;
1559
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1560
        return $name_in_source_render_array; // SKIP this name
1561
      }
1562
      $markup = $source->originalNameString;
1563
    }
1564

    
1565
    if ($plaintext) { // checks if we have any content
1566
      $name_in_source_render_array = markup_to_render_array($markup);
1567
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1568
    }
1569

    
1570
    return $name_in_source_render_array;
1571
  }
1572

    
1573

    
1574

    
1575
  /**
1576
   * Return HTML for a list of description elements.
1577
   *
1578
   * Usually these are of a specific feature type.
1579
   *
1580
   * @param $description_elements
1581
   *   array of descriptionElements which belong to the same feature.
1582
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1583
   *   calling the function _mergeFeatureTreeDescriptions().
1584
   *   @see _mergeFeatureTreeDescriptions()
1585
   *
1586
   * @param  $feature_uuid
1587
   *
1588
   * @return
1589
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1590
   *    Footnote key or anchors are not considered to be textual content.
1591
   *
1592
   * @ingroup compose
1593
   */
1594
  function compose_feature_block_items_generic($description_elements, $feature) {
1595

    
1596
    $elements_out_array = array();
1597
    $distribution_tree = null;
1598

    
1599
    /*
1600
     * $feature_block_has_content will be set true if at least one of the
1601
     * $descriptionElements contains some text which makes up some content
1602
     * for the feature block. Footnote keys are not considered
1603
     * to be content in this sense.
1604
     */
1605
    $feature_block_has_content = false;
1606

    
1607
    if (is_array($description_elements)) {
1608
      foreach ($description_elements as $description_element) {
1609
          /* decide based on the description element class
1610
           *
1611
           * Features handled here:
1612
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1613
           *
1614
           * TODO provide api_hook as extension point for this?
1615
           */
1616
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1617
        switch ($description_element->class) {
1618
          case 'TextData':
1619
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1620
            break;
1621
          case 'CategoricalData':
1622
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1623
            break;
1624
          case 'QuantitativeData':
1625
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1626
            break;
1627
          case 'IndividualsAssociation':
1628
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1629
            break;
1630
          case 'TaxonInteraction':
1631
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1632
            break;
1633
          case 'CommonTaxonName':
1634
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1635
            break;
1636
          case 'Uses':
1637
            /* IGNORE Uses classes, these are handled completely in compose_feature_block_items_use_records()  */
1638
            break;
1639
          default:
1640
            $feature_block_has_content = true;
1641
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1642
        }
1643
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1644
        // considering not empty as long as the last item added is a render array
1645
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1646
      }
1647

    
1648
      // If feature = CITATION sort the list of sources.
1649
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1650
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1651
        sort($elements_out_array);
1652
      }
1653
    }
1654

    
1655
    // sanitize: remove empty and NULL items from the render array
1656
    $tmp_out_array = $elements_out_array;
1657
    $elements_out_array = array();
1658
    foreach($tmp_out_array as $item){
1659
      if(is_array($item) && count($item) > 0){
1660
        $elements_out_array[] = $item;
1661
      }
1662
    }
1663

    
1664
    return $elements_out_array;
1665
  }
1666

    
1667
/**
1668
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1669
 *
1670
 * @parameter $elements
1671
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1672
 * @parameter $feature
1673
 *  the common feature of all $elements, must be CommonName
1674
 *
1675
 * @return
1676
 *   A drupal render array
1677
 *
1678
 * @ingroup compose
1679
 */
1680
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1681

    
1682
  $common_name_out = '';
1683
  $common_name_feature_elements = array();
1684
  $textData_commonNames = array();
1685

    
1686
  $footnote_key_suggestion = 'common-names-feature-block';
1687

    
1688
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1689

    
1690
  if (is_array($elements)) {
1691
    foreach ($elements as $element) {
1692

    
1693
      if ($element->class == 'CommonTaxonName') {
1694

    
1695
        // common name without a language or area, should not happen but is possible
1696
        $language_area_key = '';
1697
        if (isset($element->language->representation_L10n)) {
1698
          $language_area_key .= $element->language->representation_L10n ;
1699
        }
1700
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1701
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1702
        }
1703
        if($language_area_key){
1704
          $language_area_key = '<span class="language-area-label">' . $language_area_key . '<span class="separator">: </span></span>';
1705
        }
1706

    
1707
        if(isset($common_names[$language_area_key][$element->name])) {
1708
          // same name already exists for language and area combination, se we merge the description elements
1709
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1710
        } else{
1711
          // otherwise add as new entry
1712
          $common_names[$language_area_key][$element->name] = $element;
1713
        }
1714

    
1715
      }
1716
      elseif ($element->class == 'TextData') {
1717
        $textData_commonNames[] = $element;
1718
      }
1719
    }
1720
  }
1721
  // Handling common names.
1722
  if (isset($common_names) && count($common_names) > 0) {
1723
    // Sorting the array based on the key (language, + area if set).
1724
    // Comment @WA there are common names without a language, so this sorting
1725
    // can give strange results.
1726
    ksort($common_names);
1727

    
1728
    // loop over set of elements per language area
1729
    foreach ($common_names as $language_area_key => $elements) {
1730
      ksort($elements); // sort names alphabetically
1731
      $per_language_area_out = array();
1732

    
1733
      foreach ($elements as $element) {
1734
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1735
        $common_name_markup = drupal_render($common_name_render_array);
1736
        // IMPORTANT!
1737
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1738
        // this is an error and the trailing whitespace needs to be removed
1739
        if(str_endsWith($common_name_markup, "\n")){
1740
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1741
        }
1742
        $per_language_area_out[] = $common_name_markup;
1743
      }
1744

    
1745
      $common_name_feature_elements[] = $language_area_key . join(', ', $per_language_area_out);
1746
    } // End of loop over set of elements per language area
1747

    
1748

    
1749
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1750
      $common_name_feature_elements, $feature, '; ', FALSE
1751
    );
1752
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1753

    
1754
  }
1755

    
1756
  // Handling commons names as text data.
1757
  $text_data_out = array();
1758

    
1759
  foreach ($textData_commonNames as $text_data_element) {
1760
    /* footnotes are not handled correctly in compose_description_element_text_data,
1761
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1762
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1763
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1764
    $text_data_out[] = drupal_render($text_data_render_array);
1765
  }
1766

    
1767
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1768
    $text_data_out, $feature
1769
  );
1770

    
1771
  $footnotes = cdm_footnotes('BIBLIOGRAPHY-' . $footnote_key_suggestion);
1772
  $footnotes .= cdm_footnotes($footnote_key_suggestion); // FIXME is this needed at all?
1773
  $footnotes .= cdm_annotation_footnotes($footnote_key_suggestion);
1774

    
1775
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1776
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1777
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1778
    .$footnotes,
1779
    $weight
1780
  );
1781
}
1782

    
1783
/**
1784
 * Renders a single instance of the type CommonTaxonName.
1785
 *
1786
 * @param $element
1787
 *   The CDM CommonTaxonName entity.
1788
 * @param $feature_block_settings
1789
 *
1790
 * @param $footnote_key_suggestion
1791
 *
1792
 * @param $element_tag_name
1793
 *
1794
 * @return array
1795
 *   Drupal render array
1796
 *
1797
 * @ingroup compose
1798
 */
1799
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion = NULL)
1800
{
1801

    
1802
  if(!$footnote_key_suggestion) {
1803
    $footnote_key_suggestion = $element->feature->uuid;
1804
  }
1805

    
1806
  $name = '';
1807
  if(isset($element->name)){
1808
    $name = $element->name;
1809
  }
1810

    
1811

    
1812
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1813
}
1814

    
1815
/**
1816
 * Composes the render array for a CDM Distribution description element
1817
 *
1818
 * @param array $description_elements
1819
 *   Array of CDM Distribution instances
1820
 * @param $enclosingTag
1821
 *   The html tag to be use for the enclosing element
1822
 *
1823
 * @return array
1824
 *   A Drupal render array
1825
 *
1826
 * @ingroup compose
1827
 */
1828
function compose_description_elements_distribution($description_elements){
1829

    
1830
  $markup_array = array();
1831
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1832
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1833

    
1834
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1835
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1836

    
1837
  foreach ($description_elements as $description_element) {
1838
    $annotations_and_sources = handle_annotations_and_sources(
1839
      $description_element,
1840
      handle_annotations_and_sources_config($feature_block_settings),
1841
      $description_element->area->representation_L10n,
1842
      UUID_DISTRIBUTION
1843
    );
1844

    
1845

    
1846
    $status = distribution_status_label_and_markup([$description_element]);
1847

    
1848
    $out = '';
1849
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1850
      . ' " title="' . $status['label']. '">'
1851
      . $description_element->area->representation_L10n
1852
      . $status['markup'];
1853
    if(!empty($annotations_and_sources['source_references'])){
1854
      $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1855
    }
1856
    $out .= $annotations_and_sources['foot_note_keys']   . '</' . $enclosingTag . '>';
1857
    $markup_array[] = $out;
1858
  }
1859

    
1860
  RenderHints::popFromRenderStack();
1861
  return markup_to_render_array(join('<span class="separator">' . $feature_block_settings['glue'] . '</span>', $markup_array));
1862
}
1863

    
1864
  /**
1865
   * @param array $distribution_status
1866
   * @return array an array with following keys
1867
   *   - 'label': the plain text status label
1868
   *   - 'markup': markup for the status
1869
   */
1870
  function distribution_status_label_and_markup(array $distribution_status, $status_glue = '&#8210; ') {
1871

    
1872
    $status_markup = '';
1873
    $status_label = '';
1874

    
1875
    foreach($distribution_status as $status) {
1876
      $status_label .= ($status_label ? $status_glue : '') . $status->representation_L10n;
1877
      $status_markup .=  '<span class="distributionStatus"> '
1878
        . ($status_markup ? $status_glue : '')
1879
        . '<span class="distributionStatus-' . $status->idInVocabulary . '">'
1880
        .  $status->representation_L10n
1881
        . '</span></span>';
1882

    
1883
    };
1884
    return ['label' => $status_label, 'markup' => $status_markup];
1885
  }
1886

    
1887

    
1888
  /**
1889
   * Provides the merged feature tree for a taxon profile page.
1890
   *
1891
   * The merging of the profile feature tree is actually done in
1892
   * _mergeFeatureTreeDescriptions(). See this method  for details
1893
   * on the structure of the merged tree.
1894
   *
1895
   * This method provides a hook which can be used to modify the
1896
   * merged feature tree after it has been created, see
1897
   * hook_merged_taxon_feature_tree_alter()
1898
   *
1899
   * @param $taxon
1900
   *    A CDM Taxon instance
1901
   *
1902
   * @return object
1903
   *    The merged feature tree
1904
   *
1905
   */
1906
  function merged_taxon_feature_tree($taxon) {
1907

    
1908
    // 1. fetch descriptions_by_featuretree but exclude the distribution feature
1909
    $merged_tree = cdm_ws_descriptions_by_featuretree(get_profile_feature_tree(), $taxon->uuid, array(UUID_DISTRIBUTION));
1910

    
1911

    
1912
    // 2. find the distribution feature node
1913
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1914

    
1915
    if ($distribution_node) {
1916
      // 3. get the distributionInfoDTO
1917
      $query_parameters = cdm_distribution_filter_query();
1918
      $query_parameters['part'] = array('mapUriParams');
1919
      if(variable_get(DISTRIBUTION_CONDENSED)){
1920
        $query_parameters['part'][] = 'condensedDistribution';
1921
      }
1922
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1923
        $query_parameters['part'][] = 'tree';
1924
      }
1925
      else {
1926
        $query_parameters['part'][] = 'elements';
1927
      }
1928
      $query_parameters['omitLevels'] = array();
1929
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1930
        if(is_uuid($uuid)){
1931
          $query_parameters['omitLevels'][] = $uuid;
1932
        }
1933
      }
1934
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1935
      if ($customStatusColorsJson) {
1936
        $query_parameters['statusColors'] = $customStatusColorsJson;
1937
      }
1938

    
1939
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1940
      // 4. get distribution TextData is there are any
1941
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1942
        array(
1943
          'taxon' => $taxon->uuid,
1944
          'type' => 'TextData',
1945
          'features' => UUID_DISTRIBUTION
1946
        )
1947
      );
1948

    
1949
      // 5. put all distribution data into the distribution feature node
1950
      if ($distribution_text_data //if text data exists
1951
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1952
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1953
      ) { // OR if DTO has distribution elements
1954
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1955
        if ($distribution_text_data) {
1956
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1957
        }
1958
        if ($distribution_info_dto) {
1959
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1960
        }
1961
      }
1962
    }
1963

    
1964
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1965
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1966

    
1967
    return $merged_tree;
1968
  }
1969

    
1970
  /**
1971
   * @param $distribution_tree
1972
   *  A tree cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
1973
   *  and Distribution items as data array. Per data array some Distributions may
1974
   *  be with status information, others only with sources, others with both.
1975
   *  Each node may also have subordinate node items in the children field.
1976
   *  TreeNode:
1977
   *   - array data
1978
   *   - array children
1979
   *   - int numberOfChildren
1980
   *   - stdClass nodeId
1981
   *
1982
   * @param $feature_block_settings
1983
   *
1984
   * @return array
1985
   * @throws \Exception
1986
   */
1987
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1988

    
1989
    static $hierarchy_style;
1990
    // TODO expose $hierarchy_style to administration or provide a hook
1991
    if( !isset($hierarchy_style)){
1992
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1993
    }
1994

    
1995
    $render_array = array();
1996

    
1997
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1998
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1999

    
2000
    // Returning NULL if there are no description elements.
2001
    if ($distribution_tree == null) {
2002
      return $render_array;
2003
    }
2004
    // for now we are not using a render array internally to avoid performance problems
2005
    $markup = '';
2006
    if (isset($distribution_tree->rootElement->children)) {
2007
      $tree_nodes = $distribution_tree->rootElement->children;
2008
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
2009
    }
2010

    
2011
    $render_array['distribution_hierarchy'] = markup_to_render_array(
2012
      $markup,
2013
      0,
2014
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
2015
      '</div>'
2016
    );
2017

    
2018
    RenderHints::popFromRenderStack();
2019

    
2020
    return $render_array;
2021
  }
2022

    
2023
/**
2024
 * this function should produce markup as the
2025
 * compose_description_elements_distribution() function.
2026
 *
2027
 * @param array $tree_nodes
2028
 *  An array of cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
2029
 *  and Distribution items as data array. Per data array some Distributions may
2030
 *  be with status information, others only with sources, others with both.
2031
 *  TreeNode:
2032
 *   - array data
2033
 *   - array children
2034
 *   - int numberOfChildren
2035
 *   - stdClass nodeId
2036
 * @param array $feature_block_settings
2037
 * @param $markup
2038
 * @param $hierarchy_style
2039
 * @param int $level_index
2040
 *
2041
 * @throws \Exception
2042
 *
2043
 * @see compose_description_elements_distribution()
2044
 * @see compose_distribution_hierarchy()
2045
 *
2046
 */
2047
  function _compose_distribution_hierarchy(array $tree_nodes, array $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
2048

    
2049
    $level_index++;
2050
    static $enclosingTag = "span";
2051

    
2052
    $level_style = array_shift($hierarchy_style);
2053
    if(count($hierarchy_style) == 0){
2054
      // lowest defined level style will be reused for all following levels
2055
      $hierarchy_style[] = $level_style;
2056
    }
2057

    
2058
    $node_index = -1;
2059
    $per_node_markup = array();
2060

    
2061
    foreach ($tree_nodes as $node){
2062

    
2063
      $per_node_markup[++$node_index] = '';
2064
      $label = $node->nodeId->representation_L10n;
2065

    
2066
      $distributions = $node->data;
2067
      $distribution_uuids = array();
2068
      $distribution_aggregate = NULL;
2069
      $status = ['label' => '', 'markup' => ''];
2070

    
2071
      foreach($distributions as $distribution){
2072
        $distribution_uuids[] = $distribution->uuid;
2073
        // if there is more than one distribution we aggregate the sources and
2074
        // annotations into a synthetic distribution so that the footnote keys
2075
        // can be rendered consistently
2076
        if(!$distribution_aggregate) {
2077
          $distribution_aggregate = $distribution;
2078
          if(isset($distribution->status)){
2079
            $distribution_aggregate->status = [$distribution->status];
2080
          } else {
2081
            $distribution_aggregate->status = [];
2082
          }
2083
          if(!isset($distribution_aggregate->sources[0])){
2084
            $distribution_aggregate->sources = array();
2085
          }
2086
          if(!isset($distribution_aggregate->annotations[0])){
2087
            $distribution_aggregate->annotations = array();
2088
          }
2089
        } else {
2090
          if(isset($distribution->status)){
2091
            $distribution_aggregate->status[] = $distribution->status;
2092
          }
2093
          if(isset($distribution->sources[0])) {
2094
            $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
2095
              $distribution->sources);
2096
          }
2097
          if(isset($distribution->annotations[0])) {
2098
            $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
2099
              $distribution->annotations);
2100
          }
2101
        }
2102
      }
2103

    
2104
      $annotations_and_sources =  null;
2105
      if($distribution_aggregate) {
2106
        $annotations_and_sources = handle_annotations_and_sources(
2107
          $distribution_aggregate,
2108
          handle_annotations_and_sources_config($feature_block_settings),
2109
          $label,
2110
          UUID_DISTRIBUTION
2111
        );
2112

    
2113
        $status = distribution_status_label_and_markup($distribution_aggregate->status, $level_style['status_glue']);
2114
      }
2115

    
2116
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
2117
        . join(' descriptionElement-', $distribution_uuids)
2118
        . ' level_index_' . $level_index
2119
        . ' " title="' . $status['label'] . '">'
2120
        . '<span class="area_label">' . $label
2121
        . $level_style['label_suffix'] . '</span>'
2122
        . $status['markup']
2123
      ;
2124

    
2125
      if(isset($annotations_and_sources)){
2126
        if(!empty($annotations_and_sources['source_references'])){
2127
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
2128
        }
2129
        if($annotations_and_sources['foot_note_keys']) {
2130
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
2131
        }
2132
      }
2133

    
2134
      if(isset($node->children[0])){
2135
        _compose_distribution_hierarchy(
2136
          $node->children,
2137
          $feature_block_settings,
2138
          $per_node_markup[$node_index],
2139
          $hierarchy_style,
2140
          $level_index
2141
        );
2142
      }
2143

    
2144
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
2145
    }
2146
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
2147
  }
2148

    
2149

    
2150
/**
2151
 * Provides the content for a block of Uses Descriptions for a given taxon.
2152
 *
2153
 * Fetches the list of TaxonDescriptions tagged with the MARKERTYPE_USE
2154
 * and passes them to the theme function theme_cdm_UseDescription().
2155
 *
2156
 * @param string $taxon_uuid
2157
 *   The uuid of the Taxon
2158
 *
2159
 * @return array
2160
 *   A drupal render array
2161
 */
2162
function cdm_block_use_description_content($taxon_uuid, $feature) {
2163

    
2164
  $use_description_content = array();
2165

    
2166
  if (is_uuid($taxon_uuid )) {
2167
    $markerTypes = array();
2168
    $markerTypes['markerTypes'] = UUID_MARKERTYPE_USE;
2169
    $useDescriptions = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXON . '/' . $taxon_uuid . '/descriptions', $markerTypes);
2170
    if (!empty($useDescriptions)) {
2171
      $use_description_content = compose_feature_block_items_use_records($useDescriptions, $taxon_uuid, $feature);
2172
    }
2173
  }
2174

    
2175
  return $use_description_content;
2176
}
2177

    
2178
/**
2179
 * Creates a trunk of a feature object which can be used to build pseudo feature blocks like the Bibliography.
2180
 *
2181
 * @param $representation_L10n
2182
 * @param String $pseudo_feature_key
2183
 *    Will be set as uuid but should be one of 'BIBLIOGRAPHY', ... more to come. See also get_feature_block_settings()
2184
 *
2185
 * @return object
2186
 *  The feature object
2187
 */
2188
function make_pseudo_feature($representation_L10n, $pseudo_feature_key = null){
2189
  $feature = new stdClass;
2190
  $feature->representation_L10n = $representation_L10n;
2191
  $feature->uuid = NULL; // $pseudo_feature_key;
2192
  $feature->label = $pseudo_feature_key;
2193
  $feature->class = 'PseudoFeature';
2194

    
2195
  return $feature;
2196

    
2197
}
2198

    
2199
/**
2200
 * @param $root_nodes, for obtaining the  root nodes from a description you can
2201
 * use the function get_root_nodes_for_dataset($description);
2202
 *
2203
 * @return string
2204
 */
2205
function render_description_string($root_nodes, &$item_cnt = 0) {
2206

    
2207
  $out = '';
2208

    
2209
  $description_strings= [];
2210
  if (!empty($root_nodes)) {
2211
    foreach ($root_nodes as $root_node) {
2212
      if(isset($root_node->descriptionElements)) {
2213
        foreach ($root_node->descriptionElements as $element) {
2214
          $feature_label = $element->feature->representation_L10n;
2215
          if($item_cnt == 0){
2216
            $feature_label = ucfirst($feature_label);
2217
          }
2218
          switch ($element->class) {
2219
            case 'CategoricalData':
2220
              $state_data = render_state_data($element);
2221
              if (!empty($state_data)) {
2222
                if(is_suppress_state_present_display($element, $root_node)){
2223
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: '  . '</span>';
2224
                } else {
2225
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . $state_data . '</span>;' ;
2226
                }
2227
              }
2228
              break;
2229
            case 'QuantitativeData':
2230
              $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . render_quantitative_statistics($element) . '</span>;';
2231
              break;
2232
          }
2233
        }
2234
        $item_cnt++;
2235
      }
2236

    
2237
      // recurse child nodes
2238
      $child_markup = render_description_string($root_node->childNodes, $item_cnt);
2239
      if($child_markup){
2240
        $description_strings[] = $child_markup;
2241
      }
2242
    }
2243
    if(count($description_strings) > 0){
2244
      // remove last semicolon
2245
      $description_strings[count($description_strings) - 1] = preg_replace('/;$/', '', $description_strings[count($description_strings) - 1]);
2246
    }
2247
    $out  = join($description_strings,  ' ');
2248
  }
2249
  return $out;
2250
}
2251

    
2252
/**
2253
 * Compose a description as a table of Feature<->State
2254
 *
2255
 * @param $description_uuid
2256
 *
2257
 * @return array
2258
 *    The drupal render array for the page
2259
 *
2260
 * @ingroup compose
2261
 */
2262
function  compose_description_table($description_uuid, $descriptive_dataset_uuid = NULL) {
2263

    
2264
  RenderHints::pushToRenderStack('description_table');
2265

    
2266
  $render_array = [];
2267

    
2268
  $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, [$description_uuid]);
2269
  $dataSet = NULL;
2270
  // dataset passed as parameter
2271
  if ($descriptive_dataset_uuid != NULL) {
2272
    foreach ($description->descriptiveDataSets as $set) {
2273
      if ($set->uuid == $descriptive_dataset_uuid) {
2274
        $dataSet = $set;
2275
        break;
2276
      }
2277
    }
2278
  }
2279

    
2280
  if(!empty($description->descriptiveDataSets)) {
2281
    // only one dataset present
2282
    if (!isset($dataSet) && sizeof($description->descriptiveDataSets) == 1) {
2283
      foreach ($description->descriptiveDataSets as $dataSet) {
2284
        break;
2285
      }
2286
    }
2287

    
2288
    // generate description title
2289
    RenderHints::pushToRenderStack('title');
2290
    if (isset($dataSet)) {
2291

    
2292
      $described_entity_title = NULL;
2293
      if(isset($description->describedSpecimenOrObservation)){
2294
        $described_entity_title = $description->describedSpecimenOrObservation->titleCache;
2295
      } else if($description->taxon) {
2296
          $described_entity_title = render_taxon_or_name($description->taxon);
2297
      }
2298
      $title = 'Descriptive Data ' . $dataSet->titleCache .
2299
        ($described_entity_title ? ' for ' . $described_entity_title : '');
2300
    }
2301
    $render_array['title'] = markup_to_render_array($title, null, '<h3 class="title">', '</h3>');
2302
    RenderHints::popFromRenderStack();
2303
    // END of --- generate description title
2304

    
2305
    if (isset($description->types)) {
2306
      foreach ($description->types as $type) {
2307
        if ($type == 'CLONE_FOR_SOURCE') {
2308
          $render_array['source'] = markup_to_render_array("Aggregation source from " . $description->created, null, '<div class="date-created">', '</div>');
2309
          break;
2310
        }
2311
      }
2312
    }
2313
  }
2314
  // multiple datasets present see #8714 "Show multiple datasets per description as list of links"
2315
  else {
2316
    $items = [];
2317
    foreach ($description->descriptiveDataSets as $dataSet) {
2318
      $path = path_to_description($description->uuid, $dataSet->uuid);
2319
      $attributes['class'][] = html_class_attribute_ref($description);
2320
      $items[] = [
2321
        'data' => $dataSet->titleCache . icon_link($path),
2322
      ];
2323
    }
2324
    $render_array['description_elements'] = [
2325
      '#title' => 'Available data sets for description',
2326
      '#theme' => 'item_list',
2327
      '#type' => 'ul',
2328
      '#items' => $items,
2329
    ];
2330
  }
2331

    
2332
  $described_entities = [];
2333
  if (isset($description->describedSpecimenOrObservation)) {
2334
    $decr_entitiy = '<span class="label">Specimen:</span> ' . render_cdm_specimen_link($description->describedSpecimenOrObservation);
2335
    $described_entities['specimen'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2336
  }
2337
  if (isset($description->taxon)) {
2338
    $decr_entitiy = '<span class="label">Taxon:</span> ' . render_taxon_or_name($description->taxon, url(path_to_taxon($description->taxon->uuid)));
2339
    $described_entities['taxon'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2340
  }
2341

    
2342
  if(count($described_entities)){
2343
    $render_array['described_entities'] = $described_entities;
2344
    $render_array['described_entities']['#prefix'] = '<div class="described-entities">';
2345
    $render_array['described_entities']['#suffix'] = '</div>';
2346
  }
2347

    
2348

    
2349
  $root_nodes = get_root_nodes_for_dataset($description);
2350

    
2351

    
2352
  $rows = [];
2353
  $rows = description_element_table_rows($root_nodes, $rows);
2354

    
2355
  // --- create headers
2356
  $header = [0 => [], 1 => []];
2357

    
2358
  foreach($rows as $row) {
2359
    if(array_search('Character', $row['class']) && array_search('Character', $header[0]) === false){
2360
      $header[0][] = 'Character';
2361
    } elseif (array_search('Feature', $row['class']) && array_search('Feature', $header[0]) === false){
2362
      $header[0][] = 'Feature';
2363
    }
2364
    if(array_search('has_state', $row['class']) && array_search('States', $header[1]) === false){
2365
      $header[1][] = 'States';
2366
    } elseif (array_search('has_values', $row['class']) && array_search('Values', $header[1]) === false){
2367
      $header[1][] = 'Values';
2368
    }
2369
  }
2370
  asort($header[0]);
2371
  asort($header[1]);
2372
  $header[0] = join('/', $header[0]);
2373
  $header[1] = join('/', $header[1]);
2374

    
2375
  // ---
2376

    
2377
  if (!empty($rows)) {
2378
    $render_array['table'] = markup_to_render_array(theme('table', [
2379
      'header' => $header,
2380
      'rows' => $rows,
2381
      'caption' => statistical_values_explanation(),
2382
      'title' => "Table"
2383
    ]));
2384
  }
2385

    
2386
  // --- sources
2387
  if (isset($description->sources) and !empty($description->sources)) {
2388
    $items = [];
2389
    foreach ($description->sources as $source) {
2390
      if ($source->type == 'Aggregation' and isset($source->cdmSource)){
2391
        $cdm_source_entity = $source->cdmSource;
2392
        switch($cdm_source_entity->class){
2393
          case 'Taxon':
2394
            $source_link_markup = render_taxon_or_name($cdm_source_entity) . icon_link(path_to_taxon($cdm_source_entity->uuid, false));
2395
            break;
2396
          case 'TaxonDescription':
2397
          case 'NameDescription':
2398
          case 'SpecimenDescription':
2399
            $source_link_markup = render_cdm_entity_link($cdm_source_entity);
2400
            break;
2401
          default:
2402
            $source_link_markup = '<span class="error">Unhandled CdmSource</span>';
2403
        }
2404
        $items[$cdm_source_entity->titleCache] = [
2405
          'data' => $source_link_markup
2406
        ];
2407
      }
2408
    }
2409
    ksort($items);
2410
    $render_array['sources'] = [
2411
      '#title' => 'Sources',
2412
      '#theme' => 'item_list',
2413
      '#type' => 'ul',
2414
      '#items' => $items,
2415
      '#attributes' => ['class' => 'sources']
2416
    ];
2417
    $render_array['#prefix'] = '<div class="description-table">';
2418
    $render_array['#suffix'] = '</div>';
2419
  }
2420

    
2421
  RenderHints::popFromRenderStack();
2422

    
2423
  return $render_array;
2424
}
2425

    
2426
/**
2427
 * For a given description returns the root nodes according to the
2428
 *corresponding term tree. The term tree is determined as follow:
2429
 * 1. If description is part of a descriptive data set the term tree of that
2430
 *    data set is used (FIXME handle multiple term trees)
2431
 * 2. Otherwise the portal taxon profile tree is used
2432
 * @param $description
2433
 *
2434
 * @return array
2435
 */
2436
function get_root_nodes_for_dataset($description) {
2437
  if (!empty($description->descriptiveDataSets)) {
2438
    foreach ($description->descriptiveDataSets as $dataSet) {
2439
      break;// FIXME handle multiple term trees
2440
    }
2441
    $tree = cdm_ws_get(CDM_WS_TERMTREE, $dataSet->descriptiveSystem->uuid);
2442
    $root_nodes = _mergeFeatureTreeDescriptions($tree->root->childNodes, $description->elements);
2443
  }
2444
  else {
2445
    $root_nodes = _mergeFeatureTreeDescriptions(get_profile_feature_tree()->root->childNodes, $description->elements);
2446
  }
2447
  return $root_nodes;
2448
}
2449

    
2450
/**
2451
 * Recursively creates an array of row items to be used in theme_table.
2452
 *
2453
 * The array items will have am element 'class' with information on the
2454
 * nature of the DescriptionElement ('has_values' | 'has_state') and on the
2455
 * type of the FeatureNode ('Feature' | 'Character')
2456
 *
2457
 * @param array $root_nodes
2458
 * @param array $row_items
2459
 * @param int $level
2460
 *     the depth in the hierarchy
2461
 *
2462
 * @return array
2463
 *  An array of row items to be used in theme_table
2464
 *
2465
 *
2466
 */
2467
function description_element_table_rows($root_nodes, $row_items, $level = 0) {
2468

    
2469
  $indent_string = '&nbsp;&nbsp;&nbsp;';
2470
  foreach ($root_nodes as $root_node) {
2471
    if(isset($root_node->descriptionElements)) {
2472
      foreach ($root_node->descriptionElements as $element) {
2473
        $level_indent = str_pad('', $level * strlen($indent_string), $indent_string);
2474
        switch ($element->class) {
2475
          case 'QuantitativeData':
2476
            $row_items[] = [
2477
              'data' => [
2478
                [
2479
                  'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2480
                  'class' => ['level_' . $level]
2481
                ],
2482
                render_quantitative_statistics($element)
2483
              ],
2484
              'class' => ['level_' . $level, 'has_values', $element->feature->class]
2485
            ];
2486
            break;
2487
          case 'CategoricalData':
2488
            default:
2489
            if (!empty($element->stateData)) {
2490
              $supress_state_display = is_suppress_state_present_display($element, $root_node);
2491
              if(!$supress_state_display){
2492
                $state_cell = render_state_data($element);
2493
              } else {
2494
                $state_cell = "<span> </span>";
2495
              }
2496
              $row_items[] = [
2497
                'data' => [
2498
                  [
2499
                    'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2500
                    'class' => ['level_' . $level]
2501
                  ],
2502
                  $state_cell,
2503
                ],
2504
                'class' => ['level_' . $level, 'has_state', $element->feature->class]
2505
              ];
2506
            }
2507
            break;
2508
        }
2509
      }
2510
    }
2511
    // recurse child nodes
2512
    $row_items = description_element_table_rows($root_node->childNodes, $row_items, $level + 1);
2513
  }
2514
  return $row_items;
2515
}
2516

    
2517
/**
2518
 * @param $element
2519
 * @param $root_node
2520
 *
2521
 * @return bool
2522
 */
2523
function is_suppress_state_present_display($element, $root_node) {
2524
  return count($element->stateData) == 1 & $element->stateData[0]->state->representation_L10n == 'present' && is_array($root_node->childNodes);
2525
}
2526

    
2527

    
2528

    
(3-3/13)