Project

General

Profile

Download (84.4 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
 * Compare callback to be used in usort() to sort render arrays produced by
338
 * compose_description_element().
339
 *
340
 * @param $a
341
 * @param $b
342
 *
343
 * @return int Returns < 0 if $a['#value'].$a['#value-suffix'] from is less than
344
 * $b['#value'].$b['#value-suffix'], > 0 if it is greater than $b['#value'].$b['#value-suffix'],
345
 * and 0 if they are equal.
346
 */
347
function compare_description_element_render_arrays($a, $b){
348
  if ($a['#value'].$a['#value-suffix'] == $b['#value'].$b['#value-suffix']) {
349
    return 0;
350
  }
351
  return ($a['#value'].$a['#value-suffix'] < $b['#value'].$b['#value-suffix']) ? -1 : 1;
352

    
353
}
354

    
355

    
356
/**
357
 * @param $element
358
 * @param $feature_block_settings
359
 * @param $element_markup
360
 * @param $footnote_list_key_suggestion
361
 * @param bool $prepend_feature_label
362
 *
363
 * @return array|null
364
 */
365
function compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label = FALSE)
366
{
367

    
368
  $render_array = array(
369
    '#type' => 'html_tag',
370
    '#tag' => cdm_feature_block_element_tag_name($feature_block_settings),
371

    
372
    '#attributes' => array(
373
      'class' => array(
374
        'DescriptionElement',
375
        'DescriptionElement-' . $element->class,
376
        html_class_attribute_ref($element)
377
      )
378
    ),
379

    
380
    '#value' => '',
381
    '#value_suffix' => NULL
382

    
383
  );
384

    
385
  $annotations_and_sources = handle_annotations_and_sources(
386
    $element,
387
    handle_annotations_and_sources_config($feature_block_settings),
388
    $element_markup,
389
    $footnote_list_key_suggestion
390
  );
391

    
392
  $timescope_markup = '';
393
  if(isset($element->timeperiod)){
394
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, true);
395
  }
396

    
397
  // handle the special case were the TextData is used as container for original source with name
398
  // used in source information without any text stored in it.
399
  $names_used_in_source_markup = '';
400
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
401
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
402
    // remove all <span class="nameUsedInSource">...</span> from all source_references
403
    // these are expected to be at the end of the strings
404
    $pattern = '/ <span class="nameUsedInSource">.*$/';
405
    foreach( $annotations_and_sources['source_references'] as &$source_reference){
406
      $source_reference = preg_replace($pattern , '', $source_reference);
407
    }
408
  }
409

    
410
  $source_references_markup = '';
411
  if (!empty($annotations_and_sources['source_references'])) {
412
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
413
  }
414

    
415
  $feature_label = '';
416
  if ($prepend_feature_label) {
417
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
418
  }
419
  $content_markup = $names_used_in_source_markup . $element_markup . $timescope_markup . $source_references_markup;
420

    
421
  if(!$content_markup && $feature_block_settings['sources_as_content'] !== 1){
422
    // no textual content? So skip this element completely, even if there could be an footnote key
423
    // see #4379
424
    return null;
425
  }
426

    
427
    $render_array['#value'] = $feature_label . $content_markup;
428
    $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
429
  return $render_array;
430
}
431

    
432
/**
433
 * Creates a handle_annotations_and_sources configuration array from feature_block_settings.
434
 *
435
 * The handle_annotations_and_sources configuration array is meant to be used for the
436
 * method handle_annotations_and_sources().
437
 *
438
 * @param $feature_block_settings array
439
 *
440
 * @return array
441
 *   The configuration array for handle_annotations_and_sources()
442
 */
443
function handle_annotations_and_sources_config($feature_block_settings){
444

    
445
  $config = $feature_block_settings;
446
  unset($config['sources_as_content_to_bibliography']);
447
  $config['add_footnote_keys'] = 0;
448
  if($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
449
    $config['add_footnote_keys'] = 1;
450
  }
451
  $config['bibliography_aware'] = 1;
452

    
453
  return $config;
454
}
455

    
456
/**
457
 * @param $entity
458
 * @param $config array
459
 *   An associative array to configure the display of the annotations and
460
 *   sources. The array has the following keys
461
 *   - sources_as_content
462
 *   - link_to_name_used_in_source
463
 *   - link_to_reference
464
 *   - add_footnote_keys
465
 *   - bibliography_aware
466
 *   Valid values are 1 or 0.
467
 * @param $inline_text_prefix
468
 *   Only used to decide if the source references should be enclosed in
469
 *   brackets or not when displayed inline. This text will not be included into
470
 *   the response.
471
 * @param $footnote_list_key_suggestion string
472
 *    optional parameter. If this paramter is left empty (null, 0, "") the
473
 *   footnote key will be determined by the nested method calls by calling
474
 *   RenderHints::getFootnoteListKey(). NOTE: the footnore key for annotations
475
 *   will be set to RenderHints::getFootnoteListKey().FOOTNOTE_KEY_SUFFIX_ANNOTATIONS.
476
 * @return array
477
 * an associative array with the following elements:
478
 *   - foot_note_keys: all footnote keys as markup
479
 *   - source_references: an array of the source references citations
480
 *   - names used in source: an associative array of the names in source,
481
 *        the name in source strings are de-duplicated
482
 *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
483
 *
484
 * @throws \Exception
485
 *
486
 * @see cdm_entities_annotations_footnote_keys()
487
 */
488
  function handle_annotations_and_sources($entity, $config, $inline_text_prefix, $footnote_list_key_suggestion) {
489

    
490
    $annotations_and_sources = array(
491
      'foot_note_keys' => NULL,
492
      'source_references' => [],
493
      'names_used_in_source' => []
494
    );
495

    
496
    // some entity types only have single sources:
497
    $sources = cdm_entity_sources_sorted($entity);
498

    
499
    if ($config['sources_as_content'] == 1) {
500
      foreach ($sources as $source) {
501
        if (_is_original_source_type($source)) {
502
          $reference_citation = render_original_source(
503
            $source,
504
            $config['link_to_reference'] == 1,
505
            $config['link_to_name_used_in_source'] == 1
506
          );
507

    
508
          if ($reference_citation) {
509
            if (empty($inline_text_prefix)) {
510
              $annotations_and_sources['source_references'][] = $reference_citation;
511
            } else {
512
              $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
513
            }
514
          }
515

    
516
          // also put the name in source into the array, these are already included in the $reference_citation but are
517
          // still required to be available separately in some contexts.
518
          $name_in_source_render_array = compose_name_in_source(
519
            $source,
520
            $config['link_to_name_used_in_source'] == 1
521
          );
522

    
523
          if (!empty($name_in_source_render_array)) {
524
            $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
525
          }
526
        }
527
      } // END of loop over sources
528

    
529
      // annotations footnotes separate from sources
530
      $annotations_and_sources['foot_note_keys'] = render_footnote_keys(
531
        cdm_entity_annotations_as_footnote_keys($entity, $footnote_list_key_suggestion), ', '
532
      );
533

    
534
    } // END of references inline
535

    
536
    // footnotes for sources and annotations or put into into bibliography if requested ...
537
    if ($config['add_footnote_keys'] == 1) {
538
        $annotations_and_sources['foot_note_keys'] = render_entity_footnotes(
539
          $entity, ',',
540
          $footnote_list_key_suggestion,
541
          $config['link_to_reference'] == 1,
542
          $config['link_to_name_used_in_source'] == 1,
543
          !empty($config['bibliography_aware'])
544
        );
545
    }
546

    
547
    return $annotations_and_sources;
548
  }
549

    
550
/**
551
 * Get the source or the sources from a cdm entity and return them ordered by see compare_original_sources()
552
 * (Some entity types only have single sources)
553
 * @param $entity
554
 *
555
 * @return array
556
 */
557
function cdm_entity_sources_sorted($entity) {
558
  if (isset($entity->source) && is_object($entity->source)) {
559
    $sources = [$entity->source];
560
  }
561
  else if (isset($entity->sources)) {
562
    $sources = $entity->sources;
563
  }
564
  else {
565
    $sources = [];
566
  }
567
  usort($sources, 'compare_original_sources');
568
  return $sources;
569
}
570

    
571

    
572
/**
573
   * This method determines the footnote key for original sources to be shown in the bibliography block
574
   *
575
   * The footnote key depends on the value of the 'enabled' value of the bibliography_settings
576
   *    - enabled == 1 -> "BIBLIOGRAPHY"
577
   *    - enabled == 0 -> "BIBLIOGRAPHY-$key_suggestion"
578
   *
579
   * @see get_bibliography_settings() and @see constant BIBLIOGRAPHY_FOOTNOTE_KEY
580
   *
581
   * @param $key_suggestion string
582
   *    optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be retrieved by
583
   *    calling RenderHints::getFootnoteListKey().
584

    
585
   *
586
   * @return string
587
   *  the footnote_list_key
588
   */
589
  function bibliography_footnote_list_key($key_suggestion = null) {
590
    if(!$key_suggestion){
591
      $key_suggestion = RenderHints::getFootnoteListKey();
592
    }
593
    $bibliography_settings = get_bibliography_settings();
594
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? BIBLIOGRAPHY_FOOTNOTE_KEY : BIBLIOGRAPHY_FOOTNOTE_KEY . '-' . $key_suggestion;
595
    return $footnote_list_key;
596
  }
597

    
598
/**
599
 * Provides the according tag name for the description element markup which
600
 * fits the  $feature_block_settings['as_list'] value
601
 *
602
 * @param $feature_block_settings
603
 *   A feature_block_settings array, for details, please see
604
 *   get_feature_block_settings($feature_uuid = 'DEFAULT')
605
 *
606
 * @return mixed|string
607
 */
608
  function cdm_feature_block_element_tag_name($feature_block_settings){
609
    switch ($feature_block_settings['as_list']){
610
      case 'ul':
611
      case 'ol':
612
        return 'li';
613
      case 'div':
614
        if(isset($feature_block_settings['element_tag'])){
615
          return $feature_block_settings['element_tag'];
616
        }
617
        return 'span';
618
      case 'dl':
619
        return 'dd';
620
      default:
621
        return 'div'; // should never happen, throw error instead?
622
    }
623
  }
624

    
625

    
626
/* ==================== COMPOSE FUNCTIONS =============== */
627

    
628
  /**
629
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
630
   *
631
   * The taxon profile consists of drupal block elements, one for the description elements
632
   * of a specific feature. The structure is defined by specific FeatureTree.
633
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
634
   *
635
   * The merged nodes can be obtained by making use of the
636
   * function cdm_ws_descriptions_by_featuretree().
637
   *
638
   * @see cdm_ws_descriptions_by_featuretree()
639
   *
640
   * @param $mergedFeatureNodes
641
   *
642
   * @param $taxon
643
   *
644
   * @return array
645
   *  A Drupal render array containing feature blocks and the table of content
646
   *
647
   * @ingroup compose
648
   */
649
  function make_feature_block_list($mergedFeatureNodes, $taxon) {
650

    
651
    $block_list = array();
652

    
653
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
654

    
655
    $use_description_features = array(UUID_USE);
656

    
657

    
658
    RenderHints::pushToRenderStack('feature_block');
659
    // Create a drupal block for each feature
660
    $block_weight = - FEATURE_BLOCK_WEIGHT_INCREMENT;
661
    foreach ($mergedFeatureNodes as $feature_node) {
662

    
663
      $block_weight = $block_weight + FEATURE_BLOCK_WEIGHT_INCREMENT;
664

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

    
668
        RenderHints::pushToRenderStack($feature_node->term->uuid);
669
          
670
        $feature_name = cdm_term_representation($feature_node->term, 'Unnamed Feature');
671
        $feature_block_settings = get_feature_block_settings($feature_node->term->uuid);
672
        
673

    
674
        $block = feature_block($feature_name, $feature_node->term);
675
        $block->content = array();
676
        $block_content_is_empty = TRUE;
677

    
678
        if(array_search($feature_node->term->uuid, $use_description_features) !== false) {
679
          // do not show features which belong to the UseDescriptions, these are
680
          // handled by compose_feature_block_items_use_records() where the according descriptions are
681
          // fetched again separately.
682
          // UseDescriptions are a special feature introduced for palmweb
683
          continue;
684
        }
685

    
686
        /*
687
         * Content/DISTRIBUTION.
688
         */
689
        if ($feature_node->term->uuid == UUID_DISTRIBUTION) {
690
          $block = compose_feature_block_distribution($taxon, $feature_node->descriptionElements, $feature_node->term);
691
          $block_content_is_empty = FALSE;
692
        }
693

    
694
        /*
695
         * Content/COMMON_NAME.
696
         */
697
        else if ($feature_node->term->uuid == UUID_COMMON_NAME) {
698
          $common_names_render_array = compose_feature_block_items_feature_common_name($feature_node->descriptionElements, $feature_node->term);
699
          $block->content[] = $common_names_render_array;
700
          $block_content_is_empty = FALSE;
701
        }
702

    
703
        /*
704
         * Content/Use Description (Use + UseRecord)
705
         */
706
        else if ($feature_node->term->uuid == UUID_USE_RECORD) {
707
          $block->content[] = cdm_block_use_description_content($taxon->uuid, $feature_node->term);
708
          $block_content_is_empty = FALSE;
709
        }
710

    
711
        /*
712
         * Content/ALL OTHER FEATURES.
713
         */
714
        else {
715

    
716
          $media_list = array();
717
          $elements_render_array = array();
718
          $child_elements_render_array = null;
719

    
720
          if (isset($feature_node->descriptionElements[0])) {
721
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements, $feature_node->term);
722
          }
723

    
724
          // Content/ALL OTHER FEATURES/Subordinate Features
725
          // subordinate features are printed inline in one floating text,
726
          // it is expected hat subordinate features can "contain" TextData,
727
          // Qualitative- and Qualitative- DescriptionElements
728
          if (isset($feature_node->childNodes[0])) {
729
            $child_elements_render_array = compose_feature_block_items_nested($feature_node, $media_list, $feature_block_settings);
730
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
731
          }
732
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
733
          if(!$block_content_is_empty){
734
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $feature_node->term, $feature_block_settings['glue']);
735
            $block->content[] = compose_feature_media_gallery($feature_node, $media_list, $gallery_settings);
736
            /*
737
             * Footnotes for the feature block
738
             */
739
            $block->content[] = markup_to_render_array(render_footnotes(PSEUDO_FEATURE_BIBLIOGRAPHY . '-' . $feature_node->term->uuid));
740
            $block->content[] = markup_to_render_array(render_footnotes($feature_node->term->uuid));
741
            $block->content[] = markup_to_render_array(render_annotation_footnotes($feature_node->term->uuid));
742
          }
743
        } // END all other features
744

    
745
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
746
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
747

    
748
        if(!$block_content_is_empty){ // skip empty block content
749
          $block_list[$block_weight] = $block;
750
          cdm_toc_list_add_item(cdm_term_representation($feature_node->term), $feature_node->term->uuid, null, FALSE, $block_weight);
751
        } // END: skip empty block content
752
      } // END: skip empty or suppressed features
753
      RenderHints::popFromRenderStack();
754
    } // END: creating a block per feature
755

    
756
    RenderHints::popFromRenderStack();
757

    
758
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
759

    
760
    ksort($block_list);
761

    
762
    return  $block_list;
763
  }
764

    
765
/**
766
 * Creates a render array of description elements  held by child nodes of the given feature node.
767
 *
768
 * This function is called recursively!
769
 *
770
 * @param $feature_node
771
 *   The feature node.
772
 * @param array $media_list
773
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
774
 * @param $feature_block_settings
775
 *   The feature block settings.
776
 * @param $main_feature
777
 *  Only used internally in recursive calls.
778
 *
779
 * @return array
780
 *  A Drupal render array
781
 *
782
 * @ingroup compose
783
 */
784
function compose_feature_block_items_nested($feature_node, &$media_list, $feature_block_settings, $main_feature = NULL)
785
{
786

    
787
  if(!$main_feature){
788
    $main_feature = $feature_node->term;
789
  }
790
  /*
791
   * TODO should be configurable, options; YES, NO, AUTOMATIC
792
   * (automatic will only place the label if the first word of the description element text is not the same)
793
   */
794
  $prepend_feature_label = false;
795

    
796
  $render_arrays = array();
797
  foreach ($feature_node->childNodes as $child_node) {
798
    if (isset($child_node->descriptionElements[0])) {
799
      foreach ($child_node->descriptionElements as $element) {
800

    
801
        if (isset($element->media[0])) {
802
          // Append media of subordinate elements to list of main
803
          // feature.
804
          $media_list = array_merge($media_list, $element->media);
805
        }
806

    
807
        $child_node_element = null;
808
        switch ($element->class) {
809
          case 'TextData':
810
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
811
            break;
812
          case 'CategoricalData':
813
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
814
            break;
815
          case 'QuantitativeData':
816
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
817

    
818
        }
819
        if (is_array($child_node_element)) {
820
          $render_arrays[] = $child_node_element;
821
        }
822
      }
823
    }
824

    
825
    if(isset($child_node->childNodes[0])){
826
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
827
    }
828
  }
829

    
830
  return $render_arrays;
831
}
832

    
833
  /**
834
   *
835
   * @param $feature_node
836
   *  The merged feature three node which potentially contains media in its description elements.
837
   * @param $media_list
838
   *    Additional media to be merged witht the media contained in the nodes description elements
839
   * @param $gallery_settings
840
   * @return array
841
   *
842
   * @ingroup compose
843
   */
844
  function compose_feature_media_gallery($feature_node, $media_list, $gallery_settings) {
845

    
846
    if (isset($feature_node->descriptionElements)) {
847
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
848
    }
849

    
850
    $captionElements = array('title', 'rights');
851

    
852
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
853
      $gallery = compose_cdm_media_gallerie(array(
854
        'mediaList' => $media_list,
855
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $feature_node->term->uuid,
856
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
857
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
858
        'captionElements' => $captionElements,
859
      ));
860
      return markup_to_render_array($gallery);
861
    }
862

    
863
    return markup_to_render_array('');
864
  }
865

    
866
  /**
867
   * Composes the distribution feature block for a taxon
868
   *
869
   * @param $taxon
870
   * @param $descriptionElements
871
   *   an associative array with two elements:
872
   *   - '#type': must be 'DTO'
873
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
874
   * @param $feature
875
   *
876
   * @return array
877
   *  A drupal render array
878
   *
879
   * @ingroup compose
880
   */
881
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
882
    $text_data_glue = '';
883
    $text_data_sortOutArray = FALSE;
884
    $text_data_enclosingTag = 'ul';
885
    $text_data_out_array = array();
886

    
887
    $distributionElements = NULL;
888
    $distribution_info_dto = NULL;
889
    $distribution_sortOutArray = FALSE;
890

    
891
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
892

    
893
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
894
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
895
      $distribution_glue = '';
896
      $distribution_enclosingTag = 'dl';
897
    } else {
898
      $distribution_glue = '';
899
      $distribution_enclosingTag = 'ul';
900
    }
901

    
902
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
903
      // skip the DISTRIBUTION section if there is no DTO type element
904
      return array(); // FIXME is it ok to return an empty array?
905
    }
906

    
907
    $block = feature_block(
908
      cdm_term_representation($feature, 'Unnamed Feature'),
909
      $feature
910
    );
911
    $block->content = array();
912

    
913
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
914
    if (isset($descriptionElements['TextData'])) {
915
      // --- TextData
916
      foreach ($descriptionElements['TextData'] as $text_data_element) {
917
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
918
        $repr = drupal_render($text_data_render_array);
919

    
920
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
921
          $text_data_out_array[] = $repr;
922
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
923
          // not work since this array contains html attributes with uuids
924
          // and what is about cases like the bibliography where
925
          // any content can be prefixed with some foot-note anchors?
926
          $text_data_sortOutArray = TRUE;
927
          $text_data_glue = '<br/> ';
928
          $text_data_enclosingTag = 'p';
929
        }
930
      }
931
    }
932

    
933

    
934
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
935
      $block->content[] = compose_feature_block_wrap_elements(
936
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
937
      );
938
    }
939

    
940
    // --- Distribution map
941
    $distribution_map_query_parameters = NULL;
942

    
943
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
944
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
945
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
946
      )
947
    {
948
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
949
    }
950
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
951
    $block->content[] = $map_render_element;
952

    
953
    $dto_out_array = array();
954

    
955
    // --- Condensed Distribution
956
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
957
      $condensed_distribution_markup = '<p class="condensed_distribution">';
958

    
959
      $isFirst = true;
960
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
961
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
962
          if(!$isFirst){
963
            $condensed_distribution_markup .= ' ';
964
          }
965
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
966
          . $cdItem->areaStatusLabel . '</span>';
967
          $isFirst = false;
968
        }
969
      }
970

    
971
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
972
        if(!$isFirst){
973
          $condensed_distribution_markup .= ' ';
974
        }
975
        $isFirst = TRUE;
976
        $condensed_distribution_markup .= '[';
977
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
978
          if (!$isFirst) {
979
            $condensed_distribution_markup .= ' ';
980
          }
981
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
982
            . $cdItem->areaStatusLabel . '</span>';
983
          $isFirst = false;
984
        }
985
        $condensed_distribution_markup .= ']';
986
      }
987

    
988
      $condensed_distribution_markup .= '&nbsp;' . l(
989
          font_awesome_icon_markup(
990
            'fa-info-circle',
991
            array(
992
              'alt'=>'help',
993
              'class' => array('superscript')
994
            )
995
          ),
996
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
997
          array('html' => TRUE));
998
      $condensed_distribution_markup .= '</p>';
999
      $dto_out_array[] = $condensed_distribution_markup;
1000
    }
1001

    
1002
    // --- tree or list
1003
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1004
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1005

    
1006
      // --- tree
1007
      if (is_object($distribution_info_dto->tree)) {
1008
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
1009
        $dto_out_array[] = $distribution_tree_render_array;
1010
      }
1011

    
1012
      // --- sorted element list
1013
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
1014
        foreach ($distribution_info_dto->elements as $descriptionElement) {
1015
          if (is_object($descriptionElement->area)) {
1016
            $sortKey = $descriptionElement->area->representation_L10n;
1017
            $distributionElements[$sortKey] = $descriptionElement;
1018
          }
1019
        }
1020
        ksort($distributionElements);
1021
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
1022
        $dto_out_array[] = $distribution_element_render_array;
1023

    
1024
      }
1025
      //
1026
      $block->content[] = compose_feature_block_wrap_elements(
1027
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1028
      );
1029
    }
1030

    
1031
    // --- TextData at the bottom
1032
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1033
      $block->content[] = compose_feature_block_wrap_elements(
1034
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1035
      );
1036
    }
1037

    
1038
    $block->content[] = markup_to_render_array(render_footnotes('BIBLIOGRAPHY-' . UUID_DISTRIBUTION));
1039
    $block->content[] = markup_to_render_array(render_footnotes(UUID_DISTRIBUTION));
1040
    $block->content[] = markup_to_render_array(render_annotation_footnotes(UUID_DISTRIBUTION));
1041

    
1042
    return $block;
1043
  }
1044

    
1045

    
1046
  /**
1047
   * Composes a drupal render array for single CDM TextData description element.
1048
   *
1049
   * @param $element
1050
   *    The CDM TextData description element.
1051
   *  @param $feature_uuid
1052
   * @param bool $prepend_feature_label
1053
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1054
   *
1055
   * @return array
1056
   *   A drupal render array with the following elements being used:
1057
   *    - #tag: either 'div', 'li', ...
1058
   *    ⁻ #attributes: class attributes
1059
   *    - #value_prefix: (optionally) contains footnote anchors
1060
   *    - #value: contains the textual content
1061
   *    - #value_suffix: (optionally) contains footnote keys
1062
   *
1063
   * @ingroup compose
1064
   */
1065
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
1066

    
1067
    $footnote_list_key_suggestion = $feature_uuid;
1068

    
1069
    $element_markup = '';
1070
    if (isset($element->multilanguageText_L10n->text)) {
1071
      // TODO replacement of \n by <br> should be configurable
1072
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
1073
    }
1074

    
1075
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1076

    
1077
    return $render_array;
1078
  }
1079

    
1080

    
1081
/**
1082
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
1083
 *
1084
 * @param $element
1085
 *  The CDM TaxonInteraction entity
1086
 *
1087
 * @return
1088
 *  A drupal render array
1089
 *
1090
 * @ingroup compose
1091
 */
1092
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
1093

    
1094
  $out = '';
1095

    
1096

    
1097
  if (isset($element->description_L10n)) {
1098
    $out .=  ' ' . $element->description_L10n;
1099
  }
1100

    
1101
  if(isset($element->taxon2)){
1102
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1103
  }
1104

    
1105
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1106

    
1107
  return $render_array;
1108
}
1109

    
1110

    
1111
/**
1112
 * Renders a single instance of the type IndividualsAssociations.
1113
 *
1114
 * @param $element
1115
 *   The CDM IndividualsAssociations entity.
1116
 * @param $feature_block_settings
1117
 *
1118
 * @return array
1119
 *   Drupal render array
1120
 *
1121
 * @ingroup compose
1122
 */
1123
function compose_description_element_individuals_association($element, $feature_block_settings) {
1124

    
1125
  $out = '';
1126

    
1127
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1128

    
1129
  if (isset($element->description_L10n)) {
1130
    $out .=  ' ' . $element->description_L10n;
1131
  }
1132

    
1133
  $out .= drupal_render($render_array);
1134

    
1135
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1136

    
1137
  return $render_array;
1138
}
1139

    
1140
/**
1141
 * Renders a single instance of the type CategoricalData.
1142
 *
1143
 * @param $element
1144
 *  The CDM CategoricalData entity
1145
 *
1146
 * @param $feature_block_settings
1147
 *
1148
 * @param bool $prepend_feature_label
1149
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1150
 *
1151
 * @return array
1152
 *   a drupal render array for given CategoricalData element
1153
 *
1154
 * @ingroup compose
1155
 */
1156
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1157

    
1158
  $state_data_markup = render_state_data($element);
1159

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

    
1162
  return $render_array;
1163
}
1164

    
1165
/**
1166
 * @param $element
1167
 *
1168
 * @return string
1169
 * the markup
1170
 */
1171
function render_state_data($element) {
1172

    
1173
  $state_data_items = [];
1174

    
1175
  $out = '';
1176

    
1177
  if (isset($element->stateData)) {
1178
    foreach ($element->stateData as $state_data) {
1179

    
1180
      $state = NULL;
1181

    
1182
      if (isset($state_data->state)) {
1183
        $state = cdm_term_representation($state_data->state);
1184

    
1185
          $sample_count = 0;
1186
          if (isset($state_data->count)) {
1187
            $sample_count = $state_data->count;
1188
            $state .= ' [' . $state_data->count . ']';
1189
          }
1190
    
1191
          if (isset($state_data->modifyingText_L10n)) {
1192
            $state .= ' ' . $state_data->modifyingText_L10n;
1193
          }
1194
    
1195
          $modifiers_strings = cdm_modifiers_representations($state_data);
1196
          $state_data_markup = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1197
          // we could use strip_tags() to reduce the markup to text for the key but this is expensive
1198
          $sort_key = str_pad($sample_count, 6, '0', STR_PAD_LEFT) . '_' . $state_data_markup;
1199
          $state_data_items[$sort_key] = $state_data_markup;
1200
      }
1201

    
1202
    }
1203
    krsort($state_data_items);
1204
    $out = '<span class="' . html_class_attribute_ref($element) . '">' . join(', ', $state_data_items) .  '</span>';
1205
  }
1206
  return $out;
1207
}
1208

    
1209

    
1210
/**
1211
 * Theme function to render CDM DescriptionElements of the type QuantitativeData.
1212
 *
1213
 * The function renders the statisticalValues contained in the QuantitativeData
1214
 * entity according to the following scheme:
1215
 *
1216
 * (ExtremeMin)-Min-Average-Max-(ExtremeMax)
1217
 *
1218
 * All modifiers of these values are appended.
1219
 *
1220
 * If the QuantitativeData is containing more statisticalValues with further
1221
 * statisticalValue types, these additional measures will be appended to the
1222
 * above string separated by whitespace.
1223
 *
1224
 * Special cases;
1225
 * 1. Min==Max: this will be interpreted as Average
1226
 *
1227
 * @param $element
1228
 *  The CDM QuantitativeData entity
1229
 *
1230
 * @param $feature_block_settings
1231
 *
1232
 * @param bool $prepend_feature_label
1233
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1234
 *
1235
 *
1236
 * @return array
1237
 *   drupal render array for the given QuantitativeData element
1238
 *
1239
 * @ingroup compose
1240
 */
1241
function compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1242
  /*
1243
   * - statisticalValues
1244
   *   - value
1245
   *   - modifiers
1246
   *   - type
1247
   * - unit->representation_L10n
1248
   * - modifyingText
1249
   * - modifiers
1250
   * - sources
1251
   */
1252

    
1253
  $out = render_quantitative_statistics($element);
1254

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

    
1257
  return $render_array;
1258
}
1259

    
1260
/**
1261
 * Composes the HTML for quantitative statistics
1262
 * @param $element
1263
 *
1264
 * @return string
1265
 */
1266
function render_quantitative_statistics($element) {
1267

    
1268
  $out = '';
1269
  $type_representation = NULL;
1270
  $min_max = statistical_values_array();
1271
  $sample_size_markup = null;
1272

    
1273
  if (isset($element->statisticalValues)) {
1274
    $out = '<span class=\"' . html_class_attribute_ref($element) . '\">';
1275
    $other_values_markup = [];
1276
    foreach ($element->statisticalValues as $statistical_val) {
1277

    
1278
      // compile the full value string which also may contain modifiers
1279
      if (isset($statistical_val->value)) {
1280
        $statistical_val->_value = $statistical_val->value;
1281
      }
1282
      $val_modifiers_strings = cdm_modifiers_representations($statistical_val);
1283
      if ($val_modifiers_strings) {
1284
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1285
      }
1286

    
1287
      // either put into min max array or into $other_values
1288
      // for generic output to be appended to 'min-max' string
1289
      if (array_key_exists(statistical_measure_term2min_max_key($statistical_val->type), $min_max)) {
1290
        $min_max[statistical_measure_term2min_max_key($statistical_val->type)] = $statistical_val;
1291
      }
1292
      else {
1293
        drupal_set_message("Unsupported statistical value type: " . $statistical_val->type->uuid, "error");
1294
      }
1295
    } // end of loop over statisticalValues
1296

    
1297
    // create markup
1298
    $unit = null;
1299
    if (isset($element->unit)) {
1300
      $unit = ' <span class="unit" title="'
1301
        . cdm_term_representation($element->unit) . '">'
1302
        . cdm_term_representation_abbreviated($element->unit)
1303
        . '</span>';
1304
    }
1305
    $min_max_markup = statistical_values($min_max, $unit);
1306
    $out .= $min_max_markup . '</span>';
1307
  }
1308

    
1309
  if($sample_size_markup){
1310
    $out .= ' ' . $sample_size_markup;
1311

    
1312
  }
1313

    
1314
  // modifiers of the description element itself
1315
  $modifier_string = cdm_modifiers_representations($element);
1316
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1317
  if (isset($element->modifyingText_L10n)) {
1318
    $out = $element->modifyingText_L10n . ' ' . $out;
1319
  }
1320
  return $out;
1321
}
1322

    
1323
function statistical_measure_term2min_max_key($term){
1324
  static $uuid2key = [
1325
    UUID_STATISTICALMEASURE_MIN => 'Min',
1326
    UUID_STATISTICALMEASURE_MAX => 'Max',
1327
    UUID_STATISTICALMEASURE_AVERAGE => 'Average',
1328
    UUID_STATISTICALMEASURE_SAMPLESIZE => 'SampleSize',
1329
    UUID_STATISTICALMEASURE_VARIANCE => 'Variance',
1330
    UUID_STATISTICALMEASURE_TYPICALLOWERBOUNDARY => 'TypicalLowerBoundary',
1331
    UUID_STATISTICALMEASURE_TYPICALUPPERBOUNDARY => 'TypicalUpperBoundary',
1332
    UUID_STATISTICALMEASURE_STANDARDDEVIATION => 'StandardDeviation',
1333
    UUID_STATISTICALMEASURE_EXACTVALUE => 'ExactValue',
1334
    UUID_STATISTICALMEASURE_STATISTICALMEASUREUNKNOWNDATA => 'StatisticalMeasureUnknownData'
1335
  ];
1336
  return $uuid2key[$term->uuid];
1337
}
1338

    
1339

    
1340
/**
1341
 * Wraps the render array for the given feature into an enclosing html tag.
1342
 *
1343
 * Optionally the elements can be sorted and glued together by a separator string.
1344
 *
1345
 * @param array $description_element_render_arrays
1346
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1347
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1348
 * @param  $feature :
1349
 *  The feature to which the elements given in $elements are belonging to.
1350
 * @param string $glue :
1351
 *  Defaults to empty string.
1352
 * @param bool $sort
1353
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1354
 *
1355
 * @return array
1356
 *    A Drupal render array
1357
 *
1358
 * @ingroup compose
1359
 */
1360
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1361
  {
1362

    
1363
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1364
    $enclosing_tag = $feature_block_settings['as_list'];
1365

    
1366
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1367
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1368
    }
1369

    
1370
    $is_first = true;
1371
    foreach($description_element_render_arrays as &$element_render_array){
1372
      if(!is_array($element_render_array)){
1373
        $element_render_array = markup_to_render_array($element_render_array);
1374
      }
1375
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1376

    
1377
      // add the glue!
1378
      if(!$is_first) {
1379
        if (isset($element_render_array['#value'])) {
1380
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1381
        } elseif (isset($element_render_array['#markup'])) {
1382
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1383
        }
1384
      }
1385
      $is_first = false;
1386
    }
1387

    
1388
    $render_array['elements']['children'] = $description_element_render_arrays;
1389

    
1390
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1391
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1392

    
1393
    return $render_array;
1394
  }
1395

    
1396

    
1397
  /* compose nameInSource or originalNameString as markup
1398
   *
1399
   * @param $source
1400
   * @param $do_link_to_name_used_in_source
1401
   * @param $suppress_for_shown_taxon
1402
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1403
   *    for which the taxon page is being created, Defaults to TRUE
1404
   *
1405
   * @return array
1406
   *    A Drupal render array with an additional element, the render array is empty
1407
   *    if the source had no name in source information
1408
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1409
   *
1410
   * @ingroup compose
1411
   */
1412
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1413

    
1414
    $plaintext = NULL;
1415
    $markup = NULL;
1416
    $name_in_source_render_array = array();
1417

    
1418
    static $taxon_page_accepted_name = '';
1419
    $taxon_uuid = get_current_taxon_uuid();
1420
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1421

    
1422
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1423
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1424
    }
1425

    
1426
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1427
      // it is a DescriptionElementSource !
1428
      $plaintext = $source->nameUsedInSource->titleCache;
1429
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1430
        return $name_in_source_render_array; // SKIP this name
1431
      }
1432
      $markup = render_taxon_or_name($source->nameUsedInSource);
1433
      if ($do_link_to_name_used_in_source) {
1434
        $markup = l(
1435
          $markup,
1436
          path_to_name($source->nameUsedInSource->uuid),
1437
          array(
1438
            'attributes' => array(),
1439
            'absolute' => TRUE,
1440
            'html' => TRUE,
1441
          ));
1442
      }
1443
    }
1444
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1445
      // the name used in source can not be expressed as valid taxon name,
1446
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1447
      // field
1448
      // using the originalNameString as key to avoid duplicate entries
1449
      $plaintext = $source->originalNameString;
1450
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1451
        return $name_in_source_render_array; // SKIP this name
1452
      }
1453
      $markup = $source->originalNameString;
1454
    }
1455

    
1456
    if ($plaintext) { // checks if we have any content
1457
      $name_in_source_render_array = markup_to_render_array($markup);
1458
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1459
    }
1460

    
1461
    return $name_in_source_render_array;
1462
  }
1463

    
1464

    
1465

    
1466
  /**
1467
   * Return HTML for a list of description elements.
1468
   *
1469
   * Usually these are of a specific feature type.
1470
   *
1471
   * @param $description_elements
1472
   *   array of descriptionElements which belong to the same feature.
1473
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1474
   *   calling the function _mergeFeatureTreeDescriptions().
1475
   *   @see _mergeFeatureTreeDescriptions()
1476
   *
1477
   * @param  $feature_uuid
1478
   *
1479
   * @return
1480
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1481
   *    Footnote key or anchors are not considered to be textual content.
1482
   *
1483
   * @ingroup compose
1484
   */
1485
  function compose_feature_block_items_generic($description_elements, $feature) {
1486

    
1487
    $elements_out_array = array();
1488
    $distribution_tree = null;
1489

    
1490
    /*
1491
     * $feature_block_has_content will be set true if at least one of the
1492
     * $descriptionElements contains some text which makes up some content
1493
     * for the feature block. Footnote keys are not considered
1494
     * to be content in this sense.
1495
     */
1496
    $feature_block_has_content = false;
1497

    
1498
    if (is_array($description_elements)) {
1499
      foreach ($description_elements as $description_element) {
1500
          /* decide based on the description element class
1501
           *
1502
           * Features handled here:
1503
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1504
           *
1505
           * TODO provide api_hook as extension point for this?
1506
           */
1507
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1508
        switch ($description_element->class) {
1509
          case 'TextData':
1510
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1511
            break;
1512
          case 'CategoricalData':
1513
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1514
            break;
1515
          case 'QuantitativeData':
1516
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1517
            break;
1518
          case 'IndividualsAssociation':
1519
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1520
            break;
1521
          case 'TaxonInteraction':
1522
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1523
            break;
1524
          case 'CommonTaxonName':
1525
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1526
            break;
1527
          case 'Uses':
1528
            /* IGNORE Uses classes, these are handled completely in compose_feature_block_items_use_records()  */
1529
            break;
1530
          default:
1531
            $feature_block_has_content = true;
1532
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1533
        }
1534
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1535
        // considering not empty as long as the last item added is a render array
1536
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1537
      }
1538

    
1539
      // If feature = CITATION sort the list of sources.
1540
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1541
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1542
        sort($elements_out_array);
1543
      }
1544
    }
1545

    
1546
    // sanitize: remove empty and NULL items from the render array
1547
    $tmp_out_array = $elements_out_array;
1548
    $elements_out_array = array();
1549
    foreach($tmp_out_array as $item){
1550
      if(is_array($item) && count($item) > 0){
1551
        $elements_out_array[] = $item;
1552
      }
1553
    }
1554

    
1555
    return $elements_out_array;
1556
  }
1557

    
1558
/**
1559
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1560
 *
1561
 * @parameter $elements
1562
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1563
 * @parameter $feature
1564
 *  the common feature of all $elements, must be CommonName
1565
 *
1566
 * @return
1567
 *   A drupal render array
1568
 *
1569
 * @ingroup compose
1570
 */
1571
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1572

    
1573
  $common_name_out = '';
1574
  $common_name_feature_elements = array();
1575
  $textData_commonNames = array();
1576

    
1577
  $footnote_key_suggestion = 'common-names-feature-block';
1578

    
1579
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1580

    
1581
  if (is_array($elements)) {
1582
    foreach ($elements as $element) {
1583

    
1584
      if ($element->class == 'CommonTaxonName') {
1585

    
1586
        // common name without a language or area, should not happen but is possible
1587
        $language_area_key = '';
1588
        if (isset($element->language->representation_L10n)) {
1589
          $language_area_key .= $element->language->representation_L10n ;
1590
        }
1591
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1592
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1593
        }
1594
        if($language_area_key){
1595
          $language_area_key = '<span class="language-area-label">' . $language_area_key . '<span class="separator">: </span></span>';
1596
        }
1597

    
1598
        if(isset($common_names[$language_area_key][$element->name])) {
1599
          // same name already exists for language and area combination, se we merge the description elements
1600
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1601
        } else{
1602
          // otherwise add as new entry
1603
          $common_names[$language_area_key][$element->name] = $element;
1604
        }
1605

    
1606
      }
1607
      elseif ($element->class == 'TextData') {
1608
        $textData_commonNames[] = $element;
1609
      }
1610
    }
1611
  }
1612
  // Handling common names.
1613
  if (isset($common_names) && count($common_names) > 0) {
1614
    // Sorting the array based on the key (language, + area if set).
1615
    // Comment @WA there are common names without a language, so this sorting
1616
    // can give strange results.
1617
    ksort($common_names);
1618

    
1619
    // loop over set of elements per language area
1620
    foreach ($common_names as $language_area_key => $elements) {
1621
      ksort($elements); // sort names alphabetically
1622
      $per_language_area_out = array();
1623

    
1624
      foreach ($elements as $element) {
1625
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1626
        $common_name_markup = drupal_render($common_name_render_array);
1627
        // IMPORTANT!
1628
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1629
        // this is an error and the trailing whitespace needs to be removed
1630
        if(str_endsWith($common_name_markup, "\n")){
1631
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1632
        }
1633
        $per_language_area_out[] = $common_name_markup;
1634
      }
1635

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

    
1639

    
1640
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1641
      $common_name_feature_elements, $feature, '; ', FALSE
1642
    );
1643
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1644

    
1645
  }
1646

    
1647
  // Handling commons names as text data.
1648
  $text_data_out = array();
1649

    
1650
  foreach ($textData_commonNames as $text_data_element) {
1651
    /* footnotes are not handled correctly in compose_description_element_text_data,
1652
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1653
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1654
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1655
    $text_data_out[] = drupal_render($text_data_render_array);
1656
  }
1657

    
1658
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1659
    $text_data_out, $feature
1660
  );
1661

    
1662
  $footnotes = render_footnotes('BIBLIOGRAPHY-' . $footnote_key_suggestion);
1663
  $footnotes .= render_footnotes($footnote_key_suggestion); // FIXME is this needed at all?
1664
  $footnotes .= render_annotation_footnotes($footnote_key_suggestion);
1665

    
1666
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1667
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1668
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1669
    .$footnotes,
1670
    $weight
1671
  );
1672
}
1673

    
1674
/**
1675
 * Renders a single instance of the type CommonTaxonName.
1676
 *
1677
 * @param $element
1678
 *   The CDM CommonTaxonName entity.
1679
 * @param $feature_block_settings
1680
 *
1681
 * @param $footnote_key_suggestion
1682
 *
1683
 * @param $element_tag_name
1684
 *
1685
 * @return array
1686
 *   Drupal render array
1687
 *
1688
 * @ingroup compose
1689
 */
1690
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion = NULL)
1691
{
1692

    
1693
  if(!$footnote_key_suggestion) {
1694
    $footnote_key_suggestion = $element->feature->uuid;
1695
  }
1696

    
1697
  $name = '';
1698
  if(isset($element->name)){
1699
    $name = $element->name;
1700
  }
1701

    
1702

    
1703
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1704
}
1705

    
1706
/**
1707
 * Composes the render array for a CDM Distribution description element
1708
 *
1709
 * @param array $description_elements
1710
 *   Array of CDM Distribution instances
1711
 * @param $enclosingTag
1712
 *   The html tag to be use for the enclosing element
1713
 *
1714
 * @return array
1715
 *   A Drupal render array
1716
 *
1717
 * @ingroup compose
1718
 */
1719
function compose_description_elements_distribution($description_elements){
1720

    
1721
  $markup_array = array();
1722
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1723
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1724

    
1725
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1726
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1727

    
1728
  foreach ($description_elements as $description_element) {
1729
    $annotations_and_sources = handle_annotations_and_sources(
1730
      $description_element,
1731
      handle_annotations_and_sources_config($feature_block_settings),
1732
      $description_element->area->representation_L10n,
1733
      UUID_DISTRIBUTION
1734
    );
1735

    
1736

    
1737
    $status = distribution_status_label_and_markup([$description_element]);
1738

    
1739
    $out = '';
1740
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1741
      . ' " title="' . $status['label']. '">'
1742
      . $description_element->area->representation_L10n
1743
      . $status['markup'];
1744
    if(!empty($annotations_and_sources['source_references'])){
1745
      $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1746
    }
1747
    $out .= $annotations_and_sources['foot_note_keys']   . '</' . $enclosingTag . '>';
1748
    $markup_array[] = $out;
1749
  }
1750

    
1751
  RenderHints::popFromRenderStack();
1752
  return markup_to_render_array(join('<span class="separator">' . $feature_block_settings['glue'] . '</span>', $markup_array));
1753
}
1754

    
1755
  /**
1756
   * @param array $distribution_status
1757
   * @return array an array with following keys
1758
   *   - 'label': the plain text status label
1759
   *   - 'markup': markup for the status
1760
   */
1761
  function distribution_status_label_and_markup(array $distribution_status, $status_glue = '&#8210; ') {
1762

    
1763
    $status_markup = '';
1764
    $status_label = '';
1765

    
1766
    foreach($distribution_status as $status) {
1767
      $status_label .= ($status_label ? $status_glue : '') . $status->representation_L10n;
1768
      $status_markup .=  '<span class="distributionStatus"> '
1769
        . ($status_markup ? $status_glue : '')
1770
        . '<span class="distributionStatus-' . $status->idInVocabulary . '">'
1771
        .  $status->representation_L10n
1772
        . '</span></span>';
1773

    
1774
    };
1775
    return ['label' => $status_label, 'markup' => $status_markup];
1776
  }
1777

    
1778

    
1779
  /**
1780
   * Provides the merged feature tree for a taxon profile page.
1781
   *
1782
   * The merging of the profile feature tree is actually done in
1783
   * _mergeFeatureTreeDescriptions(). See this method  for details
1784
   * on the structure of the merged tree.
1785
   *
1786
   * This method provides a hook which can be used to modify the
1787
   * merged feature tree after it has been created, see
1788
   * hook_merged_taxon_feature_tree_alter()
1789
   *
1790
   * @param $taxon
1791
   *    A CDM Taxon instance
1792
   *
1793
   * @return object
1794
   *    The merged feature tree
1795
   *
1796
   */
1797
  function merged_taxon_feature_tree($taxon) {
1798

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

    
1802

    
1803
    // 2. find the distribution feature node
1804
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1805

    
1806
    if ($distribution_node) {
1807
      // 3. get the distributionInfoDTO
1808
      $query_parameters = cdm_distribution_filter_query();
1809
      $query_parameters['part'] = array('mapUriParams');
1810
      if(variable_get(DISTRIBUTION_CONDENSED)){
1811
        $query_parameters['part'][] = 'condensedDistribution';
1812
      }
1813
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1814
        $query_parameters['part'][] = 'tree';
1815
      }
1816
      else {
1817
        $query_parameters['part'][] = 'elements';
1818
      }
1819
      $query_parameters['omitLevels'] = array();
1820
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1821
        if(is_uuid($uuid)){
1822
          $query_parameters['omitLevels'][] = $uuid;
1823
        }
1824
      }
1825
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1826
      if ($customStatusColorsJson) {
1827
        $query_parameters['statusColors'] = $customStatusColorsJson;
1828
      }
1829

    
1830
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1831
      // 4. get distribution TextData is there are any
1832
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1833
        array(
1834
          'taxon' => $taxon->uuid,
1835
          'type' => 'TextData',
1836
          'features' => UUID_DISTRIBUTION
1837
        )
1838
      );
1839

    
1840
      // 5. put all distribution data into the distribution feature node
1841
      if ($distribution_text_data //if text data exists
1842
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1843
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1844
      ) { // OR if DTO has distribution elements
1845
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1846
        if ($distribution_text_data) {
1847
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1848
        }
1849
        if ($distribution_info_dto) {
1850
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1851
        }
1852
      }
1853
    }
1854

    
1855
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1856
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1857

    
1858
    return $merged_tree;
1859
  }
1860

    
1861
  /**
1862
   * @param $distribution_tree
1863
   *  A tree cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
1864
   *  and Distribution items as data array. Per data array some Distributions may
1865
   *  be with status information, others only with sources, others with both.
1866
   *  Each node may also have subordinate node items in the children field.
1867
   *  TreeNode:
1868
   *   - array data
1869
   *   - array children
1870
   *   - int numberOfChildren
1871
   *   - stdClass nodeId
1872
   *
1873
   * @param $feature_block_settings
1874
   *
1875
   * @return array
1876
   * @throws \Exception
1877
   */
1878
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1879

    
1880
    static $hierarchy_style;
1881
    // TODO expose $hierarchy_style to administration or provide a hook
1882
    if( !isset($hierarchy_style)){
1883
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1884
    }
1885

    
1886
    $render_array = array();
1887

    
1888
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1889
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1890

    
1891
    // Returning NULL if there are no description elements.
1892
    if ($distribution_tree == null) {
1893
      return $render_array;
1894
    }
1895
    // for now we are not using a render array internally to avoid performance problems
1896
    $markup = '';
1897
    if (isset($distribution_tree->rootElement->children)) {
1898
      $tree_nodes = $distribution_tree->rootElement->children;
1899
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1900
    }
1901

    
1902
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1903
      $markup,
1904
      0,
1905
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1906
      '</div>'
1907
    );
1908

    
1909
    RenderHints::popFromRenderStack();
1910

    
1911
    return $render_array;
1912
  }
1913

    
1914
/**
1915
 * this function should produce markup as the
1916
 * compose_description_elements_distribution() function.
1917
 *
1918
 * @param array $tree_nodes
1919
 *  An array of cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
1920
 *  and Distribution items as data array. Per data array some Distributions may
1921
 *  be with status information, others only with sources, others with both.
1922
 *  TreeNode:
1923
 *   - array data
1924
 *   - array children
1925
 *   - int numberOfChildren
1926
 *   - stdClass nodeId
1927
 * @param array $feature_block_settings
1928
 * @param $markup
1929
 * @param $hierarchy_style
1930
 * @param int $level_index
1931
 *
1932
 * @throws \Exception
1933
 *
1934
 * @see compose_description_elements_distribution()
1935
 * @see compose_distribution_hierarchy()
1936
 *
1937
 */
1938
  function _compose_distribution_hierarchy(array $tree_nodes, array $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1939

    
1940
    $level_index++;
1941
    static $enclosingTag = "span";
1942

    
1943
    $level_style = array_shift($hierarchy_style);
1944
    if(count($hierarchy_style) == 0){
1945
      // lowest defined level style will be reused for all following levels
1946
      $hierarchy_style[] = $level_style;
1947
    }
1948

    
1949
    $node_index = -1;
1950
    $per_node_markup = array();
1951

    
1952
    foreach ($tree_nodes as $node){
1953

    
1954
      $per_node_markup[++$node_index] = '';
1955
      $label = $node->nodeId->representation_L10n;
1956

    
1957
      $distributions = $node->data;
1958
      $distribution_uuids = array();
1959
      $distribution_aggregate = NULL;
1960
      $status = ['label' => '', 'markup' => ''];
1961

    
1962
      foreach($distributions as $distribution){
1963
        $distribution_uuids[] = $distribution->uuid;
1964
        // if there is more than one distribution we aggregate the sources and
1965
        // annotations into a synthetic distribution so that the footnote keys
1966
        // can be rendered consistently
1967
        if(!$distribution_aggregate) {
1968
          $distribution_aggregate = $distribution;
1969
          if(isset($distribution->status)){
1970
            $distribution_aggregate->status = [$distribution->status];
1971
          } else {
1972
            $distribution_aggregate->status = [];
1973
          }
1974
          if(!isset($distribution_aggregate->sources[0])){
1975
            $distribution_aggregate->sources = array();
1976
          }
1977
          if(!isset($distribution_aggregate->annotations[0])){
1978
            $distribution_aggregate->annotations = array();
1979
          }
1980
        } else {
1981
          if(isset($distribution->status)){
1982
            $distribution_aggregate->status[] = $distribution->status;
1983
          }
1984
          if(isset($distribution->sources[0])) {
1985
            $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1986
              $distribution->sources);
1987
          }
1988
          if(isset($distribution->annotations[0])) {
1989
            $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1990
              $distribution->annotations);
1991
          }
1992
        }
1993
      }
1994

    
1995
      $annotations_and_sources =  null;
1996
      if($distribution_aggregate) {
1997
        $annotations_and_sources = handle_annotations_and_sources(
1998
          $distribution_aggregate,
1999
          handle_annotations_and_sources_config($feature_block_settings),
2000
          $label,
2001
          UUID_DISTRIBUTION
2002
        );
2003

    
2004
        $status = distribution_status_label_and_markup($distribution_aggregate->status, $level_style['status_glue']);
2005
      }
2006

    
2007
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
2008
        . join(' descriptionElement-', $distribution_uuids)
2009
        . ' level_index_' . $level_index
2010
        . ' " title="' . $status['label'] . '">'
2011
        . '<span class="area_label">' . $label
2012
        . $level_style['label_suffix'] . '</span>'
2013
        . $status['markup']
2014
      ;
2015

    
2016
      if(isset($annotations_and_sources)){
2017
        if(!empty($annotations_and_sources['source_references'])){
2018
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
2019
        }
2020
        if($annotations_and_sources['foot_note_keys']) {
2021
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
2022
        }
2023
      }
2024

    
2025
      if(isset($node->children[0])){
2026
        _compose_distribution_hierarchy(
2027
          $node->children,
2028
          $feature_block_settings,
2029
          $per_node_markup[$node_index],
2030
          $hierarchy_style,
2031
          $level_index
2032
        );
2033
      }
2034

    
2035
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
2036
    }
2037
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
2038
  }
2039

    
2040

    
2041
/**
2042
 * Provides the content for a block of Uses Descriptions for a given taxon.
2043
 *
2044
 * Fetches the list of TaxonDescriptions tagged with the MARKERTYPE_USE
2045
 * and passes them to the theme function theme_cdm_UseDescription().
2046
 *
2047
 * @param string $taxon_uuid
2048
 *   The uuid of the Taxon
2049
 *
2050
 * @return array
2051
 *   A drupal render array
2052
 */
2053
function cdm_block_use_description_content($taxon_uuid, $feature) {
2054

    
2055
  $use_description_content = array();
2056

    
2057
  if (is_uuid($taxon_uuid )) {
2058
    $markerTypes = array();
2059
    $markerTypes['markerTypes'] = UUID_MARKERTYPE_USE;
2060
    $useDescriptions = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXON . '/' . $taxon_uuid . '/descriptions', $markerTypes);
2061
    if (!empty($useDescriptions)) {
2062
      $use_description_content = compose_feature_block_items_use_records($useDescriptions, $taxon_uuid, $feature);
2063
    }
2064
  }
2065

    
2066
  return $use_description_content;
2067
}
2068

    
2069
/**
2070
 * Creates a trunk of a feature object which can be used to build pseudo feature blocks like the Bibliography.
2071
 *
2072
 * @param $representation_L10n
2073
 * @param String $pseudo_feature_key
2074
 *    Will be set as uuid but should be one of 'BIBLIOGRAPHY', ... more to come. See also get_feature_block_settings()
2075
 *
2076
 * @return object
2077
 *  The feature object
2078
 */
2079
function make_pseudo_feature($representation_L10n, $pseudo_feature_key = null){
2080
  $feature = new stdClass;
2081
  $feature->representation_L10n = $representation_L10n;
2082
  $feature->uuid = NULL; // $pseudo_feature_key;
2083
  $feature->label = $pseudo_feature_key;
2084
  $feature->class = 'PseudoFeature';
2085

    
2086
  return $feature;
2087

    
2088
}
2089

    
2090
/**
2091
 * @param $root_nodes, for obtaining the  root nodes from a description you can
2092
 * use the function get_root_nodes_for_dataset($description);
2093
 *
2094
 * @return string
2095
 */
2096
function render_description_string($root_nodes, &$item_cnt = 0) {
2097

    
2098
  $out = '';
2099

    
2100
  $description_strings= [];
2101
  if (!empty($root_nodes)) {
2102
    foreach ($root_nodes as $root_node) {
2103
      if(isset($root_node->descriptionElements)) {
2104
        foreach ($root_node->descriptionElements as $element) {
2105
          $feature_label = $element->feature->representation_L10n;
2106
          if($item_cnt == 0){
2107
            $feature_label = ucfirst($feature_label);
2108
          }
2109
          switch ($element->class) {
2110
            case 'CategoricalData':
2111
              $state_data = render_state_data($element);
2112
              if (!empty($state_data)) {
2113
                if(is_suppress_state_present_display($element, $root_node)){
2114
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: '  . '</span>';
2115
                } else {
2116
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . $state_data . '</span>;' ;
2117
                }
2118
              }
2119
              break;
2120
            case 'QuantitativeData':
2121
              $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . render_quantitative_statistics($element) . '</span>;';
2122
              break;
2123
          }
2124
        }
2125
        $item_cnt++;
2126
      }
2127

    
2128
      // recurse child nodes
2129
      $child_markup = render_description_string($root_node->childNodes, $item_cnt);
2130
      if($child_markup){
2131
        $description_strings[] = $child_markup;
2132
      }
2133
    }
2134
    if(count($description_strings) > 0){
2135
      // remove last semicolon
2136
      $description_strings[count($description_strings) - 1] = preg_replace('/;$/', '', $description_strings[count($description_strings) - 1]);
2137
    }
2138
    $out  = join($description_strings,  ' ');
2139
  }
2140
  return $out;
2141
}
2142

    
2143
/**
2144
 * Compose a description as a table of Feature<->State
2145
 *
2146
 * @param $description_uuid
2147
 *
2148
 * @return array
2149
 *    The drupal render array for the page
2150
 *
2151
 * @ingroup compose
2152
 */
2153
function  compose_description_table($description_uuid, $descriptive_dataset_uuid = NULL) {
2154

    
2155
  RenderHints::pushToRenderStack('description_table');
2156

    
2157
  $render_array = [];
2158

    
2159
  $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, [$description_uuid]);
2160
  $dataSet = NULL;
2161
  // dataset passed as parameter
2162
  if ($descriptive_dataset_uuid != NULL) {
2163
    foreach ($description->descriptiveDataSets as $set) {
2164
      if ($set->uuid == $descriptive_dataset_uuid) {
2165
        $dataSet = $set;
2166
        break;
2167
      }
2168
    }
2169
  }
2170

    
2171
  if(!empty($description->descriptiveDataSets)) {
2172
    // only one dataset present
2173
    if (!isset($dataSet) && sizeof($description->descriptiveDataSets) == 1) {
2174
      foreach ($description->descriptiveDataSets as $dataSet) {
2175
        break;
2176
      }
2177
    }
2178

    
2179
    // generate description title
2180
    RenderHints::pushToRenderStack('title');
2181
    if (isset($dataSet)) {
2182

    
2183
      $described_entity_title = NULL;
2184
      if(isset($description->describedSpecimenOrObservation)){
2185
        $described_entity_title = $description->describedSpecimenOrObservation->titleCache;
2186
      } else if($description->taxon) {
2187
          $described_entity_title = render_taxon_or_name($description->taxon);
2188
      }
2189
      $title = 'Descriptive Data ' . $dataSet->titleCache .
2190
        ($described_entity_title ? ' for ' . $described_entity_title : '');
2191
    }
2192
    $render_array['title'] = markup_to_render_array($title, null, '<h3 class="title">', '</h3>');
2193
    RenderHints::popFromRenderStack();
2194
    // END of --- generate description title
2195

    
2196
    if (isset($description->types)) {
2197
      foreach ($description->types as $type) {
2198
        if ($type == 'CLONE_FOR_SOURCE') {
2199
          $render_array['source'] = markup_to_render_array("Aggregation source from " . $description->created, null, '<div class="date-created">', '</div>');
2200
          break;
2201
        }
2202
      }
2203
    }
2204
  }
2205
  // multiple datasets present see #8714 "Show multiple datasets per description as list of links"
2206
  else {
2207
    $items = [];
2208
    foreach ($description->descriptiveDataSets as $dataSet) {
2209
      $path = path_to_description($description->uuid, $dataSet->uuid);
2210
      $attributes['class'][] = html_class_attribute_ref($description);
2211
      $items[] = [
2212
        'data' => $dataSet->titleCache . icon_link($path),
2213
      ];
2214
    }
2215
    $render_array['description_elements'] = [
2216
      '#title' => 'Available data sets for description',
2217
      '#theme' => 'item_list',
2218
      '#type' => 'ul',
2219
      '#items' => $items,
2220
    ];
2221
  }
2222

    
2223
  $described_entities = [];
2224
  if (isset($description->describedSpecimenOrObservation)) {
2225
    $decr_entitiy = '<span class="label">Specimen:</span> ' . render_cdm_specimen_link($description->describedSpecimenOrObservation);
2226
    $described_entities['specimen'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2227
  }
2228
  if (isset($description->taxon)) {
2229
    $decr_entitiy = '<span class="label">Taxon:</span> ' . render_taxon_or_name($description->taxon, url(path_to_taxon($description->taxon->uuid)));
2230
    $described_entities['taxon'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2231
  }
2232

    
2233
  if(count($described_entities)){
2234
    $render_array['described_entities'] = $described_entities;
2235
    $render_array['described_entities']['#prefix'] = '<div class="described-entities">';
2236
    $render_array['described_entities']['#suffix'] = '</div>';
2237
  }
2238

    
2239

    
2240
  $root_nodes = get_root_nodes_for_dataset($description);
2241

    
2242

    
2243
  $rows = [];
2244
  $rows = description_element_table_rows($root_nodes, $rows);
2245

    
2246
  // --- create headers
2247
  $header = [0 => [], 1 => []];
2248

    
2249
  foreach($rows as $row) {
2250
    if(array_search('Character', $row['class']) && array_search('Character', $header[0]) === false){
2251
      $header[0][] = 'Character';
2252
    } elseif (array_search('Feature', $row['class']) && array_search('Feature', $header[0]) === false){
2253
      $header[0][] = 'Feature';
2254
    }
2255
    if(array_search('has_state', $row['class']) && array_search('States', $header[1]) === false){
2256
      $header[1][] = 'States';
2257
    } elseif (array_search('has_values', $row['class']) && array_search('Values', $header[1]) === false){
2258
      $header[1][] = 'Values';
2259
    }
2260
  }
2261
  asort($header[0]);
2262
  asort($header[1]);
2263
  $header[0] = join('/', $header[0]);
2264
  $header[1] = join('/', $header[1]);
2265

    
2266
  // ---
2267

    
2268
  if (!empty($rows)) {
2269
    $render_array['table'] = markup_to_render_array(theme('table', [
2270
      'header' => $header,
2271
      'rows' => $rows,
2272
      'caption' => statistical_values_explanation(),
2273
      'title' => "Table"
2274
    ]));
2275
  }
2276

    
2277
  // --- sources
2278
  if (isset($description->sources) and !empty($description->sources)) {
2279
    $items = [];
2280
    foreach ($description->sources as $source) {
2281
      if ($source->type == 'Aggregation' and isset($source->cdmSource)){
2282
        $cdm_source_entity = $source->cdmSource;
2283
        switch($cdm_source_entity->class){
2284
          case 'Taxon':
2285
            $source_link_markup = render_taxon_or_name($cdm_source_entity) . icon_link(path_to_taxon($cdm_source_entity->uuid, false));
2286
            break;
2287
          case 'TaxonDescription':
2288
          case 'NameDescription':
2289
          case 'SpecimenDescription':
2290
            $source_link_markup = render_cdm_entity_link($cdm_source_entity);
2291
            break;
2292
          default:
2293
            $source_link_markup = '<span class="error">Unhandled CdmSource</span>';
2294
        }
2295
        $items[$cdm_source_entity->titleCache] = [
2296
          'data' => $source_link_markup
2297
        ];
2298
      }
2299
    }
2300
    ksort($items);
2301
    $render_array['sources'] = [
2302
      '#title' => 'Sources',
2303
      '#theme' => 'item_list',
2304
      '#type' => 'ul',
2305
      '#items' => $items,
2306
      '#attributes' => ['class' => 'sources']
2307
    ];
2308
    $render_array['#prefix'] = '<div class="description-table">';
2309
    $render_array['#suffix'] = '</div>';
2310
  }
2311

    
2312
  RenderHints::popFromRenderStack();
2313

    
2314
  return $render_array;
2315
}
2316

    
2317
/**
2318
 * For a given description returns the root nodes according to the
2319
 *corresponding term tree. The term tree is determined as follow:
2320
 * 1. If description is part of a descriptive data set the term tree of that
2321
 *    data set is used (FIXME handle multiple term trees)
2322
 * 2. Otherwise the portal taxon profile tree is used
2323
 * @param $description
2324
 *
2325
 * @return array
2326
 */
2327
function get_root_nodes_for_dataset($description) {
2328
  if (!empty($description->descriptiveDataSets)) {
2329
    foreach ($description->descriptiveDataSets as $dataSet) {
2330
      break;// FIXME handle multiple term trees
2331
    }
2332
    $tree = cdm_ws_get(CDM_WS_TERMTREE, $dataSet->descriptiveSystem->uuid);
2333
    $root_nodes = _mergeFeatureTreeDescriptions($tree->root->childNodes, $description->elements);
2334
  }
2335
  else {
2336
    $root_nodes = _mergeFeatureTreeDescriptions(get_profile_feature_tree()->root->childNodes, $description->elements);
2337
  }
2338
  return $root_nodes;
2339
}
2340

    
2341
/**
2342
 * Recursively creates an array of row items to be used in theme_table.
2343
 *
2344
 * The array items will have am element 'class' with information on the
2345
 * nature of the DescriptionElement ('has_values' | 'has_state') and on the
2346
 * type of the FeatureNode ('Feature' | 'Character')
2347
 *
2348
 * @param array $root_nodes
2349
 * @param array $row_items
2350
 * @param int $level
2351
 *     the depth in the hierarchy
2352
 *
2353
 * @return array
2354
 *  An array of row items to be used in theme_table
2355
 *
2356
 *
2357
 */
2358
function description_element_table_rows($root_nodes, $row_items, $level = 0) {
2359

    
2360
  $indent_string = '&nbsp;&nbsp;&nbsp;';
2361
  foreach ($root_nodes as $root_node) {
2362
    if(isset($root_node->descriptionElements)) {
2363
      foreach ($root_node->descriptionElements as $element) {
2364
        $level_indent = str_pad('', $level * strlen($indent_string), $indent_string);
2365
        switch ($element->class) {
2366
          case 'QuantitativeData':
2367
            $row_items[] = [
2368
              'data' => [
2369
                [
2370
                  'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2371
                  'class' => ['level_' . $level]
2372
                ],
2373
                render_quantitative_statistics($element)
2374
              ],
2375
              'class' => ['level_' . $level, 'has_values', $element->feature->class]
2376
            ];
2377
            break;
2378
          case 'CategoricalData':
2379
            default:
2380
            if (!empty($element->stateData)) {
2381
              $supress_state_display = is_suppress_state_present_display($element, $root_node);
2382
              if(!$supress_state_display){
2383
                $state_cell = render_state_data($element);
2384
              } else {
2385
                $state_cell = "<span> </span>";
2386
              }
2387
              $row_items[] = [
2388
                'data' => [
2389
                  [
2390
                    'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2391
                    'class' => ['level_' . $level]
2392
                  ],
2393
                  $state_cell,
2394
                ],
2395
                'class' => ['level_' . $level, 'has_state', $element->feature->class]
2396
              ];
2397
            }
2398
            break;
2399
        }
2400
      }
2401
    }
2402
    // recurse child nodes
2403
    $row_items = description_element_table_rows($root_node->childNodes, $row_items, $level + 1);
2404
  }
2405
  return $row_items;
2406
}
2407

    
2408
/**
2409
 * @param $element
2410
 * @param $root_node
2411
 *
2412
 * @return bool
2413
 */
2414
function is_suppress_state_present_display($element, $root_node) {
2415
  return count($element->stateData) == 1 & $element->stateData[0]->state->representation_L10n == 'present' && is_array($root_node->childNodes);
2416
}
2417

    
2418

    
2419

    
(3-3/14)