Project

General

Profile

Download (65.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
  if ($cdm_distribution_filter['filter_rules']['statusOrderPreference']) {
77
    $query['statusOrderPreference'] = 1;
78
  }
79
  if ($cdm_distribution_filter['filter_rules']['subAreaPreference']) {
80
    $query['subAreaPreference'] = 1;
81
  }
82
  if (is_array($cdm_distribution_filter['hiddenAreaMarkerType']) && count($cdm_distribution_filter['hiddenAreaMarkerType']) > 0) {
83
    $query['hiddenAreaMarkerType'] = '';
84
    foreach ($cdm_distribution_filter['hiddenAreaMarkerType'] as $marker_type => $enabled) {
85
      if ($enabled) {
86
        $query['hiddenAreaMarkerType'] .= ($query['hiddenAreaMarkerType'] ? ',' : '') . $marker_type;
87
      }
88
    }
89
  }
90

    
91
  return $query;
92
}
93

    
94
/**
95
 * Merge the fields 'annotations', 'markers', 'sources', 'media' from the source CDM DescriptionElement into  the target.
96
 *
97
 * @param object $target
98
 *   The source CDM DescriptionElement
99
 * @param object $source
100
 *   The target CDM DescriptionElement
101
 */
102
function cdm_merge_description_elements(&$target, &$source) {
103
  static $fields_to_merge = array('annotations', 'markers', 'sources', 'media');
104

    
105
  foreach ($fields_to_merge as $field) {
106
    if (is_array($source->$field)) {
107
      if (!is_array($target->$field)) {
108
        $target->$field = $source->$field;
109
      }
110
      else {
111
        $target->$field = array_merge($target->$field, $source->$field);
112
      }
113
    }
114
  }
115
}
116

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

    
135
  if (!$fragment) {
136
    $fragment = $label;
137
  }
138
  $fragment = generalizeString($fragment);
139

    
140
  $class_attributes = 'feature-toc-item-' . $class_attribute_suffix;
141

    
142
  $new_item = toc_list_item(
143
    theme(
144
      'cdm_feature_name',
145
      array('feature_name' => $label)),
146
      array('class' => $class_attributes),
147
      $fragment
148
    );
149

    
150
  if ($as_first_element) {
151
    array_unshift($toc_list_items, $new_item);
152
  }
153
  else {
154
    $toc_list_items[] = $new_item;
155
  }
156

    
157
}
158

    
159
/**
160
 * Returns the statically cached table of content items as render array.
161
 *
162
 * @see cdm_toc_list_add_item()
163
 *
164
 * @return array
165
 *   a render array of table of content items suitable for theme_item_list()
166
 */
167
function &cdm_toc_list(){
168
  $toc_list_items = &drupal_static('toc_list_items', array());
169

    
170
  return $toc_list_items;
171
}
172

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

    
200

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

    
228
    case "MediaKey":
229
      $cdm_ws_pasepath = CDM_WS_MEDIAKEY;
230
      break;
231

    
232
    case "MultiAccessKey":
233
      $cdm_ws_pasepath = CDM_WS_MULTIACCESSKEY;
234
      break;
235

    
236
  }
237

    
238
  if (!$cdm_ws_pasepath) {
239
    drupal_set_message(t('Type parameter is not valid: ') . $type, 'error');
240
  }
241

    
242
  $queryParameters = '';
243
  if (is_numeric($pageSize)) {
244
    $queryParameters = "pageSize=" . $pageSize;
245
  }
246
  else {
247
    $queryParameters = "pageSize=0";
248
  }
249

    
250
  if (is_numeric($pageNumber)) {
251
    $queryParameters = "pageNumber=" . $pageNumber;
252
  }
253
  else {
254
    $queryParameters = "pageNumber=0";
255
  }
256
  $queryParameters = NULL;
257
  if ($taxonUuid) {
258
    $queryParameters = "findByTaxonomicScope=$taxonUuid";
259
  }
260
  $pager = cdm_ws_get($cdm_ws_pasepath, NULL, $queryParameters);
261

    
262
  if (!$pager || $pager->count == 0) {
263
    return array();
264
  }
265
  return $pager->records;
266
}
267

    
268

    
269
/**
270
 * Creates a list item for a table of content, suitable as data element for a themed list
271
 *
272
 * @see theme_list()
273
 *
274
 * @param $label
275
 * @param $http_request_params
276
 * @param $attributes
277
 * @return array
278
 */
279
function toc_list_item($label, $attributes = array(), $fragment = null) {
280

    
281
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
282
  $http_request_params = drupal_static('http_request_params', drupal_get_query_parameters());
283

    
284
  $item =  array(
285
    'data' => l(
286
      $label,
287
      $_GET['q'],
288
      array(
289
        'attributes' => array('class' => array('toc')),
290
        'fragment' => generalizeString($label),
291
        'query' => $http_request_params,
292
      )
293
    ),
294
  );
295
  $item['attributes'] = $attributes;
296
  return $item;
297
}
298

    
299
/**
300
 * Creates the footnotes for the given CDM DescriptionElement instance.
301
 *
302
 * Footnotes are created for annotations and original sources,
303
 * optionally the sources are put into a separate bibliography.
304
 *
305
 * @param $descriptionElement
306
 *   A CDM DescriptionElement instance
307
 * @param $separator
308
 *   Optional parameter. The separator string to concatenate the footnote ids, default is ','
309
 * @param $footnote_list_key_suggestion
310
 *   will be overridden for original sources if the bibliography block is enabled
311
 *
312
 * @return String
313
 *   The foot note keys
314
 */
315
function cdm_create_description_element_footnotes($description_element, $separator = ',',
316
          $footnote_list_key_suggestion = null, $do_link_to_reference = FALSE,
317
          $do_link_to_name_used_in_source = FALSE
318
    ){
319

    
320

    
321
  // Annotations as footnotes.
322
  $footNoteKeys = cdm_annotations_as_footnotekeys($description_element, $footnote_list_key_suggestion);
323

    
324
  // Source references as footnotes.
325
  $bibliography_settings = get_bibliography_settings();
326
  $original_source_footnote_tag = $bibliography_settings['enabled'] == 1 ? 'div' : null; // null will cause original_source_footnote_list_key to use the default
327

    
328
  usort($description_element->sources, 'compare_original_sources');
329
  foreach ($description_element->sources as $source) {
330
    if (_is_original_source_type($source)) {
331
      $fn_key = FootnoteManager::addNewFootnote(
332
        original_source_footnote_list_key($footnote_list_key_suggestion),
333
        theme('cdm_OriginalSource', array(
334
          'source' => $source,
335
          'doLink' => $do_link_to_reference,
336
          'do_link_to_name_used_in_source' => $do_link_to_name_used_in_source
337

    
338
        )),
339
        $original_source_footnote_tag
340
      );
341
      // Ensure uniqueness of the footnote keys.
342
      cdm_add_footnote_to_array($footNoteKeys, $fn_key);
343
    }
344
  }
345
  // Sort and render footnote keys.
346
  $footnoteKeyListStr = '';
347
  asort($footNoteKeys);
348
  foreach ($footNoteKeys as $footNoteKey) {
349
    $footnoteKeyListStr .= theme('cdm_footnote_key',
350
      array(
351
        'footnoteKey' => $footNoteKey,
352
        'separator' => ($footnoteKeyListStr ? $separator : '')));
353
  }
354
  return $footnoteKeyListStr;
355
}
356

    
357

    
358
/**
359
 * Compare callback to be used in usort() to sort render arrays produced by compose_description_element().
360
 *
361
 * @param $a
362
 * @param $b
363
 */
364
function compare_description_element_render_arrays($a, $b){
365
  if ($a['#value'].$a['#value-suffix'] == $b['#value'].$b['#value-suffix']) {
366
    return 0;
367
  }
368
  return ($a['#value'].$a['#value-suffix'] < $b['#value'].$b['#value-suffix']) ? -1 : 1;
369

    
370
}
371

    
372

    
373
/**
374
 * @param $render_array
375
 * @param $element
376
 * @param $feature_block_settings
377
 * @param $element_markup
378
 * @param $footnote_list_key_suggestion
379
 */
380
function compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label = FALSE)
381
{
382

    
383
  $render_array = array(
384
    '#type' => 'html_tag',
385
    '#tag' => cdm_feature_block_element_tag_name($feature_block_settings),
386

    
387
    '#attributes' => array(
388
      'class' => array(
389
        'DescriptionElement',
390
        'DescriptionElement-' . $element->class,
391
        html_class_attribute_ref($element)
392
      )
393
    ),
394

    
395
    '#value' => '',
396
    '#value_suffix' => NULL
397

    
398
  );
399

    
400
  $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion);
401

    
402
  // handle the special case were the TextData is used as container for original source with name
403
  // used in source information without any text stored in it.
404
  $names_used_in_source_markup = '';
405
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
406
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
407
    // remove all <span class="nameUsedInSource">...</span> from all source_references
408
    // these are expected to be at the end of the strings
409
    $pattern = '/ <span class="nameUsedInSource">.*$/';
410
    foreach( $annotations_and_sources['source_references'] as &$source_reference){
411
      $source_reference = preg_replace($pattern , '', $source_reference);
412
    }
413
  }
414

    
415

    
416
  $source_references_markup = '';
417
  if (!empty($annotations_and_sources['source_references'])) {
418
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
419
  }
420

    
421
  $feature_label = '';
422
  if ($prepend_feature_label) {
423
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
424
  }
425
  $render_array['#value'] = $feature_label . $names_used_in_source_markup . $element_markup . $source_references_markup;
426
  $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
427

    
428
  return $render_array;
429
}
430

    
431

    
432
  /**
433
   * @param $element
434
   * @param $feature_block_settings
435
   * @param $element_text
436
   *   used to decide if the source references should be enclosed in brackets or not
437
   * @param $footnote_list_key_suggestion
438
   * @return array
439
   *   an associative array with the following elements:
440
   *   - foot_note_keys: all footnote keys as markup
441
   *   - source_references: an array of the source references citations
442
   *   - names used in source: an associative array of the names in source,
443
   *        the name in source strings are de-duplicated
444
   *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
445
   *
446
   *
447
   */
448
  function handle_annotations_and_sources($element, $feature_block_settings, $element_text, $footnote_list_key_suggestion) {
449
    $annotations_and_sources = array(
450
      'foot_note_keys' => NULL,
451
      'source_references' => array(),
452
      'names_used_in_source' => array()
453
    );
454

    
455
    usort($element->sources, 'compare_original_sources');
456

    
457
    if ($feature_block_settings['sources_as_content'] == 1) {
458
      foreach ($element->sources as $source) {
459

    
460
        $referenceCitation = theme('cdm_OriginalSource',
461
          array(
462
            'source' => $source,
463
            'doLink' => $feature_block_settings['link_to_reference'] == 1,
464
            'do_link_to_name_used_in_source' => $feature_block_settings['link_to_name_used_in_source'] == 1,
465
          )
466
        );
467

    
468
        if ($referenceCitation) {
469
          if (empty($element_text)) {
470
            $annotations_and_sources['source_references'][] = $referenceCitation;
471
          }
472
          else {
473
            $annotations_and_sources['source_references'][] = ' (' . $referenceCitation . ')';
474
          }
475
        }
476

    
477
        $name_in_source_render_array = compose_name_in_source(
478
          $source,
479
          $feature_block_settings['link_to_name_used_in_source'] == 1
480
        );
481

    
482
        if(!empty($name_in_source_render_array)){
483
          $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
484
        }
485
      } // END of loop over sources
486

    
487
      // annotations footnotes separate.
488
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
489
        array(
490
          'cdmBase_list' => $element,
491
          'footnote_list_key' => $footnote_list_key_suggestion,
492
        )
493
      );
494

    
495
    } // END of references inline
496

    
497
    // put sources into bibliography if requested ...
498
    if ($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
499
      $annotations_and_sources['foot_note_keys'] = cdm_create_description_element_footnotes(
500
        $element, ',',
501
        $footnote_list_key_suggestion,
502
        $feature_block_settings['link_to_reference'] == 1,
503
        $feature_block_settings['link_to_name_used_in_source'] == 1
504
      );
505
    }
506

    
507
    return $annotations_and_sources;
508
  }
509

    
510

    
511
  /**
512
   *
513
   *
514
   * @return string
515
   *  the footnote_list_key
516
   */
517
  function original_source_footnote_list_key($key_suggestion = null) {
518
    if(!$key_suggestion){
519
      $key_suggestion = RenderHints::getFootnoteListKey();
520
    }
521
    $bibliography_settings = get_bibliography_settings();
522
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? 'BIBLIOGRAPHY' : 'BIBLIOGRAPHY-' . $key_suggestion;
523
    return $footnote_list_key;
524
  }
525

    
526
  /**
527
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
528
   *
529
   * @param $feature_block_settings
530
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
531
   */
532
  function cdm_feature_block_element_tag_name($feature_block_settings){
533
    switch ($feature_block_settings['as_list']){
534
      case 'ul':
535
      case 'ol':
536
        return 'li';
537
      case 'div':
538
        if(isset($feature_block_settings['element_tag'])){
539
          return $feature_block_settings['element_tag'];
540
        }
541
        return 'span';
542
      case 'dl':
543
        return 'dd';
544
      default:
545
        return 'div'; // should never happen, throw error instead?
546
    }
547
  }
548

    
549

    
550
/* ==================== COMPOSE FUNCTIONS =============== */
551

    
552
  /**
553
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
554
   *
555
   * The taxon profile consists of drupal block elements, one for the description elements
556
   * of a specific feature. The structure is defined by specific FeatureTree.
557
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
558
   *
559
   * The merged nodes can be obtained by making use of the
560
   * function cdm_ws_descriptions_by_featuretree().
561
   *
562
   * @see cdm_ws_descriptions_by_featuretree()
563
   *
564
   * @param $mergedFeatureNodes
565
   *
566
   * @param $taxon
567
   *
568
   * @return array
569
   *  A Drupal render array containing feature blocks and the table of content
570
   *
571
   * @ingroup compose
572
   */
573
  function compose_feature_blocks($mergedFeatureNodes, $taxon) {
574

    
575
    $block_list = array();
576

    
577
    RenderHints::pushToRenderStack('feature_nodes');
578

    
579
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
580

    
581
    // Create a drupal block for each feature
582
    foreach ($mergedFeatureNodes as $node) {
583

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

    
587
        $feature_name = cdm_term_representation($node->feature, 'Unnamed Feature');
588
        $feature_block_settings = get_feature_block_settings($node->feature->uuid);
589

    
590
        $block = feature_block($feature_name, $node->feature);
591
        $block->content = array();
592
        $block_content_is_empty = TRUE;
593

    
594
        /*
595
         * Content/DISTRIBUTION.
596
         */
597

    
598
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
599
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
600
          $block_content_is_empty = FALSE;
601
        }
602
        /*
603
         * Content/COMMON_NAME.
604
         */
605
        else if ($node->feature->uuid == UUID_COMMON_NAME) {
606
          $common_names_render_array = compose_feature_block_items_feature_common_name($node->descriptionElements, $node->feature);
607
          $block->content[] = $common_names_render_array;
608
          $block_content_is_empty = FALSE;
609
        }
610

    
611
        else if ($node->feature->uuid == UUID_USE_RECORD) {
612
          $block_uses_content_html = theme('cdm_block_Uses', array('taxonUuid' => $taxon->uuid));
613
          $block->content[] = markup_to_render_array($block_uses_content_html);
614
          $block_content_is_empty = FALSE;
615
        }
616

    
617
        /*
618
         * Content/ALL OTHER FEATURES.
619
         */
620
        else {
621

    
622
          $media_list = array();
623
          $elements_render_array = array();
624
          $child_elements_render_array = null;
625

    
626
          if (isset($node->descriptionElements[0])) {
627
            $elements_render_array = compose_feature_block_items_generic($node->descriptionElements, $node->feature);
628
          }
629

    
630
          // Content/ALL OTHER FEATURES/Subordinate Features
631
          // subordinate features are printed inline in one floating text,
632
          // it is expected hat subordinate features can "contain" TextData,
633
          // Qualitative- and Qualitative- DescriptionElements
634
          if (isset($node->childNodes[0])) {
635
            $child_elements_render_array = compose_feature_block_items_nested($node, $media_list, $feature_block_settings);
636
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
637
          }
638
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
639
          if(!$block_content_is_empty){
640
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $node->feature);
641
            $block->content[] = compose_feature_media_gallery($node, $media_list, $gallery_settings);
642
            /*
643
             * Footnotes for the feature block
644
             */
645
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $node->feature->uuid)));
646
            $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $node->feature->uuid)));
647
            $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $node->feature->uuid)));
648
          }
649
        } // END all other features
650

    
651
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
652
        drupal_alter('cdm_feature_node_block_content', $block->content, $node->feature, $node->descriptionElements);
653

    
654
        if(!$block_content_is_empty){ // skip empty block content
655
          $block_list[] = $block;
656
          cdm_toc_list_add_item(cdm_term_representation($node->feature), $node->feature->uuid);
657
        } // END: skip empty block content
658
      } // END: skip empty or suppressed features
659
    } // END: creating a block per feature
660

    
661
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
662

    
663
    RenderHints::popFromRenderStack();
664

    
665
    return _block_get_renderable_array($block_list);
666
  }
667

    
668
/**
669
 * Creates a render array of description elements  held by child nodes of the given feature node.
670
 *
671
 * This function is called recursively!
672
 *
673
 * @param $node
674
 *   The feature node.
675
 * @param array $media_list
676
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
677
 * @param $feature_block_settings
678
 *   The feature block settings.
679
 * @param $main_feature
680
 *  Only used internally in recursive calls.
681
 *
682
 * @return array
683
 *  A Drupal render array
684
 *
685
 * @ingroup compose
686
 */
687
function compose_feature_block_items_nested($node, &$media_list, $feature_block_settings, $main_feature = NULL)
688
{
689

    
690
  if(!$main_feature){
691
    $main_feature = $node->feature;
692
  }
693
  /*
694
   * TODO should be configurable, options; YES, NO, AUTOMATIC
695
   * (automatic will only place the label if the first word of the description element text is not the same)
696
   */
697
  $prepend_feature_label = false;
698

    
699
  $render_arrays = array();
700
  foreach ($node->childNodes as $child_node) {
701
    if (isset($child_node->descriptionElements[0])) {
702
      foreach ($child_node->descriptionElements as $element) {
703

    
704
        if (isset($element->media[0])) {
705
          // Append media of subordinate elements to list of main
706
          // feature.
707
          $media_list = array_merge($media_list, $element->media);
708
        }
709

    
710
        $child_node_element = null;
711
        switch ($element->class) {
712
          case 'TextData':
713
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
714
            break;
715
          case 'CategoricalData':
716
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
717
            break;
718
          case 'QuantitativeData':
719
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
720

    
721
        }
722
        if (is_array($child_node_element)) {
723
          $render_arrays[] = $child_node_element;
724
        }
725
      }
726
    }
727

    
728
    if(isset($child_node->childNodes[0])){
729
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
730
    }
731
  }
732

    
733
  return $render_arrays;
734
}
735

    
736
  /**
737
   *
738
   * @param $node
739
   *  The merged feature three node which potentially contains media in its description elements.
740
   * @param $media_list
741
   *    Additional media to be merged witht the media contained in the nodes description elements
742
   * @param $gallery_settings
743
   * @return array
744
   *
745
   * @ingroup compose
746
   */
747
  function compose_feature_media_gallery($node, $media_list, $gallery_settings) {
748

    
749
    if (isset($node->descriptionElements)) {
750
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
751
    }
752

    
753
    $captionElements = array('title', 'rights');
754

    
755
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
756
      $gallery = theme('cdm_media_gallerie', array(
757
        'mediaList' => $media_list,
758
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $node->feature->uuid,
759
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
760
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
761
        'captionElements' => $captionElements,
762
      ));
763
      return markup_to_render_array($gallery);
764
    }
765

    
766
    return markup_to_render_array('');
767
  }
768

    
769
  /**
770
   * Composes the distribution feature block for a taxon
771
   *
772
   * @param $taxon
773
   * @param $descriptionElements
774
   *   an associative array with two elements:
775
   *   - '#type': must be 'DTO'
776
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
777
   * @param $feature
778
   *
779
   * @return array
780
   *  A drupal render array
781
   *
782
   * @ingroup compose
783
   */
784
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
785
    $text_data_glue = '';
786
    $text_data_sortOutArray = FALSE;
787
    $text_data_enclosingTag = 'ul';
788
    $text_data_out_array = array();
789

    
790
    $distributionElements = NULL;
791
    $distribution_info_dto = NULL;
792
    $distribution_sortOutArray = FALSE;
793

    
794
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
795

    
796
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
797
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
798
      $distribution_glue = '';
799
      $distribution_enclosingTag = 'dl';
800
    } else {
801
      $distribution_glue = '';
802
      $distribution_enclosingTag = 'ul';
803
    }
804

    
805
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
806
      // skip the DISTRIBUTION section if there is no DTO type element
807
      return array(); // FIXME is it ok to return an empty array?
808
    }
809

    
810
    $block = feature_block(
811
      cdm_term_representation($feature, 'Unnamed Feature'),
812
      $feature
813
    );
814

    
815
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
816
    if (isset($descriptionElements['TextData'])) {
817
      // --- TextData
818
      foreach ($descriptionElements['TextData'] as $text_data_element) {
819
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
820
        $repr = drupal_render($text_data_render_array);
821

    
822
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
823
          $text_data_out_array[] = $repr;
824
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
825
          // not work since this array contains html attributes with uuids
826
          // and what is about cases like the bibliography where
827
          // any content can be prefixed with some foot-note anchors?
828
          $text_data_sortOutArray = TRUE;
829
          $text_data_glue = '<br/> ';
830
          $text_data_enclosingTag = 'p';
831
        }
832
      }
833
    }
834

    
835

    
836
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
837
      $block->content[] = compose_feature_block_wrap_elements(
838
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
839
      );
840
    }
841

    
842
    // --- Distribution map
843
    $distribution_map_query_parameters = NULL;
844
    if (isset($descriptionElements['DistributionInfoDTO'])) {
845
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
846
    }
847
    $map_render_element = compose_distribution_map($taxon, $distribution_map_query_parameters);
848
    $block->content[] = $map_render_element;
849

    
850
    $dto_out_array = array();
851

    
852
    // --- Condensed Distribution
853
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
854
      $condensed_distribution_markup = '<p class="condensed_distribution">';
855

    
856
      $isFirst = true;
857
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
858
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
859
          if(!$isFirst){
860
            $condensed_distribution_markup .= ' ';
861
          }
862
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
863
          . $cdItem->areaStatusLabel . '</span>';
864
          $isFirst = false;
865
        }
866
      }
867

    
868
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
869
        if(!$isFirst){
870
          $condensed_distribution_markup .= ' ';
871
        }
872
        $isFirst = TRUE;
873
        $condensed_distribution_markup .= '[';
874
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
875
          if (!$isFirst) {
876
            $condensed_distribution_markup .= ' ';
877
          }
878
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
879
            . $cdItem->areaStatusLabel . '</span>';
880
          $isFirst = false;
881
        }
882
        $condensed_distribution_markup .= ']';
883
      }
884

    
885
      $condensed_distribution_markup .= '&nbsp;' . l(
886
          font_awesome_icon_markup(
887
            'fa-info-circle',
888
            array(
889
              'alt'=>'help',
890
              'class' => array('superscript')
891
            )
892
          ),
893
          'cdm_dataportal/help/condensed_distribution',
894
          array('html' => TRUE));
895
      $condensed_distribution_markup .= '</p>';
896
      $dto_out_array[] = $condensed_distribution_markup;
897
    }
898

    
899
    // --- tree or list
900
    if (isset($descriptionElements['DistributionInfoDTO'])) {
901
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
902

    
903
      // --- tree
904
      if (is_object($distribution_info_dto->tree)) {
905
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
906
        $dto_out_array[] = $distribution_tree_render_array;
907
      }
908

    
909
      // --- sorted element list
910
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
911
        foreach ($distribution_info_dto->elements as $descriptionElement) {
912
          if (is_object($descriptionElement->area)) {
913
            $sortKey = $descriptionElement->area->representation_L10n;
914
            $distributionElements[$sortKey] = $descriptionElement;
915
          }
916
        }
917
        ksort($distributionElements);
918
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
919
        $dto_out_array[] = $distribution_element_render_array;
920

    
921
      }
922
      //
923
      $block->content[] = compose_feature_block_wrap_elements(
924
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
925
      );
926
    }
927

    
928
    // --- TextData at the bottom
929
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
930
      $block->content[] = compose_feature_block_wrap_elements(
931
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
932
      );
933
    }
934

    
935
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
936
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
937
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
938

    
939
    return $block;
940
  }
941

    
942

    
943
  /**
944
   * Composes a drupal render array for single CDM TextData description element.
945
   *
946
   * @param $element
947
   *    The CDM TextData description element.
948
   *  @param $feature_uuid
949
   * @param bool $prepend_feature_label
950
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
951
   *
952
   * @return array
953
   *   A drupal render array with the following elements being used:
954
   *    - #tag: either 'div', 'li', ...
955
   *    ⁻ #attributes: class attributes
956
   *    - #value_prefix: (optionally) contains footnote anchors
957
   *    - #value: contains the textual content
958
   *    - #value_suffix: (optionally) contains footnote keys
959
   *
960
   * @ingroup compose
961
   */
962
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
963

    
964
    $footnote_list_key_suggestion = $feature_uuid;
965

    
966
    $element_markup = '';
967
    if (isset($element->multilanguageText_L10n->text)) {
968
      // TODO replacement of \n by <br> should be configurable
969
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
970
    }
971

    
972
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
973

    
974
    return $render_array;
975
  }
976

    
977

    
978
/**
979
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
980
 *
981
 * @param $element
982
 *  The CDM TaxonInteraction entity
983
 *
984
 * @return
985
 *  A drupal render array
986
 *
987
 * @ingroup compose
988
 */
989
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
990

    
991
  $out = '';
992

    
993

    
994
  if (isset($element->description_L10n)) {
995
    $out .=  ' ' . $element->description_L10n;
996
  }
997

    
998
  if(isset($element->taxon2)){
999
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
1000
  }
1001

    
1002
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1003

    
1004
  return $render_array;
1005
}
1006

    
1007

    
1008
/**
1009
 * Renders a single instance of the type IndividualsAssociations.
1010
 *
1011
 * @param $element
1012
 *   The CDM IndividualsAssociations entity.
1013
 * @param $feature_block_settings
1014
 *
1015
 * @return array
1016
 *   Drupal render array
1017
 *
1018
 * @ingroup compose
1019
 */
1020
function compose_description_element_individuals_association($element, $feature_block_settings) {
1021

    
1022
  $out = '';
1023

    
1024
  $render_array = compose_cdm_specimenOrObservation($element->associatedSpecimenOrObservation);
1025

    
1026
  if (isset($element->description_L10n)) {
1027
    $out .=  ' ' . $element->description_L10n;
1028
  }
1029

    
1030
  $out .= drupal_render($render_array);
1031

    
1032
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1033

    
1034
  return $render_array;
1035
}
1036

    
1037
/**
1038
 * Renders a single instance of the type CategoricalData.
1039
 *
1040
 * @param $element
1041
 *  The CDM CategoricalData entity
1042
 *
1043
 * @param $feature_block_settings
1044
 *
1045
 * @param bool $prepend_feature_label
1046
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1047
 *
1048
 * @return string
1049
 *   a html representation of the given CategoricalData element
1050
 *
1051
 * @ingroup compose
1052
 */
1053
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1054

    
1055
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1056

    
1057
  $state_data_strings = array();
1058
  if (isset($element->stateData)) {
1059
    foreach ($element->stateData as $state_data) {
1060

    
1061
      $state  = NULL;
1062

    
1063
      if (isset($state_data->state)) {
1064
        $state = cdm_term_representation($state_data->state);
1065
      }
1066

    
1067
      if (isset($state_data->modifyingText_L10n)) {
1068
        $state = ' ' . $state_data->modifyingText_L10n;
1069
      }
1070

    
1071
      $modifiers_strings = cdm_modifers_representations($state_data);
1072

    
1073
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1074

    
1075
    }
1076
  }
1077

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

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

    
1082
  return $render_array;
1083
}
1084

    
1085

    
1086
/**
1087
 * Theme function to render CDM DescriptionElements of the type QuantitativeData.
1088
 *
1089
 * The function renders the statisticalValues contained in the QuantitativeData
1090
 * entity according to the following scheme:
1091
 *
1092
 * (ExtremeMin)-Min-Average-Max-(ExtremeMax)
1093
 *
1094
 * All modifiers of these values are appended.
1095
 *
1096
 * If the QuantitativeData is containing more statisticalValues with further
1097
 * statisticalValue types, these additional measures will be appended to the
1098
 * above string separated by whitespace.
1099
 *
1100
 * Special cases;
1101
 * 1. Min==Max: this will be interpreted as Average
1102
 *
1103
 * @param $element
1104
 *  The CDM QuantitativeData entity
1105
 *
1106
 * @param $feature_block_settings
1107
 *
1108
 * @param bool $prepend_feature_label
1109
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1110
 *
1111
 *
1112
 * @return string
1113
 *   a html representation of the given QuantitativeData element
1114
 *
1115
 * @ingroup themeable
1116
 */
1117
function compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1118
  /*
1119
   * - statisticalValues
1120
   *   - value
1121
   *   - modifiers
1122
   *   - type
1123
   * - unit->representation_L10n
1124
   * - modifyingText
1125
   * - modifiers
1126
   * - sources
1127
   */
1128

    
1129
  $out = '';
1130
  $type_representation = NULL;
1131
  $min_max = min_max_array();
1132

    
1133

    
1134
  $other_values = array();
1135

    
1136
  if (isset($element->statisticalValues)) {
1137
    $other_values_markup = array();
1138
    foreach ($element->statisticalValues as $statistical_val) {
1139

    
1140
      // compile the full value string which also may contain modifiers
1141
      if (isset($statistical_val->value)) {
1142
        $statistical_val->_value = $statistical_val->value;
1143
      }
1144
      $val_modifiers_strings = cdm_modifers_representations($statistical_val);
1145
      if ($val_modifiers_strings) {
1146
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1147
      }
1148

    
1149
      // either put into min max array or into $other_values
1150
      // for generic output to be appended to 'min-max' string
1151
      if (array_key_exists($statistical_val->type->titleCache, $min_max)) {
1152
        $min_max[$statistical_val->type->titleCache] = $statistical_val;
1153
      }
1154
      else {
1155
        $other_values[] = $statistical_val;
1156
      }
1157
    } // end of loop over statisticalValues
1158

    
1159
    // create markup
1160

    
1161
    $min_max_markup = min_max_markup($min_max);
1162

    
1163

    
1164
    foreach ($other_values as $statistical_val) {
1165
      $statistical_val_type_representation = NULL;
1166
      if (isset($statistical_val->type)) {
1167
        $statistical_val_type_representation = cdm_term_representation($statistical_val->type);
1168
        // $statistical_val->type->termType;
1169
        // $statistical_val->type->userFriendlyTypeName;
1170
      }
1171
      $value_markup = '<span class="' . html_class_attribute_ref($statistical_val) . ' ' . $statistical_val->type->termType . ' ">'
1172
        . $statistical_val->_value . '</span>';
1173
      $value_markup = $value_markup .
1174
        ($statistical_val_type_representation ? ' <span class="type">' . $statistical_val_type_representation . '</span>' : '');
1175
      $other_values_markup[] = $value_markup;
1176
    }
1177

    
1178

    
1179
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1180
  }
1181

    
1182
  if (isset($element->unit)) {
1183
    $out .= ' <span class="unit" title="'
1184
      . cdm_term_representation($element->unit) . '">'
1185
      . cdm_term_representation_abbreviated($element->unit)
1186
      . '</span>';
1187
  }
1188

    
1189
  // modifiers of the description element itself
1190
  $modifier_string = cdm_modifers_representations($element);
1191
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1192
  if (isset($element->modifyingText_L10n)) {
1193
    $out = $element->modifyingText_L10n . ' ' . $out;
1194
  }
1195

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

    
1198
  return $render_array;
1199
}
1200

    
1201

    
1202
/**
1203
 * Wraps the render array for the given feature into an enclosing html tag.
1204
 *
1205
 * Optionally the elements can be sorted and glued together by a separator string.
1206
 *
1207
 * @param array $description_element_render_arrays
1208
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1209
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1210
 * @param  $feature :
1211
 *  The feature to which the elements given in $elements are belonging to.
1212
 * @param string $glue :
1213
 *  Defaults to empty string.
1214
 * @param bool $sort
1215
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1216
 *
1217
 * @return array
1218
 *    A Drupal render array
1219
 *
1220
 * @ingroup compose
1221
 */
1222
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1223
  {
1224

    
1225
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1226
    $enclosing_tag = $feature_block_settings['as_list'];
1227

    
1228
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1229
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1230
    }
1231

    
1232
    $is_first = true;
1233
    foreach($description_element_render_arrays as &$element_render_array){
1234
      if(!is_array($element_render_array)){
1235
        $element_render_array = markup_to_render_array($element_render_array);
1236
      }
1237
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1238

    
1239
      // add the glue!
1240
      if(!$is_first) {
1241
        if (isset($element_render_array['#value'])) {
1242
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1243
        } elseif (isset($element_render_array['#markup'])) {
1244
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1245
        }
1246
      }
1247
      $is_first = false;
1248
    }
1249

    
1250
    $render_array['elements']['children'] = $description_element_render_arrays;
1251

    
1252
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1253
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1254

    
1255
    return $render_array;
1256
  }
1257

    
1258

    
1259
  /* compose nameInSource or originalNameString as markup
1260
   *
1261
   * @param $source
1262
   * @param $do_link_to_name_used_in_source
1263
   * @param $suppress_for_shown_taxon
1264
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1265
   *    for which the taxon page is being created, Defaults to TRUE
1266
   *
1267
   * @return array
1268
   *    A Drupal render array with an additional element, the render array is empty
1269
   *    if the source had no name in source information
1270
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1271
   *
1272
   * @ingroup compose
1273
   */
1274
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1275

    
1276
    $plaintext = NULL;
1277
    $markup = NULL;
1278
    $name_in_source_render_array = array();
1279

    
1280
    static $taxon_page_accepted_name = '';
1281
    if($suppress_for_shown_taxon && arg(1) == 'taxon' && empty($taxon_page_accepted_name)){
1282

    
1283
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, arg(2));
1284
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1285
    }
1286

    
1287
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1288
      // it is a DescriptionElementSource !
1289
      $plaintext = $source->nameUsedInSource->titleCache;
1290
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1291
        return $name_in_source_render_array; // SKIP this name
1292
      }
1293
      $markup = render_taxon_or_name($source->nameUsedInSource);
1294
      if ($do_link_to_name_used_in_source) {
1295
        $markup = l(
1296
          $markup,
1297
          path_to_name($source->nameUsedInSource->uuid),
1298
          array(
1299
            'attributes' => array(),
1300
            'absolute' => TRUE,
1301
            'html' => TRUE,
1302
          ));
1303
      }
1304
    }
1305
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1306
      // the name used in source can not be expressed as valid taxon name,
1307
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1308
      // field
1309
      // using the originalNameString as key to avoid duplicate entries
1310
      $plaintext = $source->originalNameString;
1311
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1312
        return $name_in_source_render_array; // SKIP this name
1313
      }
1314
      $markup = $source->originalNameString;
1315
    }
1316

    
1317
    if ($plaintext) { // checks if we have any content
1318
      $name_in_source_render_array = markup_to_render_array($markup);
1319
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1320
    }
1321

    
1322
    return $name_in_source_render_array;
1323
  }
1324

    
1325

    
1326

    
1327
  /**
1328
   * Return HTML for a list of description elements.
1329
   *
1330
   * Usually these are of a specific feature type.
1331
   *
1332
   * @param $description_elements
1333
   *   array of descriptionElements which belong to the same feature.
1334
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1335
   *   calling the function _mergeFeatureTreeDescriptions().
1336
   *   @see _mergeFeatureTreeDescriptions()
1337
   *
1338
   * @param  $feature_uuid
1339
   *
1340
   * @return
1341
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1342
   *    Footnote key or anchors are not considered to be textual content.
1343
   *
1344
   * @ingroup compose
1345
   */
1346
  function compose_feature_block_items_generic($description_elements, $feature) {
1347

    
1348
    $elements_out_array = array();
1349
    $distribution_tree = null;
1350

    
1351
    /*
1352
     * $feature_block_has_content will be set true if at least one of the
1353
     * $descriptionElements contains some text which makes up some content
1354
     * for the feature block. Footnote keys are not considered
1355
     * to be content in this sense.
1356
     */
1357
    $feature_block_has_content = false;
1358

    
1359
    if (is_array($description_elements)) {
1360
      foreach ($description_elements as $description_element) {
1361
          /* decide based on the description element class
1362
           *
1363
           * Features handled here:
1364
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1365
           *
1366
           * TODO provide api_hook as extension point for this?
1367
           */
1368
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1369
        switch ($description_element->class) {
1370
          case 'TextData':
1371
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1372
            break;
1373
          case 'CategoricalData':
1374
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1375
            break;
1376
          case 'QuantitativeData':
1377
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1378
            break;
1379
          case 'IndividualsAssociation':
1380
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1381
            break;
1382
          case 'TaxonInteraction':
1383
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1384
            break;
1385
          case 'CommonTaxonName':
1386
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1387
            break;
1388
          case 'Uses':
1389
            /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1390
            break;
1391
          default:
1392
            $feature_block_has_content = true;
1393
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1394
        }
1395
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1396
        // considering not empty as long as the last item added is a render array
1397
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1398
      }
1399

    
1400
      // If feature = CITATION sort the list of sources.
1401
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1402
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1403
        sort($elements_out_array);
1404
      }
1405
    }
1406

    
1407
    return $elements_out_array;
1408
  }
1409

    
1410
/**
1411
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1412
 *
1413
 * @parameter $elements
1414
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1415
 * @parameter $feature
1416
 *  the common feature of all $elements, must be CommonName
1417
 *
1418
 * @return
1419
 *   A drupal render array
1420
 *
1421
 * @ingroup compose
1422
 */
1423
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1424

    
1425
  $common_name_out = '';
1426
  $common_name_feature_elements = array();
1427
  $textData_commonNames = array();
1428

    
1429
  $footnote_key_suggestion = 'common-names-feature-block';
1430

    
1431
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1432

    
1433
  if (is_array($elements)) {
1434
    foreach ($elements as $element) {
1435

    
1436
      if ($element->class == 'CommonTaxonName') {
1437

    
1438
        // common name without a language or area, should not happen but is possible
1439
        $language_area_key = '';
1440
        if (isset($element->language->representation_L10n)) {
1441
          $language_area_key .= '<span class="language-label">' . $element->language->representation_L10n . '</span>';
1442
        }
1443
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1444
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1445
        }
1446

    
1447
        if(isset($common_names[$language_area_key][$element->name])) {
1448
          // same name already exists for language and area combination, se we merge the description elements
1449
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1450
        } else{
1451
          // otherwise add as new entry
1452
          $common_names[$language_area_key][$element->name] = $element;
1453
        }
1454

    
1455
      }
1456
      elseif ($element->class == 'TextData') {
1457
        $textData_commonNames[] = $element;
1458
      }
1459
    }
1460
  }
1461
  // Handling common names.
1462
  if (isset($common_names) && count($common_names) > 0) {
1463
    // Sorting the array based on the key (language, + area if set).
1464
    // Comment @WA there are common names without a language, so this sorting
1465
    // can give strange results.
1466
    ksort($common_names);
1467

    
1468
    // loop over set of elements per language area
1469
    foreach ($common_names as $language_area_key => $elements) {
1470
      ksort($elements); // sort names alphabetically
1471
      $per_language_area_out = array();
1472

    
1473
      foreach ($elements as $element) {
1474
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1475
        $common_name_markup = drupal_render($common_name_render_array);
1476
        // IMPORTANT!
1477
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1478
        // this is an error and the trailing whitespace needs to be removed
1479
        if(str_endsWith($common_name_markup, "\n")){
1480
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1481
        }
1482
        $per_language_area_out[] = $common_name_markup;
1483
      }
1484

    
1485
      $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1486
    } // End of loop over set of elements per language area
1487

    
1488

    
1489
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1490
      $common_name_feature_elements, $feature, '; ', FALSE
1491
    );
1492
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1493

    
1494
  }
1495

    
1496
  // Handling commons names as text data.
1497
  $text_data_out = array();
1498

    
1499
  foreach ($textData_commonNames as $text_data_element) {
1500
    /* footnotes are not handled correctly in compose_description_element_text_data,
1501
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1502
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1503
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1504
    $text_data_out[] = drupal_render($text_data_render_array);
1505
  }
1506

    
1507
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1508
    $text_data_out, $feature
1509
  );
1510

    
1511
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1512
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1513
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1514

    
1515
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1516
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1517
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1518
    .$footnotes,
1519
    $weight
1520
  );
1521
}
1522

    
1523
/**
1524
 * Renders a single instance of the type CommonTaxonName.
1525
 *
1526
 * @param $element
1527
 *   The CDM CommonTaxonName entity.
1528
 * @param $feature_block_settings
1529
 *
1530
 * @param $footnote_key_suggestion
1531
 *
1532
 * @param $element_tag_name
1533
 *
1534
 * @return array
1535
 *   Drupal render array
1536
 *
1537
 * @ingroup compose
1538
 */
1539
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion = NULL)
1540
{
1541

    
1542
  if(!$footnote_key_suggestion) {
1543
    $footnote_key_suggestion = $element->feature->uuid;
1544
  }
1545

    
1546
  $name = '';
1547
  if(isset($element->name)){
1548
    $name = $element->name;
1549
  }
1550

    
1551

    
1552
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key_suggestion);
1553
}
1554

    
1555
/**
1556
 * Composes the render array for a CDM Distribution description element
1557
 *
1558
 * @param array $description_elements
1559
 *   Array of CDM Distribution instances
1560
 * @param $enclosingTag
1561
 *   The html tag to be use for the enclosing element
1562
 *
1563
 * @return array
1564
 *   A Drupal render array
1565
 *
1566
 * @ingroup compose
1567
 */
1568
function compose_description_elements_distribution($description_elements){
1569

    
1570
  $out = '';
1571
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1572
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1573

    
1574
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1575
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1576

    
1577
  foreach ($description_elements as $description_element) {
1578
    $annotations_and_sources = handle_annotations_and_sources(
1579
      $description_element,
1580
      $feature_block_settings,
1581
      $description_element->area->representation_L10n,
1582
      UUID_DISTRIBUTION
1583
    );
1584

    
1585

    
1586
    list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1587

    
1588
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1589
      . ' " title="' . $status_label. '">'
1590
      . $description_element->area->representation_L10n
1591
      . $status_markup;
1592
    if(!empty($annotations_and_sources['source_references'])){
1593
      $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1594
    }
1595
    $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1596
  }
1597

    
1598
  RenderHints::popFromRenderStack();
1599
  return markup_to_render_array($out);
1600
}
1601

    
1602
  /**
1603
   * @param $descriptionElement
1604
   * @return array
1605
   */
1606
  function distribution_status_label_and_markup($descriptionElement) {
1607
    $status_markup = '';
1608
    $status_label = '';
1609

    
1610
    if (isset($descriptionElement->status)) {
1611
      $status_label = $descriptionElement->status->representation_L10n;
1612
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1613
        . $status_label . ' </span>';
1614

    
1615
    };
1616
    return array($status_label, $status_markup);
1617
  }
1618

    
1619

    
1620
  /**
1621
   * Provides the merged feature tree for a taxon profile page.
1622
   *
1623
   * The merging of the profile feature tree is actully done in
1624
   * _mergeFeatureTreeDescriptions(). See this method  for details
1625
   * on the structure of the merged tree.
1626
   *
1627
   * This method provides t hook which can be used to modify the
1628
   * merged feature tree after it has been created, see
1629
   * hook_merged_taxon_feature_tree_alter()
1630
   *
1631
   * @param $taxon
1632
   *   A CDM Taxon instance
1633
   *
1634
   * @return object
1635
   *  The merged feature tree
1636
   *
1637
   */
1638
  function merged_taxon_feature_tree($taxon) {
1639

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

    
1643

    
1644
    // 2. find the distribution feature node
1645
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1646

    
1647
    if ($distribution_node) {
1648
      // 3. get the distributionInfoDTO
1649
      $query_parameters = cdm_distribution_filter_query();
1650
      $query_parameters['part'] = array('mapUriParams');
1651
      if(variable_get(DISTRIBUTION_CONDENSED)){
1652
        $query_parameters['part'][] = 'condensedDistribution';
1653
      }
1654
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1655
        $query_parameters['part'][] = 'tree';
1656
      }
1657
      else {
1658
        $query_parameters['part'][] = 'elements';
1659
      }
1660
      $query_parameters['omitLevels'] = array();
1661
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1662
        if(is_uuid($uuid)){
1663
          $query_parameters['omitLevels'][] = $uuid;
1664
        }
1665
      }
1666
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1667
      if ($customStatusColorsJson) {
1668
        $query_parameters['statusColors'] = $customStatusColorsJson;
1669
      }
1670

    
1671
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1672
      // 4. get distribution TextData is there are any
1673
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1674
        array(
1675
          'taxon' => $taxon->uuid,
1676
          'type' => 'TextData',
1677
          'features' => UUID_DISTRIBUTION
1678
        )
1679
      );
1680

    
1681
      // 5. put all distribution data into the distribution feature node
1682
      if ($distribution_text_data //if text data exists
1683
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1684
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1685
      ) { // OR if DTO has distribution elements
1686
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1687
        if ($distribution_text_data) {
1688
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1689
        }
1690
        if ($distribution_info_dto) {
1691
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1692
        }
1693
      }
1694
    }
1695

    
1696
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1697
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1698

    
1699
    return $merged_tree;
1700
  }
1701

    
1702

    
1703
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1704

    
1705
    static $hierarchy_style;
1706
    // TODO expose $hierarchy_style to administration of provide a hook
1707
    if( !isset($hierarchy_style)){
1708
      $hierarchy_style = array(
1709
        // level 2
1710
        array(
1711
          'label_suffix' => '',
1712
          'element_glue' => ', ',
1713
          'element_set_pre' => '(',
1714
          'element_set_post' => ')'
1715
        ),
1716
        // level 1
1717
        array(
1718
          'label_suffix' => '',
1719
          'element_glue' => '; ',
1720
          'element_set_pre' => '',
1721
          'element_set_post' => ''
1722
        ),
1723
        // level 0
1724
        array(
1725
          'label_suffix' => ':',
1726
          'element_glue' => ' ',
1727
          'element_set_pre' => '',
1728
          'element_set_post' => ''
1729
        ),
1730
      );
1731
    }
1732

    
1733
    $render_array = array();
1734

    
1735
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1736
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1737

    
1738
    // Returning NULL if there are no description elements.
1739
    if ($distribution_tree == null) {
1740
      return $render_array;
1741
    }
1742
    // for now we are not using a render array internally to avoid performance problems
1743
    $markup = '';
1744
    if (isset($distribution_tree->rootElement->children)) {
1745
      $tree_nodes = $distribution_tree->rootElement->children;
1746
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1747
    }
1748

    
1749
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1750
      $markup,
1751
      0,
1752
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1753
      '</div>'
1754
    );
1755

    
1756
    return $render_array;
1757
  }
1758

    
1759
  /**
1760
   * this function should produce markup as the compose_description_elements_distribution()
1761
   * function.
1762
   *
1763
   * @see compose_description_elements_distribution()
1764
   *
1765
   * @param $distribution_tree
1766
   * @param $feature_block_settings
1767
   * @param $tree_nodes
1768
   * @param $markup
1769
   * @param $hierarchy_style
1770
   */
1771
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1772

    
1773
    $level_index++;
1774
    static $enclosingTag = "span";
1775

    
1776
    $level_style = array_pop($hierarchy_style);
1777
    if(count($hierarchy_style) == 0){
1778
      // lowest defined level style will be reused for all following levels
1779
      $hierarchy_style[] = $level_style;
1780
    }
1781

    
1782
    $node_index = -1;
1783
    $per_node_markup = array();
1784
    foreach ($tree_nodes as $node){
1785

    
1786
      $per_node_markup[++$node_index] = '';
1787

    
1788
      $label = $node->nodeId->representation_L10n;
1789

    
1790
      $distributions = $node->data;
1791
      $distribution_uuids = array();
1792
      $distribution_aggregate = NULL;
1793
        foreach($distributions as $distribution){
1794

    
1795
          $distribution_uuids[] = $distribution->uuid;
1796

    
1797
          // if there is more than one distribution we aggregate the sources and
1798
          // annotations into a synthetic distribution so that the footnote keys
1799
          // can be rendered consistently
1800
          if(!$distribution_aggregate) {
1801
            $distribution_aggregate = $distribution;
1802
            if(!isset($distribution_aggregate->sources[0])){
1803
              $distribution_aggregate->sources = array();
1804
            }
1805
            if(!isset($distribution_aggregate->annotations[0])){
1806
              $distribution_aggregate->annotations = array();
1807
            }
1808
          } else {
1809
            if(isset($distribution->sources[0])) {
1810
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1811
                $distribution->sources);
1812
            }
1813
            if(isset($distribution->annotations[0])) {
1814
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1815
                $distribution->annotations);
1816
            }
1817
          }
1818
        }
1819

    
1820
      $status_label= '';
1821
      $status_markup = '';
1822
      $annotations_and_sources =  null;
1823
      if($distribution_aggregate) {
1824
        $annotations_and_sources = handle_annotations_and_sources(
1825
          $distribution_aggregate,
1826
          $feature_block_settings,
1827
          $label,
1828
          UUID_DISTRIBUTION
1829
        );
1830

    
1831
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1832
      }
1833

    
1834
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1835
        . join(' descriptionElement-', $distribution_uuids)
1836
        . ' level_index_' . $level_index
1837
        . ' " title="' . $status_label . '">'
1838
        . '<span class="area_label">' . $label
1839
        . $level_style['label_suffix'] . ' </span>'
1840
        .  $status_markup
1841
      ;
1842

    
1843
      if(isset($annotations_and_sources)){
1844
        if(!empty($annotations_and_sources['source_references'])){
1845
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1846
        }
1847
        if($annotations_and_sources['foot_note_keys']) {
1848
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1849
        }
1850
      }
1851

    
1852
      if(isset($node->children[0])){
1853
        _compose_distribution_hierarchy(
1854
          $node->children,
1855
          $feature_block_settings,
1856
          $per_node_markup[$node_index],
1857
          $hierarchy_style,
1858
          $level_index
1859
        );
1860
      }
1861

    
1862
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1863
    }
1864
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1865
  }
1866

    
1867

    
(2-2/8)