Project

General

Profile

Download (56.7 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_cdm_common_names($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_cdm_descriptionElements($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_cdm_descriptionElements() 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_cdm_descriptionElementTextData()
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
   * @param $taxon
668
   * @param $descriptionElements
669
   *   an associative array with two elements:
670
   *   - '#type': must be 'DTO'
671
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
672
   * @param $feature
673
   *
674
   * @return array
675
   *  A drupal render array
676
   *
677
   * @ingroup compose
678
   */
679
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
680
    $text_data_glue = '';
681
    $text_data_sortOutArray = FALSE;
682
    $text_data_enclosingTag = 'ul';
683
    $text_data_out_array = array();
684

    
685
    $distributionElements = NULL;
686
    $distribution_info_dto = NULL;
687
    $distribution_sortOutArray = FALSE;
688

    
689
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
690

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

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

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

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

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

    
731

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

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

    
750
    $dto_out_array = array();
751

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

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

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

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

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

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

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

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

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

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

    
847
    return $block;
848
  }
849

    
850

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

    
874
    $footnote_list_key_suggestion = $feature_uuid;
875

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

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

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

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

    
904
    $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element_text, $footnote_list_key_suggestion);
905

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

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

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

    
920
    return $render_array;
921
  }
922

    
923

    
924

    
925
  /**
926
   * Returns HTML for the texts in a description $elements.
927
   *
928
   * Joins the texts in $elements and encloses with a HTML tag.
929
   *
930
   * @param  $elements
931
   * @param  feature:
932
   *  The feature to which the elements given in $elements are belonging to.
933
   * @param  glue:
934
   *  Defaults to empty string.
935
   * @param $sort
936
   *   Boolean Whether to sort the $elements alphabetically, default is FALSE
937
   * @param  $enclosing_tag
938
   *
939
   * @ingroup compose
940
   */
941
  function compose_cdm_feature_block_elements($elements, $feature, $glue = '', $sort = FALSE, $enclosing_tag = 'ul') {
942

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

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

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

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

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

    
962

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

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

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

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

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

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

    
1026
    return $name_in_source_render_array;
1027
  }
1028

    
1029
  /**
1030
   * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1031
   *
1032
   * @parameter $elements
1033
   *  an array of CDM DescriptionElements either of type CommonName or TextData
1034
   * @parameter $feature
1035
   *  the common feature of all $elements, must be CommonName
1036
   *
1037
   * @return
1038
   *   A drupal render array
1039
   *
1040
   * @ingroup compose
1041
   */
1042
  function compose_cdm_common_names($elements, $feature, $weight = FALSE) {
1043

    
1044
    $common_name_out = '';
1045
    $common_name_feature_elements = array();
1046
    $textData_commonNames = array();
1047

    
1048
    $footnote_key_suggestion = 'common-names-feature-block';
1049

    
1050
    $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1051

    
1052
    $element_tag_name = cdm_feature_block_element_tag_name($feature_block_settings);
1053

    
1054
    if (is_array($elements)) {
1055
      foreach ($elements as $element) {
1056

    
1057
        if ($element->class == 'CommonTaxonName') {
1058

    
1059
          // common name without a language or area, should not happen but is possible
1060
          $language_area_key = '';
1061
          if (isset($element->language->representation_L10n)) {
1062
            $language_area_key .= '<b>' . $element->language->representation_L10n . '</b>';
1063
          }
1064
          if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1065
            $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1066
          }
1067

    
1068
          if(isset($common_names[$language_area_key][$element->name])) {
1069
            // same name already exists for language and areae combination, se we merge the description elements
1070
            cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1071
          } else{
1072
            // otherwise add as new entry
1073
            $common_names[$language_area_key][$element->name] = $element;
1074
          }
1075

    
1076
        }
1077
        elseif ($element->class == 'TextData') {
1078
          $textData_commonNames[] = $element;
1079
        }
1080
      }
1081
    }
1082
    // Handling common names.
1083
    if (isset($common_names) && count($common_names) > 0) {
1084
      // Sorting the array based on the key (language, + area if set).
1085
      // Comment @WA there are common names without a language, so this sorting
1086
      // can give strange results.
1087
      ksort($common_names);
1088

    
1089
      // loop over set of elements per language area
1090
      foreach ($common_names as $language_area_key => $elements) {
1091
        ksort($elements); // sort names alphabetically
1092
        $per_language_area_out = array();
1093
        // loop over set of individual elements
1094
        foreach ($elements as $element) {
1095
          if ($element->name) {
1096
            $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element->name, $footnote_key_suggestion);
1097
            $source_references_markup = '';
1098
            if(!empty($annotations_and_sources['source_references'])){
1099
              $source_references_markup = ' ' . join(', ', $annotations_and_sources['source_references']);
1100
            }
1101
            $per_language_area_out[] = '<' . $element_tag_name. ' class="' . html_class_attribute_ref($element) . '">'
1102
              . $element->name . $source_references_markup . $annotations_and_sources['foot_note_keys'] . '</' . $element_tag_name. '>';
1103
          }
1104
        } // End of loop over set of individual elements
1105
        $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1106
      } // End of loop over set of elements per language area
1107

    
1108

    
1109
      $common_name_feature_elements_render_array = compose_cdm_feature_block_elements(
1110
        $common_name_feature_elements,
1111
        $feature,
1112
        '; ',
1113
        FALSE,
1114
        $feature_block_settings['as_list']
1115
      );
1116
      $common_name_out .= $common_name_feature_elements_render_array['#markup'];
1117

    
1118
    }
1119

    
1120
    // Handling commons names as text data.
1121
    $text_data_out = array();
1122

    
1123
    foreach ($textData_commonNames as $text_data_element) {
1124
      /* footnotes are not handled correctly in compose_cdm_descriptionElementTextData,
1125
         need to set 'common-names-feature-block' as $footnote_key_suggestion */
1126
      RenderHints::setFootnoteListKey($footnote_key_suggestion);
1127
      $text_data_render_array = compose_cdm_descriptionElementTextData($text_data_element, TRUE, $text_data_element->feature->uuid);
1128
      $text_data_out[] = drupal_render($text_data_render_array);
1129
    }
1130

    
1131
    $common_name_out_text_data = compose_cdm_feature_block_elements(
1132
      $text_data_out,
1133
      $feature
1134
    );
1135

    
1136
    $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1137
    $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1138
    $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1139

    
1140
    return  markup_to_render_array(
1141
      '<div class="common_names_as_common_names">' . $common_name_out . '</div>'
1142
      .'<div class="common_names_as_text_data">' . $common_name_out_text_data['#markup'] . '</div>'
1143
      .$footnotes,
1144
      $weight
1145
    );
1146
  }
1147

    
1148
  /**
1149
   * Return HTML for a list of description elements.
1150
   *
1151
   * Usually these are of a specific feature type.
1152
   *
1153
   * @param $descriptionElements
1154
   *   array of descriptionElements which belong to the same feature.
1155
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1156
   *   calling the function _mergeFeatureTreeDescriptions().
1157
   *   @see _mergeFeatureTreeDescriptions()
1158
   *
1159
   * @param  $feature_uuid
1160
   *
1161
   * @return
1162
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1163
   *    Footnote key or anchors are not considered to be textual content.
1164
   *
1165
   * @ingroup compose
1166
   */
1167
  function compose_cdm_descriptionElements($descriptionElements, $feature) {
1168

    
1169
    $render_array = array();
1170
    $elements_out_array = array();
1171
    $distribution_tree = null;
1172

    
1173
    /*
1174
     * $feature_block_has_content will be set true if at least one of the
1175
     * $descriptionElements contains some text which makes up some content
1176
     * for the feature block. Footnote keys are not considered
1177
     * to be content in this sense.
1178
     */
1179
    $feature_block_has_content = false;
1180

    
1181
    RenderHints::pushToRenderStack($feature->uuid);
1182

    
1183
    if (is_array($descriptionElements)) {
1184
      // --- normal description element arrays
1185
      foreach ($descriptionElements as $descriptionElement) {
1186

    
1187
        // --- IMAGE_SOURCES --- //
1188
        if ($descriptionElement->feature->uuid == UUID_IMAGE_SOURCES) {
1189
          $image_sources[] = $descriptionElement;
1190
        }
1191
        // --- USE TEXTDATA --- //
1192
        elseif ($descriptionElement->feature->uuid == UUID_USE) {
1193
          // Do nothing to avoid rendering.
1194
        } else {
1195
          /* decide based on the description element class
1196
           *
1197
           * Features handled here:
1198
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1199
           *
1200
           *
1201
           * TODO provide api_hook as extension point for this?
1202
           */
1203
          $feature_block_settings = get_feature_block_settings($descriptionElement->feature->uuid);
1204
          $asListElement  = $feature_block_settings['as_list'] == 'ul';
1205
          switch ($descriptionElement->class) {
1206
            case 'TextData':
1207
              $text_data_render_array = compose_cdm_descriptionElementTextData($descriptionElement, $asListElement, $descriptionElement->feature->uuid);
1208
              $feature_block_has_content = $feature_block_has_content || !empty($text_data_render_array['#value']);
1209
              $elements_out_array[] = drupal_render($text_data_render_array);
1210
              break;
1211
            case 'CategoricalData':
1212
              $feature_block_has_content = true;
1213
              $elements_out_array[] = theme('cdm_descriptionElement_CategoricalData', array('element' => $descriptionElement));
1214
              break;
1215
            case 'QuantitativeData':
1216
              $feature_block_has_content = true;
1217
              $elements_out_array[] = theme('cdm_descriptionElement_QuantitativeData', array('element' => $descriptionElement));
1218
              break;
1219
            case 'IndividualsAssociation':
1220
              $feature_block_has_content = true;
1221
              $elements_out_array[] = theme('cdm_descriptionElement_IndividualsAssociation', array('element' => $descriptionElement));
1222
              break;
1223
            case 'TaxonInteraction':
1224
              $feature_block_has_content = true;
1225
              $elements_out_array[] = theme('cdm_descriptionElement_TaxonInteraction', array('element' => $descriptionElement));
1226
              break;
1227
            case 'Uses':
1228
              /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1229
              break;
1230
            default:
1231
              $feature_block_has_content = true;
1232
              $elements_out_array[] = '<li>No method for rendering unknown description class: ' . $descriptionElement->class . '</li>';
1233
          }
1234
        }
1235
      } // --- END loop over normal description element arrays
1236

    
1237
      // If feature = CITATION sort the list of sources.
1238
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1239
      if ($descriptionElement->feature->uuid == UUID_CITATION) {
1240
        sort($elements_out_array);
1241
      }
1242

    
1243
      if (isset($image_sources)) {
1244
        $elements_out_array[] = theme('cdm_description_element_image_source', array('image_sources' => $image_sources, 'asListElement' => TRUE));
1245
        $feature_block_has_content = true;
1246
      }
1247
    } // END normal description element arrays
1248

    
1249
    if($feature_block_has_content){
1250
      $render_array = compose_cdm_feature_block_elements(
1251
        $elements_out_array,
1252
        $feature
1253
      );
1254
    }
1255

    
1256
    RenderHints::popFromRenderStack();
1257
    return $render_array;
1258
  }
1259

    
1260

    
1261
  /**
1262
   * Composes the render array for a CDM Distribution element
1263
   *
1264
   * @param $descriptionElements
1265
   *   The CDM Distribution element
1266
   * @param $enclosingTag
1267
   *   The html tag to be use for the enclosing element
1268
   *
1269
   * @return array
1270
   *   A Drupal render array
1271
   *
1272
   * @ingroup compose
1273
   */
1274
  function compose_cdm_descriptionElement_Distribution($descriptionElements, $enclosingTag = "span"){
1275

    
1276
    $out = '';
1277
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1278
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1279

    
1280
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1281

    
1282
    foreach ($descriptionElements as $descriptionElement) {
1283
      $annotations_and_sources = handle_annotations_and_sources(
1284
        $descriptionElement,
1285
        $feature_block_settings,
1286
        $descriptionElement->area->representation_L10n,
1287
        UUID_DISTRIBUTION
1288
      );
1289

    
1290

    
1291
      list($status_label, $status_markup) = distribution_status_label_and_markup($descriptionElement);
1292

    
1293
      $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $descriptionElement->uuid
1294
        . ' " title="' . $status_label. '">'
1295
        . $descriptionElement->area->representation_L10n
1296
        . $status_markup;
1297
      if(!empty($annotations_and_sources['source_references'])){
1298
        $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1299
      }
1300
      $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1301
    }
1302

    
1303
    RenderHints::popFromRenderStack();
1304
    return markup_to_render_array($out);
1305
  }
1306

    
1307
  /**
1308
   * @param $descriptionElement
1309
   * @return array
1310
   */
1311
  function distribution_status_label_and_markup($descriptionElement) {
1312
    $status_markup = '';
1313
    $status_label = '';
1314

    
1315
    if (isset($descriptionElement->status)) {
1316
      $status_label = $descriptionElement->status->representation_L10n;
1317
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1318
        . $status_label . ' </span>';
1319

    
1320
    };
1321
    return array($status_label, $status_markup);
1322
  }
1323

    
1324

    
1325
  /**
1326
   * Provides the merged feature tree for a taxon profile page.
1327
   *
1328
   * The merging of the profile feature tree is actully done in
1329
   * _mergeFeatureTreeDescriptions(). See this method  for details
1330
   * on the structure of the merged tree.
1331
   *
1332
   * This method provides t hook which can be used to modify the
1333
   * merged feature tree after it has been created, see
1334
   * hook_merged_taxon_feature_tree_alter()
1335
   *
1336
   * @param $taxon
1337
   *   A CDM Taxon instance
1338
   *
1339
   * @return object
1340
   *  The merged feature tree
1341
   *
1342
   */
1343
  function merged_taxon_feature_tree($taxon) {
1344

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

    
1348

    
1349
    // 2. find the distribution feature node
1350
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1351

    
1352
    if ($distribution_node) {
1353
      // 3. get the distributionInfoDTO
1354
      $query_parameters = cdm_distribution_filter_query();
1355
      $query_parameters['part'] = array('mapUriParams');
1356
      if(variable_get(DISTRIBUTION_CONDENSED)){
1357
        $query_parameters['part'][] = 'condensedDistribution';
1358
      }
1359
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1360
        $query_parameters['part'][] = 'tree';
1361
      }
1362
      else {
1363
        $query_parameters['part'][] = 'elements';
1364
      }
1365
      $query_parameters['omitLevels'] = array();
1366
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1367
        if(is_uuid($uuid)){
1368
          $query_parameters['omitLevels'][] = $uuid;
1369
        }
1370
      }
1371
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1372
      if ($customStatusColorsJson) {
1373
        $query_parameters['statusColors'] = $customStatusColorsJson;
1374
      }
1375

    
1376
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1377
      // 4. get distribution TextData is there are any
1378
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1379
        array(
1380
          'taxon' => $taxon->uuid,
1381
          'type' => 'TextData',
1382
          'features' => UUID_DISTRIBUTION
1383
        )
1384
      );
1385

    
1386
      // 5. put all distribution data into the distribution feature node
1387
      if ($distribution_text_data //if text data exists
1388
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1389
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1390
      ) { // OR if DTO has distribution elements
1391
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1392
        if ($distribution_text_data) {
1393
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1394
        }
1395
        if ($distribution_info_dto) {
1396
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1397
        }
1398
      }
1399
    }
1400

    
1401
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1402
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1403

    
1404
    return $merged_tree;
1405
  }
1406

    
1407

    
1408
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1409

    
1410
    static $hierarchy_style;
1411
    // TODO expose $hierarchy_style to administration of provide a hook
1412
    if( !isset($hierarchy_style)){
1413
      $hierarchy_style = array(
1414
        // level 2
1415
        array(
1416
          'label_suffix' => '',
1417
          'element_glue' => ', ',
1418
          'element_set_pre' => '(',
1419
          'element_set_post' => ')'
1420
        ),
1421
        // level 1
1422
        array(
1423
          'label_suffix' => '',
1424
          'element_glue' => '; ',
1425
          'element_set_pre' => '',
1426
          'element_set_post' => ''
1427
        ),
1428
        // level 0
1429
        array(
1430
          'label_suffix' => ':',
1431
          'element_glue' => ' ',
1432
          'element_set_pre' => '',
1433
          'element_set_post' => ''
1434
        ),
1435
      );
1436
    }
1437

    
1438
    $render_array = array();
1439

    
1440
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1441
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1442

    
1443
    // Returning NULL if there are no description elements.
1444
    if ($distribution_tree == null) {
1445
      return $render_array;
1446
    }
1447
    // for now we are not using a render array internally to avoid performance problems
1448
    $markup = '';
1449
    if (isset($distribution_tree->rootElement->children)) {
1450
      $tree_nodes = $distribution_tree->rootElement->children;
1451
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1452
    }
1453

    
1454
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1455
      $markup,
1456
      0,
1457
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1458
      '</div>'
1459
    );
1460

    
1461
    return $render_array;
1462
  }
1463

    
1464
  /**
1465
   * this function should produce markup as the compose_cdm_descriptionElement_Distribution()
1466
   * function.
1467
   *
1468
   * @see compose_cdm_descriptionElement_Distribution()
1469
   *
1470
   * @param $distribution_tree
1471
   * @param $feature_block_settings
1472
   * @param $tree_nodes
1473
   * @param $markup
1474
   * @param $hierarchy_style
1475
   */
1476
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1477

    
1478
    $level_index++;
1479
    static $enclosingTag = "span";
1480

    
1481
    $level_style = array_pop($hierarchy_style);
1482
    if(count($hierarchy_style) == 0){
1483
      // lowest defined level style will be reused for all following levels
1484
      $hierarchy_style[] = $level_style;
1485
    }
1486

    
1487
    $node_index = -1;
1488
    $per_node_markup = array();
1489
    foreach ($tree_nodes as $node){
1490

    
1491
      $per_node_markup[++$node_index] = '';
1492

    
1493
      $label = $node->nodeId->representation_L10n;
1494

    
1495
      $distributions = $node->data;
1496
      $distribution_uuids = array();
1497
      $distribution_aggregate = NULL;
1498
        foreach($distributions as $distribution){
1499

    
1500
          $distribution_uuids[] = $distribution->uuid;
1501

    
1502
          // if there is more than one distribution we aggregate the sources and
1503
          // annotations into a synthetic distribution so that the footnote keys
1504
          // can be rendered consistently
1505
          if(!$distribution_aggregate) {
1506
            $distribution_aggregate = $distribution;
1507
            if(!isset($distribution_aggregate->sources[0])){
1508
              $distribution_aggregate->sources = array();
1509
            }
1510
            if(!isset($distribution_aggregate->annotations[0])){
1511
              $distribution_aggregate->annotations = array();
1512
            }
1513
          } else {
1514
            if(isset($distribution->sources[0])) {
1515
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1516
                $distribution->sources);
1517
            }
1518
            if(isset($distribution->annotations[0])) {
1519
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1520
                $distribution->annotations);
1521
            }
1522
          }
1523
        }
1524

    
1525
      $status_label= '';
1526
      $status_markup = '';
1527
      $annotations_and_sources =  null;
1528
      if($distribution_aggregate) {
1529
        $annotations_and_sources = handle_annotations_and_sources(
1530
          $distribution_aggregate,
1531
          $feature_block_settings,
1532
          $label,
1533
          UUID_DISTRIBUTION
1534
        );
1535

    
1536
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1537
      }
1538

    
1539
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1540
        . join(' descriptionElement-', $distribution_uuids)
1541
        . ' level_index_' . $level_index
1542
        . ' " title="' . $status_label . '">'
1543
        . '<span class="area_label">' . $label
1544
        . $level_style['label_suffix'] . ' </span>'
1545
        .  $status_markup
1546
      ;
1547

    
1548
      if(isset($annotations_and_sources)){
1549
        if(!empty($annotations_and_sources['source_references'])){
1550
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1551
        }
1552
        if($annotations_and_sources['foot_note_keys']) {
1553
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1554
        }
1555
      }
1556

    
1557
      if(isset($node->children[0])){
1558
        _compose_distribution_hierarchy(
1559
          $node->children,
1560
          $feature_block_settings,
1561
          $per_node_markup[$node_index],
1562
          $hierarchy_style,
1563
          $level_index
1564
        );
1565
      }
1566

    
1567
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1568
    }
1569
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1570
  }
1571

    
1572

    
(2-2/8)