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
        render_original_source($source,
390
          $do_link_to_reference,
391
          $do_link_to_name_used_in_source
392
        ),
393
        $original_source_footnote_tag
394
      );
395
      // Ensure uniqueness of the footnote keys.
396
      cdm_add_footnote_to_array($footNoteKeys, $fn_key);
397
    }
398
  }
399
  // Sort and render footnote keys.
400
  $footnoteKeyListStr = '';
401
  asort($footNoteKeys);
402
  foreach ($footNoteKeys as $footNoteKey) {
403
    $footnoteKeyListStr .= theme('cdm_footnote_key',
404
      array(
405
        'footnoteKey' => $footNoteKey,
406
        'separator' => ($footnoteKeyListStr ? $separator : '')));
407
  }
408
  return $footnoteKeyListStr;
409
}
410

    
411

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

    
424
}
425

    
426

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

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

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

    
449
    '#value' => '',
450
    '#value_suffix' => NULL
451

    
452
  );
453

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

    
461
  $timescope_markup = '';
462
  if(isset($element->timeperiod)){
463
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, true);
464
  }
465

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

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

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

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

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

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

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

    
522
  return $config;
523
}
524

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

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

    
557
    usort($entity->sources, 'compare_original_sources');
558

    
559
    if ($config['sources_as_content'] == 1) {
560
      foreach ($entity->sources as $source) {
561
        if (_is_original_source_type($source)) {
562
          $reference_citation = render_original_source(
563
              $source,
564
             $config['link_to_reference'] == 1,
565
              $config['link_to_name_used_in_source'] == 1
566
          );
567

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

    
576
          // also put the name in source into the array, these are already included in the $reference_citation but are
577
          // still required to be available separately in some contexts.
578
          $name_in_source_render_array = compose_name_in_source(
579
            $source,
580
            $config['link_to_name_used_in_source'] == 1
581
          );
582

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

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

    
597
    } // END of references inline
598

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

    
618
    return $annotations_and_sources;
619
  }
620

    
621

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

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

    
660

    
661
/* ==================== COMPOSE FUNCTIONS =============== */
662

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

    
686
    $block_list = array();
687

    
688
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
689

    
690
    $use_description_features = array(UUID_USE);
691

    
692

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

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

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

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

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

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

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

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

    
743
        /*
744
         * Content/ALL OTHER FEATURES.
745
         */
746
        else {
747

    
748
          $media_list = array();
749
          $elements_render_array = array();
750
          $child_elements_render_array = null;
751

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

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

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

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

    
788
    RenderHints::popFromRenderStack();
789

    
790
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
791

    
792
    return  $block_list;
793
  }
794

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

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

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

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

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

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

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

    
860
  return $render_arrays;
861
}
862

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

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

    
880
    $captionElements = array('title', 'rights');
881

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

    
893
    return markup_to_render_array('');
894
  }
895

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

    
917
    $distributionElements = NULL;
918
    $distribution_info_dto = NULL;
919
    $distribution_sortOutArray = FALSE;
920

    
921
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
922

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

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

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

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

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

    
962

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

    
969
    // --- Distribution map
970
    $distribution_map_query_parameters = NULL;
971

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

    
982
    $dto_out_array = array();
983

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

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

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

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

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

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

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

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

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

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

    
1071
    return $block;
1072
  }
1073

    
1074

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

    
1096
    $footnote_list_key_suggestion = $feature_uuid;
1097

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

    
1104
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1105

    
1106
    return $render_array;
1107
  }
1108

    
1109

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

    
1123
  $out = '';
1124

    
1125

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

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

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

    
1136
  return $render_array;
1137
}
1138

    
1139

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

    
1154
  $out = '';
1155

    
1156
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1157

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

    
1162
  $out .= drupal_render($render_array);
1163

    
1164
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1165

    
1166
  return $render_array;
1167
}
1168

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

    
1187
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1188

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

    
1193
      $state  = NULL;
1194

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

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

    
1203
      $modifiers_strings = cdm_modifers_representations($state_data);
1204

    
1205
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1206

    
1207
    }
1208
  }
1209

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

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

    
1214
  return $render_array;
1215
}
1216

    
1217

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

    
1261
  $out = '';
1262
  $type_representation = NULL;
1263
  $min_max = min_max_array();
1264

    
1265
  $other_values = array();
1266

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

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

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

    
1290
    // create markup
1291

    
1292
    $min_max_markup = min_max_markup($min_max);
1293

    
1294

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

    
1309

    
1310
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1311
  }
1312

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

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

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

    
1329
  return $render_array;
1330
}
1331

    
1332

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

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

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

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

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

    
1381
    $render_array['elements']['children'] = $description_element_render_arrays;
1382

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

    
1386
    return $render_array;
1387
  }
1388

    
1389

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

    
1407
    $plaintext = NULL;
1408
    $markup = NULL;
1409
    $name_in_source_render_array = array();
1410

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

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

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

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

    
1454
    return $name_in_source_render_array;
1455
  }
1456

    
1457

    
1458

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

    
1480
    $elements_out_array = array();
1481
    $distribution_tree = null;
1482

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

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

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

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

    
1548
    return $elements_out_array;
1549
  }
1550

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

    
1566
  $common_name_out = '';
1567
  $common_name_feature_elements = array();
1568
  $textData_commonNames = array();
1569

    
1570
  $footnote_key_suggestion = 'common-names-feature-block';
1571

    
1572
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1573

    
1574
  if (is_array($elements)) {
1575
    foreach ($elements as $element) {
1576

    
1577
      if ($element->class == 'CommonTaxonName') {
1578

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

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

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

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

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

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

    
1632

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

    
1638
  }
1639

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

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

    
1651
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1652
    $text_data_out, $feature
1653
  );
1654

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

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

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

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

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

    
1695

    
1696
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1697
}
1698

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

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

    
1718
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1719
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1720

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

    
1729

    
1730
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1731

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

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

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

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

    
1764
    };
1765
    return array($status_label, $status_markup);
1766
  }
1767

    
1768

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

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

    
1792

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

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

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

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

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

    
1848
    return $merged_tree;
1849
  }
1850

    
1851

    
1852
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1853

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

    
1860
    $render_array = array();
1861

    
1862
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1863
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1864

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

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

    
1883
    RenderHints::popFromRenderStack();
1884

    
1885
    return $render_array;
1886
  }
1887

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

    
1902
    $level_index++;
1903
    static $enclosingTag = "span";
1904

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

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

    
1915
      $per_node_markup[++$node_index] = '';
1916

    
1917
      $label = $node->nodeId->representation_L10n;
1918

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

    
1924
          $distribution_uuids[] = $distribution->uuid;
1925

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

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

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

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

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

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

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

    
1996

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

    
2011
  $use_description_content = array();
2012

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

    
2022
  return $use_description_content;
2023
}
2024

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

    
2041
  return $feature;
2042

    
2043
}
2044

    
2045

    
(2-2/10)