Project

General

Profile

Download (56.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
   * @param $element
360
   * @param $feature_block_settings
361
   * @param $element_text
362
   *   used to decide if the source references should be enclosed in brackets or not
363
   * @param $footnote_list_key_suggestion
364
   * @return array
365
   *   an associative array with the following elements:
366
   *   - foot_note_keys: all footnote keys as markup
367
   *   - source_references: an array of the source references citations
368
   *   - names used in source: an associative array of the names in source,
369
   *        the name in source strings are de-duplicated
370
   *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
371
   *
372
   *
373
   */
374
  function handle_annotations_and_sources($element, $feature_block_settings, $element_text, $footnote_list_key_suggestion) {
375
    $annotations_and_sources = array(
376
      'foot_note_keys' => NULL,
377
      'source_references' => array(),
378
      'names_used_in_source' => array()
379
    );
380

    
381
    usort($element->sources, 'compare_original_sources');
382

    
383
    if ($feature_block_settings['sources_as_content'] == 1) {
384
      foreach ($element->sources as $source) {
385

    
386
        $referenceCitation = theme('cdm_OriginalSource',
387
          array(
388
            'source' => $source,
389
            'doLink' => $feature_block_settings['link_to_reference'] == 1,
390
            'do_link_to_name_used_in_source' => $feature_block_settings['link_to_name_used_in_source'] == 1,
391
          )
392
        );
393

    
394
        if ($referenceCitation) {
395
          if (empty($element_text)) {
396
            $annotations_and_sources['source_references'][] = $referenceCitation;
397
          }
398
          else {
399
            $annotations_and_sources['source_references'][] = ' (' . $referenceCitation . ')';
400
          }
401
        }
402

    
403
        $name_in_source_render_array = compose_name_in_source(
404
          $source,
405
          $feature_block_settings['link_to_name_used_in_source'] == 1
406
        );
407

    
408
        if(!empty($name_in_source_render_array)){
409
          $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
410
        }
411
      } // END of loop over sources
412

    
413
      // annotations footnotes separate.
414
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
415
        array(
416
          'cdmBase_list' => $element,
417
          'footnote_list_key' => $footnote_list_key_suggestion,
418
        )
419
      );
420

    
421
    } // END of references inline
422

    
423
    // put sources into bibliography if requested ...
424
    if ($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
425
      $annotations_and_sources['foot_note_keys'] = cdm_create_description_element_footnotes(
426
        $element, ',',
427
        $footnote_list_key_suggestion,
428
        $feature_block_settings['link_to_reference'] == 1,
429
        $feature_block_settings['link_to_name_used_in_source'] == 1
430
      );
431
    }
432

    
433
    return $annotations_and_sources;
434
  }
435

    
436

    
437
  /**
438
   *
439
   *
440
   * @return string
441
   *  the footnote_list_key
442
   */
443
  function original_source_footnote_list_key($key_suggestion = null) {
444
    if(!$key_suggestion){
445
      $key_suggestion = RenderHints::getFootnoteListKey();
446
    }
447
    $bibliography_settings = get_bibliography_settings();
448
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? 'BIBLIOGRAPHY' : 'BIBLIOGRAPHY-' . $key_suggestion;
449
    return $footnote_list_key;
450
  }
451

    
452
  /**
453
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
454
   *
455
   * @param $feature_block_settings
456
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
457
   */
458
  function cdm_feature_block_element_tag_name($feature_block_settings){
459
    switch ($feature_block_settings['as_list']){
460
      case 'ul':
461
      case 'ol':
462
        return 'li';
463
      case 'div':
464
        if(isset($feature_block_settings['element_tag'])){
465
          return $feature_block_settings['element_tag'];
466
        }
467
        return 'span';
468
      case 'dl':
469
        return 'dd';
470
      default:
471
        return 'div'; // should never happen, throw error instead?
472
    }
473
  }
474

    
475

    
476
/* ==================== COMPOSE FUNCTIONS =============== */
477

    
478
  /**
479
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
480
   *
481
   * The taxon profile consists of drupal block elements, one for the description elements
482
   * of a specific feature. The structure is defined by specific FeatureTree.
483
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
484
   *
485
   * The merged nodes can be obtained by making use of the
486
   * function cdm_ws_descriptions_by_featuretree().
487
   *
488
   * @see cdm_ws_descriptions_by_featuretree()
489
   *
490
   * @param $mergedFeatureNodes
491
   *
492
   * @param $taxon
493
   *
494
   * @return array
495
   *  A Drupal render array containing feature blocks and the table of content
496
   *
497
   * @ingroup compose
498
   */
499
  function compose_cdm_feature_nodes($mergedFeatureNodes, $taxon) {
500

    
501
    $block_list = array();
502

    
503
    RenderHints::pushToRenderStack('feature_nodes');
504

    
505
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
506

    
507
    // Create a drupal block for each feature
508
    foreach ($mergedFeatureNodes as $node) {
509

    
510
      if ((isset($node->descriptionElements['#type']) ||
511
          has_feature_node_description_elements($node)) && $node->feature->uuid != UUID_IMAGE) { // skip empty or supressed features
512

    
513
        $feature_name = cdm_term_representation($node->feature, 'Unnamed Feature');
514

    
515
        $block = feature_block($feature_name, $node->feature);
516
        $block->content = array();
517
        $block_content_is_empty = TRUE;
518
        $block_content_weight = 0;
519

    
520
        /*
521
         * Content/DISTRIBUTION.
522
         */
523

    
524
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
525
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
526
          $block_content_is_empty = FALSE;
527
        }
528
        /*
529
         * Content/COMMON_NAME.
530
         */
531
        else if ($node->feature->uuid == UUID_COMMON_NAME) {
532
          $common_names_render_array = compose_description_elements_common_name($node->descriptionElements, $node->feature);
533
          $block->content[] = $common_names_render_array;
534
          $block_content_is_empty = FALSE;
535
        }
536

    
537
        else if ($node->feature->uuid == UUID_USE_RECORD) {
538
          $block_uses_content_html = theme('cdm_block_Uses', array('taxonUuid' => $taxon->uuid));
539
          $block->content[] = markup_to_render_array($block_uses_content_html);
540
          $block_content_is_empty = FALSE;
541
        }
542

    
543
        /*
544
         * Content/ALL OTHER FEATURES.
545
         */
546
        else {
547

    
548
          $media_list = array();
549
          $out_child_elements = '';
550

    
551
          if (isset($node->descriptionElements)) {
552
            $taxon_uuid = NULL;
553
            if(isset($taxon) ) {
554
              $taxon_uuid = $taxon->uuid;
555
            }
556
            $elements_render_array = compose_description_elements($node->descriptionElements, $node->feature, $taxon_uuid);
557
            $block_content_is_empty = empty($elements_render_array);
558
            $block->content[] = $elements_render_array;
559
          }
560

    
561
          // Content/ALL OTHER FEATURES/Subordinate Features
562
          // subordinate features are printed inline in one floating text,
563
          // it is expected hat subordinate features can "contain" TextData,
564
          // Qualitative- and Qualitative- DescriptioneElements
565
          if (isset($node->childNodes[0])) {
566

    
567
            // TODO support more than one level of children.
568
            // can this be solved by recursively calling this function?
569
            // @see http://dev.e-taxonomy.eu/trac/ticket/2393
570
            $text = '';
571
            foreach ($node->childNodes as $child) {
572

    
573
              if (isset($child->descriptionElements) && is_array($child->descriptionElements)) {
574
                foreach ($child->descriptionElements as $element) {
575

    
576
                  //TODO it woud be better if we could use compose_description_elements() directly instead of the below stuff
577

    
578
                  if (is_array($element->media)) {
579
                    // Append media of subordinate elements to list of main
580
                    // feature.
581
                    $media_list = array_merge($media_list, $element->media);
582
                  }
583

    
584
                  switch ($element->class) {
585
                    case 'TextData':
586
                      // FIXME use compose_description_element_textdata()
587
                      if(isset($element->multilanguageText_L10n->text)){
588
                        $out_child_elements = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
589
                      }
590
                      $out_child_elements = str_replace($child->feature->titleCache, '<em>' . $child->feature->representation_L10n . '</em>', $out_child_elements);
591
                      break;
592
                    case 'CategoricalData':
593
                      $out_child_elements  = '<em>' . $child->feature->representation_L10n . '</em> '
594
                        . theme('cdm_descriptionElement_CategoricalData', array('element' => $element));
595
                      break;
596
                    case 'QuantitativeData':
597
                      $out_child_elements = '<em>' . $child->feature->representation_L10n . '</em> '
598
                        . theme('cdm_descriptionElement_QuantitativeData', array('element' => $element));
599

    
600
                  }
601

    
602
                }
603
                $text .= " " . $out_child_elements;
604
                $out_child_elements = '';
605
              }
606
            }
607
            $block_content_is_empty = $block_content_is_empty && empty($text);
608
            $block->content[] = markup_to_render_array($text);
609
            $block_content_is_empty = $block_content_is_empty && empty($media_list);
610
          }
611

    
612
          $block->content[] = compose_feature_media_gallery($node, $media_list, $gallery_settings);
613
          /*
614
           * Footnotes for the feature block
615
           */
616
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $node->feature->uuid)));
617
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $node->feature->uuid)));
618
          $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $node->feature->uuid)));
619
        } // END all other features
620

    
621
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
622
        drupal_alter('cdm_feature_node_block_content', $block->content, $node->feature, $node->descriptionElements);
623

    
624
        if(!$block_content_is_empty){ // skip empty block content
625
          $block_list[] = $block;
626
          cdm_toc_list_add_item(cdm_term_representation($node->feature), $node->feature->uuid);
627
        } // END: skip empty block content
628
      } // END: skip empty or supressed features
629
    } // END: creating a block per feature
630

    
631
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
632

    
633
    RenderHints::popFromRenderStack();
634

    
635
    return _block_get_renderable_array($block_list);
636
  }
637

    
638
  /**
639
   * @param $node
640
   * @param $media_list
641
   * @param $gallery_settings
642
   * @return array
643
   */
644
  function compose_feature_media_gallery($node, $media_list, $gallery_settings) {
645

    
646
    if (isset($node->descriptionElements)) {
647
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
648
    }
649

    
650
    $captionElements = array('title', 'rights');
651

    
652
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
653
      $gallery = theme('cdm_media_gallerie', array(
654
        'mediaList' => $media_list,
655
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $node->feature->uuid,
656
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
657
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
658
        'captionElements' => $captionElements,
659
      ));
660
      return markup_to_render_array($gallery);
661
    }
662

    
663
    return markup_to_render_array('');
664
  }
665

    
666
  /**
667
   * Composes the distribution feature block for a taxon
668
   *
669
   * @param $taxon
670
   * @param $descriptionElements
671
   *   an associative array with two elements:
672
   *   - '#type': must be 'DTO'
673
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
674
   * @param $feature
675
   *
676
   * @return array
677
   *  A drupal render array
678
   *
679
   * @ingroup compose
680
   */
681
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
682
    $text_data_glue = '';
683
    $text_data_sortOutArray = FALSE;
684
    $text_data_enclosingTag = 'ul';
685
    $text_data_out_array = array();
686

    
687
    $distributionElements = NULL;
688
    $distribution_info_dto = NULL;
689
    $distribution_sortOutArray = FALSE;
690

    
691
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
692

    
693
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
694
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
695
      $distribution_glue = '';
696
      $distribution_enclosingTag = 'dl';
697
    } else {
698
      $distribution_glue = '';
699
      $distribution_enclosingTag = 'ul';
700
    }
701

    
702
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
703
      // skip the DISTRIBUTION section if there is no DTO type element
704
      return array(); // FIXME is it ok to return an empty array?
705
    }
706

    
707
    $block = feature_block(
708
      cdm_term_representation($feature, 'Unnamed Feature'),
709
      $feature
710
    );
711

    
712
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
713
    if (isset($descriptionElements['TextData'])) {
714
      // --- TextData
715
      foreach ($descriptionElements['TextData'] as $text_data_element) {
716
        $asListElement = FALSE;
717
        $text_data_render_array = compose_description_element_textdata($text_data_element, $asListElement, $text_data_element->feature->uuid);
718
        $repr = drupal_render($text_data_render_array);
719

    
720
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
721
          $text_data_out_array[] = $repr;
722
          // TODO HINT: sorting in compose_cdm_feature_block_elements will
723
          // not work since this array contains html attributes with uuids
724
          // and what is about cases like the bibliography where
725
          // any content can be prefixed with some foot-note anchors?
726
          $text_data_sortOutArray = TRUE;
727
          $text_data_glue = '<br/> ';
728
          $text_data_enclosingTag = 'p';
729
        }
730
      }
731
    }
732

    
733

    
734
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
735
      $block->content[] = compose_cdm_feature_block_elements(
736
        $text_data_out_array,
737
        $feature,
738
        $text_data_glue,
739
        $text_data_sortOutArray,
740
        $text_data_enclosingTag
741
      );
742
    }
743

    
744
    // --- Distribution map
745
    $distribution_map_query_parameters = NULL;
746
    if (isset($descriptionElements['DistributionInfoDTO'])) {
747
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
748
    }
749
    $map_render_element = compose_distribution_map($taxon, $distribution_map_query_parameters);
750
    $block->content[] = $map_render_element;
751

    
752
    $dto_out_array = array();
753

    
754
    // --- Condensed Distribution
755
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
756
      $condensed_distribution_markup = '<p class="condensed_distribution">';
757

    
758
      $isFirst = true;
759
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
760
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
761
          if(!$isFirst){
762
            $condensed_distribution_markup .= ' ';
763
          }
764
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
765
          . $cdItem->areaStatusLabel . '</span>';
766
          $isFirst = false;
767
        }
768
      }
769

    
770
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
771
        if(!$isFirst){
772
          $condensed_distribution_markup .= ' ';
773
        }
774
        $isFirst = TRUE;
775
        $condensed_distribution_markup .= '[';
776
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
777
          if (!$isFirst) {
778
            $condensed_distribution_markup .= ' ';
779
          }
780
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
781
            . $cdItem->areaStatusLabel . '</span>';
782
          $isFirst = false;
783
        }
784
        $condensed_distribution_markup .= ']';
785
      }
786

    
787
      $condensed_distribution_markup .= '&nbsp;' . l(
788
          font_awesome_icon_markup(
789
            'fa-info-circle',
790
            array(
791
              'alt'=>'help',
792
              'class' => array('superscript')
793
            )
794
          ),
795
          'cdm_dataportal/help/condensed_distribution',
796
          array('html' => TRUE));
797
      $condensed_distribution_markup .= '</p>';
798
      $dto_out_array[] = $condensed_distribution_markup;
799
    }
800

    
801
    // --- tree or list
802
    if (isset($descriptionElements['DistributionInfoDTO'])) {
803
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
804

    
805
      // --- tree
806
      if (is_object($distribution_info_dto->tree)) {
807
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
808
        $dto_out_array[] = drupal_render($distribution_tree_render_array);
809
      }
810

    
811
      // --- sorted element list
812
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
813
        foreach ($distribution_info_dto->elements as $descriptionElement) {
814
          if (is_object($descriptionElement->area)) {
815
            $sortKey = $descriptionElement->area->representation_L10n;
816
            $distributionElements[$sortKey] = $descriptionElement;
817
          }
818
        }
819
        ksort($distributionElements);
820
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
821
        $dto_out_array[] = drupal_render($distribution_element_render_array);
822

    
823
      }
824
      //
825
      $block->content[] = compose_cdm_feature_block_elements(
826
        $dto_out_array,
827
        $feature,
828
        $distribution_glue,
829
        $distribution_sortOutArray,
830
        $distribution_enclosingTag
831
      );
832
    }
833

    
834
    // --- TextData at the bottom
835
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
836
      $block->content[] = compose_cdm_feature_block_elements(
837
        $text_data_out_array,
838
        $feature,
839
        $text_data_glue,
840
        $text_data_sortOutArray,
841
        $text_data_enclosingTag
842
      );
843
    }
844

    
845
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
846
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
847
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
848

    
849
    return $block;
850
  }
851

    
852

    
853
  /**
854
   * Composes a drupal render array for CDM TextData description elements.
855
   *
856
   * @param $element
857
   *    The CDM TextData description element which contains the textual  information.
858
   * @param $asListElement
859
   *    A boolean which determines whether the citations should
860
   *     be rendered as a list or not.
861
   *    TODO remove and replace $asListElement by $feature_block_settings['as_list']
862
   *  @param $feature_uuid
863
   *
864
   * @return array
865
   *   A drupal render array with the following elements being used:
866
   *    - #tag: either 'div', 'li', ...
867
   *    ⁻ #attributes: class attributes
868
   *    - #value_prefix: (optionally) contains footnote anchors
869
   *    - #value: contains the textual content
870
   *    - #value_suffix: (optionally) contains footnote keys
871
   *
872
   * @ingroup compose
873
   */
874
  function compose_description_element_textdata($element, $asListElement, $feature_uuid) {
875

    
876
    $footnote_list_key_suggestion = $feature_uuid;
877

    
878
    // FIXME $feature_block_settings should be passed as parameter!!!!!
879
    $feature_block_settings = get_feature_block_settings($feature_uuid);
880

    
881
    // FIXME remove this hack ---------------------------
882
    $default_theme = variable_get('theme_default', NULL);
883
    if($default_theme == 'garland_cichorieae' || $default_theme == 'cyprus'
884
      || $default_theme == 'flore_afrique_centrale' || $default_theme == 'flora_malesiana' || $default_theme == 'flore_gabon' ){
885
      $asListElement = $feature_block_settings['as_list'] == 'ul';
886
    }
887
    // --------------------------------------------------
888

    
889
    $render_array = array(
890
      '#type' => 'html_tag',
891
      '#tag' => $asListElement ? 'li' : 'span',
892
      '#attributes' => array(
893
        'class' => 'DescriptionElement DescriptionElement-' . $element->class . '
894
      ' .  html_class_attribute_ref($element)
895
      ),
896
      '#value' => '',
897
      '#value_suffix' => NULL
898
    );
899

    
900
    $element_text = '';
901
    if (isset($element->multilanguageText_L10n->text)) {
902
      // TODO replacement of \n by <br> should be configurable
903
      $element_text = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
904
    }
905

    
906
    $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element_text, $footnote_list_key_suggestion);
907

    
908
    $names_used_in_source_markup = '';
909
    if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_text)) {
910
      // $element_text ==  NULL  usually occurs only in the case of CITATIONS!!!
911
      $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
912
    }
913

    
914
    $source_references_markup = '';
915
    if(!empty($annotations_and_sources['source_references'])){
916
      $source_references_markup = '<span class="sources">'. join(' ', $annotations_and_sources['source_references']) . '<span>';
917
    }
918

    
919
    $render_array['#value'] = $names_used_in_source_markup . $element_text . $source_references_markup;
920
    $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
921

    
922
    return $render_array;
923
  }
924

    
925

    
926

    
927
  /**
928
   * Creates a render array for string representations of description elements for the given feature.
929
   *
930
   * @param array $elements
931
   *   An array of strings. Can be plaintext or markup.
932
   * @param  feature:
933
   *  The feature to which the elements given in $elements are belonging to.
934
   * @param  glue:
935
   *  Defaults to empty string.
936
   * @param $sort
937
   *   Boolean Whether to sort the $elements alphabetically, default is FALSE
938
   * @param  $enclosing_tag
939
   *
940
   * @ingroup compose
941
   */
942
  function compose_cdm_feature_block_elements(array $elements, $feature, $glue = '', $sort = FALSE, $enclosing_tag = 'ul') {
943

    
944
    $feature_block_settings = get_feature_block_settings($feature->uuid);
945
    if($feature_block_settings['as_list']){
946
      $enclosing_tag = $feature_block_settings['as_list'];
947
    }
948

    
949
    $out = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
950

    
951
    if ($sort) {
952
      sort($elements);
953
    }
954

    
955
    //TODO it would be nice if any element would get "feature-block-element" as additional class attribute
956
    //     this will become possible once all $elemets are real Drupal render arrays
957
    $out .= join($glue, $elements) ;
958

    
959
    $out .= '</' . $enclosing_tag . '>';
960
    return markup_to_render_array($out);
961
  }
962

    
963

    
964
  /* compose nameInSource or originalNameString as markup
965
   *
966
   * @param $source
967
   * @param $do_link_to_name_used_in_source
968
   * @param $suppress_for_shown_taxon
969
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
970
   *    for which the taxon page is being created, Defaults to TRUE
971
   *
972
   * @return array
973
   *    A Drupal render array with an additional element, the render array is empty
974
   *    if the source had no name in source information
975
   *    - #_plaintext: contains the plaintext version of the name (custom element)
976
   *
977
   * @ingroup compose
978
   */
979
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
980

    
981
    $plaintext = NULL;
982
    $markup = NULL;
983
    $name_in_source_render_array = array();
984

    
985
    static $taxon_page_accepted_name = '';
986
    if($suppress_for_shown_taxon && arg(1) == 'taxon' && empty($taxon_page_accepted_name)){
987

    
988
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, arg(2));
989
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
990
    }
991

    
992
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
993
      // it is a DescriptionElementSource !
994
      $plaintext = $source->nameUsedInSource->titleCache;
995
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
996
        return $name_in_source_render_array; // SKIP this name
997
      }
998
      $markup = render_taxon_or_name($source->nameUsedInSource);
999
      if ($do_link_to_name_used_in_source) {
1000
        $markup = l(
1001
          $markup,
1002
          path_to_name($source->nameUsedInSource->uuid),
1003
          array(
1004
            'attributes' => array(),
1005
            'absolute' => TRUE,
1006
            'html' => TRUE,
1007
          ));
1008
      }
1009
    }
1010
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1011
      // the name used in source can not be expressed as valid taxon name,
1012
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1013
      // field
1014
      // using the originalNameString as key to avoid duplicate entries
1015
      $plaintext = $source->originalNameString;
1016
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1017
        return $name_in_source_render_array; // SKIP this name
1018
      }
1019
      $markup = $source->originalNameString;
1020
    }
1021

    
1022
    if ($plaintext) { // checks if we have any content
1023
      $name_in_source_render_array = markup_to_render_array($markup);
1024
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1025
    }
1026

    
1027
    return $name_in_source_render_array;
1028
  }
1029

    
1030

    
1031

    
1032
  /**
1033
   * Return HTML for a list of description elements.
1034
   *
1035
   * Usually these are of a specific feature type.
1036
   *
1037
   * @param $descriptionElements
1038
   *   array of descriptionElements which belong to the same feature.
1039
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1040
   *   calling the function _mergeFeatureTreeDescriptions().
1041
   *   @see _mergeFeatureTreeDescriptions()
1042
   *
1043
   * @param  $feature_uuid
1044
   *
1045
   * @return
1046
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1047
   *    Footnote key or anchors are not considered to be textual content.
1048
   *
1049
   * @ingroup compose
1050
   */
1051
  function compose_description_elements($descriptionElements, $feature) {
1052

    
1053
    $render_array = array();
1054
    $elements_out_array = array();
1055
    $distribution_tree = null;
1056

    
1057
    /*
1058
     * $feature_block_has_content will be set true if at least one of the
1059
     * $descriptionElements contains some text which makes up some content
1060
     * for the feature block. Footnote keys are not considered
1061
     * to be content in this sense.
1062
     */
1063
    $feature_block_has_content = false;
1064

    
1065
    RenderHints::pushToRenderStack($feature->uuid);
1066

    
1067
    if (is_array($descriptionElements)) {
1068
      foreach ($descriptionElements as $descriptionElement) {
1069
          /* decide based on the description element class
1070
           *
1071
           * Features handled here:
1072
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1073
           *
1074
           *
1075
           * TODO provide api_hook as extension point for this?
1076
           */
1077
          $feature_block_settings = get_feature_block_settings($descriptionElement->feature->uuid);
1078
          $asListElement  = $feature_block_settings['as_list'] == 'ul';
1079
          switch ($descriptionElement->class) {
1080
            case 'TextData':
1081
              $text_data_render_array = compose_description_element_textdata($descriptionElement, $asListElement, $descriptionElement->feature->uuid);
1082
              $feature_block_has_content = $feature_block_has_content || !empty($text_data_render_array['#value']);
1083
              $elements_out_array[] = drupal_render($text_data_render_array);
1084
              break;
1085
            case 'CategoricalData':
1086
              $feature_block_has_content = true;
1087
              $elements_out_array[] = theme('cdm_descriptionElement_CategoricalData', array('element' => $descriptionElement));
1088
              break;
1089
            case 'QuantitativeData':
1090
              $feature_block_has_content = true;
1091
              $elements_out_array[] = theme('cdm_descriptionElement_QuantitativeData', array('element' => $descriptionElement));
1092
              break;
1093
            case 'IndividualsAssociation':
1094
              $feature_block_has_content = true;
1095
              $elements_out_array[] = theme('cdm_descriptionElement_IndividualsAssociation', array('element' => $descriptionElement));
1096
              break;
1097
            case 'TaxonInteraction':
1098
              $feature_block_has_content = true;
1099
              $elements_out_array[] = theme('cdm_descriptionElement_TaxonInteraction', array('element' => $descriptionElement));
1100
              break;
1101
            case 'Uses':
1102
              /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1103
              break;
1104
            default:
1105
              $feature_block_has_content = true;
1106
              $elements_out_array[] = '<li>No method for rendering unknown description class: ' . $descriptionElement->class . '</li>';
1107
          }
1108
      } // --- END loop over normal description element arrays
1109

    
1110
      // If feature = CITATION sort the list of sources.
1111
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1112
      if ($descriptionElement->feature->uuid == UUID_CITATION) {
1113
        sort($elements_out_array);
1114
      }
1115

    
1116
    } // END normal description element arrays
1117

    
1118
    if($feature_block_has_content){
1119
      $render_array = compose_cdm_feature_block_elements(
1120
        $elements_out_array,
1121
        $feature
1122
      );
1123
    }
1124

    
1125
    RenderHints::popFromRenderStack();
1126
    return $render_array;
1127
  }
1128

    
1129
/**
1130
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1131
 *
1132
 * @parameter $elements
1133
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1134
 * @parameter $feature
1135
 *  the common feature of all $elements, must be CommonName
1136
 *
1137
 * @return
1138
 *   A drupal render array
1139
 *
1140
 * @ingroup compose
1141
 */
1142
function compose_description_elements_common_name($elements, $feature, $weight = FALSE) {
1143

    
1144
  $common_name_out = '';
1145
  $common_name_feature_elements = array();
1146
  $textData_commonNames = array();
1147

    
1148
  $footnote_key_suggestion = 'common-names-feature-block';
1149

    
1150
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1151

    
1152
  $element_tag_name = cdm_feature_block_element_tag_name($feature_block_settings);
1153

    
1154
  if (is_array($elements)) {
1155
    foreach ($elements as $element) {
1156

    
1157
      if ($element->class == 'CommonTaxonName') {
1158

    
1159
        // common name without a language or area, should not happen but is possible
1160
        $language_area_key = '';
1161
        if (isset($element->language->representation_L10n)) {
1162
          $language_area_key .= '<b>' . $element->language->representation_L10n . '</b>';
1163
        }
1164
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1165
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1166
        }
1167

    
1168
        if(isset($common_names[$language_area_key][$element->name])) {
1169
          // same name already exists for language and areae combination, se we merge the description elements
1170
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1171
        } else{
1172
          // otherwise add as new entry
1173
          $common_names[$language_area_key][$element->name] = $element;
1174
        }
1175

    
1176
      }
1177
      elseif ($element->class == 'TextData') {
1178
        $textData_commonNames[] = $element;
1179
      }
1180
    }
1181
  }
1182
  // Handling common names.
1183
  if (isset($common_names) && count($common_names) > 0) {
1184
    // Sorting the array based on the key (language, + area if set).
1185
    // Comment @WA there are common names without a language, so this sorting
1186
    // can give strange results.
1187
    ksort($common_names);
1188

    
1189
    // loop over set of elements per language area
1190
    foreach ($common_names as $language_area_key => $elements) {
1191
      ksort($elements); // sort names alphabetically
1192
      $per_language_area_out = array();
1193
      // loop over set of individual elements
1194
      foreach ($elements as $element) {
1195
        if ($element->name) {
1196
          $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element->name, $footnote_key_suggestion);
1197
          $source_references_markup = '';
1198
          if(!empty($annotations_and_sources['source_references'])){
1199
            $source_references_markup = ' ' . join(', ', $annotations_and_sources['source_references']);
1200
          }
1201
          $per_language_area_out[] = '<' . $element_tag_name. ' class="' . html_class_attribute_ref($element) . '">'
1202
            . $element->name . $source_references_markup . $annotations_and_sources['foot_note_keys'] . '</' . $element_tag_name. '>';
1203
        }
1204
      } // End of loop over set of individual elements
1205
      $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1206
    } // End of loop over set of elements per language area
1207

    
1208

    
1209
    $common_name_feature_elements_render_array = compose_cdm_feature_block_elements(
1210
      $common_name_feature_elements,
1211
      $feature,
1212
      '; ',
1213
      FALSE,
1214
      $feature_block_settings['as_list']
1215
    );
1216
    $common_name_out .= $common_name_feature_elements_render_array['#markup'];
1217

    
1218
  }
1219

    
1220
  // Handling commons names as text data.
1221
  $text_data_out = array();
1222

    
1223
  foreach ($textData_commonNames as $text_data_element) {
1224
    /* footnotes are not handled correctly in compose_description_element_textdata,
1225
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1226
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1227
    $text_data_render_array = compose_description_element_textdata($text_data_element, TRUE, $text_data_element->feature->uuid);
1228
    $text_data_out[] = drupal_render($text_data_render_array);
1229
  }
1230

    
1231
  $common_name_out_text_data = compose_cdm_feature_block_elements(
1232
    $text_data_out,
1233
    $feature
1234
  );
1235

    
1236
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1237
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1238
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1239

    
1240
  return  markup_to_render_array(
1241
    '<div class="common_names_as_common_names">' . $common_name_out . '</div>'
1242
    .'<div class="common_names_as_text_data">' . $common_name_out_text_data['#markup'] . '</div>'
1243
    .$footnotes,
1244
    $weight
1245
  );
1246
}
1247

    
1248
  /**
1249
   * Composes the render array for a CDM Distribution element
1250
   *
1251
   * @param $descriptionElements
1252
   *   The CDM Distribution element
1253
   * @param $enclosingTag
1254
   *   The html tag to be use for the enclosing element
1255
   *
1256
   * @return array
1257
   *   A Drupal render array
1258
   *
1259
   * @ingroup compose
1260
   */
1261
  function compose_description_elements_distribution($descriptionElements){
1262

    
1263
    $out = '';
1264
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1265
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1266

    
1267
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1268
    $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1269

    
1270
    foreach ($descriptionElements as $descriptionElement) {
1271
      $annotations_and_sources = handle_annotations_and_sources(
1272
        $descriptionElement,
1273
        $feature_block_settings,
1274
        $descriptionElement->area->representation_L10n,
1275
        UUID_DISTRIBUTION
1276
      );
1277

    
1278

    
1279
      list($status_label, $status_markup) = distribution_status_label_and_markup($descriptionElement);
1280

    
1281
      $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $descriptionElement->uuid
1282
        . ' " title="' . $status_label. '">'
1283
        . $descriptionElement->area->representation_L10n
1284
        . $status_markup;
1285
      if(!empty($annotations_and_sources['source_references'])){
1286
        $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1287
      }
1288
      $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1289
    }
1290

    
1291
    RenderHints::popFromRenderStack();
1292
    return markup_to_render_array($out);
1293
  }
1294

    
1295
  /**
1296
   * @param $descriptionElement
1297
   * @return array
1298
   */
1299
  function distribution_status_label_and_markup($descriptionElement) {
1300
    $status_markup = '';
1301
    $status_label = '';
1302

    
1303
    if (isset($descriptionElement->status)) {
1304
      $status_label = $descriptionElement->status->representation_L10n;
1305
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1306
        . $status_label . ' </span>';
1307

    
1308
    };
1309
    return array($status_label, $status_markup);
1310
  }
1311

    
1312

    
1313
  /**
1314
   * Provides the merged feature tree for a taxon profile page.
1315
   *
1316
   * The merging of the profile feature tree is actully done in
1317
   * _mergeFeatureTreeDescriptions(). See this method  for details
1318
   * on the structure of the merged tree.
1319
   *
1320
   * This method provides t hook which can be used to modify the
1321
   * merged feature tree after it has been created, see
1322
   * hook_merged_taxon_feature_tree_alter()
1323
   *
1324
   * @param $taxon
1325
   *   A CDM Taxon instance
1326
   *
1327
   * @return object
1328
   *  The merged feature tree
1329
   *
1330
   */
1331
  function merged_taxon_feature_tree($taxon) {
1332

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

    
1336

    
1337
    // 2. find the distribution feature node
1338
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1339

    
1340
    if ($distribution_node) {
1341
      // 3. get the distributionInfoDTO
1342
      $query_parameters = cdm_distribution_filter_query();
1343
      $query_parameters['part'] = array('mapUriParams');
1344
      if(variable_get(DISTRIBUTION_CONDENSED)){
1345
        $query_parameters['part'][] = 'condensedDistribution';
1346
      }
1347
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1348
        $query_parameters['part'][] = 'tree';
1349
      }
1350
      else {
1351
        $query_parameters['part'][] = 'elements';
1352
      }
1353
      $query_parameters['omitLevels'] = array();
1354
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1355
        if(is_uuid($uuid)){
1356
          $query_parameters['omitLevels'][] = $uuid;
1357
        }
1358
      }
1359
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1360
      if ($customStatusColorsJson) {
1361
        $query_parameters['statusColors'] = $customStatusColorsJson;
1362
      }
1363

    
1364
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1365
      // 4. get distribution TextData is there are any
1366
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1367
        array(
1368
          'taxon' => $taxon->uuid,
1369
          'type' => 'TextData',
1370
          'features' => UUID_DISTRIBUTION
1371
        )
1372
      );
1373

    
1374
      // 5. put all distribution data into the distribution feature node
1375
      if ($distribution_text_data //if text data exists
1376
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1377
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1378
      ) { // OR if DTO has distribution elements
1379
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1380
        if ($distribution_text_data) {
1381
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1382
        }
1383
        if ($distribution_info_dto) {
1384
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1385
        }
1386
      }
1387
    }
1388

    
1389
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1390
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1391

    
1392
    return $merged_tree;
1393
  }
1394

    
1395

    
1396
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1397

    
1398
    static $hierarchy_style;
1399
    // TODO expose $hierarchy_style to administration of provide a hook
1400
    if( !isset($hierarchy_style)){
1401
      $hierarchy_style = array(
1402
        // level 2
1403
        array(
1404
          'label_suffix' => '',
1405
          'element_glue' => ', ',
1406
          'element_set_pre' => '(',
1407
          'element_set_post' => ')'
1408
        ),
1409
        // level 1
1410
        array(
1411
          'label_suffix' => '',
1412
          'element_glue' => '; ',
1413
          'element_set_pre' => '',
1414
          'element_set_post' => ''
1415
        ),
1416
        // level 0
1417
        array(
1418
          'label_suffix' => ':',
1419
          'element_glue' => ' ',
1420
          'element_set_pre' => '',
1421
          'element_set_post' => ''
1422
        ),
1423
      );
1424
    }
1425

    
1426
    $render_array = array();
1427

    
1428
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1429
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1430

    
1431
    // Returning NULL if there are no description elements.
1432
    if ($distribution_tree == null) {
1433
      return $render_array;
1434
    }
1435
    // for now we are not using a render array internally to avoid performance problems
1436
    $markup = '';
1437
    if (isset($distribution_tree->rootElement->children)) {
1438
      $tree_nodes = $distribution_tree->rootElement->children;
1439
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1440
    }
1441

    
1442
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1443
      $markup,
1444
      0,
1445
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1446
      '</div>'
1447
    );
1448

    
1449
    return $render_array;
1450
  }
1451

    
1452
  /**
1453
   * this function should produce markup as the compose_description_elements_distribution()
1454
   * function.
1455
   *
1456
   * @see compose_description_elements_distribution()
1457
   *
1458
   * @param $distribution_tree
1459
   * @param $feature_block_settings
1460
   * @param $tree_nodes
1461
   * @param $markup
1462
   * @param $hierarchy_style
1463
   */
1464
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1465

    
1466
    $level_index++;
1467
    static $enclosingTag = "span";
1468

    
1469
    $level_style = array_pop($hierarchy_style);
1470
    if(count($hierarchy_style) == 0){
1471
      // lowest defined level style will be reused for all following levels
1472
      $hierarchy_style[] = $level_style;
1473
    }
1474

    
1475
    $node_index = -1;
1476
    $per_node_markup = array();
1477
    foreach ($tree_nodes as $node){
1478

    
1479
      $per_node_markup[++$node_index] = '';
1480

    
1481
      $label = $node->nodeId->representation_L10n;
1482

    
1483
      $distributions = $node->data;
1484
      $distribution_uuids = array();
1485
      $distribution_aggregate = NULL;
1486
        foreach($distributions as $distribution){
1487

    
1488
          $distribution_uuids[] = $distribution->uuid;
1489

    
1490
          // if there is more than one distribution we aggregate the sources and
1491
          // annotations into a synthetic distribution so that the footnote keys
1492
          // can be rendered consistently
1493
          if(!$distribution_aggregate) {
1494
            $distribution_aggregate = $distribution;
1495
            if(!isset($distribution_aggregate->sources[0])){
1496
              $distribution_aggregate->sources = array();
1497
            }
1498
            if(!isset($distribution_aggregate->annotations[0])){
1499
              $distribution_aggregate->annotations = array();
1500
            }
1501
          } else {
1502
            if(isset($distribution->sources[0])) {
1503
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1504
                $distribution->sources);
1505
            }
1506
            if(isset($distribution->annotations[0])) {
1507
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1508
                $distribution->annotations);
1509
            }
1510
          }
1511
        }
1512

    
1513
      $status_label= '';
1514
      $status_markup = '';
1515
      $annotations_and_sources =  null;
1516
      if($distribution_aggregate) {
1517
        $annotations_and_sources = handle_annotations_and_sources(
1518
          $distribution_aggregate,
1519
          $feature_block_settings,
1520
          $label,
1521
          UUID_DISTRIBUTION
1522
        );
1523

    
1524
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1525
      }
1526

    
1527
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1528
        . join(' descriptionElement-', $distribution_uuids)
1529
        . ' level_index_' . $level_index
1530
        . ' " title="' . $status_label . '">'
1531
        . '<span class="area_label">' . $label
1532
        . $level_style['label_suffix'] . ' </span>'
1533
        .  $status_markup
1534
      ;
1535

    
1536
      if(isset($annotations_and_sources)){
1537
        if(!empty($annotations_and_sources['source_references'])){
1538
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1539
        }
1540
        if($annotations_and_sources['foot_note_keys']) {
1541
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1542
        }
1543
      }
1544

    
1545
      if(isset($node->children[0])){
1546
        _compose_distribution_hierarchy(
1547
          $node->children,
1548
          $feature_block_settings,
1549
          $per_node_markup[$node_index],
1550
          $hierarchy_style,
1551
          $level_index
1552
        );
1553
      }
1554

    
1555
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1556
    }
1557
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1558
  }
1559

    
1560

    
(2-2/8)