Project

General

Profile

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

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

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

    
44
  $computed_elements = array();
45
  $other_elements = array();
46

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

    
58
  if (count($computed_elements) > 0) {
59
    return $computed_elements;
60
  }
61
  else {
62
    return $other_elements;
63
  }
64
}
65

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

    
76
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
77
  if($feature_block_settings['sort_elements'] == SORT_HIERARCHICAL){
78
    $query['distributionOrder'] = 'AREA_ORDER';
79
  }
80

    
81
  $query['recipe'] = variable_get(DISTRIBUTION_CONDENSED_RECIPE, DISTRIBUTION_CONDENSED_RECIPE_DEFAULT);
82

    
83

    
84

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

    
100
  return $query;
101
}
102

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

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

    
126
/**
127
 * Adds an entry to the end of the table of content items list
128
 *
129
 * The  table of content items are crated internally by calling
130
 * toc_list_item() the resulting item is added to the statically cached
131
 * list of toc elements
132
 *
133
 * @param string $label
134
 *   The label of toc entry
135
 * @param $class_attribute_suffix
136
 *   The suffix to be appended to the class attribute prefix: "feature-toc-item-"
137
 * @param string $fragment
138
 *   Optional parameter to define a url fragment different from the $label,
139
 *   if the $fragment is not defined the $label will be used
140
 */
141
function cdm_toc_list_add_item($label, $class_attribute_suffix, $fragment = NULL, $as_first_element = FALSE) {
142
  $toc_list_items = &cdm_toc_list();
143

    
144
  if (!$fragment) {
145
    $fragment = $label;
146
  }
147
  $fragment = generalizeString($fragment);
148

    
149
  $class_attributes = 'feature-toc-item-' . $class_attribute_suffix;
150

    
151
  $new_item = toc_list_item(
152
    theme(
153
      'cdm_feature_name',
154
      array('feature_name' => $label)),
155
      array('class' => $class_attributes),
156
      $fragment
157
    );
158

    
159
  if ($as_first_element) {
160
    array_unshift($toc_list_items, $new_item);
161
  }
162
  else {
163
    $toc_list_items[] = $new_item;
164
  }
165

    
166
}
167

    
168
/**
169
 * Returns the statically cached table of content items as render array.
170
 *
171
 * @see cdm_toc_list_add_item()
172
 *
173
 * @return array
174
 *   a render array of table of content items suitable for theme_item_list()
175
 */
176
function &cdm_toc_list(){
177
  $toc_list_items = &drupal_static('toc_list_items', array());
178

    
179
  return $toc_list_items;
180
}
181

    
182
/**
183
 * Prepares an empty Drupal block for displaying description elements of a specific CDM Feature.
184
 *
185
 * The block can also be used for pseudo Features like a bibliography. Pseudo features are
186
 * derived from other data on the fly and so not exist as such in the cdm data. In case
187
 * of pseudo features the $feature is left empty
188
 *
189
 * @param $feature_name
190
 *   A label describing the feature, usually the localized feature representation.
191
 * @param object $feature
192
 *   The CDM Feature for which the block is created. (optional)
193
 * @return object
194
 *   A Drupal block object
195
 */
196
function feature_block($feature_name, $feature = NULL) {
197
  $block = new stdclass(); // Empty object.
198
  $block->module = 'cdm_dataportal';
199
  $block->delta = generalizeString($feature_name);
200
  $block->region = NULL;
201
  $class_attribute = $feature ? html_class_attribute_ref($feature) : '';
202
  $block->subject = '<a name="' . $block->delta . '"></a><span class="' . $class_attribute . '">'
203
    . theme('cdm_feature_name', array('feature_name' => $feature_name))
204
    . '</span>';
205
  $block->module = "cdm_dataportal-feature";
206
  $block->content = '';
207
  return $block;
208
}
209

    
210

    
211
/**
212
 * Returns a list of a specific type of IdentificationKeys.
213
 *
214
 * The list can be restricted by a taxon.
215
 *
216
 * @param string $type
217
 *   The simple name of the cdm class implementing the interface
218
 *   IdentificationKey, valid values are:
219
 *   PolytomousKey, MediaKey, MultiAccessKey.
220
 * @param string $taxonUuid
221
 *   If given this parameter restrict the listed keys to those which have
222
 *   the taxon identified be this uuid in scope.
223
 *
224
 * @return array
225
 *   List with identification keys.
226
 */
227
function _list_IdentificationKeys($type, $taxonUuid = NULL, $pageSize = NULL, $pageNumber = NULL) {
228
  if (!$type) {
229
    drupal_set_message(t('Type parameter is missing'), 'error');
230
    return;
231
  }
232
  $cdm_ws_pasepath = NULL;
233
  switch ($type) {
234
    case "PolytomousKey":
235
      $cdm_ws_pasepath = CDM_WS_POLYTOMOUSKEY;
236
      break;
237

    
238
    case "MediaKey":
239
      $cdm_ws_pasepath = CDM_WS_MEDIAKEY;
240
      break;
241

    
242
    case "MultiAccessKey":
243
      $cdm_ws_pasepath = CDM_WS_MULTIACCESSKEY;
244
      break;
245

    
246
  }
247

    
248
  if (!$cdm_ws_pasepath) {
249
    drupal_set_message(t('Type parameter is not valid: ') . $type, 'error');
250
  }
251

    
252
  $queryParameters = '';
253
  if (is_numeric($pageSize)) {
254
    $queryParameters = "pageSize=" . $pageSize;
255
  }
256
  else {
257
    $queryParameters = "pageSize=0";
258
  }
259

    
260
  if (is_numeric($pageNumber)) {
261
    $queryParameters = "pageNumber=" . $pageNumber;
262
  }
263
  else {
264
    $queryParameters = "pageNumber=0";
265
  }
266
  $queryParameters = NULL;
267
  if ($taxonUuid) {
268
    $queryParameters = "findByTaxonomicScope=$taxonUuid";
269
  }
270
  $pager = cdm_ws_get($cdm_ws_pasepath, NULL, $queryParameters);
271

    
272
  if (!$pager || $pager->count == 0) {
273
    return array();
274
  }
275
  return $pager->records;
276
}
277

    
278

    
279
/**
280
 * Creates a list item for a table of content, suitable as data element for a themed list
281
 *
282
 * @see theme_list()
283
 *
284
 * @param $label
285
 * @param $http_request_params
286
 * @param $attributes
287
 * @return array
288
 */
289
function toc_list_item($label, $attributes = array(), $fragment = null) {
290

    
291
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
292
  $http_request_params = drupal_static('http_request_params', drupal_get_query_parameters());
293

    
294
  $item =  array(
295
    'data' => l(
296
      $label,
297
      $_GET['q'],
298
      array(
299
        'attributes' => array('class' => array('toc')),
300
        'fragment' => generalizeString($label),
301
        'query' => $http_request_params,
302
      )
303
    ),
304
  );
305
  $item['attributes'] = $attributes;
306
  return $item;
307
}
308

    
309
/**
310
 * Creates the footnotes for the given CDM DescriptionElement instance.
311
 *
312
 * Footnotes are created for annotations and original sources,
313
 * optionally the sources are put into a separate bibliography.
314
 *
315
 * @param $descriptionElement
316
 *   A CDM DescriptionElement instance
317
 * @param $separator
318
 *   Optional parameter. The separator string to concatenate the footnote ids, default is ','
319
 * @param $footnote_list_key_suggestion
320
 *   will be overridden for original sources if the bibliography block is enabled
321
 *
322
 * @return String
323
 *   The foot note keys
324
 */
325
function cdm_create_description_element_footnotes(
326
          $description_element,
327
          $separator = ',',
328
          $footnote_list_key_suggestion = null,
329
          $do_link_to_reference = FALSE,
330
          $do_link_to_name_used_in_source = FALSE
331
    )
332
{
333

    
334
  return cdm_create_footnotes($description_element,
335
    $separator,
336
    $footnote_list_key_suggestion,
337
    $do_link_to_reference,
338
    $do_link_to_name_used_in_source,
339
    true
340

    
341
  );
342
}
343

    
344
/**
345
 * Creates the footnotes for the given CDM instance.
346
 *
347
 * Footnotes are created for annotations and original sources.
348
 *
349
 * @param $descriptionElement
350
 *   A CDM DescriptionElement instance
351
 * @param $separator
352
 *   Optional parameter. The separator string to concatenate the footnote ids, default is ','
353
 * @param $footnote_list_key_suggestion
354
 *   will be overridden for original sources if the bibliography block is enabled
355
 * @$original_source_footnote_tag
356
 *    null will cause original_source_footnote_list_key to use the default
357
 *
358
 * @return String
359
 *   The foot note keys
360
 */
361
function cdm_create_footnotes(
362
    $description_element,
363
    $separator = ',',
364
    $footnote_list_key_suggestion = null,
365
    $do_link_to_reference = FALSE,
366
    $do_link_to_name_used_in_source = FALSE,
367
    $is_bibliography_aware = FALSE
368
  ){
369

    
370
  // Annotations as footnotes.
371
  $footNoteKeys = cdm_annotations_as_footnotekeys($description_element, $footnote_list_key_suggestion);
372

    
373
  // Source references as footnotes.
374

    
375
  if($is_bibliography_aware){
376
    $bibliography_settings = get_bibliography_settings();
377
    $sources_footnote_list_key = original_source_footnote_list_key($footnote_list_key_suggestion);
378
    $original_source_footnote_tag = $bibliography_settings['enabled'] == 1 ? 'div' : null; // null will cause original_source_footnote_list_key to use the default
379
  } else {
380
    $sources_footnote_list_key = $footnote_list_key_suggestion;
381
    $original_source_footnote_tag = NULL;
382
  }
383

    
384
  usort($description_element->sources, 'compare_original_sources');
385
  foreach ($description_element->sources as $source) {
386
    if (_is_original_source_type($source)) {
387
      $fn_key = FootnoteManager::addNewFootnote(
388
        $sources_footnote_list_key,
389
        theme('cdm_OriginalSource', array(
390
          'source' => $source,
391
          'doLink' => $do_link_to_reference,
392
          'do_link_to_name_used_in_source' => $do_link_to_name_used_in_source
393

    
394
        )),
395
        $original_source_footnote_tag
396
      );
397
      // Ensure uniqueness of the footnote keys.
398
      cdm_add_footnote_to_array($footNoteKeys, $fn_key);
399
    }
400
  }
401
  // Sort and render footnote keys.
402
  $footnoteKeyListStr = '';
403
  asort($footNoteKeys);
404
  foreach ($footNoteKeys as $footNoteKey) {
405
    $footnoteKeyListStr .= theme('cdm_footnote_key',
406
      array(
407
        'footnoteKey' => $footNoteKey,
408
        'separator' => ($footnoteKeyListStr ? $separator : '')));
409
  }
410
  return $footnoteKeyListStr;
411
}
412

    
413

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

    
426
}
427

    
428

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

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

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

    
451
    '#value' => '',
452
    '#value_suffix' => NULL
453

    
454
  );
455

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

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

    
476

    
477
  $source_references_markup = '';
478
  if (!empty($annotations_and_sources['source_references'])) {
479
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
480
  }
481

    
482
  $feature_label = '';
483
  if ($prepend_feature_label) {
484
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
485
  }
486
  $content_markup = $names_used_in_source_markup . $element_markup . $source_references_markup;
487

    
488
  if(!$content_markup && $feature_block_settings['sources_as_content'] !== 1){
489
    // no textual content? So skip this element completely, even if there could be an footnote key
490
    // see #4379
491
    return null;
492
  }
493

    
494
    $render_array['#value'] = $feature_label . $content_markup;
495
    $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
496
  return $render_array;
497
}
498

    
499
/**
500
 * Creates a handle_annotations_and_sources configuration array from feature_block_settings.
501
 *
502
 * The handle_annotations_and_sources configuration array is meant to be used for the
503
 * method handle_annotations_and_sources().
504
 *
505
 * @param $feature_block_settings array
506
 *
507
 * @return array
508
 *   The configuration array for handle_annotations_and_sources()
509
 */
510
function handle_annotations_and_sources_config($feature_block_settings){
511

    
512
  $config = $feature_block_settings;
513
  unset($config['sources_as_content_to_bibliography']);
514
  $config['add_footnote_keys'] = 0;
515
  if($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
516
    $config['add_footnote_keys'] = 1;
517
  }
518
  $config['bibliography_aware'] = 1;
519

    
520
  return $config;
521
}
522

    
523
  /**
524
   * @param $entity
525
   * @param $config array
526
   *   An associative array to configure the display of the annotations and sources.
527
   *   The array has the following keys
528
   *   - sources_as_content
529
   *   - link_to_name_used_in_source
530
   *   - link_to_reference
531
   *   - add_footnote_keys
532
   *   - bibliography_aware
533
   *   Valid values are 1 or 0.
534
   * @param $inline_text_prefix
535
   *   Only used to decide if the source references should be enclosed in brackets or not when displayed inline.
536
   *   This text will not be included into the response.
537
   * @param $footnote_list_key_suggestion
538
   *
539
   * @return array
540
   *   an associative array with the following elements:
541
   *   - foot_note_keys: all footnote keys as markup
542
   *   - source_references: an array of the source references citations
543
   *   - names used in source: an associative array of the names in source,
544
   *        the name in source strings are de-duplicated
545
   *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
546
   */
547
  function handle_annotations_and_sources($entity, $config, $inline_text_prefix, $footnote_list_key_suggestion) {
548

    
549
    $annotations_and_sources = array(
550
      'foot_note_keys' => NULL,
551
      'source_references' => array(),
552
      'names_used_in_source' => array()
553
    );
554

    
555
    usort($entity->sources, 'compare_original_sources');
556

    
557
    if ($config['sources_as_content'] == 1) {
558
      foreach ($entity->sources as $source) {
559

    
560
        $reference_citation = theme('cdm_OriginalSource',
561
          array(
562
            'source' => $source,
563
            'doLink' => $config['link_to_reference'] == 1,
564
            'do_link_to_name_used_in_source' => $config['link_to_name_used_in_source'] == 1,
565
          )
566
        );
567

    
568
        if ($reference_citation) {
569
          if (empty($inline_text_prefix)) {
570
            $annotations_and_sources['source_references'][] = $reference_citation;
571
          }
572
          else {
573
            $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
574
          }
575
        }
576

    
577
        $name_in_source_render_array = compose_name_in_source(
578
          $source,
579
          $config['link_to_name_used_in_source'] == 1
580
        );
581

    
582
        if(!empty($name_in_source_render_array)){
583
          $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
584
        }
585
      } // END of loop over sources
586

    
587
      // annotations footnotes separate.
588
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
589
        array(
590
          'cdmBase_list' => $entity,
591
          'footnote_list_key' => $footnote_list_key_suggestion,
592
        )
593
      );
594

    
595
    } // END of references inline
596

    
597
    // sources as footnotes or put into into bibliography if requested ...
598
    if ($config['add_footnote_keys'] == 1) {
599
      if(empty($config['bibliography_aware'])) {
600
        $annotations_and_sources['foot_note_keys'] = cdm_create_footnotes(
601
          $entity, ',',
602
          $footnote_list_key_suggestion,
603
          $config['link_to_reference'] == 1,
604
          $config['link_to_name_used_in_source'] == 1
605
        );
606
      } else {
607
        $annotations_and_sources['foot_note_keys'] = cdm_create_description_element_footnotes(
608
          $entity, ',',
609
          $footnote_list_key_suggestion,
610
          $config['link_to_reference'] == 1,
611
          $config['link_to_name_used_in_source'] == 1
612
        );
613
      }
614
    }
615

    
616
    return $annotations_and_sources;
617
  }
618

    
619

    
620
  /**
621
   *
622
   *
623
   * @return string
624
   *  the footnote_list_key
625
   */
626
  function original_source_footnote_list_key($key_suggestion = null) {
627
    if(!$key_suggestion){
628
      $key_suggestion = RenderHints::getFootnoteListKey();
629
    }
630
    $bibliography_settings = get_bibliography_settings();
631
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? 'BIBLIOGRAPHY' : 'BIBLIOGRAPHY-' . $key_suggestion;
632
    return $footnote_list_key;
633
  }
634

    
635
  /**
636
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
637
   *
638
   * @param $feature_block_settings
639
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
640
   */
641
  function cdm_feature_block_element_tag_name($feature_block_settings){
642
    switch ($feature_block_settings['as_list']){
643
      case 'ul':
644
      case 'ol':
645
        return 'li';
646
      case 'div':
647
        if(isset($feature_block_settings['element_tag'])){
648
          return $feature_block_settings['element_tag'];
649
        }
650
        return 'span';
651
      case 'dl':
652
        return 'dd';
653
      default:
654
        return 'div'; // should never happen, throw error instead?
655
    }
656
  }
657

    
658

    
659
/* ==================== COMPOSE FUNCTIONS =============== */
660

    
661
  /**
662
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
663
   *
664
   * The taxon profile consists of drupal block elements, one for the description elements
665
   * of a specific feature. The structure is defined by specific FeatureTree.
666
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
667
   *
668
   * The merged nodes can be obtained by making use of the
669
   * function cdm_ws_descriptions_by_featuretree().
670
   *
671
   * @see cdm_ws_descriptions_by_featuretree()
672
   *
673
   * @param $mergedFeatureNodes
674
   *
675
   * @param $taxon
676
   *
677
   * @return array
678
   *  A Drupal render array containing feature blocks and the table of content
679
   *
680
   * @ingroup compose
681
   */
682
  function compose_feature_blocks($mergedFeatureNodes, $taxon) {
683

    
684
    $block_list = array();
685

    
686
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
687

    
688

    
689
    RenderHints::pushToRenderStack('feature_block');
690
    // Create a drupal block for each feature
691
    foreach ($mergedFeatureNodes as $node) {
692

    
693
      if ((isset($node->descriptionElements['#type']) ||
694
          has_feature_node_description_elements($node)) && $node->feature->uuid != UUID_IMAGE) { // skip empty or suppressed features
695

    
696
        RenderHints::pushToRenderStack($node->feature->uuid);
697
          
698
        $feature_name = cdm_term_representation($node->feature, 'Unnamed Feature');
699
        $feature_block_settings = get_feature_block_settings($node->feature->uuid);
700
        
701

    
702
        $block = feature_block($feature_name, $node->feature);
703
        $block->content = array();
704
        $block_content_is_empty = TRUE;
705

    
706
        /*
707
         * Content/DISTRIBUTION.
708
         */
709
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
710
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
711
          $block_content_is_empty = FALSE;
712
        }
713
        /*
714
         * Content/COMMON_NAME.
715
         */
716
        else if ($node->feature->uuid == UUID_COMMON_NAME) {
717
          $common_names_render_array = compose_feature_block_items_feature_common_name($node->descriptionElements, $node->feature);
718
          $block->content[] = $common_names_render_array;
719
          $block_content_is_empty = FALSE;
720
        }
721

    
722
        else if ($node->feature->uuid == UUID_USE_RECORD) {
723
          $block_uses_content_html = theme('cdm_block_Uses', array('taxonUuid' => $taxon->uuid));
724
          $block->content[] = markup_to_render_array($block_uses_content_html);
725
          $block_content_is_empty = FALSE;
726
        }
727

    
728
        /*
729
         * Content/ALL OTHER FEATURES.
730
         */
731
        else {
732

    
733
          $media_list = array();
734
          $elements_render_array = array();
735
          $child_elements_render_array = null;
736

    
737
          if (isset($node->descriptionElements[0])) {
738
            $elements_render_array = compose_feature_block_items_generic($node->descriptionElements, $node->feature);
739
          }
740

    
741
          // Content/ALL OTHER FEATURES/Subordinate Features
742
          // subordinate features are printed inline in one floating text,
743
          // it is expected hat subordinate features can "contain" TextData,
744
          // Qualitative- and Qualitative- DescriptionElements
745
          if (isset($node->childNodes[0])) {
746
            $child_elements_render_array = compose_feature_block_items_nested($node, $media_list, $feature_block_settings);
747
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
748
          }
749
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
750
          if(!$block_content_is_empty){
751
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $node->feature);
752
            $block->content[] = compose_feature_media_gallery($node, $media_list, $gallery_settings);
753
            /*
754
             * Footnotes for the feature block
755
             */
756
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $node->feature->uuid)));
757
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $node->feature->uuid)));
758
            $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $node->feature->uuid)));
759
          }
760
        } // END all other features
761

    
762
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
763
        drupal_alter('cdm_feature_node_block_content', $block->content, $node->feature, $node->descriptionElements);
764

    
765
        if(!$block_content_is_empty){ // skip empty block content
766
          $block_list[] = $block;
767
          cdm_toc_list_add_item(cdm_term_representation($node->feature), $node->feature->uuid);
768
        } // END: skip empty block content
769
      } // END: skip empty or suppressed features
770
      RenderHints::popFromRenderStack();
771
    } // END: creating a block per feature
772

    
773
    RenderHints::popFromRenderStack();
774

    
775
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
776

    
777
    return _block_get_renderable_array($block_list);
778
  }
779

    
780
/**
781
 * Creates a render array of description elements  held by child nodes of the given feature node.
782
 *
783
 * This function is called recursively!
784
 *
785
 * @param $node
786
 *   The feature node.
787
 * @param array $media_list
788
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
789
 * @param $feature_block_settings
790
 *   The feature block settings.
791
 * @param $main_feature
792
 *  Only used internally in recursive calls.
793
 *
794
 * @return array
795
 *  A Drupal render array
796
 *
797
 * @ingroup compose
798
 */
799
function compose_feature_block_items_nested($node, &$media_list, $feature_block_settings, $main_feature = NULL)
800
{
801

    
802
  if(!$main_feature){
803
    $main_feature = $node->feature;
804
  }
805
  /*
806
   * TODO should be configurable, options; YES, NO, AUTOMATIC
807
   * (automatic will only place the label if the first word of the description element text is not the same)
808
   */
809
  $prepend_feature_label = false;
810

    
811
  $render_arrays = array();
812
  foreach ($node->childNodes as $child_node) {
813
    if (isset($child_node->descriptionElements[0])) {
814
      foreach ($child_node->descriptionElements as $element) {
815

    
816
        if (isset($element->media[0])) {
817
          // Append media of subordinate elements to list of main
818
          // feature.
819
          $media_list = array_merge($media_list, $element->media);
820
        }
821

    
822
        $child_node_element = null;
823
        switch ($element->class) {
824
          case 'TextData':
825
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
826
            break;
827
          case 'CategoricalData':
828
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
829
            break;
830
          case 'QuantitativeData':
831
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
832

    
833
        }
834
        if (is_array($child_node_element)) {
835
          $render_arrays[] = $child_node_element;
836
        }
837
      }
838
    }
839

    
840
    if(isset($child_node->childNodes[0])){
841
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
842
    }
843
  }
844

    
845
  return $render_arrays;
846
}
847

    
848
  /**
849
   *
850
   * @param $node
851
   *  The merged feature three node which potentially contains media in its description elements.
852
   * @param $media_list
853
   *    Additional media to be merged witht the media contained in the nodes description elements
854
   * @param $gallery_settings
855
   * @return array
856
   *
857
   * @ingroup compose
858
   */
859
  function compose_feature_media_gallery($node, $media_list, $gallery_settings) {
860

    
861
    if (isset($node->descriptionElements)) {
862
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
863
    }
864

    
865
    $captionElements = array('title', 'rights');
866

    
867
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
868
      $gallery = compose_cdm_media_gallerie(array(
869
        'mediaList' => $media_list,
870
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $node->feature->uuid,
871
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
872
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
873
        'captionElements' => $captionElements,
874
      ));
875
      return markup_to_render_array($gallery);
876
    }
877

    
878
    return markup_to_render_array('');
879
  }
880

    
881
  /**
882
   * Composes the distribution feature block for a taxon
883
   *
884
   * @param $taxon
885
   * @param $descriptionElements
886
   *   an associative array with two elements:
887
   *   - '#type': must be 'DTO'
888
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
889
   * @param $feature
890
   *
891
   * @return array
892
   *  A drupal render array
893
   *
894
   * @ingroup compose
895
   */
896
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
897
    $text_data_glue = '';
898
    $text_data_sortOutArray = FALSE;
899
    $text_data_enclosingTag = 'ul';
900
    $text_data_out_array = array();
901

    
902
    $distributionElements = NULL;
903
    $distribution_info_dto = NULL;
904
    $distribution_sortOutArray = FALSE;
905

    
906
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
907

    
908
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
909
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
910
      $distribution_glue = '';
911
      $distribution_enclosingTag = 'dl';
912
    } else {
913
      $distribution_glue = '';
914
      $distribution_enclosingTag = 'ul';
915
    }
916

    
917
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
918
      // skip the DISTRIBUTION section if there is no DTO type element
919
      return array(); // FIXME is it ok to return an empty array?
920
    }
921

    
922
    $block = feature_block(
923
      cdm_term_representation($feature, 'Unnamed Feature'),
924
      $feature
925
    );
926

    
927
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
928
    if (isset($descriptionElements['TextData'])) {
929
      // --- TextData
930
      foreach ($descriptionElements['TextData'] as $text_data_element) {
931
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
932
        $repr = drupal_render($text_data_render_array);
933

    
934
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
935
          $text_data_out_array[] = $repr;
936
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
937
          // not work since this array contains html attributes with uuids
938
          // and what is about cases like the bibliography where
939
          // any content can be prefixed with some foot-note anchors?
940
          $text_data_sortOutArray = TRUE;
941
          $text_data_glue = '<br/> ';
942
          $text_data_enclosingTag = 'p';
943
        }
944
      }
945
    }
946

    
947

    
948
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
949
      $block->content[] = compose_feature_block_wrap_elements(
950
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
951
      );
952
    }
953

    
954
    // --- Distribution map
955
    $distribution_map_query_parameters = NULL;
956

    
957
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
958
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
959
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
960
      )
961
    {
962
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
963
    }
964
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
965
    $block->content[] = $map_render_element;
966

    
967
    $dto_out_array = array();
968

    
969
    // --- Condensed Distribution
970
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
971
      $condensed_distribution_markup = '<p class="condensed_distribution">';
972

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

    
985
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
986
        if(!$isFirst){
987
          $condensed_distribution_markup .= ' ';
988
        }
989
        $isFirst = TRUE;
990
        $condensed_distribution_markup .= '[';
991
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
992
          if (!$isFirst) {
993
            $condensed_distribution_markup .= ' ';
994
          }
995
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
996
            . $cdItem->areaStatusLabel . '</span>';
997
          $isFirst = false;
998
        }
999
        $condensed_distribution_markup .= ']';
1000
      }
1001

    
1002
      $condensed_distribution_markup .= '&nbsp;' . l(
1003
          font_awesome_icon_markup(
1004
            'fa-info-circle',
1005
            array(
1006
              'alt'=>'help',
1007
              'class' => array('superscript')
1008
            )
1009
          ),
1010
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
1011
          array('html' => TRUE));
1012
      $condensed_distribution_markup .= '</p>';
1013
      $dto_out_array[] = $condensed_distribution_markup;
1014
    }
1015

    
1016
    // --- tree or list
1017
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1018
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1019

    
1020
      // --- tree
1021
      if (is_object($distribution_info_dto->tree)) {
1022
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
1023
        $dto_out_array[] = $distribution_tree_render_array;
1024
      }
1025

    
1026
      // --- sorted element list
1027
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
1028
        foreach ($distribution_info_dto->elements as $descriptionElement) {
1029
          if (is_object($descriptionElement->area)) {
1030
            $sortKey = $descriptionElement->area->representation_L10n;
1031
            $distributionElements[$sortKey] = $descriptionElement;
1032
          }
1033
        }
1034
        ksort($distributionElements);
1035
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
1036
        $dto_out_array[] = $distribution_element_render_array;
1037

    
1038
      }
1039
      //
1040
      $block->content[] = compose_feature_block_wrap_elements(
1041
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1042
      );
1043
    }
1044

    
1045
    // --- TextData at the bottom
1046
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1047
      $block->content[] = compose_feature_block_wrap_elements(
1048
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1049
      );
1050
    }
1051

    
1052
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
1053
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1054
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1055

    
1056
    return $block;
1057
  }
1058

    
1059

    
1060
  /**
1061
   * Composes a drupal render array for single CDM TextData description element.
1062
   *
1063
   * @param $element
1064
   *    The CDM TextData description element.
1065
   *  @param $feature_uuid
1066
   * @param bool $prepend_feature_label
1067
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1068
   *
1069
   * @return array
1070
   *   A drupal render array with the following elements being used:
1071
   *    - #tag: either 'div', 'li', ...
1072
   *    ⁻ #attributes: class attributes
1073
   *    - #value_prefix: (optionally) contains footnote anchors
1074
   *    - #value: contains the textual content
1075
   *    - #value_suffix: (optionally) contains footnote keys
1076
   *
1077
   * @ingroup compose
1078
   */
1079
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
1080

    
1081
    $footnote_list_key_suggestion = $feature_uuid;
1082

    
1083
    $element_markup = '';
1084
    if (isset($element->multilanguageText_L10n->text)) {
1085
      // TODO replacement of \n by <br> should be configurable
1086
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
1087
    }
1088

    
1089
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1090

    
1091
    return $render_array;
1092
  }
1093

    
1094

    
1095
/**
1096
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
1097
 *
1098
 * @param $element
1099
 *  The CDM TaxonInteraction entity
1100
 *
1101
 * @return
1102
 *  A drupal render array
1103
 *
1104
 * @ingroup compose
1105
 */
1106
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
1107

    
1108
  $out = '';
1109

    
1110

    
1111
  if (isset($element->description_L10n)) {
1112
    $out .=  ' ' . $element->description_L10n;
1113
  }
1114

    
1115
  if(isset($element->taxon2)){
1116
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1117
  }
1118

    
1119
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1120

    
1121
  return $render_array;
1122
}
1123

    
1124

    
1125
/**
1126
 * Renders a single instance of the type IndividualsAssociations.
1127
 *
1128
 * @param $element
1129
 *   The CDM IndividualsAssociations entity.
1130
 * @param $feature_block_settings
1131
 *
1132
 * @return array
1133
 *   Drupal render array
1134
 *
1135
 * @ingroup compose
1136
 */
1137
function compose_description_element_individuals_association($element, $feature_block_settings) {
1138

    
1139
  $out = '';
1140

    
1141
  $render_array = compose_cdm_specimenOrObservation($element->associatedSpecimenOrObservation);
1142

    
1143
  if (isset($element->description_L10n)) {
1144
    $out .=  ' ' . $element->description_L10n;
1145
  }
1146

    
1147
  $out .= drupal_render($render_array);
1148

    
1149
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1150

    
1151
  return $render_array;
1152
}
1153

    
1154
/**
1155
 * Renders a single instance of the type CategoricalData.
1156
 *
1157
 * @param $element
1158
 *  The CDM CategoricalData entity
1159
 *
1160
 * @param $feature_block_settings
1161
 *
1162
 * @param bool $prepend_feature_label
1163
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1164
 *
1165
 * @return string
1166
 *   a html representation of the given CategoricalData element
1167
 *
1168
 * @ingroup compose
1169
 */
1170
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1171

    
1172
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1173

    
1174
  $state_data_strings = array();
1175
  if (isset($element->stateData)) {
1176
    foreach ($element->stateData as $state_data) {
1177

    
1178
      $state  = NULL;
1179

    
1180
      if (isset($state_data->state)) {
1181
        $state = cdm_term_representation($state_data->state);
1182
      }
1183

    
1184
      if (isset($state_data->modifyingText_L10n)) {
1185
        $state = ' ' . $state_data->modifyingText_L10n;
1186
      }
1187

    
1188
      $modifiers_strings = cdm_modifers_representations($state_data);
1189

    
1190
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1191

    
1192
    }
1193
  }
1194

    
1195
  $out = '<span class="' . html_class_attribute_ref($element) . '">' . implode(', ', $state_data_strings) . '</span>';
1196

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

    
1199
  return $render_array;
1200
}
1201

    
1202

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

    
1246
  $out = '';
1247
  $type_representation = NULL;
1248
  $min_max = min_max_array();
1249

    
1250
  $other_values = array();
1251

    
1252
  if (isset($element->statisticalValues)) {
1253
    $other_values_markup = array();
1254
    foreach ($element->statisticalValues as $statistical_val) {
1255

    
1256
      // compile the full value string which also may contain modifiers
1257
      if (isset($statistical_val->value)) {
1258
        $statistical_val->_value = $statistical_val->value;
1259
      }
1260
      $val_modifiers_strings = cdm_modifers_representations($statistical_val);
1261
      if ($val_modifiers_strings) {
1262
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1263
      }
1264

    
1265
      // either put into min max array or into $other_values
1266
      // for generic output to be appended to 'min-max' string
1267
      if (array_key_exists($statistical_val->type->titleCache, $min_max)) {
1268
        $min_max[$statistical_val->type->titleCache] = $statistical_val;
1269
      }
1270
      else {
1271
        $other_values[] = $statistical_val;
1272
      }
1273
    } // end of loop over statisticalValues
1274

    
1275
    // create markup
1276

    
1277
    $min_max_markup = min_max_markup($min_max);
1278

    
1279

    
1280
    foreach ($other_values as $statistical_val) {
1281
      $statistical_val_type_representation = NULL;
1282
      if (isset($statistical_val->type)) {
1283
        $statistical_val_type_representation = cdm_term_representation($statistical_val->type);
1284
        // $statistical_val->type->termType;
1285
        // $statistical_val->type->userFriendlyTypeName;
1286
      }
1287
      $value_markup = '<span class="' . html_class_attribute_ref($statistical_val) . ' ' . $statistical_val->type->termType . ' ">'
1288
        . $statistical_val->_value . '</span>';
1289
      $value_markup = $value_markup .
1290
        ($statistical_val_type_representation ? ' <span class="type">' . $statistical_val_type_representation . '</span>' : '');
1291
      $other_values_markup[] = $value_markup;
1292
    }
1293

    
1294

    
1295
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1296
  }
1297

    
1298
  if (isset($element->unit)) {
1299
    $out .= ' <span class="unit" title="'
1300
      . cdm_term_representation($element->unit) . '">'
1301
      . cdm_term_representation_abbreviated($element->unit)
1302
      . '</span>';
1303
  }
1304

    
1305
  // modifiers of the description element itself
1306
  $modifier_string = cdm_modifers_representations($element);
1307
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1308
  if (isset($element->modifyingText_L10n)) {
1309
    $out = $element->modifyingText_L10n . ' ' . $out;
1310
  }
1311

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

    
1314
  return $render_array;
1315
}
1316

    
1317

    
1318
/**
1319
 * Wraps the render array for the given feature into an enclosing html tag.
1320
 *
1321
 * Optionally the elements can be sorted and glued together by a separator string.
1322
 *
1323
 * @param array $description_element_render_arrays
1324
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1325
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1326
 * @param  $feature :
1327
 *  The feature to which the elements given in $elements are belonging to.
1328
 * @param string $glue :
1329
 *  Defaults to empty string.
1330
 * @param bool $sort
1331
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1332
 *
1333
 * @return array
1334
 *    A Drupal render array
1335
 *
1336
 * @ingroup compose
1337
 */
1338
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1339
  {
1340

    
1341
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1342
    $enclosing_tag = $feature_block_settings['as_list'];
1343

    
1344
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1345
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1346
    }
1347

    
1348
    $is_first = true;
1349
    foreach($description_element_render_arrays as &$element_render_array){
1350
      if(!is_array($element_render_array)){
1351
        $element_render_array = markup_to_render_array($element_render_array);
1352
      }
1353
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1354

    
1355
      // add the glue!
1356
      if(!$is_first) {
1357
        if (isset($element_render_array['#value'])) {
1358
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1359
        } elseif (isset($element_render_array['#markup'])) {
1360
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1361
        }
1362
      }
1363
      $is_first = false;
1364
    }
1365

    
1366
    $render_array['elements']['children'] = $description_element_render_arrays;
1367

    
1368
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1369
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1370

    
1371
    return $render_array;
1372
  }
1373

    
1374

    
1375
  /* compose nameInSource or originalNameString as markup
1376
   *
1377
   * @param $source
1378
   * @param $do_link_to_name_used_in_source
1379
   * @param $suppress_for_shown_taxon
1380
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1381
   *    for which the taxon page is being created, Defaults to TRUE
1382
   *
1383
   * @return array
1384
   *    A Drupal render array with an additional element, the render array is empty
1385
   *    if the source had no name in source information
1386
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1387
   *
1388
   * @ingroup compose
1389
   */
1390
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1391

    
1392
    $plaintext = NULL;
1393
    $markup = NULL;
1394
    $name_in_source_render_array = array();
1395

    
1396
    static $taxon_page_accepted_name = '';
1397
    $taxon_uuid = get_current_taxon_uuid();
1398
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1399

    
1400
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1401
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1402
    }
1403

    
1404
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1405
      // it is a DescriptionElementSource !
1406
      $plaintext = $source->nameUsedInSource->titleCache;
1407
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1408
        return $name_in_source_render_array; // SKIP this name
1409
      }
1410
      $markup = render_taxon_or_name($source->nameUsedInSource);
1411
      if ($do_link_to_name_used_in_source) {
1412
        $markup = l(
1413
          $markup,
1414
          path_to_name($source->nameUsedInSource->uuid),
1415
          array(
1416
            'attributes' => array(),
1417
            'absolute' => TRUE,
1418
            'html' => TRUE,
1419
          ));
1420
      }
1421
    }
1422
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1423
      // the name used in source can not be expressed as valid taxon name,
1424
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1425
      // field
1426
      // using the originalNameString as key to avoid duplicate entries
1427
      $plaintext = $source->originalNameString;
1428
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1429
        return $name_in_source_render_array; // SKIP this name
1430
      }
1431
      $markup = $source->originalNameString;
1432
    }
1433

    
1434
    if ($plaintext) { // checks if we have any content
1435
      $name_in_source_render_array = markup_to_render_array($markup);
1436
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1437
    }
1438

    
1439
    return $name_in_source_render_array;
1440
  }
1441

    
1442

    
1443

    
1444
  /**
1445
   * Return HTML for a list of description elements.
1446
   *
1447
   * Usually these are of a specific feature type.
1448
   *
1449
   * @param $description_elements
1450
   *   array of descriptionElements which belong to the same feature.
1451
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1452
   *   calling the function _mergeFeatureTreeDescriptions().
1453
   *   @see _mergeFeatureTreeDescriptions()
1454
   *
1455
   * @param  $feature_uuid
1456
   *
1457
   * @return
1458
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1459
   *    Footnote key or anchors are not considered to be textual content.
1460
   *
1461
   * @ingroup compose
1462
   */
1463
  function compose_feature_block_items_generic($description_elements, $feature) {
1464

    
1465
    $elements_out_array = array();
1466
    $distribution_tree = null;
1467

    
1468
    /*
1469
     * $feature_block_has_content will be set true if at least one of the
1470
     * $descriptionElements contains some text which makes up some content
1471
     * for the feature block. Footnote keys are not considered
1472
     * to be content in this sense.
1473
     */
1474
    $feature_block_has_content = false;
1475

    
1476
    if (is_array($description_elements)) {
1477
      foreach ($description_elements as $description_element) {
1478
          /* decide based on the description element class
1479
           *
1480
           * Features handled here:
1481
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1482
           *
1483
           * TODO provide api_hook as extension point for this?
1484
           */
1485
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1486
        switch ($description_element->class) {
1487
          case 'TextData':
1488
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1489
            break;
1490
          case 'CategoricalData':
1491
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1492
            break;
1493
          case 'QuantitativeData':
1494
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1495
            break;
1496
          case 'IndividualsAssociation':
1497
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1498
            break;
1499
          case 'TaxonInteraction':
1500
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1501
            break;
1502
          case 'CommonTaxonName':
1503
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1504
            break;
1505
          case 'Uses':
1506
            /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1507
            break;
1508
          default:
1509
            $feature_block_has_content = true;
1510
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1511
        }
1512
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1513
        // considering not empty as long as the last item added is a render array
1514
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1515
      }
1516

    
1517
      // If feature = CITATION sort the list of sources.
1518
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1519
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1520
        sort($elements_out_array);
1521
      }
1522
    }
1523

    
1524
    // sanitize: remove empty and NULL items from the render array
1525
    $tmp_out_array = $elements_out_array;
1526
    $elements_out_array = array();
1527
    foreach($tmp_out_array as $item){
1528
      if(is_array($item) && count($item) > 0){
1529
        $elements_out_array[] = $item;
1530
      }
1531
    }
1532

    
1533
    return $elements_out_array;
1534
  }
1535

    
1536
/**
1537
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1538
 *
1539
 * @parameter $elements
1540
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1541
 * @parameter $feature
1542
 *  the common feature of all $elements, must be CommonName
1543
 *
1544
 * @return
1545
 *   A drupal render array
1546
 *
1547
 * @ingroup compose
1548
 */
1549
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1550

    
1551
  $common_name_out = '';
1552
  $common_name_feature_elements = array();
1553
  $textData_commonNames = array();
1554

    
1555
  $footnote_key_suggestion = 'common-names-feature-block';
1556

    
1557
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1558

    
1559
  if (is_array($elements)) {
1560
    foreach ($elements as $element) {
1561

    
1562
      if ($element->class == 'CommonTaxonName') {
1563

    
1564
        // common name without a language or area, should not happen but is possible
1565
        $language_area_key = '';
1566
        if (isset($element->language->representation_L10n)) {
1567
          $language_area_key .= $element->language->representation_L10n ;
1568
        }
1569
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1570
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1571
        }
1572
        if($language_area_key){
1573
          $language_area_key = '<span class="language-area-label">' . $language_area_key . '<span class="separator">: </span></span>';
1574
        }
1575

    
1576
        if(isset($common_names[$language_area_key][$element->name])) {
1577
          // same name already exists for language and area combination, se we merge the description elements
1578
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1579
        } else{
1580
          // otherwise add as new entry
1581
          $common_names[$language_area_key][$element->name] = $element;
1582
        }
1583

    
1584
      }
1585
      elseif ($element->class == 'TextData') {
1586
        $textData_commonNames[] = $element;
1587
      }
1588
    }
1589
  }
1590
  // Handling common names.
1591
  if (isset($common_names) && count($common_names) > 0) {
1592
    // Sorting the array based on the key (language, + area if set).
1593
    // Comment @WA there are common names without a language, so this sorting
1594
    // can give strange results.
1595
    ksort($common_names);
1596

    
1597
    // loop over set of elements per language area
1598
    foreach ($common_names as $language_area_key => $elements) {
1599
      ksort($elements); // sort names alphabetically
1600
      $per_language_area_out = array();
1601

    
1602
      foreach ($elements as $element) {
1603
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1604
        $common_name_markup = drupal_render($common_name_render_array);
1605
        // IMPORTANT!
1606
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1607
        // this is an error and the trailing whitespace needs to be removed
1608
        if(str_endsWith($common_name_markup, "\n")){
1609
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1610
        }
1611
        $per_language_area_out[] = $common_name_markup;
1612
      }
1613

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

    
1617

    
1618
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1619
      $common_name_feature_elements, $feature, '; ', FALSE
1620
    );
1621
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1622

    
1623
  }
1624

    
1625
  // Handling commons names as text data.
1626
  $text_data_out = array();
1627

    
1628
  foreach ($textData_commonNames as $text_data_element) {
1629
    /* footnotes are not handled correctly in compose_description_element_text_data,
1630
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1631
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1632
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1633
    $text_data_out[] = drupal_render($text_data_render_array);
1634
  }
1635

    
1636
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1637
    $text_data_out, $feature
1638
  );
1639

    
1640
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1641
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1642
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1643

    
1644
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1645
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1646
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1647
    .$footnotes,
1648
    $weight
1649
  );
1650
}
1651

    
1652
/**
1653
 * Renders a single instance of the type CommonTaxonName.
1654
 *
1655
 * @param $element
1656
 *   The CDM CommonTaxonName entity.
1657
 * @param $feature_block_settings
1658
 *
1659
 * @param $footnote_key_suggestion
1660
 *
1661
 * @param $element_tag_name
1662
 *
1663
 * @return array
1664
 *   Drupal render array
1665
 *
1666
 * @ingroup compose
1667
 */
1668
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion = NULL)
1669
{
1670

    
1671
  if(!$footnote_key_suggestion) {
1672
    $footnote_key_suggestion = $element->feature->uuid;
1673
  }
1674

    
1675
  $name = '';
1676
  if(isset($element->name)){
1677
    $name = $element->name;
1678
  }
1679

    
1680

    
1681
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1682
}
1683

    
1684
/**
1685
 * Composes the render array for a CDM Distribution description element
1686
 *
1687
 * @param array $description_elements
1688
 *   Array of CDM Distribution instances
1689
 * @param $enclosingTag
1690
 *   The html tag to be use for the enclosing element
1691
 *
1692
 * @return array
1693
 *   A Drupal render array
1694
 *
1695
 * @ingroup compose
1696
 */
1697
function compose_description_elements_distribution($description_elements){
1698

    
1699
  $out = '';
1700
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1701
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1702

    
1703
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1704
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1705

    
1706
  foreach ($description_elements as $description_element) {
1707
    $annotations_and_sources = handle_annotations_and_sources(
1708
      $description_element,
1709
      handle_annotations_and_sources_config($feature_block_settings),
1710
      $description_element->area->representation_L10n,
1711
      UUID_DISTRIBUTION
1712
    );
1713

    
1714

    
1715
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1716

    
1717
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1718
      . ' " title="' . $status_label. '">'
1719
      . $description_element->area->representation_L10n
1720
      . $status_markup;
1721
    if(!empty($annotations_and_sources['source_references'])){
1722
      $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1723
    }
1724
    $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1725
  }
1726

    
1727
  RenderHints::popFromRenderStack();
1728
  return markup_to_render_array($out);
1729
}
1730

    
1731
  /**
1732
   * @param $descriptionElement
1733
   * @return array
1734
   */
1735
  function distribution_status_label_and_markup($descriptionElement, $status_glue = '&#8210; ') {
1736
    $status_markup = '';
1737
    $status_label = '';
1738

    
1739
    if (isset($descriptionElement->status)) {
1740
      $status_label = $descriptionElement->status->representation_L10n;
1741
      $status_markup =  '<span class="distributionStatus"> '
1742
        . $status_glue
1743
        . '<span class="distributionStatus-' . $descriptionElement->status->idInVocabulary . '">'
1744
        . $status_label
1745
        . '</span></span>';
1746

    
1747
    };
1748
    return array($status_label, $status_markup);
1749
  }
1750

    
1751

    
1752
  /**
1753
   * Provides the merged feature tree for a taxon profile page.
1754
   *
1755
   * The merging of the profile feature tree is actully done in
1756
   * _mergeFeatureTreeDescriptions(). See this method  for details
1757
   * on the structure of the merged tree.
1758
   *
1759
   * This method provides t hook which can be used to modify the
1760
   * merged feature tree after it has been created, see
1761
   * hook_merged_taxon_feature_tree_alter()
1762
   *
1763
   * @param $taxon
1764
   *   A CDM Taxon instance
1765
   *
1766
   * @return object
1767
   *  The merged feature tree
1768
   *
1769
   */
1770
  function merged_taxon_feature_tree($taxon) {
1771

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

    
1775

    
1776
    // 2. find the distribution feature node
1777
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1778

    
1779
    if ($distribution_node) {
1780
      // 3. get the distributionInfoDTO
1781
      $query_parameters = cdm_distribution_filter_query();
1782
      $query_parameters['part'] = array('mapUriParams');
1783
      if(variable_get(DISTRIBUTION_CONDENSED)){
1784
        $query_parameters['part'][] = 'condensedDistribution';
1785
      }
1786
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1787
        $query_parameters['part'][] = 'tree';
1788
      }
1789
      else {
1790
        $query_parameters['part'][] = 'elements';
1791
      }
1792
      $query_parameters['omitLevels'] = array();
1793
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1794
        if(is_uuid($uuid)){
1795
          $query_parameters['omitLevels'][] = $uuid;
1796
        }
1797
      }
1798
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1799
      if ($customStatusColorsJson) {
1800
        $query_parameters['statusColors'] = $customStatusColorsJson;
1801
      }
1802

    
1803
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1804
      // 4. get distribution TextData is there are any
1805
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1806
        array(
1807
          'taxon' => $taxon->uuid,
1808
          'type' => 'TextData',
1809
          'features' => UUID_DISTRIBUTION
1810
        )
1811
      );
1812

    
1813
      // 5. put all distribution data into the distribution feature node
1814
      if ($distribution_text_data //if text data exists
1815
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1816
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1817
      ) { // OR if DTO has distribution elements
1818
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1819
        if ($distribution_text_data) {
1820
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1821
        }
1822
        if ($distribution_info_dto) {
1823
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1824
        }
1825
      }
1826
    }
1827

    
1828
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1829
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1830

    
1831
    return $merged_tree;
1832
  }
1833

    
1834

    
1835
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1836

    
1837
    static $hierarchy_style;
1838
    // TODO expose $hierarchy_style to administration or provide a hook
1839
    if( !isset($hierarchy_style)){
1840
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1841
    }
1842

    
1843
    $render_array = array();
1844

    
1845
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1846
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1847

    
1848
    // Returning NULL if there are no description elements.
1849
    if ($distribution_tree == null) {
1850
      return $render_array;
1851
    }
1852
    // for now we are not using a render array internally to avoid performance problems
1853
    $markup = '';
1854
    if (isset($distribution_tree->rootElement->children)) {
1855
      $tree_nodes = $distribution_tree->rootElement->children;
1856
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1857
    }
1858

    
1859
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1860
      $markup,
1861
      0,
1862
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1863
      '</div>'
1864
    );
1865

    
1866
    RenderHints::popFromRenderStack();
1867

    
1868
    return $render_array;
1869
  }
1870

    
1871
  /**
1872
   * this function should produce markup as the compose_description_elements_distribution()
1873
   * function.
1874
   *
1875
   * @see compose_description_elements_distribution()
1876
   *
1877
   * @param $distribution_tree
1878
   * @param $feature_block_settings
1879
   * @param $tree_nodes
1880
   * @param $markup
1881
   * @param $hierarchy_style
1882
   */
1883
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1884

    
1885
    $level_index++;
1886
    static $enclosingTag = "span";
1887

    
1888
    $level_style = array_shift($hierarchy_style);
1889
    if(count($hierarchy_style) == 0){
1890
      // lowest defined level style will be reused for all following levels
1891
      $hierarchy_style[] = $level_style;
1892
    }
1893

    
1894
    $node_index = -1;
1895
    $per_node_markup = array();
1896
    foreach ($tree_nodes as $node){
1897

    
1898
      $per_node_markup[++$node_index] = '';
1899

    
1900
      $label = $node->nodeId->representation_L10n;
1901

    
1902
      $distributions = $node->data;
1903
      $distribution_uuids = array();
1904
      $distribution_aggregate = NULL;
1905
        foreach($distributions as $distribution){
1906

    
1907
          $distribution_uuids[] = $distribution->uuid;
1908

    
1909
          // if there is more than one distribution we aggregate the sources and
1910
          // annotations into a synthetic distribution so that the footnote keys
1911
          // can be rendered consistently
1912
          if(!$distribution_aggregate) {
1913
            $distribution_aggregate = $distribution;
1914
            if(!isset($distribution_aggregate->sources[0])){
1915
              $distribution_aggregate->sources = array();
1916
            }
1917
            if(!isset($distribution_aggregate->annotations[0])){
1918
              $distribution_aggregate->annotations = array();
1919
            }
1920
          } else {
1921
            if(isset($distribution->sources[0])) {
1922
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1923
                $distribution->sources);
1924
            }
1925
            if(isset($distribution->annotations[0])) {
1926
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1927
                $distribution->annotations);
1928
            }
1929
          }
1930
        }
1931

    
1932
      $status_label= '';
1933
      $status_markup = '';
1934
      $annotations_and_sources =  null;
1935
      if($distribution_aggregate) {
1936
        $annotations_and_sources = handle_annotations_and_sources(
1937
          $distribution_aggregate,
1938
          handle_annotations_and_sources_config($feature_block_settings),
1939
          $label,
1940
          UUID_DISTRIBUTION
1941
        );
1942

    
1943
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution, $level_style['status_glue']);
1944
      }
1945

    
1946
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1947
        . join(' descriptionElement-', $distribution_uuids)
1948
        . ' level_index_' . $level_index
1949
        . ' " title="' . $status_label . '">'
1950
        . '<span class="area_label">' . $label
1951
        . $level_style['label_suffix'] . '</span>'
1952
        . $status_markup
1953
      ;
1954

    
1955
      if(isset($annotations_and_sources)){
1956
        if(!empty($annotations_and_sources['source_references'])){
1957
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1958
        }
1959
        if($annotations_and_sources['foot_note_keys']) {
1960
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1961
        }
1962
      }
1963

    
1964
      if(isset($node->children[0])){
1965
        _compose_distribution_hierarchy(
1966
          $node->children,
1967
          $feature_block_settings,
1968
          $per_node_markup[$node_index],
1969
          $hierarchy_style,
1970
          $level_index
1971
        );
1972
      }
1973

    
1974
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1975
    }
1976
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
1977
  }
1978

    
1979

    
(2-2/10)