Project

General

Profile

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

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

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

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

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

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

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

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

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

    
83

    
84

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

    
100
  return $query;
101
}
102

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

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

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

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

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

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

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

    
166
}
167

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

    
179
  return $toc_list_items;
180
}
181

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

    
210

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

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

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

    
246
  }
247

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

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

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

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

    
278

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

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

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

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

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

    
341
  );
342
}
343

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

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

    
373
  // Source references as footnotes.
374

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

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

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

    
413

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

    
426
}
427

    
428

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

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

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

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

    
454
  );
455

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

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

    
476

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

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

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

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

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

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

    
520
  return $config;
521
}
522

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

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

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

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

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

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

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

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

    
595
    } // END of references inline
596

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

    
616
    return $annotations_and_sources;
617
  }
618

    
619

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

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

    
658

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

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

    
684
    $block_list = array();
685

    
686
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
687

    
688
    $use_description_features = array(UUID_USE);
689

    
690

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

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

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

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

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

    
716
        /*
717
         * Content/DISTRIBUTION.
718
         */
719
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
720
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
721
          $block_content_is_empty = FALSE;
722
        }
723

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

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

    
741
        /*
742
         * Content/ALL OTHER FEATURES.
743
         */
744
        else {
745

    
746
          $media_list = array();
747
          $elements_render_array = array();
748
          $child_elements_render_array = null;
749

    
750
          if (isset($node->descriptionElements[0])) {
751
            $elements_render_array = compose_feature_block_items_generic($node->descriptionElements, $node->feature);
752
          }
753

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

    
775
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
776
        drupal_alter('cdm_feature_node_block_content', $block->content, $node->feature, $node->descriptionElements);
777

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

    
786
    RenderHints::popFromRenderStack();
787

    
788
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
789

    
790
    return  $block_list;
791
  }
792

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

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

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

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

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

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

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

    
858
  return $render_arrays;
859
}
860

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

    
874
    if (isset($node->descriptionElements)) {
875
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
876
    }
877

    
878
    $captionElements = array('title', 'rights');
879

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

    
891
    return markup_to_render_array('');
892
  }
893

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

    
915
    $distributionElements = NULL;
916
    $distribution_info_dto = NULL;
917
    $distribution_sortOutArray = FALSE;
918

    
919
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
920

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

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

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

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

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

    
960

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

    
967
    // --- Distribution map
968
    $distribution_map_query_parameters = NULL;
969

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

    
980
    $dto_out_array = array();
981

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

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

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

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

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

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

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

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

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

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

    
1069
    return $block;
1070
  }
1071

    
1072

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

    
1094
    $footnote_list_key_suggestion = $feature_uuid;
1095

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

    
1102
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
1103

    
1104
    return $render_array;
1105
  }
1106

    
1107

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

    
1121
  $out = '';
1122

    
1123

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

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

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

    
1134
  return $render_array;
1135
}
1136

    
1137

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

    
1152
  $out = '';
1153

    
1154
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
1155

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

    
1160
  $out .= drupal_render($render_array);
1161

    
1162
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1163

    
1164
  return $render_array;
1165
}
1166

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

    
1185
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1186

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

    
1191
      $state  = NULL;
1192

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

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

    
1201
      $modifiers_strings = cdm_modifers_representations($state_data);
1202

    
1203
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1204

    
1205
    }
1206
  }
1207

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

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

    
1212
  return $render_array;
1213
}
1214

    
1215

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

    
1259
  $out = '';
1260
  $type_representation = NULL;
1261
  $min_max = min_max_array();
1262

    
1263
  $other_values = array();
1264

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

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

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

    
1288
    // create markup
1289

    
1290
    $min_max_markup = min_max_markup($min_max);
1291

    
1292

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

    
1307

    
1308
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1309
  }
1310

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

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

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

    
1327
  return $render_array;
1328
}
1329

    
1330

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

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

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

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

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

    
1379
    $render_array['elements']['children'] = $description_element_render_arrays;
1380

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

    
1384
    return $render_array;
1385
  }
1386

    
1387

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

    
1405
    $plaintext = NULL;
1406
    $markup = NULL;
1407
    $name_in_source_render_array = array();
1408

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

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

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

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

    
1452
    return $name_in_source_render_array;
1453
  }
1454

    
1455

    
1456

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

    
1478
    $elements_out_array = array();
1479
    $distribution_tree = null;
1480

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

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

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

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

    
1546
    return $elements_out_array;
1547
  }
1548

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

    
1564
  $common_name_out = '';
1565
  $common_name_feature_elements = array();
1566
  $textData_commonNames = array();
1567

    
1568
  $footnote_key_suggestion = 'common-names-feature-block';
1569

    
1570
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1571

    
1572
  if (is_array($elements)) {
1573
    foreach ($elements as $element) {
1574

    
1575
      if ($element->class == 'CommonTaxonName') {
1576

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

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

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

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

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

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

    
1630

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

    
1636
  }
1637

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

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

    
1649
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1650
    $text_data_out, $feature
1651
  );
1652

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

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

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

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

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

    
1693

    
1694
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1695
}
1696

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

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

    
1716
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1717
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1718

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

    
1727

    
1728
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1729

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

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

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

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

    
1762
    };
1763
    return array($status_label, $status_markup);
1764
  }
1765

    
1766

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

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

    
1790

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

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

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

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

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

    
1846
    return $merged_tree;
1847
  }
1848

    
1849

    
1850
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1851

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

    
1858
    $render_array = array();
1859

    
1860
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1861
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1862

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

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

    
1881
    RenderHints::popFromRenderStack();
1882

    
1883
    return $render_array;
1884
  }
1885

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

    
1900
    $level_index++;
1901
    static $enclosingTag = "span";
1902

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

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

    
1913
      $per_node_markup[++$node_index] = '';
1914

    
1915
      $label = $node->nodeId->representation_L10n;
1916

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

    
1922
          $distribution_uuids[] = $distribution->uuid;
1923

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

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

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

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

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

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

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

    
1994

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

    
2009
  $use_description_content = array();
2010

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

    
2020
  return $use_description_content;
2021
}
2022

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

    
2039
  return $feature;
2040

    
2041
}
2042

    
2043

    
(2-2/10)