Project

General

Profile

Download (71.5 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
  $timescope_markup = '';
464
  if(isset($element->timeperiod)){
465
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, false);
466
  }
467

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

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

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

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

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

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

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

    
524
  return $config;
525
}
526

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

    
553
    $annotations_and_sources = array(
554
      'foot_note_keys' => NULL,
555
      'source_references' => array(),
556
      'names_used_in_source' => array()
557
    );
558

    
559
    usort($entity->sources, 'compare_original_sources');
560

    
561
    if ($config['sources_as_content'] == 1) {
562
      foreach ($entity->sources as $source) {
563
        if (_is_original_source_type($source)) {
564
          $reference_citation = theme('cdm_OriginalSource',
565
            array(
566
              'source' => $source,
567
              'doLink' => $config['link_to_reference'] == 1,
568
              'do_link_to_name_used_in_source' => $config['link_to_name_used_in_source'] == 1,
569
            )
570
          );
571

    
572
          if ($reference_citation) {
573
            if (empty($inline_text_prefix)) {
574
              $annotations_and_sources['source_references'][] = $reference_citation;
575
            } else {
576
              $annotations_and_sources['source_references'][] = ' (' . $reference_citation . ')';
577
            }
578
          }
579

    
580
          $name_in_source_render_array = compose_name_in_source(
581
            $source,
582
            $config['link_to_name_used_in_source'] == 1
583
          );
584

    
585
          if (!empty($name_in_source_render_array)) {
586
            $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
587
          }
588
        }
589
      } // END of loop over sources
590

    
591
      // annotations footnotes separate.
592
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
593
        array(
594
          'cdmBase_list' => $entity,
595
          'footnote_list_key' => $footnote_list_key_suggestion,
596
        )
597
      );
598

    
599
    } // END of references inline
600

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

    
620
    return $annotations_and_sources;
621
  }
622

    
623

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

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

    
662

    
663
/* ==================== COMPOSE FUNCTIONS =============== */
664

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

    
688
    $block_list = array();
689

    
690
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
691

    
692
    $use_description_features = array(UUID_USE);
693

    
694

    
695
    RenderHints::pushToRenderStack('feature_block');
696
    // Create a drupal block for each feature
697
    foreach ($mergedFeatureNodes as $feature_node) {
698

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

    
702
        RenderHints::pushToRenderStack($feature_node->term->uuid);
703
          
704
        $feature_name = cdm_term_representation($feature_node->term, 'Unnamed Feature');
705
        $feature_block_settings = get_feature_block_settings($feature_node->term->uuid);
706
        
707

    
708
        $block = feature_block($feature_name, $feature_node->term);
709
        $block->content = array();
710
        $block_content_is_empty = TRUE;
711

    
712
        if(array_search($feature_node->term->uuid, $use_description_features) !== false) {
713
          // do not show features which belong to the UseDescriptions, these are
714
          // handled by compose_feature_block_items_use_records() where the according descriptions are
715
          // fetched again separately.
716
          // UseDescriptions are a special feature introduced for palmweb
717
          continue;
718
        }
719

    
720
        /*
721
         * Content/DISTRIBUTION.
722
         */
723
        if ($feature_node->term->uuid == UUID_DISTRIBUTION) {
724
          $block = compose_feature_block_distribution($taxon, $feature_node->descriptionElements, $feature_node->term);
725
          $block_content_is_empty = FALSE;
726
        }
727

    
728
        /*
729
         * Content/COMMON_NAME.
730
         */
731
        else if ($feature_node->term->uuid == UUID_COMMON_NAME) {
732
          $common_names_render_array = compose_feature_block_items_feature_common_name($feature_node->descriptionElements, $feature_node->term);
733
          $block->content[] = $common_names_render_array;
734
          $block_content_is_empty = FALSE;
735
        }
736

    
737
        /*
738
         * Content/Use Description (Use + UseRecord)
739
         */
740
        else if ($feature_node->term->uuid == UUID_USE_RECORD) {
741
          $block->content[] = cdm_block_use_description_content($taxon->uuid, $feature_node->term);
742
          $block_content_is_empty = FALSE;
743
        }
744

    
745
        /*
746
         * Content/ALL OTHER FEATURES.
747
         */
748
        else {
749

    
750
          $media_list = array();
751
          $elements_render_array = array();
752
          $child_elements_render_array = null;
753

    
754
          if (isset($feature_node->descriptionElements[0])) {
755
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements, $feature_node->term);
756
          }
757

    
758
          // Content/ALL OTHER FEATURES/Subordinate Features
759
          // subordinate features are printed inline in one floating text,
760
          // it is expected hat subordinate features can "contain" TextData,
761
          // Qualitative- and Qualitative- DescriptionElements
762
          if (isset($feature_node->childNodes[0])) {
763
            $child_elements_render_array = compose_feature_block_items_nested($feature_node, $media_list, $feature_block_settings);
764
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
765
          }
766
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
767
          if(!$block_content_is_empty){
768
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $feature_node->term, $feature_block_settings['glue']);
769
            $block->content[] = compose_feature_media_gallery($feature_node, $media_list, $gallery_settings);
770
            /*
771
             * Footnotes for the feature block
772
             */
773
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $feature_node->term->uuid)));
774
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $feature_node->term->uuid)));
775
            $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $feature_node->term->uuid)));
776
          }
777
        } // END all other features
778

    
779
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
780
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
781

    
782
        if(!$block_content_is_empty){ // skip empty block content
783
          $block_list[] = $block;
784
          cdm_toc_list_add_item(cdm_term_representation($feature_node->term), $feature_node->term->uuid);
785
        } // END: skip empty block content
786
      } // END: skip empty or suppressed features
787
      RenderHints::popFromRenderStack();
788
    } // END: creating a block per feature
789

    
790
    RenderHints::popFromRenderStack();
791

    
792
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
793

    
794
    return  $block_list;
795
  }
796

    
797
/**
798
 * Creates a render array of description elements  held by child nodes of the given feature node.
799
 *
800
 * This function is called recursively!
801
 *
802
 * @param $feature_node
803
 *   The feature node.
804
 * @param array $media_list
805
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
806
 * @param $feature_block_settings
807
 *   The feature block settings.
808
 * @param $main_feature
809
 *  Only used internally in recursive calls.
810
 *
811
 * @return array
812
 *  A Drupal render array
813
 *
814
 * @ingroup compose
815
 */
816
function compose_feature_block_items_nested($feature_node, &$media_list, $feature_block_settings, $main_feature = NULL)
817
{
818

    
819
  if(!$main_feature){
820
    $main_feature = $feature_node->term;
821
  }
822
  /*
823
   * TODO should be configurable, options; YES, NO, AUTOMATIC
824
   * (automatic will only place the label if the first word of the description element text is not the same)
825
   */
826
  $prepend_feature_label = false;
827

    
828
  $render_arrays = array();
829
  foreach ($feature_node->childNodes as $child_node) {
830
    if (isset($child_node->descriptionElements[0])) {
831
      foreach ($child_node->descriptionElements as $element) {
832

    
833
        if (isset($element->media[0])) {
834
          // Append media of subordinate elements to list of main
835
          // feature.
836
          $media_list = array_merge($media_list, $element->media);
837
        }
838

    
839
        $child_node_element = null;
840
        switch ($element->class) {
841
          case 'TextData':
842
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
843
            break;
844
          case 'CategoricalData':
845
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
846
            break;
847
          case 'QuantitativeData':
848
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
849

    
850
        }
851
        if (is_array($child_node_element)) {
852
          $render_arrays[] = $child_node_element;
853
        }
854
      }
855
    }
856

    
857
    if(isset($child_node->childNodes[0])){
858
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
859
    }
860
  }
861

    
862
  return $render_arrays;
863
}
864

    
865
  /**
866
   *
867
   * @param $feature_node
868
   *  The merged feature three node which potentially contains media in its description elements.
869
   * @param $media_list
870
   *    Additional media to be merged witht the media contained in the nodes description elements
871
   * @param $gallery_settings
872
   * @return array
873
   *
874
   * @ingroup compose
875
   */
876
  function compose_feature_media_gallery($feature_node, $media_list, $gallery_settings) {
877

    
878
    if (isset($feature_node->descriptionElements)) {
879
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
880
    }
881

    
882
    $captionElements = array('title', 'rights');
883

    
884
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
885
      $gallery = compose_cdm_media_gallerie(array(
886
        'mediaList' => $media_list,
887
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $feature_node->term->uuid,
888
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
889
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
890
        'captionElements' => $captionElements,
891
      ));
892
      return markup_to_render_array($gallery);
893
    }
894

    
895
    return markup_to_render_array('');
896
  }
897

    
898
  /**
899
   * Composes the distribution feature block for a taxon
900
   *
901
   * @param $taxon
902
   * @param $descriptionElements
903
   *   an associative array with two elements:
904
   *   - '#type': must be 'DTO'
905
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
906
   * @param $feature
907
   *
908
   * @return array
909
   *  A drupal render array
910
   *
911
   * @ingroup compose
912
   */
913
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
914
    $text_data_glue = '';
915
    $text_data_sortOutArray = FALSE;
916
    $text_data_enclosingTag = 'ul';
917
    $text_data_out_array = array();
918

    
919
    $distributionElements = NULL;
920
    $distribution_info_dto = NULL;
921
    $distribution_sortOutArray = FALSE;
922

    
923
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
924

    
925
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
926
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
927
      $distribution_glue = '';
928
      $distribution_enclosingTag = 'dl';
929
    } else {
930
      $distribution_glue = '';
931
      $distribution_enclosingTag = 'ul';
932
    }
933

    
934
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
935
      // skip the DISTRIBUTION section if there is no DTO type element
936
      return array(); // FIXME is it ok to return an empty array?
937
    }
938

    
939
    $block = feature_block(
940
      cdm_term_representation($feature, 'Unnamed Feature'),
941
      $feature
942
    );
943

    
944
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
945
    if (isset($descriptionElements['TextData'])) {
946
      // --- TextData
947
      foreach ($descriptionElements['TextData'] as $text_data_element) {
948
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
949
        $repr = drupal_render($text_data_render_array);
950

    
951
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
952
          $text_data_out_array[] = $repr;
953
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
954
          // not work since this array contains html attributes with uuids
955
          // and what is about cases like the bibliography where
956
          // any content can be prefixed with some foot-note anchors?
957
          $text_data_sortOutArray = TRUE;
958
          $text_data_glue = '<br/> ';
959
          $text_data_enclosingTag = 'p';
960
        }
961
      }
962
    }
963

    
964

    
965
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
966
      $block->content[] = compose_feature_block_wrap_elements(
967
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
968
      );
969
    }
970

    
971
    // --- Distribution map
972
    $distribution_map_query_parameters = NULL;
973

    
974
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
975
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
976
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
977
      )
978
    {
979
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
980
    }
981
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
982
    $block->content[] = $map_render_element;
983

    
984
    $dto_out_array = array();
985

    
986
    // --- Condensed Distribution
987
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
988
      $condensed_distribution_markup = '<p class="condensed_distribution">';
989

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

    
1002
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
1003
        if(!$isFirst){
1004
          $condensed_distribution_markup .= ' ';
1005
        }
1006
        $isFirst = TRUE;
1007
        $condensed_distribution_markup .= '[';
1008
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
1009
          if (!$isFirst) {
1010
            $condensed_distribution_markup .= ' ';
1011
          }
1012
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
1013
            . $cdItem->areaStatusLabel . '</span>';
1014
          $isFirst = false;
1015
        }
1016
        $condensed_distribution_markup .= ']';
1017
      }
1018

    
1019
      $condensed_distribution_markup .= '&nbsp;' . l(
1020
          font_awesome_icon_markup(
1021
            'fa-info-circle',
1022
            array(
1023
              'alt'=>'help',
1024
              'class' => array('superscript')
1025
            )
1026
          ),
1027
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
1028
          array('html' => TRUE));
1029
      $condensed_distribution_markup .= '</p>';
1030
      $dto_out_array[] = $condensed_distribution_markup;
1031
    }
1032

    
1033
    // --- tree or list
1034
    if (isset($descriptionElements['DistributionInfoDTO'])) {
1035
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
1036

    
1037
      // --- tree
1038
      if (is_object($distribution_info_dto->tree)) {
1039
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
1040
        $dto_out_array[] = $distribution_tree_render_array;
1041
      }
1042

    
1043
      // --- sorted element list
1044
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
1045
        foreach ($distribution_info_dto->elements as $descriptionElement) {
1046
          if (is_object($descriptionElement->area)) {
1047
            $sortKey = $descriptionElement->area->representation_L10n;
1048
            $distributionElements[$sortKey] = $descriptionElement;
1049
          }
1050
        }
1051
        ksort($distributionElements);
1052
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
1053
        $dto_out_array[] = $distribution_element_render_array;
1054

    
1055
      }
1056
      //
1057
      $block->content[] = compose_feature_block_wrap_elements(
1058
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
1059
      );
1060
    }
1061

    
1062
    // --- TextData at the bottom
1063
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
1064
      $block->content[] = compose_feature_block_wrap_elements(
1065
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
1066
      );
1067
    }
1068

    
1069
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
1070
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1071
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
1072

    
1073
    return $block;
1074
  }
1075

    
1076

    
1077
  /**
1078
   * Composes a drupal render array for single CDM TextData description element.
1079
   *
1080
   * @param $element
1081
   *    The CDM TextData description element.
1082
   *  @param $feature_uuid
1083
   * @param bool $prepend_feature_label
1084
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1085
   *
1086
   * @return array
1087
   *   A drupal render array with the following elements being used:
1088
   *    - #tag: either 'div', 'li', ...
1089
   *    ⁻ #attributes: class attributes
1090
   *    - #value_prefix: (optionally) contains footnote anchors
1091
   *    - #value: contains the textual content
1092
   *    - #value_suffix: (optionally) contains footnote keys
1093
   *
1094
   * @ingroup compose
1095
   */
1096
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
1097

    
1098
    $footnote_list_key_suggestion = $feature_uuid;
1099

    
1100
    $element_markup = '';
1101
    if (isset($element->multilanguageText_L10n->text)) {
1102
      // TODO replacement of \n by <br> should be configurable
1103
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
1104
    }
1105

    
1106
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1107

    
1108
    return $render_array;
1109
  }
1110

    
1111

    
1112
/**
1113
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
1114
 *
1115
 * @param $element
1116
 *  The CDM TaxonInteraction entity
1117
 *
1118
 * @return
1119
 *  A drupal render array
1120
 *
1121
 * @ingroup compose
1122
 */
1123
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
1124

    
1125
  $out = '';
1126

    
1127

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

    
1132
  if(isset($element->taxon2)){
1133
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1134
  }
1135

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

    
1138
  return $render_array;
1139
}
1140

    
1141

    
1142
/**
1143
 * Renders a single instance of the type IndividualsAssociations.
1144
 *
1145
 * @param $element
1146
 *   The CDM IndividualsAssociations entity.
1147
 * @param $feature_block_settings
1148
 *
1149
 * @return array
1150
 *   Drupal render array
1151
 *
1152
 * @ingroup compose
1153
 */
1154
function compose_description_element_individuals_association($element, $feature_block_settings) {
1155

    
1156
  $out = '';
1157

    
1158
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1159

    
1160
  if (isset($element->description_L10n)) {
1161
    $out .=  ' ' . $element->description_L10n;
1162
  }
1163

    
1164
  $out .= drupal_render($render_array);
1165

    
1166
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1167

    
1168
  return $render_array;
1169
}
1170

    
1171
/**
1172
 * Renders a single instance of the type CategoricalData.
1173
 *
1174
 * @param $element
1175
 *  The CDM CategoricalData entity
1176
 *
1177
 * @param $feature_block_settings
1178
 *
1179
 * @param bool $prepend_feature_label
1180
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1181
 *
1182
 * @return string
1183
 *   a html representation of the given CategoricalData element
1184
 *
1185
 * @ingroup compose
1186
 */
1187
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1188

    
1189
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1190

    
1191
  $state_data_strings = array();
1192
  if (isset($element->stateData)) {
1193
    foreach ($element->stateData as $state_data) {
1194

    
1195
      $state  = NULL;
1196

    
1197
      if (isset($state_data->state)) {
1198
        $state = cdm_term_representation($state_data->state);
1199
      }
1200

    
1201
      if (isset($state_data->modifyingText_L10n)) {
1202
        $state = ' ' . $state_data->modifyingText_L10n;
1203
      }
1204

    
1205
      $modifiers_strings = cdm_modifers_representations($state_data);
1206

    
1207
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1208

    
1209
    }
1210
  }
1211

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

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

    
1216
  return $render_array;
1217
}
1218

    
1219

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

    
1263
  $out = '';
1264
  $type_representation = NULL;
1265
  $min_max = min_max_array();
1266

    
1267
  $other_values = array();
1268

    
1269
  if (isset($element->statisticalValues)) {
1270
    $other_values_markup = array();
1271
    foreach ($element->statisticalValues as $statistical_val) {
1272

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

    
1282
      // either put into min max array or into $other_values
1283
      // for generic output to be appended to 'min-max' string
1284
      if (array_key_exists($statistical_val->type->titleCache, $min_max)) {
1285
        $min_max[$statistical_val->type->titleCache] = $statistical_val;
1286
      }
1287
      else {
1288
        $other_values[] = $statistical_val;
1289
      }
1290
    } // end of loop over statisticalValues
1291

    
1292
    // create markup
1293

    
1294
    $min_max_markup = min_max_markup($min_max);
1295

    
1296

    
1297
    foreach ($other_values as $statistical_val) {
1298
      $statistical_val_type_representation = NULL;
1299
      if (isset($statistical_val->type)) {
1300
        $statistical_val_type_representation = cdm_term_representation($statistical_val->type);
1301
        // $statistical_val->type->termType;
1302
        // $statistical_val->type->userFriendlyTypeName;
1303
      }
1304
      $value_markup = '<span class="' . html_class_attribute_ref($statistical_val) . ' ' . $statistical_val->type->termType . ' ">'
1305
        . $statistical_val->_value . '</span>';
1306
      $value_markup = $value_markup .
1307
        ($statistical_val_type_representation ? ' <span class="type">' . $statistical_val_type_representation . '</span>' : '');
1308
      $other_values_markup[] = $value_markup;
1309
    }
1310

    
1311

    
1312
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1313
  }
1314

    
1315
  if (isset($element->unit)) {
1316
    $out .= ' <span class="unit" title="'
1317
      . cdm_term_representation($element->unit) . '">'
1318
      . cdm_term_representation_abbreviated($element->unit)
1319
      . '</span>';
1320
  }
1321

    
1322
  // modifiers of the description element itself
1323
  $modifier_string = cdm_modifers_representations($element);
1324
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1325
  if (isset($element->modifyingText_L10n)) {
1326
    $out = $element->modifyingText_L10n . ' ' . $out;
1327
  }
1328

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

    
1331
  return $render_array;
1332
}
1333

    
1334

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

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

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

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

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

    
1383
    $render_array['elements']['children'] = $description_element_render_arrays;
1384

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

    
1388
    return $render_array;
1389
  }
1390

    
1391

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

    
1409
    $plaintext = NULL;
1410
    $markup = NULL;
1411
    $name_in_source_render_array = array();
1412

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

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

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

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

    
1456
    return $name_in_source_render_array;
1457
  }
1458

    
1459

    
1460

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

    
1482
    $elements_out_array = array();
1483
    $distribution_tree = null;
1484

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

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

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

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

    
1550
    return $elements_out_array;
1551
  }
1552

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

    
1568
  $common_name_out = '';
1569
  $common_name_feature_elements = array();
1570
  $textData_commonNames = array();
1571

    
1572
  $footnote_key_suggestion = 'common-names-feature-block';
1573

    
1574
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1575

    
1576
  if (is_array($elements)) {
1577
    foreach ($elements as $element) {
1578

    
1579
      if ($element->class == 'CommonTaxonName') {
1580

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

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

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

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

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

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

    
1634

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

    
1640
  }
1641

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

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

    
1653
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1654
    $text_data_out, $feature
1655
  );
1656

    
1657
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1658
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1659
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1660

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

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

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

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

    
1697

    
1698
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1699
}
1700

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

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

    
1720
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1721
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1722

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

    
1731

    
1732
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1733

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

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

    
1750
  /**
1751
   * @param $descriptionElement
1752
   * @return array
1753
   */
1754
  function distribution_status_label_and_markup($descriptionElement, $status_glue = '&#8210; ') {
1755
    $status_markup = '';
1756
    $status_label = '';
1757

    
1758
    if (isset($descriptionElement->status)) {
1759
      $status_label = $descriptionElement->status->representation_L10n;
1760
      $status_markup =  '<span class="distributionStatus"> '
1761
        . $status_glue
1762
        . '<span class="distributionStatus-' . $descriptionElement->status->idInVocabulary . '">'
1763
        . $status_label
1764
        . '</span></span>';
1765

    
1766
    };
1767
    return array($status_label, $status_markup);
1768
  }
1769

    
1770

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

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

    
1794

    
1795
    // 2. find the distribution feature node
1796
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1797

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

    
1822
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1823
      // 4. get distribution TextData is there are any
1824
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1825
        array(
1826
          'taxon' => $taxon->uuid,
1827
          'type' => 'TextData',
1828
          'features' => UUID_DISTRIBUTION
1829
        )
1830
      );
1831

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

    
1847
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1848
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1849

    
1850
    return $merged_tree;
1851
  }
1852

    
1853

    
1854
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1855

    
1856
    static $hierarchy_style;
1857
    // TODO expose $hierarchy_style to administration or provide a hook
1858
    if( !isset($hierarchy_style)){
1859
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1860
    }
1861

    
1862
    $render_array = array();
1863

    
1864
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1865
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1866

    
1867
    // Returning NULL if there are no description elements.
1868
    if ($distribution_tree == null) {
1869
      return $render_array;
1870
    }
1871
    // for now we are not using a render array internally to avoid performance problems
1872
    $markup = '';
1873
    if (isset($distribution_tree->rootElement->children)) {
1874
      $tree_nodes = $distribution_tree->rootElement->children;
1875
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1876
    }
1877

    
1878
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1879
      $markup,
1880
      0,
1881
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1882
      '</div>'
1883
    );
1884

    
1885
    RenderHints::popFromRenderStack();
1886

    
1887
    return $render_array;
1888
  }
1889

    
1890
  /**
1891
   * this function should produce markup as the compose_description_elements_distribution()
1892
   * function.
1893
   *
1894
   * @see compose_description_elements_distribution()
1895
   *
1896
   * @param $distribution_tree
1897
   * @param $feature_block_settings
1898
   * @param $tree_nodes
1899
   * @param $markup
1900
   * @param $hierarchy_style
1901
   */
1902
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1903

    
1904
    $level_index++;
1905
    static $enclosingTag = "span";
1906

    
1907
    $level_style = array_shift($hierarchy_style);
1908
    if(count($hierarchy_style) == 0){
1909
      // lowest defined level style will be reused for all following levels
1910
      $hierarchy_style[] = $level_style;
1911
    }
1912

    
1913
    $node_index = -1;
1914
    $per_node_markup = array();
1915
    foreach ($tree_nodes as $node){
1916

    
1917
      $per_node_markup[++$node_index] = '';
1918

    
1919
      $label = $node->nodeId->representation_L10n;
1920

    
1921
      $distributions = $node->data;
1922
      $distribution_uuids = array();
1923
      $distribution_aggregate = NULL;
1924
        foreach($distributions as $distribution){
1925

    
1926
          $distribution_uuids[] = $distribution->uuid;
1927

    
1928
          // if there is more than one distribution we aggregate the sources and
1929
          // annotations into a synthetic distribution so that the footnote keys
1930
          // can be rendered consistently
1931
          if(!$distribution_aggregate) {
1932
            $distribution_aggregate = $distribution;
1933
            if(!isset($distribution_aggregate->sources[0])){
1934
              $distribution_aggregate->sources = array();
1935
            }
1936
            if(!isset($distribution_aggregate->annotations[0])){
1937
              $distribution_aggregate->annotations = array();
1938
            }
1939
          } else {
1940
            if(isset($distribution->sources[0])) {
1941
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1942
                $distribution->sources);
1943
            }
1944
            if(isset($distribution->annotations[0])) {
1945
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1946
                $distribution->annotations);
1947
            }
1948
          }
1949
        }
1950

    
1951
      $status_label= '';
1952
      $status_markup = '';
1953
      $annotations_and_sources =  null;
1954
      if($distribution_aggregate) {
1955
        $annotations_and_sources = handle_annotations_and_sources(
1956
          $distribution_aggregate,
1957
          handle_annotations_and_sources_config($feature_block_settings),
1958
          $label,
1959
          UUID_DISTRIBUTION
1960
        );
1961

    
1962
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution, $level_style['status_glue']);
1963
      }
1964

    
1965
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1966
        . join(' descriptionElement-', $distribution_uuids)
1967
        . ' level_index_' . $level_index
1968
        . ' " title="' . $status_label . '">'
1969
        . '<span class="area_label">' . $label
1970
        . $level_style['label_suffix'] . '</span>'
1971
        . $status_markup
1972
      ;
1973

    
1974
      if(isset($annotations_and_sources)){
1975
        if(!empty($annotations_and_sources['source_references'])){
1976
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1977
        }
1978
        if($annotations_and_sources['foot_note_keys']) {
1979
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1980
        }
1981
      }
1982

    
1983
      if(isset($node->children[0])){
1984
        _compose_distribution_hierarchy(
1985
          $node->children,
1986
          $feature_block_settings,
1987
          $per_node_markup[$node_index],
1988
          $hierarchy_style,
1989
          $level_index
1990
        );
1991
      }
1992

    
1993
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1994
    }
1995
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
1996
  }
1997

    
1998

    
1999
/**
2000
 * Provides the content for a block of Uses Descriptions for a given taxon.
2001
 *
2002
 * Fetches the list of TaxonDescriptions tagged with the MARKERTYPE_USE
2003
 * and passes them to the theme function theme_cdm_UseDescription().
2004
 *
2005
 * @param string $taxon_uuid
2006
 *   The uuid of the Taxon
2007
 *
2008
 * @return array
2009
 *   A drupal render array
2010
 */
2011
function cdm_block_use_description_content($taxon_uuid, $feature) {
2012

    
2013
  $use_description_content = array();
2014

    
2015
  if (is_uuid($taxon_uuid )) {
2016
    $markerTypes = array();
2017
    $markerTypes['markerTypes'] = UUID_MARKERTYPE_USE;
2018
    $useDescriptions = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXON . '/' . $taxon_uuid . '/descriptions', $markerTypes);
2019
    if (!empty($useDescriptions)) {
2020
      $use_description_content = compose_feature_block_items_use_records($useDescriptions, $taxon_uuid, $feature);
2021
    }
2022
  }
2023

    
2024
  return $use_description_content;
2025
}
2026

    
2027
/**
2028
 * Creates a trunk of a feature object which can be used to build pseudo feature blocks like the Bibliography.
2029
 *
2030
 * @param $representation_L10n
2031
 * @param String $pseudo_feature_key
2032
 *    Will be set as uuid but should be one of 'BIBLIOGRAPHY', ... more to come. See also get_feature_block_settings()
2033
 *
2034
 * @return object
2035
 *  The feature object
2036
 */
2037
function make_pseudo_feature($representation_L10n, $pseudo_feature_key = null){
2038
  $feature = new stdClass;
2039
  $feature->representation_L10n = $representation_L10n;
2040
  $feature->uuid = $pseudo_feature_key;
2041
  $feature->class = 'PseudoFeature';
2042

    
2043
  return $feature;
2044

    
2045
}
2046

    
2047

    
(2-2/10)