Project

General

Profile

Download (84.3 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
 */
485
  function handle_annotations_and_sources($entity, $config, $inline_text_prefix, $footnote_list_key_suggestion) {
486

    
487
    $annotations_and_sources = array(
488
      'foot_note_keys' => NULL,
489
      'source_references' => [],
490
      'names_used_in_source' => []
491
    );
492

    
493
    // some entity types only have single sources:
494
    $sources = cdm_entity_sources_sorted($entity);
495

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

    
505
          if ($reference_citation) {
506
            if (empty($inline_text_prefix)) {
507
              $annotations_and_sources['source_references'][] = $reference_citation;
508
            } else {
509
              $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
510
            }
511
          }
512

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

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

    
526
      // annotations footnotes separate from sources
527
      $annotations_and_sources['foot_note_keys'] = render_footnote_keys(
528
        cdm_entity_annotations_as_footnote_keys($entity, $footnote_list_key_suggestion), ', '
529
      );
530

    
531
    } // END of references inline
532

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

    
544
    return $annotations_and_sources;
545
  }
546

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

    
568

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

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

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

    
622

    
623
/* ==================== COMPOSE FUNCTIONS =============== */
624

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

    
648
    $block_list = array();
649

    
650
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
651

    
652
    $use_description_features = array(UUID_USE);
653

    
654

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

    
660
      $block_weight = $block_weight + FEATURE_BLOCK_WEIGHT_INCREMENT;
661

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

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

    
671
        $block = feature_block($feature_name, $feature_node->term);
672
        $block->content = array();
673
        $block_content_is_empty = TRUE;
674

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

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

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

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

    
708
        /*
709
         * Content/ALL OTHER FEATURES.
710
         */
711
        else {
712

    
713
          $media_list = array();
714
          $elements_render_array = array();
715
          $child_elements_render_array = null;
716

    
717
          if (isset($feature_node->descriptionElements[0])) {
718
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements, $feature_node->term);
719
          }
720

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

    
742
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
743
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
744

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

    
753
    RenderHints::popFromRenderStack();
754

    
755
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
756

    
757
    ksort($block_list);
758

    
759
    return  $block_list;
760
  }
761

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

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

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

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

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

    
815
        }
816
        if (is_array($child_node_element)) {
817
          $render_arrays[] = $child_node_element;
818
        }
819
      }
820
    }
821

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

    
827
  return $render_arrays;
828
}
829

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

    
843
    if (isset($feature_node->descriptionElements)) {
844
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
845
    }
846

    
847
    $captionElements = array('title', 'rights');
848

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

    
860
    return markup_to_render_array('');
861
  }
862

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

    
884
    $distributionElements = NULL;
885
    $distribution_info_dto = NULL;
886
    $distribution_sortOutArray = FALSE;
887

    
888
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
889

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

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

    
904
    $block = feature_block(
905
      cdm_term_representation($feature, 'Unnamed Feature'),
906
      $feature
907
    );
908
    $block->content = array();
909

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

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

    
930

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

    
937
    // --- Distribution map
938
    $distribution_map_query_parameters = NULL;
939

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

    
950
    $dto_out_array = array();
951

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

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

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

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

    
999
    // --- tree or list
1000
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1001
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1002

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

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

    
1021
      }
1022
      //
1023
      $block->content[] = compose_feature_block_wrap_elements(
1024
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1025
      );
1026
    }
1027

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

    
1035
    $block->content[] = markup_to_render_array(render_footnotes('BIBLIOGRAPHY-' . UUID_DISTRIBUTION));
1036
    $block->content[] = markup_to_render_array(render_footnotes(UUID_DISTRIBUTION));
1037
    $block->content[] = markup_to_render_array(render_annotation_footnotes(UUID_DISTRIBUTION));
1038

    
1039
    return $block;
1040
  }
1041

    
1042

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

    
1064
    $footnote_list_key_suggestion = $feature_uuid;
1065

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

    
1072
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1073

    
1074
    return $render_array;
1075
  }
1076

    
1077

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

    
1091
  $out = '';
1092

    
1093

    
1094
  if (isset($element->description_L10n)) {
1095
    $out .=  ' ' . $element->description_L10n;
1096
  }
1097

    
1098
  if(isset($element->taxon2)){
1099
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1100
  }
1101

    
1102
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1103

    
1104
  return $render_array;
1105
}
1106

    
1107

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

    
1122
  $out = '';
1123

    
1124
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1125

    
1126
  if (isset($element->description_L10n)) {
1127
    $out .=  ' ' . $element->description_L10n;
1128
  }
1129

    
1130
  $out .= drupal_render($render_array);
1131

    
1132
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1133

    
1134
  return $render_array;
1135
}
1136

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

    
1155
  $state_data_markup = render_state_data($element);
1156

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

    
1159
  return $render_array;
1160
}
1161

    
1162
/**
1163
 * @param $element
1164
 *
1165
 * @return string
1166
 * the markup
1167
 */
1168
function render_state_data($element) {
1169

    
1170
  $state_data_items = [];
1171

    
1172
  $out = '';
1173

    
1174
  if (isset($element->stateData)) {
1175
    foreach ($element->stateData as $state_data) {
1176

    
1177
      $state = NULL;
1178

    
1179
      if (isset($state_data->state)) {
1180
        $state = cdm_term_representation($state_data->state);
1181

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

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

    
1206

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

    
1250
  $out = render_quantitative_statistics($element);
1251

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

    
1254
  return $render_array;
1255
}
1256

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

    
1265
  $out = '';
1266
  $type_representation = NULL;
1267
  $min_max = statistical_values_array();
1268
  $sample_size_markup = null;
1269

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

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

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

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

    
1306
  if($sample_size_markup){
1307
    $out .= ' ' . $sample_size_markup;
1308

    
1309
  }
1310

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

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

    
1336

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

    
1360
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1361
    $enclosing_tag = $feature_block_settings['as_list'];
1362

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

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

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

    
1385
    $render_array['elements']['children'] = $description_element_render_arrays;
1386

    
1387
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1388
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1389

    
1390
    return $render_array;
1391
  }
1392

    
1393

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

    
1411
    $plaintext = NULL;
1412
    $markup = NULL;
1413
    $name_in_source_render_array = array();
1414

    
1415
    static $taxon_page_accepted_name = '';
1416
    $taxon_uuid = get_current_taxon_uuid();
1417
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1418

    
1419
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1420
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1421
    }
1422

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

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

    
1458
    return $name_in_source_render_array;
1459
  }
1460

    
1461

    
1462

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

    
1484
    $elements_out_array = array();
1485
    $distribution_tree = null;
1486

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

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

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

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

    
1552
    return $elements_out_array;
1553
  }
1554

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

    
1570
  $common_name_out = '';
1571
  $common_name_feature_elements = array();
1572
  $textData_commonNames = array();
1573

    
1574
  $footnote_key_suggestion = 'common-names-feature-block';
1575

    
1576
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1577

    
1578
  if (is_array($elements)) {
1579
    foreach ($elements as $element) {
1580

    
1581
      if ($element->class == 'CommonTaxonName') {
1582

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

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

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

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

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

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

    
1636

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

    
1642
  }
1643

    
1644
  // Handling commons names as text data.
1645
  $text_data_out = array();
1646

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

    
1655
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1656
    $text_data_out, $feature
1657
  );
1658

    
1659
  $footnotes = render_footnotes('BIBLIOGRAPHY-' . $footnote_key_suggestion);
1660
  $footnotes .= render_footnotes($footnote_key_suggestion); // FIXME is this needed at all?
1661
  $footnotes .= render_annotation_footnotes($footnote_key_suggestion);
1662

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

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

    
1690
  if(!$footnote_key_suggestion) {
1691
    $footnote_key_suggestion = $element->feature->uuid;
1692
  }
1693

    
1694
  $name = '';
1695
  if(isset($element->name)){
1696
    $name = $element->name;
1697
  }
1698

    
1699

    
1700
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1701
}
1702

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

    
1718
  $markup_array = array();
1719
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1720
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1721

    
1722
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1723
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1724

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

    
1733

    
1734
    $status = distribution_status_label_and_markup([$description_element]);
1735

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

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

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

    
1760
    $status_markup = '';
1761
    $status_label = '';
1762

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

    
1771
    };
1772
    return ['label' => $status_label, 'markup' => $status_markup];
1773
  }
1774

    
1775

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

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

    
1799

    
1800
    // 2. find the distribution feature node
1801
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1802

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

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

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

    
1852
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1853
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1854

    
1855
    return $merged_tree;
1856
  }
1857

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

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

    
1883
    $render_array = array();
1884

    
1885
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1886
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1887

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

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

    
1906
    RenderHints::popFromRenderStack();
1907

    
1908
    return $render_array;
1909
  }
1910

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

    
1937
    $level_index++;
1938
    static $enclosingTag = "span";
1939

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

    
1946
    $node_index = -1;
1947
    $per_node_markup = array();
1948

    
1949
    foreach ($tree_nodes as $node){
1950

    
1951
      $per_node_markup[++$node_index] = '';
1952
      $label = $node->nodeId->representation_L10n;
1953

    
1954
      $distributions = $node->data;
1955
      $distribution_uuids = array();
1956
      $distribution_aggregate = NULL;
1957
      $status = ['label' => '', 'markup' => ''];
1958

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

    
1992
      $annotations_and_sources =  null;
1993
      if($distribution_aggregate) {
1994
        $annotations_and_sources = handle_annotations_and_sources(
1995
          $distribution_aggregate,
1996
          handle_annotations_and_sources_config($feature_block_settings),
1997
          $label,
1998
          UUID_DISTRIBUTION
1999
        );
2000

    
2001
        $status = distribution_status_label_and_markup($distribution_aggregate->status, $level_style['status_glue']);
2002
      }
2003

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

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

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

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

    
2037

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

    
2052
  $use_description_content = array();
2053

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

    
2063
  return $use_description_content;
2064
}
2065

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

    
2083
  return $feature;
2084

    
2085
}
2086

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

    
2095
  $out = '';
2096

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

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

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

    
2152
  RenderHints::pushToRenderStack('description_table');
2153

    
2154
  $render_array = [];
2155

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

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

    
2176
    // generate description title
2177
    RenderHints::pushToRenderStack('title');
2178
    if (isset($dataSet)) {
2179

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

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

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

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

    
2236

    
2237
  $root_nodes = get_root_nodes_for_dataset($description);
2238

    
2239

    
2240
  $rows = [];
2241
  $rows = description_element_table_rows($root_nodes, $rows);
2242

    
2243
  // --- create headers
2244
  $header = [0 => [], 1 => []];
2245

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

    
2263
  // ---
2264

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

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

    
2309
  RenderHints::popFromRenderStack();
2310

    
2311
  return $render_array;
2312
}
2313

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

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

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

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

    
2415

    
2416

    
(3-3/14)