Project

General

Profile

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

    
3
const BIBLIOGRAPHY_FOOTNOTE_KEY = PSEUDO_FEATURE_BIBLIOGRAPHY;
4

    
5

    
6
/**
7
 * Returns the localized representations of the modifiers hold by the
8
 * supplied cdm instance concatenated into one string.
9
 *
10
 * @param object $iModifieable
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_modifers_representations($iModifieable, $glue = ', ') {
19
  $modifiers_strings = array();
20
  if (isset($iModifieable->modifiers)) {
21
    foreach ($iModifieable->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: "feature-toc-item-"
140
 * @param string $fragment
141
 *   Optional parameter to define a url fragment different from the $label,
142
 *   if the $fragment is not defined the $label will be used
143
 * @param boolean $as_first_element
144
 *   Place the new item as fist one. This parameter is ignored when $weight is being set
145
 * @param integer $weight
146
 *   Defines the weight for the ordering the item in the toc list.
147
 *   The item will be placed at the end if weigth is NULL.
148
 */
149
function cdm_toc_list_add_item($label, $class_attribute_suffix, $fragment = NULL, $as_first_element = FALSE, $weight = null) {
150

    
151
  $toc_list_items = &cdm_toc_list();
152

    
153
  if (!$fragment) {
154
    $fragment = $label;
155
  }
156
  $fragment = generalizeString($fragment);
157

    
158
  $class_attributes = 'feature-toc-item-' . $class_attribute_suffix;
159

    
160
  $new_item = toc_list_item(
161
    theme(
162
      'cdm_feature_name',
163
      array('feature_name' => $label)),
164
      array('class' => $class_attributes),
165
      $fragment
166
    );
167

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

    
181
}
182

    
183
/**
184
 * Returns the statically cached table of content items as render array.
185
 *
186
 * @see cdm_toc_list_add_item()
187
 *
188
 * @return array
189
 *   a render array of table of content items suitable for theme_item_list()
190
 */
191
function &cdm_toc_list(){
192
  $toc_list_items = &drupal_static('toc_list_items', array());
193

    
194
  return $toc_list_items;
195
}
196

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

    
226

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

    
254
    case "MediaKey":
255
      $cdm_ws_pasepath = CDM_WS_MEDIAKEY;
256
      break;
257

    
258
    case "MultiAccessKey":
259
      $cdm_ws_pasepath = CDM_WS_MULTIACCESSKEY;
260
      break;
261

    
262
  }
263

    
264
  if (!$cdm_ws_pasepath) {
265
    drupal_set_message(t('Type parameter is not valid: ') . $type, 'error');
266
  }
267

    
268
  $queryParameters = '';
269
  if (is_numeric($pageSize)) {
270
    $queryParameters = "pageSize=" . $pageSize;
271
  }
272
  else {
273
    $queryParameters = "pageSize=0";
274
  }
275

    
276
  if (is_numeric($pageNumber)) {
277
    $queryParameters = "pageNumber=" . $pageNumber;
278
  }
279
  else {
280
    $queryParameters = "pageNumber=0";
281
  }
282
  $queryParameters = NULL;
283
  if ($taxonUuid) {
284
    $queryParameters = "findByTaxonomicScope=$taxonUuid";
285
  }
286
  $pager = cdm_ws_get($cdm_ws_pasepath, NULL, $queryParameters);
287

    
288
  if (!$pager || $pager->count == 0) {
289
    return array();
290
  }
291
  return $pager->records;
292
}
293

    
294

    
295
/**
296
 * Creates a list item for a table of content, suitable as data element for a themed list
297
 *
298
 * @see theme_list()
299
 *
300
 * @param $label
301
 * @param $http_request_params
302
 * @param $attributes
303
 * @return array
304
 */
305
function toc_list_item($label, $attributes = array(), $fragment = null) {
306

    
307
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
308
  $http_request_params = drupal_static('http_request_params', drupal_get_query_parameters());
309

    
310
  $item =  array(
311
    'data' => l(
312
      $label,
313
      $_GET['q'],
314
      array(
315
        'attributes' => array('class' => array('toc')),
316
        'fragment' => generalizeString($label),
317
        'query' => $http_request_params,
318
      )
319
    ),
320
  );
321
  $item['attributes'] = $attributes;
322
  return $item;
323
}
324

    
325
/**
326
 * Creates the footnotes for the given CDM instance.
327
 *
328
 * Footnotes are created for annotations and original sources whereas the resulting footnote keys depend on the
329
 * parameters $footnote_list_key_suggestion and $is_bibliography_aware, see parameter $footnote_list_key_suggestion
330
 * for more details.
331
 *
332
 * possible keys for
333
 *     - annotation footnotes:
334
 *       - $footnote_list_key_suggestion
335
 *       - RenderHints::getFootnoteListKey().'-annotations'
336
 *     - original source footnotes
337
 *       - "BIBLIOGRAPHY" (when !$is_bibliography_aware && bibliography_settings['enabled'] == 1 )
338
 *       - "BIBLIOGRAPHY-$footnote_list_key_suggestion" (when !$is_bibliography_aware && bibliography_settings['enabled'] == 0 )
339
 *       - $footnote_list_key_suggestion (when $is_bibliography_aware)
340
 *
341
 * @param $descriptionElement
342
 *   A CDM DescriptionElement instance
343
 * @param $separator
344
 *   Optional parameter. The separator string to concatenate the footnote ids, default is ','
345
 * @param $footnote_list_key_suggestion string
346
 *    Optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be determined by the nested
347
 *    method calls by calling RenderHints::getFootnoteListKey(). NOTE: the footnote key for annotations will be set to
348
 *    RenderHints::getFootnoteListKey().'-annotations'. @see cdm_annotations_as_footnotekeys()
349
 *    For original sources the $footnote_list_key_suggestion will be overwritten by bibliography_footnote_list_key() when
350
 *    $is_bibliography_aware is set TRUE.
351
 * @$original_source_footnote_tag
352
 *    null will cause bibliography_footnote_list_key to use the default
353
 *
354
 * @return String
355
 *   The foot note keys
356
 */
357
function cdm_create_footnotes(
358
    $description_element,
359
    $separator = ',',
360
    $footnote_list_key_suggestion = null,
361
    $do_link_to_reference = FALSE,
362
    $do_link_to_name_used_in_source = FALSE,
363
    $is_bibliography_aware = FALSE
364
  ){
365

    
366
  $sources = cdm_entity_sources_sorted($description_element);
367

    
368
  // Annotations as footnotes.
369
  $footNoteKeys = cdm_entity_annotations_as_footnotekeys($description_element, $footnote_list_key_suggestion);
370

    
371
  // Source references as footnotes.
372
  if($is_bibliography_aware){
373
    $bibliography_settings = get_bibliography_settings();
374
    $sources_footnote_list_key = bibliography_footnote_list_key($footnote_list_key_suggestion);
375
    $original_source_footnote_tag = $bibliography_settings['enabled'] == 1 ? 'div' : null; // null will cause bibliography_footnote_list_key to use the default
376
  } else {
377
    $sources_footnote_list_key = $footnote_list_key_suggestion;
378
    if(!$sources_footnote_list_key) {
379
      RenderHints::getFootnoteListKey();
380
    }
381
    $original_source_footnote_tag = NULL;
382
  }
383

    
384
  foreach ($sources as $source) {
385
    if (_is_original_source_type($source)) {
386
      $fn_key = FootnoteManager::addNewFootnote(
387
        $sources_footnote_list_key,
388
        render_original_source(
389
          $source,
390
          $do_link_to_reference,
391
          $do_link_to_name_used_in_source
392
        ),
393
        $original_source_footnote_tag
394
      );
395
      // Ensure uniqueness of the footnote keys.
396
      cdm_add_footnote_to_array($footNoteKeys, $fn_key);
397
    }
398
  }
399
  // Sort and render footnote keys.
400
  $footnoteKeyListStr = '';
401
  asort($footNoteKeys);
402
  foreach ($footNoteKeys as $footNoteKey) {
403
    try{
404
      $footnoteKeyListStr .= theme('cdm_footnote_key',
405
        array(
406
          'footnoteKey' => $footNoteKey,
407
          'separator' => ($footnoteKeyListStr ? $separator : '')));
408
    } catch (Exception $e) {
409
      drupal_set_message("Exception: " . $e->getMessage(),  'error');
410
    }
411
  }
412
  return $footnoteKeyListStr;
413
}
414

    
415

    
416
/**
417
 * Compare callback to be used in usort() to sort render arrays produced by compose_description_element().
418
 *
419
 * @param $a
420
 * @param $b
421
 */
422
function compare_description_element_render_arrays($a, $b){
423
  if ($a['#value'].$a['#value-suffix'] == $b['#value'].$b['#value-suffix']) {
424
    return 0;
425
  }
426
  return ($a['#value'].$a['#value-suffix'] < $b['#value'].$b['#value-suffix']) ? -1 : 1;
427

    
428
}
429

    
430

    
431
/**
432
 * @param $render_array
433
 * @param $element
434
 * @param $feature_block_settings
435
 * @param $element_markup
436
 * @param $footnote_list_key_suggestion
437
 */
438
function compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label = FALSE)
439
{
440

    
441
  $render_array = array(
442
    '#type' => 'html_tag',
443
    '#tag' => cdm_feature_block_element_tag_name($feature_block_settings),
444

    
445
    '#attributes' => array(
446
      'class' => array(
447
        'DescriptionElement',
448
        'DescriptionElement-' . $element->class,
449
        html_class_attribute_ref($element)
450
      )
451
    ),
452

    
453
    '#value' => '',
454
    '#value_suffix' => NULL
455

    
456
  );
457

    
458
  $annotations_and_sources = handle_annotations_and_sources(
459
    $element,
460
    handle_annotations_and_sources_config($feature_block_settings),
461
    $element_markup,
462
    $footnote_list_key_suggestion
463
  );
464

    
465
  $timescope_markup = '';
466
  if(isset($element->timeperiod)){
467
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, true);
468
  }
469

    
470
  // handle the special case were the TextData is used as container for original source with name
471
  // used in source information without any text stored in it.
472
  $names_used_in_source_markup = '';
473
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
474
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
475
    // remove all <span class="nameUsedInSource">...</span> from all source_references
476
    // these are expected to be at the end of the strings
477
    $pattern = '/ <span class="nameUsedInSource">.*$/';
478
    foreach( $annotations_and_sources['source_references'] as &$source_reference){
479
      $source_reference = preg_replace($pattern , '', $source_reference);
480
    }
481
  }
482

    
483
  $source_references_markup = '';
484
  if (!empty($annotations_and_sources['source_references'])) {
485
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
486
  }
487

    
488
  $feature_label = '';
489
  if ($prepend_feature_label) {
490
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
491
  }
492
  $content_markup = $names_used_in_source_markup . $element_markup . $timescope_markup . $source_references_markup;
493

    
494
  if(!$content_markup && $feature_block_settings['sources_as_content'] !== 1){
495
    // no textual content? So skip this element completely, even if there could be an footnote key
496
    // see #4379
497
    return null;
498
  }
499

    
500
    $render_array['#value'] = $feature_label . $content_markup;
501
    $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
502
  return $render_array;
503
}
504

    
505
/**
506
 * Creates a handle_annotations_and_sources configuration array from feature_block_settings.
507
 *
508
 * The handle_annotations_and_sources configuration array is meant to be used for the
509
 * method handle_annotations_and_sources().
510
 *
511
 * @param $feature_block_settings array
512
 *
513
 * @return array
514
 *   The configuration array for handle_annotations_and_sources()
515
 */
516
function handle_annotations_and_sources_config($feature_block_settings){
517

    
518
  $config = $feature_block_settings;
519
  unset($config['sources_as_content_to_bibliography']);
520
  $config['add_footnote_keys'] = 0;
521
  if($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
522
    $config['add_footnote_keys'] = 1;
523
  }
524
  $config['bibliography_aware'] = 1;
525

    
526
  return $config;
527
}
528

    
529
  /**
530
   * @param $entity
531
   * @param $config array
532
   *   An associative array to configure the display of the annotations and sources.
533
   *   The array has the following keys
534
   *   - sources_as_content
535
   *   - link_to_name_used_in_source
536
   *   - link_to_reference
537
   *   - add_footnote_keys
538
   *   - bibliography_aware
539
   *   Valid values are 1 or 0.
540
   * @param $inline_text_prefix
541
   *   Only used to decide if the source references should be enclosed in brackets or not when displayed inline.
542
   *   This text will not be included into the response.
543
   * @param $footnote_list_key_suggestion string
544
   *    optional parameter. If this paramter is left empty (null, 0, "") the footnote key will be determined by the nested
545
   *    method calls by calling RenderHints::getFootnoteListKey(). NOTE: the footnore key for annotations will be set to
546
   *    RenderHints::getFootnoteListKey().'-annotations'. @see cdm_annotations_as_footnotekeys()
547
   *
548
   * @return array
549
   *   an associative array with the following elements:
550
   *   - foot_note_keys: all footnote keys as markup
551
   *   - source_references: an array of the source references citations
552
   *   - names used in source: an associative array of the names in source,
553
   *        the name in source strings are de-duplicated
554
   *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
555
   */
556
  function handle_annotations_and_sources($entity, $config, $inline_text_prefix, $footnote_list_key_suggestion) {
557

    
558
    $annotations_and_sources = array(
559
      'foot_note_keys' => NULL,
560
      'source_references' => array(),
561
      'names_used_in_source' => array()
562
    );
563

    
564
    // some entity types only have single sources:
565
    $sources = cdm_entity_sources_sorted($entity);
566

    
567
    if ($config['sources_as_content'] == 1) {
568
      foreach ($sources as $source) {
569
        if (_is_original_source_type($source)) {
570
          $reference_citation = render_original_source(
571
            $source,
572
            $config['link_to_reference'] == 1,
573
            $config['link_to_name_used_in_source'] == 1
574
          );
575

    
576
          if ($reference_citation) {
577
            if (empty($inline_text_prefix)) {
578
              $annotations_and_sources['source_references'][] = $reference_citation;
579
            } else {
580
              $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
581
            }
582
          }
583

    
584
          // also put the name in source into the array, these are already included in the $reference_citation but are
585
          // still required to be available separately in some contexts.
586
          $name_in_source_render_array = compose_name_in_source(
587
            $source,
588
            $config['link_to_name_used_in_source'] == 1
589
          );
590

    
591
          if (!empty($name_in_source_render_array)) {
592
            $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
593
          }
594
        }
595
      } // END of loop over sources
596

    
597
    // annotations footnotes separate.
598
    $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
599
      array(
600
        'cdmBase_list' => $entity,
601
        'footnote_list_key' => $footnote_list_key_suggestion,
602
      )
603
    );
604

    
605
    } // END of references inline
606

    
607
    // footnotes for sources and annotations or put into into bibliography if requested ...
608
    if ($config['add_footnote_keys'] == 1) {
609
        $annotations_and_sources['foot_note_keys'] = cdm_create_footnotes(
610
          $entity, ',',
611
          $footnote_list_key_suggestion,
612
          $config['link_to_reference'] == 1,
613
          $config['link_to_name_used_in_source'] == 1,
614
          !empty($config['bibliography_aware'])
615
        );
616
    }
617

    
618
    return $annotations_and_sources;
619
  }
620

    
621
/**
622
 * Get the source or the sources from a cdm entity and return them ordered by see compare_original_sources()
623
 * (Some entity types only have single sources)
624
 * @param $entity
625
 *
626
 * @return array
627
 */
628
function cdm_entity_sources_sorted($entity) {
629
  if (isset($entity->source) && is_object($entity->source)) {
630
    $sources = [$entity->source];
631
  }
632
  else if (isset($entity->sources)) {
633
    $sources = $entity->sources;
634
  }
635
  else {
636
    $sources = [];
637
  }
638
  usort($sources, 'compare_original_sources');
639
  return $sources;
640
}
641

    
642

    
643
/**
644
   * This method determines the footnote key for original sources to be shown in the bibliography block
645
   *
646
   * The footnote key depends on the value of the 'enabled' value of the bibliography_settings
647
   *    - enabled == 1 -> "BIBLIOGRAPHY"
648
   *    - enabled == 0 -> "BIBLIOGRAPHY-$key_suggestion"
649
   *
650
   * @see get_bibliography_settings() and @see constant BIBLIOGRAPHY_FOOTNOTE_KEY
651
   *
652
   * @param $key_suggestion string
653
   *    optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be retrieved by
654
   *    calling RenderHints::getFootnoteListKey().
655

    
656
   *
657
   * @return string
658
   *  the footnote_list_key
659
   */
660
  function bibliography_footnote_list_key($key_suggestion = null) {
661
    if(!$key_suggestion){
662
      $key_suggestion = RenderHints::getFootnoteListKey();
663
    }
664
    $bibliography_settings = get_bibliography_settings();
665
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? BIBLIOGRAPHY_FOOTNOTE_KEY : BIBLIOGRAPHY_FOOTNOTE_KEY . '-' . $key_suggestion;
666
    return $footnote_list_key;
667
  }
668

    
669
  /**
670
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
671
   *
672
   * @param $feature_block_settings
673
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
674
   */
675
  function cdm_feature_block_element_tag_name($feature_block_settings){
676
    switch ($feature_block_settings['as_list']){
677
      case 'ul':
678
      case 'ol':
679
        return 'li';
680
      case 'div':
681
        if(isset($feature_block_settings['element_tag'])){
682
          return $feature_block_settings['element_tag'];
683
        }
684
        return 'span';
685
      case 'dl':
686
        return 'dd';
687
      default:
688
        return 'div'; // should never happen, throw error instead?
689
    }
690
  }
691

    
692

    
693
/* ==================== COMPOSE FUNCTIONS =============== */
694

    
695
  /**
696
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
697
   *
698
   * The taxon profile consists of drupal block elements, one for the description elements
699
   * of a specific feature. The structure is defined by specific FeatureTree.
700
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
701
   *
702
   * The merged nodes can be obtained by making use of the
703
   * function cdm_ws_descriptions_by_featuretree().
704
   *
705
   * @see cdm_ws_descriptions_by_featuretree()
706
   *
707
   * @param $mergedFeatureNodes
708
   *
709
   * @param $taxon
710
   *
711
   * @return array
712
   *  A Drupal render array containing feature blocks and the table of content
713
   *
714
   * @ingroup compose
715
   */
716
  function make_feature_block_list($mergedFeatureNodes, $taxon) {
717

    
718
    $block_list = array();
719

    
720
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
721

    
722
    $use_description_features = array(UUID_USE);
723

    
724

    
725
    RenderHints::pushToRenderStack('feature_block');
726
    // Create a drupal block for each feature
727
    $block_weight = - FEATURE_BLOCK_WEIGHT_INCREMENT;
728
    foreach ($mergedFeatureNodes as $feature_node) {
729

    
730
      $block_weight = $block_weight + FEATURE_BLOCK_WEIGHT_INCREMENT;
731

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

    
735
        RenderHints::pushToRenderStack($feature_node->term->uuid);
736
          
737
        $feature_name = cdm_term_representation($feature_node->term, 'Unnamed Feature');
738
        $feature_block_settings = get_feature_block_settings($feature_node->term->uuid);
739
        
740

    
741
        $block = feature_block($feature_name, $feature_node->term);
742
        $block->content = array();
743
        $block_content_is_empty = TRUE;
744

    
745
        if(array_search($feature_node->term->uuid, $use_description_features) !== false) {
746
          // do not show features which belong to the UseDescriptions, these are
747
          // handled by compose_feature_block_items_use_records() where the according descriptions are
748
          // fetched again separately.
749
          // UseDescriptions are a special feature introduced for palmweb
750
          continue;
751
        }
752

    
753
        /*
754
         * Content/DISTRIBUTION.
755
         */
756
        if ($feature_node->term->uuid == UUID_DISTRIBUTION) {
757
          $block = compose_feature_block_distribution($taxon, $feature_node->descriptionElements, $feature_node->term);
758
          $block_content_is_empty = FALSE;
759
        }
760

    
761
        /*
762
         * Content/COMMON_NAME.
763
         */
764
        else if ($feature_node->term->uuid == UUID_COMMON_NAME) {
765
          $common_names_render_array = compose_feature_block_items_feature_common_name($feature_node->descriptionElements, $feature_node->term);
766
          $block->content[] = $common_names_render_array;
767
          $block_content_is_empty = FALSE;
768
        }
769

    
770
        /*
771
         * Content/Use Description (Use + UseRecord)
772
         */
773
        else if ($feature_node->term->uuid == UUID_USE_RECORD) {
774
          $block->content[] = cdm_block_use_description_content($taxon->uuid, $feature_node->term);
775
          $block_content_is_empty = FALSE;
776
        }
777

    
778
        /*
779
         * Content/ALL OTHER FEATURES.
780
         */
781
        else {
782

    
783
          $media_list = array();
784
          $elements_render_array = array();
785
          $child_elements_render_array = null;
786

    
787
          if (isset($feature_node->descriptionElements[0])) {
788
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements, $feature_node->term);
789
          }
790

    
791
          // Content/ALL OTHER FEATURES/Subordinate Features
792
          // subordinate features are printed inline in one floating text,
793
          // it is expected hat subordinate features can "contain" TextData,
794
          // Qualitative- and Qualitative- DescriptionElements
795
          if (isset($feature_node->childNodes[0])) {
796
            $child_elements_render_array = compose_feature_block_items_nested($feature_node, $media_list, $feature_block_settings);
797
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
798
          }
799
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
800
          if(!$block_content_is_empty){
801
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $feature_node->term, $feature_block_settings['glue']);
802
            $block->content[] = compose_feature_media_gallery($feature_node, $media_list, $gallery_settings);
803
            /*
804
             * Footnotes for the feature block
805
             */
806
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => PSEUDO_FEATURE_BIBLIOGRAPHY . '-' . $feature_node->term->uuid)));
807
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $feature_node->term->uuid)));
808
            $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $feature_node->term->uuid)));
809
          }
810
        } // END all other features
811

    
812
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
813
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
814

    
815
        if(!$block_content_is_empty){ // skip empty block content
816
          $block_list[$block_weight] = $block;
817
          cdm_toc_list_add_item(cdm_term_representation($feature_node->term), $feature_node->term->uuid, null, FALSE, $block_weight);
818
        } // END: skip empty block content
819
      } // END: skip empty or suppressed features
820
      RenderHints::popFromRenderStack();
821
    } // END: creating a block per feature
822

    
823
    RenderHints::popFromRenderStack();
824

    
825
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
826

    
827
    ksort($block_list);
828

    
829
    return  $block_list;
830
  }
831

    
832
/**
833
 * Creates a render array of description elements  held by child nodes of the given feature node.
834
 *
835
 * This function is called recursively!
836
 *
837
 * @param $feature_node
838
 *   The feature node.
839
 * @param array $media_list
840
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
841
 * @param $feature_block_settings
842
 *   The feature block settings.
843
 * @param $main_feature
844
 *  Only used internally in recursive calls.
845
 *
846
 * @return array
847
 *  A Drupal render array
848
 *
849
 * @ingroup compose
850
 */
851
function compose_feature_block_items_nested($feature_node, &$media_list, $feature_block_settings, $main_feature = NULL)
852
{
853

    
854
  if(!$main_feature){
855
    $main_feature = $feature_node->term;
856
  }
857
  /*
858
   * TODO should be configurable, options; YES, NO, AUTOMATIC
859
   * (automatic will only place the label if the first word of the description element text is not the same)
860
   */
861
  $prepend_feature_label = false;
862

    
863
  $render_arrays = array();
864
  foreach ($feature_node->childNodes as $child_node) {
865
    if (isset($child_node->descriptionElements[0])) {
866
      foreach ($child_node->descriptionElements as $element) {
867

    
868
        if (isset($element->media[0])) {
869
          // Append media of subordinate elements to list of main
870
          // feature.
871
          $media_list = array_merge($media_list, $element->media);
872
        }
873

    
874
        $child_node_element = null;
875
        switch ($element->class) {
876
          case 'TextData':
877
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
878
            break;
879
          case 'CategoricalData':
880
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
881
            break;
882
          case 'QuantitativeData':
883
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
884

    
885
        }
886
        if (is_array($child_node_element)) {
887
          $render_arrays[] = $child_node_element;
888
        }
889
      }
890
    }
891

    
892
    if(isset($child_node->childNodes[0])){
893
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
894
    }
895
  }
896

    
897
  return $render_arrays;
898
}
899

    
900
  /**
901
   *
902
   * @param $feature_node
903
   *  The merged feature three node which potentially contains media in its description elements.
904
   * @param $media_list
905
   *    Additional media to be merged witht the media contained in the nodes description elements
906
   * @param $gallery_settings
907
   * @return array
908
   *
909
   * @ingroup compose
910
   */
911
  function compose_feature_media_gallery($feature_node, $media_list, $gallery_settings) {
912

    
913
    if (isset($feature_node->descriptionElements)) {
914
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
915
    }
916

    
917
    $captionElements = array('title', 'rights');
918

    
919
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
920
      $gallery = compose_cdm_media_gallerie(array(
921
        'mediaList' => $media_list,
922
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $feature_node->term->uuid,
923
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
924
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
925
        'captionElements' => $captionElements,
926
      ));
927
      return markup_to_render_array($gallery);
928
    }
929

    
930
    return markup_to_render_array('');
931
  }
932

    
933
  /**
934
   * Composes the distribution feature block for a taxon
935
   *
936
   * @param $taxon
937
   * @param $descriptionElements
938
   *   an associative array with two elements:
939
   *   - '#type': must be 'DTO'
940
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
941
   * @param $feature
942
   *
943
   * @return array
944
   *  A drupal render array
945
   *
946
   * @ingroup compose
947
   */
948
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
949
    $text_data_glue = '';
950
    $text_data_sortOutArray = FALSE;
951
    $text_data_enclosingTag = 'ul';
952
    $text_data_out_array = array();
953

    
954
    $distributionElements = NULL;
955
    $distribution_info_dto = NULL;
956
    $distribution_sortOutArray = FALSE;
957

    
958
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
959

    
960
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
961
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
962
      $distribution_glue = '';
963
      $distribution_enclosingTag = 'dl';
964
    } else {
965
      $distribution_glue = '';
966
      $distribution_enclosingTag = 'ul';
967
    }
968

    
969
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
970
      // skip the DISTRIBUTION section if there is no DTO type element
971
      return array(); // FIXME is it ok to return an empty array?
972
    }
973

    
974
    $block = feature_block(
975
      cdm_term_representation($feature, 'Unnamed Feature'),
976
      $feature
977
    );
978
    $block->content = array();
979

    
980
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
981
    if (isset($descriptionElements['TextData'])) {
982
      // --- TextData
983
      foreach ($descriptionElements['TextData'] as $text_data_element) {
984
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
985
        $repr = drupal_render($text_data_render_array);
986

    
987
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
988
          $text_data_out_array[] = $repr;
989
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
990
          // not work since this array contains html attributes with uuids
991
          // and what is about cases like the bibliography where
992
          // any content can be prefixed with some foot-note anchors?
993
          $text_data_sortOutArray = TRUE;
994
          $text_data_glue = '<br/> ';
995
          $text_data_enclosingTag = 'p';
996
        }
997
      }
998
    }
999

    
1000

    
1001
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1002
      $block->content[] = compose_feature_block_wrap_elements(
1003
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1004
      );
1005
    }
1006

    
1007
    // --- Distribution map
1008
    $distribution_map_query_parameters = NULL;
1009

    
1010
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
1011
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
1012
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
1013
      )
1014
    {
1015
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
1016
    }
1017
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
1018
    $block->content[] = $map_render_element;
1019

    
1020
    $dto_out_array = array();
1021

    
1022
    // --- Condensed Distribution
1023
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
1024
      $condensed_distribution_markup = '<p class="condensed_distribution">';
1025

    
1026
      $isFirst = true;
1027
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
1028
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
1029
          if(!$isFirst){
1030
            $condensed_distribution_markup .= ' ';
1031
          }
1032
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
1033
          . $cdItem->areaStatusLabel . '</span>';
1034
          $isFirst = false;
1035
        }
1036
      }
1037

    
1038
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
1039
        if(!$isFirst){
1040
          $condensed_distribution_markup .= ' ';
1041
        }
1042
        $isFirst = TRUE;
1043
        $condensed_distribution_markup .= '[';
1044
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
1045
          if (!$isFirst) {
1046
            $condensed_distribution_markup .= ' ';
1047
          }
1048
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
1049
            . $cdItem->areaStatusLabel . '</span>';
1050
          $isFirst = false;
1051
        }
1052
        $condensed_distribution_markup .= ']';
1053
      }
1054

    
1055
      $condensed_distribution_markup .= '&nbsp;' . l(
1056
          font_awesome_icon_markup(
1057
            'fa-info-circle',
1058
            array(
1059
              'alt'=>'help',
1060
              'class' => array('superscript')
1061
            )
1062
          ),
1063
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
1064
          array('html' => TRUE));
1065
      $condensed_distribution_markup .= '</p>';
1066
      $dto_out_array[] = $condensed_distribution_markup;
1067
    }
1068

    
1069
    // --- tree or list
1070
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1071
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1072

    
1073
      // --- tree
1074
      if (is_object($distribution_info_dto->tree)) {
1075
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
1076
        $dto_out_array[] = $distribution_tree_render_array;
1077
      }
1078

    
1079
      // --- sorted element list
1080
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
1081
        foreach ($distribution_info_dto->elements as $descriptionElement) {
1082
          if (is_object($descriptionElement->area)) {
1083
            $sortKey = $descriptionElement->area->representation_L10n;
1084
            $distributionElements[$sortKey] = $descriptionElement;
1085
          }
1086
        }
1087
        ksort($distributionElements);
1088
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
1089
        $dto_out_array[] = $distribution_element_render_array;
1090

    
1091
      }
1092
      //
1093
      $block->content[] = compose_feature_block_wrap_elements(
1094
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1095
      );
1096
    }
1097

    
1098
    // --- TextData at the bottom
1099
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1100
      $block->content[] = compose_feature_block_wrap_elements(
1101
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1102
      );
1103
    }
1104

    
1105
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
1106
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1107
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1108

    
1109
    return $block;
1110
  }
1111

    
1112

    
1113
  /**
1114
   * Composes a drupal render array for single CDM TextData description element.
1115
   *
1116
   * @param $element
1117
   *    The CDM TextData description element.
1118
   *  @param $feature_uuid
1119
   * @param bool $prepend_feature_label
1120
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1121
   *
1122
   * @return array
1123
   *   A drupal render array with the following elements being used:
1124
   *    - #tag: either 'div', 'li', ...
1125
   *    ⁻ #attributes: class attributes
1126
   *    - #value_prefix: (optionally) contains footnote anchors
1127
   *    - #value: contains the textual content
1128
   *    - #value_suffix: (optionally) contains footnote keys
1129
   *
1130
   * @ingroup compose
1131
   */
1132
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
1133

    
1134
    $footnote_list_key_suggestion = $feature_uuid;
1135

    
1136
    $element_markup = '';
1137
    if (isset($element->multilanguageText_L10n->text)) {
1138
      // TODO replacement of \n by <br> should be configurable
1139
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
1140
    }
1141

    
1142
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1143

    
1144
    return $render_array;
1145
  }
1146

    
1147

    
1148
/**
1149
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
1150
 *
1151
 * @param $element
1152
 *  The CDM TaxonInteraction entity
1153
 *
1154
 * @return
1155
 *  A drupal render array
1156
 *
1157
 * @ingroup compose
1158
 */
1159
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
1160

    
1161
  $out = '';
1162

    
1163

    
1164
  if (isset($element->description_L10n)) {
1165
    $out .=  ' ' . $element->description_L10n;
1166
  }
1167

    
1168
  if(isset($element->taxon2)){
1169
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1170
  }
1171

    
1172
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1173

    
1174
  return $render_array;
1175
}
1176

    
1177

    
1178
/**
1179
 * Renders a single instance of the type IndividualsAssociations.
1180
 *
1181
 * @param $element
1182
 *   The CDM IndividualsAssociations entity.
1183
 * @param $feature_block_settings
1184
 *
1185
 * @return array
1186
 *   Drupal render array
1187
 *
1188
 * @ingroup compose
1189
 */
1190
function compose_description_element_individuals_association($element, $feature_block_settings) {
1191

    
1192
  $out = '';
1193

    
1194
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1195

    
1196
  if (isset($element->description_L10n)) {
1197
    $out .=  ' ' . $element->description_L10n;
1198
  }
1199

    
1200
  $out .= drupal_render($render_array);
1201

    
1202
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1203

    
1204
  return $render_array;
1205
}
1206

    
1207
/**
1208
 * Renders a single instance of the type CategoricalData.
1209
 *
1210
 * @param $element
1211
 *  The CDM CategoricalData entity
1212
 *
1213
 * @param $feature_block_settings
1214
 *
1215
 * @param bool $prepend_feature_label
1216
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1217
 *
1218
 * @return array
1219
 *   a drupal render array for given CategoricalData element
1220
 *
1221
 * @ingroup compose
1222
 */
1223
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1224

    
1225
  $state_data_markup = render_state_data($element);
1226

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

    
1229
  return $render_array;
1230
}
1231

    
1232
/**
1233
 * @param $element
1234
 *
1235
 * @return string
1236
 * the markup
1237
 */
1238
function render_state_data($element) {
1239

    
1240
  $state_data_items = [];
1241

    
1242
  if (isset($element->stateData)) {
1243
    foreach ($element->stateData as $state_data) {
1244

    
1245
      $state = NULL;
1246

    
1247
      if (isset($state_data->state)) {
1248
        $state = cdm_term_representation($state_data->state);
1249

    
1250
          $sample_count = 0;
1251
          if (isset($state_data->count)) {
1252
            $sample_count = $state_data->count;
1253
            $state .= ' [' . $state_data->count . ']';
1254
          }
1255
    
1256
          if (isset($state_data->modifyingText_L10n)) {
1257
            $state .= ' ' . $state_data->modifyingText_L10n;
1258
          }
1259
    
1260
          $modifiers_strings = cdm_modifers_representations($state_data);
1261
          $state_data_markup = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1262
          // we could use strip_tags() to reduce the markup to text for the key but this is expensive
1263
          $sort_key = str_pad($sample_count, 6, '0', STR_PAD_LEFT) . '_' . $state_data_markup;
1264
          $state_data_items[$sort_key] = $state_data_markup;
1265
      }
1266

    
1267
    }
1268
    krsort($state_data_items);
1269
    $out = '<span class="' . html_class_attribute_ref($element) . '">' . join(', ', $state_data_items) .  '</span>';
1270
  }
1271
  return $out;
1272
}
1273

    
1274

    
1275
/**
1276
 * Theme function to render CDM DescriptionElements of the type QuantitativeData.
1277
 *
1278
 * The function renders the statisticalValues contained in the QuantitativeData
1279
 * entity according to the following scheme:
1280
 *
1281
 * (ExtremeMin)-Min-Average-Max-(ExtremeMax)
1282
 *
1283
 * All modifiers of these values are appended.
1284
 *
1285
 * If the QuantitativeData is containing more statisticalValues with further
1286
 * statisticalValue types, these additional measures will be appended to the
1287
 * above string separated by whitespace.
1288
 *
1289
 * Special cases;
1290
 * 1. Min==Max: this will be interpreted as Average
1291
 *
1292
 * @param $element
1293
 *  The CDM QuantitativeData entity
1294
 *
1295
 * @param $feature_block_settings
1296
 *
1297
 * @param bool $prepend_feature_label
1298
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1299
 *
1300
 *
1301
 * @return array
1302
 *   drupal render array for the given QuantitativeData element
1303
 *
1304
 * @ingroup compose
1305
 */
1306
function compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1307
  /*
1308
   * - statisticalValues
1309
   *   - value
1310
   *   - modifiers
1311
   *   - type
1312
   * - unit->representation_L10n
1313
   * - modifyingText
1314
   * - modifiers
1315
   * - sources
1316
   */
1317

    
1318
  $out = render_quantitative_statistics($element);
1319

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

    
1322
  return $render_array;
1323
}
1324

    
1325
/**
1326
 * Composes the HTML for quantitative statistics
1327
 * @param $element
1328
 *
1329
 * @return string
1330
 */
1331
function render_quantitative_statistics($element) {
1332

    
1333
  $out = '';
1334
  $type_representation = NULL;
1335
  $min_max = statistical_values_array();
1336
  $sample_size_markup = null;
1337

    
1338
  if (isset($element->statisticalValues)) {
1339
    $out = '<span class=\"' . html_class_attribute_ref($element) . '\">';
1340
    $other_values_markup = [];
1341
    foreach ($element->statisticalValues as $statistical_val) {
1342

    
1343
      // compile the full value string which also may contain modifiers
1344
      if (isset($statistical_val->value)) {
1345
        $statistical_val->_value = $statistical_val->value;
1346
      }
1347
      $val_modifiers_strings = cdm_modifers_representations($statistical_val);
1348
      if ($val_modifiers_strings) {
1349
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1350
      }
1351

    
1352
      // either put into min max array or into $other_values
1353
      // for generic output to be appended to 'min-max' string
1354
      if (array_key_exists(statistical_measure_term2min_max_key($statistical_val->type), $min_max)) {
1355
        $min_max[statistical_measure_term2min_max_key($statistical_val->type)] = $statistical_val;
1356
      }
1357
      else {
1358
        drupal_set_message("Unsupported statistical value type: " . $statistical_val->type->uuid, "error");
1359
      }
1360
    } // end of loop over statisticalValues
1361

    
1362
    // create markup
1363
    $unit = null;
1364
    if (isset($element->unit)) {
1365
      $unit = ' <span class="unit" title="'
1366
        . cdm_term_representation($element->unit) . '">'
1367
        . cdm_term_representation_abbreviated($element->unit)
1368
        . '</span>';
1369
    }
1370
    $min_max_markup = statistical_values($min_max, $unit);
1371
    $out .= $min_max_markup . '</span>';
1372
  }
1373

    
1374
  if($sample_size_markup){
1375
    $out .= ' ' . $sample_size_markup;
1376

    
1377
  }
1378

    
1379
  // modifiers of the description element itself
1380
  $modifier_string = cdm_modifers_representations($element);
1381
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1382
  if (isset($element->modifyingText_L10n)) {
1383
    $out = $element->modifyingText_L10n . ' ' . $out;
1384
  }
1385
  return $out;
1386
}
1387

    
1388
function statistical_measure_term2min_max_key($term){
1389
  static $uuid2key = [
1390
    UUID_STATISTICALMEASURE_MIN => 'Min',
1391
    UUID_STATISTICALMEASURE_MAX => 'Max',
1392
    UUID_STATISTICALMEASURE_AVERAGE => 'Average',
1393
    UUID_STATISTICALMEASURE_SAMPLESIZE => 'SampleSize',
1394
    UUID_STATISTICALMEASURE_VARIANCE => 'Variance',
1395
    UUID_STATISTICALMEASURE_TYPICALLOWERBOUNDARY => 'TypicalLowerBoundary',
1396
    UUID_STATISTICALMEASURE_TYPICALUPPERBOUNDARY => 'TypicalUpperBoundary',
1397
    UUID_STATISTICALMEASURE_STANDARDDEVIATION => 'StandardDeviation',
1398
    UUID_STATISTICALMEASURE_EXACTVALUE => 'ExactValue',
1399
    UUID_STATISTICALMEASURE_STATISTICALMEASUREUNKNOWNDATA => 'StatisticalMeasureUnknownData'
1400
  ];
1401
  return $uuid2key[$term->uuid];
1402
}
1403

    
1404

    
1405
/**
1406
 * Wraps the render array for the given feature into an enclosing html tag.
1407
 *
1408
 * Optionally the elements can be sorted and glued together by a separator string.
1409
 *
1410
 * @param array $description_element_render_arrays
1411
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1412
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1413
 * @param  $feature :
1414
 *  The feature to which the elements given in $elements are belonging to.
1415
 * @param string $glue :
1416
 *  Defaults to empty string.
1417
 * @param bool $sort
1418
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1419
 *
1420
 * @return array
1421
 *    A Drupal render array
1422
 *
1423
 * @ingroup compose
1424
 */
1425
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1426
  {
1427

    
1428
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1429
    $enclosing_tag = $feature_block_settings['as_list'];
1430

    
1431
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1432
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1433
    }
1434

    
1435
    $is_first = true;
1436
    foreach($description_element_render_arrays as &$element_render_array){
1437
      if(!is_array($element_render_array)){
1438
        $element_render_array = markup_to_render_array($element_render_array);
1439
      }
1440
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1441

    
1442
      // add the glue!
1443
      if(!$is_first) {
1444
        if (isset($element_render_array['#value'])) {
1445
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1446
        } elseif (isset($element_render_array['#markup'])) {
1447
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1448
        }
1449
      }
1450
      $is_first = false;
1451
    }
1452

    
1453
    $render_array['elements']['children'] = $description_element_render_arrays;
1454

    
1455
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1456
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1457

    
1458
    return $render_array;
1459
  }
1460

    
1461

    
1462
  /* compose nameInSource or originalNameString as markup
1463
   *
1464
   * @param $source
1465
   * @param $do_link_to_name_used_in_source
1466
   * @param $suppress_for_shown_taxon
1467
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1468
   *    for which the taxon page is being created, Defaults to TRUE
1469
   *
1470
   * @return array
1471
   *    A Drupal render array with an additional element, the render array is empty
1472
   *    if the source had no name in source information
1473
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1474
   *
1475
   * @ingroup compose
1476
   */
1477
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1478

    
1479
    $plaintext = NULL;
1480
    $markup = NULL;
1481
    $name_in_source_render_array = array();
1482

    
1483
    static $taxon_page_accepted_name = '';
1484
    $taxon_uuid = get_current_taxon_uuid();
1485
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1486

    
1487
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1488
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1489
    }
1490

    
1491
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1492
      // it is a DescriptionElementSource !
1493
      $plaintext = $source->nameUsedInSource->titleCache;
1494
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1495
        return $name_in_source_render_array; // SKIP this name
1496
      }
1497
      $markup = render_taxon_or_name($source->nameUsedInSource);
1498
      if ($do_link_to_name_used_in_source) {
1499
        $markup = l(
1500
          $markup,
1501
          path_to_name($source->nameUsedInSource->uuid),
1502
          array(
1503
            'attributes' => array(),
1504
            'absolute' => TRUE,
1505
            'html' => TRUE,
1506
          ));
1507
      }
1508
    }
1509
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1510
      // the name used in source can not be expressed as valid taxon name,
1511
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1512
      // field
1513
      // using the originalNameString as key to avoid duplicate entries
1514
      $plaintext = $source->originalNameString;
1515
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1516
        return $name_in_source_render_array; // SKIP this name
1517
      }
1518
      $markup = $source->originalNameString;
1519
    }
1520

    
1521
    if ($plaintext) { // checks if we have any content
1522
      $name_in_source_render_array = markup_to_render_array($markup);
1523
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1524
    }
1525

    
1526
    return $name_in_source_render_array;
1527
  }
1528

    
1529

    
1530

    
1531
  /**
1532
   * Return HTML for a list of description elements.
1533
   *
1534
   * Usually these are of a specific feature type.
1535
   *
1536
   * @param $description_elements
1537
   *   array of descriptionElements which belong to the same feature.
1538
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1539
   *   calling the function _mergeFeatureTreeDescriptions().
1540
   *   @see _mergeFeatureTreeDescriptions()
1541
   *
1542
   * @param  $feature_uuid
1543
   *
1544
   * @return
1545
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1546
   *    Footnote key or anchors are not considered to be textual content.
1547
   *
1548
   * @ingroup compose
1549
   */
1550
  function compose_feature_block_items_generic($description_elements, $feature) {
1551

    
1552
    $elements_out_array = array();
1553
    $distribution_tree = null;
1554

    
1555
    /*
1556
     * $feature_block_has_content will be set true if at least one of the
1557
     * $descriptionElements contains some text which makes up some content
1558
     * for the feature block. Footnote keys are not considered
1559
     * to be content in this sense.
1560
     */
1561
    $feature_block_has_content = false;
1562

    
1563
    if (is_array($description_elements)) {
1564
      foreach ($description_elements as $description_element) {
1565
          /* decide based on the description element class
1566
           *
1567
           * Features handled here:
1568
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1569
           *
1570
           * TODO provide api_hook as extension point for this?
1571
           */
1572
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1573
        switch ($description_element->class) {
1574
          case 'TextData':
1575
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1576
            break;
1577
          case 'CategoricalData':
1578
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1579
            break;
1580
          case 'QuantitativeData':
1581
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1582
            break;
1583
          case 'IndividualsAssociation':
1584
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1585
            break;
1586
          case 'TaxonInteraction':
1587
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1588
            break;
1589
          case 'CommonTaxonName':
1590
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1591
            break;
1592
          case 'Uses':
1593
            /* IGNORE Uses classes, these are handled completely in compose_feature_block_items_use_records()  */
1594
            break;
1595
          default:
1596
            $feature_block_has_content = true;
1597
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1598
        }
1599
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1600
        // considering not empty as long as the last item added is a render array
1601
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1602
      }
1603

    
1604
      // If feature = CITATION sort the list of sources.
1605
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1606
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1607
        sort($elements_out_array);
1608
      }
1609
    }
1610

    
1611
    // sanitize: remove empty and NULL items from the render array
1612
    $tmp_out_array = $elements_out_array;
1613
    $elements_out_array = array();
1614
    foreach($tmp_out_array as $item){
1615
      if(is_array($item) && count($item) > 0){
1616
        $elements_out_array[] = $item;
1617
      }
1618
    }
1619

    
1620
    return $elements_out_array;
1621
  }
1622

    
1623
/**
1624
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1625
 *
1626
 * @parameter $elements
1627
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1628
 * @parameter $feature
1629
 *  the common feature of all $elements, must be CommonName
1630
 *
1631
 * @return
1632
 *   A drupal render array
1633
 *
1634
 * @ingroup compose
1635
 */
1636
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1637

    
1638
  $common_name_out = '';
1639
  $common_name_feature_elements = array();
1640
  $textData_commonNames = array();
1641

    
1642
  $footnote_key_suggestion = 'common-names-feature-block';
1643

    
1644
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1645

    
1646
  if (is_array($elements)) {
1647
    foreach ($elements as $element) {
1648

    
1649
      if ($element->class == 'CommonTaxonName') {
1650

    
1651
        // common name without a language or area, should not happen but is possible
1652
        $language_area_key = '';
1653
        if (isset($element->language->representation_L10n)) {
1654
          $language_area_key .= $element->language->representation_L10n ;
1655
        }
1656
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1657
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1658
        }
1659
        if($language_area_key){
1660
          $language_area_key = '<span class="language-area-label">' . $language_area_key . '<span class="separator">: </span></span>';
1661
        }
1662

    
1663
        if(isset($common_names[$language_area_key][$element->name])) {
1664
          // same name already exists for language and area combination, se we merge the description elements
1665
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1666
        } else{
1667
          // otherwise add as new entry
1668
          $common_names[$language_area_key][$element->name] = $element;
1669
        }
1670

    
1671
      }
1672
      elseif ($element->class == 'TextData') {
1673
        $textData_commonNames[] = $element;
1674
      }
1675
    }
1676
  }
1677
  // Handling common names.
1678
  if (isset($common_names) && count($common_names) > 0) {
1679
    // Sorting the array based on the key (language, + area if set).
1680
    // Comment @WA there are common names without a language, so this sorting
1681
    // can give strange results.
1682
    ksort($common_names);
1683

    
1684
    // loop over set of elements per language area
1685
    foreach ($common_names as $language_area_key => $elements) {
1686
      ksort($elements); // sort names alphabetically
1687
      $per_language_area_out = array();
1688

    
1689
      foreach ($elements as $element) {
1690
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1691
        $common_name_markup = drupal_render($common_name_render_array);
1692
        // IMPORTANT!
1693
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1694
        // this is an error and the trailing whitespace needs to be removed
1695
        if(str_endsWith($common_name_markup, "\n")){
1696
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1697
        }
1698
        $per_language_area_out[] = $common_name_markup;
1699
      }
1700

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

    
1704

    
1705
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1706
      $common_name_feature_elements, $feature, '; ', FALSE
1707
    );
1708
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1709

    
1710
  }
1711

    
1712
  // Handling commons names as text data.
1713
  $text_data_out = array();
1714

    
1715
  foreach ($textData_commonNames as $text_data_element) {
1716
    /* footnotes are not handled correctly in compose_description_element_text_data,
1717
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1718
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1719
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1720
    $text_data_out[] = drupal_render($text_data_render_array);
1721
  }
1722

    
1723
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1724
    $text_data_out, $feature
1725
  );
1726

    
1727
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1728
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1729
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1730

    
1731
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1732
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1733
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1734
    .$footnotes,
1735
    $weight
1736
  );
1737
}
1738

    
1739
/**
1740
 * Renders a single instance of the type CommonTaxonName.
1741
 *
1742
 * @param $element
1743
 *   The CDM CommonTaxonName entity.
1744
 * @param $feature_block_settings
1745
 *
1746
 * @param $footnote_key_suggestion
1747
 *
1748
 * @param $element_tag_name
1749
 *
1750
 * @return array
1751
 *   Drupal render array
1752
 *
1753
 * @ingroup compose
1754
 */
1755
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion = NULL)
1756
{
1757

    
1758
  if(!$footnote_key_suggestion) {
1759
    $footnote_key_suggestion = $element->feature->uuid;
1760
  }
1761

    
1762
  $name = '';
1763
  if(isset($element->name)){
1764
    $name = $element->name;
1765
  }
1766

    
1767

    
1768
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1769
}
1770

    
1771
/**
1772
 * Composes the render array for a CDM Distribution description element
1773
 *
1774
 * @param array $description_elements
1775
 *   Array of CDM Distribution instances
1776
 * @param $enclosingTag
1777
 *   The html tag to be use for the enclosing element
1778
 *
1779
 * @return array
1780
 *   A Drupal render array
1781
 *
1782
 * @ingroup compose
1783
 */
1784
function compose_description_elements_distribution($description_elements){
1785

    
1786
  $markup_array = array();
1787
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1788
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1789

    
1790
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1791
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1792

    
1793
  foreach ($description_elements as $description_element) {
1794
    $annotations_and_sources = handle_annotations_and_sources(
1795
      $description_element,
1796
      handle_annotations_and_sources_config($feature_block_settings),
1797
      $description_element->area->representation_L10n,
1798
      UUID_DISTRIBUTION
1799
    );
1800

    
1801

    
1802
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1803

    
1804
    $out = '';
1805
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1806
      . ' " title="' . $status_label. '">'
1807
      . $description_element->area->representation_L10n
1808
      . $status_markup;
1809
    if(!empty($annotations_and_sources['source_references'])){
1810
      $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1811
    }
1812
    $out .= $annotations_and_sources['foot_note_keys']   . '</' . $enclosingTag . '>';
1813
    $markup_array[] = $out;
1814
  }
1815

    
1816
  RenderHints::popFromRenderStack();
1817
  return markup_to_render_array(join('<span class="separator">' . $feature_block_settings['glue'] . '</span>', $markup_array));
1818
}
1819

    
1820
  /**
1821
   * @param $descriptionElement
1822
   * @return array
1823
   */
1824
  function distribution_status_label_and_markup($descriptionElement, $status_glue = '&#8210; ') {
1825
    $status_markup = '';
1826
    $status_label = '';
1827

    
1828
    if (isset($descriptionElement->status)) {
1829
      $status_label = $descriptionElement->status->representation_L10n;
1830
      $status_markup =  '<span class="distributionStatus"> '
1831
        . $status_glue
1832
        . '<span class="distributionStatus-' . $descriptionElement->status->idInVocabulary . '">'
1833
        . $status_label
1834
        . '</span></span>';
1835

    
1836
    };
1837
    return array($status_label, $status_markup);
1838
  }
1839

    
1840

    
1841
  /**
1842
   * Provides the merged feature tree for a taxon profile page.
1843
   *
1844
   * The merging of the profile feature tree is actually done in
1845
   * _mergeFeatureTreeDescriptions(). See this method  for details
1846
   * on the structure of the merged tree.
1847
   *
1848
   * This method provides a hook which can be used to modify the
1849
   * merged feature tree after it has been created, see
1850
   * hook_merged_taxon_feature_tree_alter()
1851
   *
1852
   * @param $taxon
1853
   *    A CDM Taxon instance
1854
   *
1855
   * @return object
1856
   *    The merged feature tree
1857
   *
1858
   */
1859
  function merged_taxon_feature_tree($taxon) {
1860

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

    
1864

    
1865
    // 2. find the distribution feature node
1866
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1867

    
1868
    if ($distribution_node) {
1869
      // 3. get the distributionInfoDTO
1870
      $query_parameters = cdm_distribution_filter_query();
1871
      $query_parameters['part'] = array('mapUriParams');
1872
      if(variable_get(DISTRIBUTION_CONDENSED)){
1873
        $query_parameters['part'][] = 'condensedDistribution';
1874
      }
1875
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1876
        $query_parameters['part'][] = 'tree';
1877
      }
1878
      else {
1879
        $query_parameters['part'][] = 'elements';
1880
      }
1881
      $query_parameters['omitLevels'] = array();
1882
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1883
        if(is_uuid($uuid)){
1884
          $query_parameters['omitLevels'][] = $uuid;
1885
        }
1886
      }
1887
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1888
      if ($customStatusColorsJson) {
1889
        $query_parameters['statusColors'] = $customStatusColorsJson;
1890
      }
1891

    
1892
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1893
      // 4. get distribution TextData is there are any
1894
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1895
        array(
1896
          'taxon' => $taxon->uuid,
1897
          'type' => 'TextData',
1898
          'features' => UUID_DISTRIBUTION
1899
        )
1900
      );
1901

    
1902
      // 5. put all distribution data into the distribution feature node
1903
      if ($distribution_text_data //if text data exists
1904
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1905
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1906
      ) { // OR if DTO has distribution elements
1907
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1908
        if ($distribution_text_data) {
1909
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1910
        }
1911
        if ($distribution_info_dto) {
1912
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1913
        }
1914
      }
1915
    }
1916

    
1917
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1918
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1919

    
1920
    return $merged_tree;
1921
  }
1922

    
1923

    
1924
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1925

    
1926
    static $hierarchy_style;
1927
    // TODO expose $hierarchy_style to administration or provide a hook
1928
    if( !isset($hierarchy_style)){
1929
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1930
    }
1931

    
1932
    $render_array = array();
1933

    
1934
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1935
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1936

    
1937
    // Returning NULL if there are no description elements.
1938
    if ($distribution_tree == null) {
1939
      return $render_array;
1940
    }
1941
    // for now we are not using a render array internally to avoid performance problems
1942
    $markup = '';
1943
    if (isset($distribution_tree->rootElement->children)) {
1944
      $tree_nodes = $distribution_tree->rootElement->children;
1945
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1946
    }
1947

    
1948
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1949
      $markup,
1950
      0,
1951
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1952
      '</div>'
1953
    );
1954

    
1955
    RenderHints::popFromRenderStack();
1956

    
1957
    return $render_array;
1958
  }
1959

    
1960
  /**
1961
   * this function should produce markup as the compose_description_elements_distribution()
1962
   * function.
1963
   *
1964
   * @see compose_description_elements_distribution()
1965
   *
1966
   * @param $distribution_tree
1967
   * @param $feature_block_settings
1968
   * @param $tree_nodes
1969
   * @param $markup
1970
   * @param $hierarchy_style
1971
   */
1972
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1973

    
1974
    $level_index++;
1975
    static $enclosingTag = "span";
1976

    
1977
    $level_style = array_shift($hierarchy_style);
1978
    if(count($hierarchy_style) == 0){
1979
      // lowest defined level style will be reused for all following levels
1980
      $hierarchy_style[] = $level_style;
1981
    }
1982

    
1983
    $node_index = -1;
1984
    $per_node_markup = array();
1985
    foreach ($tree_nodes as $node){
1986

    
1987
      $per_node_markup[++$node_index] = '';
1988

    
1989
      $label = $node->nodeId->representation_L10n;
1990

    
1991
      $distributions = $node->data;
1992
      $distribution_uuids = array();
1993
      $distribution_aggregate = NULL;
1994
        foreach($distributions as $distribution){
1995

    
1996
          $distribution_uuids[] = $distribution->uuid;
1997

    
1998
          // if there is more than one distribution we aggregate the sources and
1999
          // annotations into a synthetic distribution so that the footnote keys
2000
          // can be rendered consistently
2001
          if(!$distribution_aggregate) {
2002
            $distribution_aggregate = $distribution;
2003
            if(!isset($distribution_aggregate->sources[0])){
2004
              $distribution_aggregate->sources = array();
2005
            }
2006
            if(!isset($distribution_aggregate->annotations[0])){
2007
              $distribution_aggregate->annotations = array();
2008
            }
2009
          } else {
2010
            if(isset($distribution->sources[0])) {
2011
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
2012
                $distribution->sources);
2013
            }
2014
            if(isset($distribution->annotations[0])) {
2015
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
2016
                $distribution->annotations);
2017
            }
2018
          }
2019
        }
2020

    
2021
      $status_label= '';
2022
      $status_markup = '';
2023
      $annotations_and_sources =  null;
2024
      if($distribution_aggregate) {
2025
        $annotations_and_sources = handle_annotations_and_sources(
2026
          $distribution_aggregate,
2027
          handle_annotations_and_sources_config($feature_block_settings),
2028
          $label,
2029
          UUID_DISTRIBUTION
2030
        );
2031

    
2032
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution, $level_style['status_glue']);
2033
      }
2034

    
2035
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
2036
        . join(' descriptionElement-', $distribution_uuids)
2037
        . ' level_index_' . $level_index
2038
        . ' " title="' . $status_label . '">'
2039
        . '<span class="area_label">' . $label
2040
        . $level_style['label_suffix'] . '</span>'
2041
        . $status_markup
2042
      ;
2043

    
2044
      if(isset($annotations_and_sources)){
2045
        if(!empty($annotations_and_sources['source_references'])){
2046
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
2047
        }
2048
        if($annotations_and_sources['foot_note_keys']) {
2049
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
2050
        }
2051
      }
2052

    
2053
      if(isset($node->children[0])){
2054
        _compose_distribution_hierarchy(
2055
          $node->children,
2056
          $feature_block_settings,
2057
          $per_node_markup[$node_index],
2058
          $hierarchy_style,
2059
          $level_index
2060
        );
2061
      }
2062

    
2063
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
2064
    }
2065
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
2066
  }
2067

    
2068

    
2069
/**
2070
 * Provides the content for a block of Uses Descriptions for a given taxon.
2071
 *
2072
 * Fetches the list of TaxonDescriptions tagged with the MARKERTYPE_USE
2073
 * and passes them to the theme function theme_cdm_UseDescription().
2074
 *
2075
 * @param string $taxon_uuid
2076
 *   The uuid of the Taxon
2077
 *
2078
 * @return array
2079
 *   A drupal render array
2080
 */
2081
function cdm_block_use_description_content($taxon_uuid, $feature) {
2082

    
2083
  $use_description_content = array();
2084

    
2085
  if (is_uuid($taxon_uuid )) {
2086
    $markerTypes = array();
2087
    $markerTypes['markerTypes'] = UUID_MARKERTYPE_USE;
2088
    $useDescriptions = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXON . '/' . $taxon_uuid . '/descriptions', $markerTypes);
2089
    if (!empty($useDescriptions)) {
2090
      $use_description_content = compose_feature_block_items_use_records($useDescriptions, $taxon_uuid, $feature);
2091
    }
2092
  }
2093

    
2094
  return $use_description_content;
2095
}
2096

    
2097
/**
2098
 * Creates a trunk of a feature object which can be used to build pseudo feature blocks like the Bibliography.
2099
 *
2100
 * @param $representation_L10n
2101
 * @param String $pseudo_feature_key
2102
 *    Will be set as uuid but should be one of 'BIBLIOGRAPHY', ... more to come. See also get_feature_block_settings()
2103
 *
2104
 * @return object
2105
 *  The feature object
2106
 */
2107
function make_pseudo_feature($representation_L10n, $pseudo_feature_key = null){
2108
  $feature = new stdClass;
2109
  $feature->representation_L10n = $representation_L10n;
2110
  $feature->uuid = NULL; // $pseudo_feature_key;
2111
  $feature->label = $pseudo_feature_key;
2112
  $feature->class = 'PseudoFeature';
2113

    
2114
  return $feature;
2115

    
2116
}
2117

    
2118
/**
2119
 * @param $root_nodes, for obtaining the  root nodes from a description you can
2120
 * use the function get_root_nodes_for_dataset($description);
2121
 *
2122
 * @return string
2123
 */
2124
function render_description_string($root_nodes, &$item_cnt = 0) {
2125

    
2126
  $out = '';
2127

    
2128
  $description_strings= [];
2129
  if (!empty($root_nodes)) {
2130
    foreach ($root_nodes as $root_node) {
2131
      if(isset($root_node->descriptionElements)) {
2132
        foreach ($root_node->descriptionElements as $element) {
2133
          $feature_label = $element->feature->representation_L10n;
2134
          if($item_cnt == 0){
2135
            $feature_label = ucfirst($feature_label);
2136
          }
2137
          switch ($element->class) {
2138
            case 'CategoricalData':
2139
              $state_data = render_state_data($element);
2140
              if (!empty($state_data)) {
2141
                if(is_suppress_state_present_display($element, $root_node)){
2142
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: '  . '</span>';
2143
                } else {
2144
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . $state_data . '</span>;' ;
2145
                }
2146
              }
2147
              break;
2148
            case 'QuantitativeData':
2149
              $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . render_quantitative_statistics($element) . '</span>;';
2150
              break;
2151
          }
2152
        }
2153
        $item_cnt++;
2154
      }
2155

    
2156
      // recurse child nodes
2157
      $child_markup = render_description_string($root_node->childNodes, $item_cnt);
2158
      if($child_markup){
2159
        $description_strings[] = $child_markup;
2160
      }
2161
    }
2162
    if(count($description_strings) > 0){
2163
      // remove last semicolon
2164
      $description_strings[count($description_strings) - 1] = preg_replace('/;$/', '', $description_strings[count($description_strings) - 1]);
2165
    }
2166
    $out  = join($description_strings,  ' ');
2167
  }
2168
  return $out;
2169
}
2170

    
2171
/**
2172
 * Compose a description as a table of Feature<->State
2173
 *
2174
 * @param $description_uuid
2175
 *
2176
 * @return array
2177
 *    The drupal render array for the page
2178
 *
2179
 * @ingroup compose
2180
 */
2181
function  compose_description_table($description_uuid, $descriptive_dataset_uuid = NULL) {
2182

    
2183
  RenderHints::pushToRenderStack('description_table');
2184

    
2185
  $render_array = [];
2186

    
2187
  $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, [$description_uuid]);
2188
  $dataSet = NULL;
2189
  // dataset passed as parameter
2190
  if ($descriptive_dataset_uuid != NULL) {
2191
    foreach ($description->descriptiveDataSets as $set) {
2192
      if ($set->uuid == $descriptive_dataset_uuid) {
2193
        $dataSet = $set;
2194
        break;
2195
      }
2196
    }
2197
  }
2198

    
2199
  if(!empty($description->descriptiveDataSets)) {
2200
    // only one dataset present
2201
    if (!isset($dataSet) && sizeof($description->descriptiveDataSets) == 1) {
2202
      foreach ($description->descriptiveDataSets as $dataSet) {
2203
        break;
2204
      }
2205
    }
2206

    
2207
    // generate description title
2208
    RenderHints::pushToRenderStack('title');
2209
    if (isset($dataSet)) {
2210

    
2211
      $described_entity_title = NULL;
2212
      if(isset($description->describedSpecimenOrObservation)){
2213
        $described_entity_title = $description->describedSpecimenOrObservation->titleCache;
2214
      } else if($description->taxon) {
2215
          $described_entity_title = render_taxon_or_name($description->taxon);
2216
      }
2217
      $title = 'Descriptive Data ' . $dataSet->titleCache .
2218
        ($described_entity_title ? ' for ' . $described_entity_title : '');
2219
    }
2220
    $render_array['title'] = markup_to_render_array($title, null, '<h3 class="title">', '</h3>');
2221
    RenderHints::popFromRenderStack();
2222
    // END of --- generate description title
2223

    
2224
    if (isset($description->types)) {
2225
      foreach ($description->types as $type) {
2226
        if ($type == 'CLONE_FOR_SOURCE') {
2227
          $render_array['source'] = markup_to_render_array("Aggregation source from " . $description->created, null, '<div class="date-created">', '</div>');
2228
          break;
2229
        }
2230
      }
2231
    }
2232
  }
2233
  // multiple datasets present see #8714 "Show multiple datasets per description as list of links"
2234
  else {
2235
    $items = [];
2236
    foreach ($description->descriptiveDataSets as $dataSet) {
2237
      $path = path_to_description($description->uuid, $dataSet->uuid);
2238
      $attributes['class'][] = html_class_attribute_ref($description);
2239
      $items[] = [
2240
        'data' => $dataSet->titleCache . icon_link($path),
2241
      ];
2242
    }
2243
    $render_array['description_elements'] = [
2244
      '#title' => 'Available data sets for description',
2245
      '#theme' => 'item_list',
2246
      '#type' => 'ul',
2247
      '#items' => $items,
2248
    ];
2249
  }
2250

    
2251
  $described_entities = [];
2252
  if (isset($description->describedSpecimenOrObservation)) {
2253
    $decr_entitiy = '<span class="label">Specimen:</span> ' . render_cdm_specimen_link($description->describedSpecimenOrObservation);
2254
    $described_entities['specimen'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2255
  }
2256
  if (isset($description->taxon)) {
2257
    $decr_entitiy = '<span class="label">Taxon:</span> ' . render_taxon_or_name($description->taxon, url(path_to_taxon($description->taxon->uuid)));
2258
    $described_entities['taxon'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2259
  }
2260

    
2261
  if(count($described_entities)){
2262
    $render_array['described_entities'] = $described_entities;
2263
    $render_array['described_entities']['#prefix'] = '<div class="described-entities">';
2264
    $render_array['described_entities']['#suffix'] = '</div>';
2265
  }
2266

    
2267

    
2268
  $root_nodes = get_root_nodes_for_dataset($description);
2269

    
2270

    
2271
  $rows = [];
2272
  $rows = description_element_table_rows($root_nodes, $rows);
2273

    
2274
  // --- create headers
2275
  $header = [0 => [], 1 => []];
2276

    
2277
  foreach($rows as $row) {
2278
    if(array_search('Character', $row['class']) && array_search('Character', $header[0]) === false){
2279
      $header[0][] = 'Character';
2280
    } elseif (array_search('Feature', $row['class']) && array_search('Feature', $header[0]) === false){
2281
      $header[0][] = 'Feature';
2282
    }
2283
    if(array_search('has_state', $row['class']) && array_search('States', $header[1]) === false){
2284
      $header[1][] = 'States';
2285
    } elseif (array_search('has_values', $row['class']) && array_search('Values', $header[1]) === false){
2286
      $header[1][] = 'Values';
2287
    }
2288
  }
2289
  asort($header[0]);
2290
  asort($header[1]);
2291
  $header[0] = join('/', $header[0]);
2292
  $header[1] = join('/', $header[1]);
2293

    
2294
  // ---
2295

    
2296
  if (!empty($rows)) {
2297
    $render_array['table'] = markup_to_render_array(theme('table', [
2298
      'header' => $header,
2299
      'rows' => $rows,
2300
      'caption' => statistical_values_explanation(),
2301
      'title' => "Table"
2302
    ]));
2303
  }
2304

    
2305
  // --- sources
2306
  if (isset($description->sources) and !empty($description->sources)) {
2307
    $items = [];
2308
    foreach ($description->sources as $source) {
2309
      if ($source->type == 'Aggregation' and isset($source->cdmSource)){
2310
        $cdm_source_entity = $source->cdmSource;
2311
        switch($cdm_source_entity->class){
2312
          case 'Taxon':
2313
            $source_link_markup = render_taxon_or_name($cdm_source_entity) . icon_link(path_to_taxon($cdm_source_entity->uuid, false));
2314
            break;
2315
          case 'TaxonDescription':
2316
          case 'NameDescription':
2317
          case 'SpecimenDescription':
2318
            $source_link_markup = render_cdm_entity_link($cdm_source_entity);
2319
            break;
2320
          default:
2321
            $source_link_markup = '<span class="error">Unhandled CdmSource</span>';
2322
        }
2323
        $items[$cdm_source_entity->titleCache] = [
2324
          'data' => $source_link_markup
2325
        ];
2326
      }
2327
    }
2328
    ksort($items);
2329
    $render_array['sources'] = [
2330
      '#title' => 'Sources',
2331
      '#theme' => 'item_list',
2332
      '#type' => 'ul',
2333
      '#items' => $items,
2334
      '#attributes' => ['class' => 'sources']
2335
    ];
2336
    $render_array['#prefix'] = '<div class="description-table">';
2337
    $render_array['#suffix'] = '</div>';
2338
  }
2339

    
2340
  RenderHints::popFromRenderStack();
2341

    
2342
  return $render_array;
2343
}
2344

    
2345
/**
2346
 * For a given description returns the root nodes according to the
2347
 *corresponding term tree. The term tree is determined as follow:
2348
 * 1. If description is part of a descriptive data set the term tree of that
2349
 *    data set is used (FIXME handle multiple term trees)
2350
 * 2. Otherwise the portal taxon profile tree is used
2351
 * @param $description
2352
 *
2353
 * @return array
2354
 */
2355
function get_root_nodes_for_dataset($description) {
2356
  if (!empty($description->descriptiveDataSets)) {
2357
    foreach ($description->descriptiveDataSets as $dataSet) {
2358
      break;// FIXME handle multiple term trees
2359
    }
2360
    $tree = cdm_ws_get(CDM_WS_TERMTREE, $dataSet->descriptiveSystem->uuid);
2361
    $root_nodes = _mergeFeatureTreeDescriptions($tree->root->childNodes, $description->elements);
2362
  }
2363
  else {
2364
    $root_nodes = _mergeFeatureTreeDescriptions(get_profile_feature_tree()->root->childNodes, $description->elements);
2365
  }
2366
  return $root_nodes;
2367
}
2368

    
2369
/**
2370
 * Recursively creates an array of row items to be used in theme_table.
2371
 *
2372
 * The array items will have am element 'class' with information on the
2373
 * nature of the DescriptionElement ('has_values' | 'has_state') and on the
2374
 * type of the FeatureNode ('Feature' | 'Character')
2375
 *
2376
 * @param array $root_nodes
2377
 * @param array $row_items
2378
 * @param int $level
2379
 *     the depth in the hierarchy
2380
 *
2381
 * @return array
2382
 *  An array of row items to be used in theme_table
2383
 *
2384
 *
2385
 */
2386
function description_element_table_rows($root_nodes, $row_items, $level = 0) {
2387

    
2388
  $indent_string = '&nbsp;&nbsp;&nbsp;';
2389
  foreach ($root_nodes as $root_node) {
2390
    if(isset($root_node->descriptionElements)) {
2391
      foreach ($root_node->descriptionElements as $element) {
2392
        $level_indent = str_pad('', $level * strlen($indent_string), $indent_string);
2393
        switch ($element->class) {
2394
          case 'QuantitativeData':
2395
            $row_items[] = [
2396
              'data' => [
2397
                [
2398
                  'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2399
                  'class' => ['level_' . $level]
2400
                ],
2401
                render_quantitative_statistics($element)
2402
              ],
2403
              'class' => ['level_' . $level, 'has_values', $element->feature->class]
2404
            ];
2405
            break;
2406
          case 'CategoricalData':
2407
            default:
2408
            if (!empty($element->stateData)) {
2409
              $supress_state_display = is_suppress_state_present_display($element, $root_node);
2410
              if(!$supress_state_display){
2411
                $state_cell = render_state_data($element);
2412
              } else {
2413
                $state_cell = "<span> </span>";
2414
              }
2415
              $row_items[] = [
2416
                'data' => [
2417
                  [
2418
                    'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2419
                    'class' => ['level_' . $level]
2420
                  ],
2421
                  $state_cell,
2422
                ],
2423
                'class' => ['level_' . $level, 'has_state', $element->feature->class]
2424
              ];
2425
            }
2426
            break;
2427
        }
2428
      }
2429
    }
2430
    // recurse child nodes
2431
    $row_items = description_element_table_rows($root_node->childNodes, $row_items, $level + 1);
2432
  }
2433
  return $row_items;
2434
}
2435

    
2436
/**
2437
 * @param $element
2438
 * @param $root_node
2439
 *
2440
 * @return bool
2441
 */
2442
function is_suppress_state_present_display($element, $root_node) {
2443
  return count($element->stateData) == 1 & $element->stateData[0]->state->representation_L10n == 'present' && is_array($root_node->childNodes);
2444
}
2445

    
2446

    
2447

    
(3-3/13)