Project

General

Profile

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

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

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

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

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

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

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

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

    
91
  return $query;
92
}
93

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

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

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

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

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

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

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

    
157
}
158

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

    
170
  return $toc_list_items;
171
}
172

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

    
200

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

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

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

    
236
  }
237

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

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

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

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

    
268

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

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

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

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

    
320

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

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

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

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

    
357

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

    
370
}
371

    
372

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

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

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

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

    
398
  );
399

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

    
402
  // handle the special case were the TextData is used as container for original source with name
403
  // used in source information without any text stored in it.
404
  $names_used_in_source_markup = '';
405
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
406
    // $element_text ==  NULL  usually occurs only in the case of CITATIONS!!!
407
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
408
  }
409

    
410
  $source_references_markup = '';
411
  if (!empty($annotations_and_sources['source_references'])) {
412
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
413
  }
414

    
415
  $render_array['#value'] = $names_used_in_source_markup . $element_markup . $source_references_markup;
416
  $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
417

    
418
  return $render_array;
419
}
420

    
421

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

    
445
    usort($element->sources, 'compare_original_sources');
446

    
447
    if ($feature_block_settings['sources_as_content'] == 1) {
448
      foreach ($element->sources as $source) {
449

    
450
        $referenceCitation = theme('cdm_OriginalSource',
451
          array(
452
            'source' => $source,
453
            'doLink' => $feature_block_settings['link_to_reference'] == 1,
454
            'do_link_to_name_used_in_source' => $feature_block_settings['link_to_name_used_in_source'] == 1,
455
          )
456
        );
457

    
458
        if ($referenceCitation) {
459
          if (empty($element_text)) {
460
            $annotations_and_sources['source_references'][] = $referenceCitation;
461
          }
462
          else {
463
            $annotations_and_sources['source_references'][] = ' (' . $referenceCitation . ')';
464
          }
465
        }
466

    
467
        $name_in_source_render_array = compose_name_in_source(
468
          $source,
469
          $feature_block_settings['link_to_name_used_in_source'] == 1
470
        );
471

    
472
        if(!empty($name_in_source_render_array)){
473
          $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
474
        }
475
      } // END of loop over sources
476

    
477
      // annotations footnotes separate.
478
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
479
        array(
480
          'cdmBase_list' => $element,
481
          'footnote_list_key' => $footnote_list_key_suggestion,
482
        )
483
      );
484

    
485
    } // END of references inline
486

    
487
    // put sources into bibliography if requested ...
488
    if ($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
489
      $annotations_and_sources['foot_note_keys'] = cdm_create_description_element_footnotes(
490
        $element, ',',
491
        $footnote_list_key_suggestion,
492
        $feature_block_settings['link_to_reference'] == 1,
493
        $feature_block_settings['link_to_name_used_in_source'] == 1
494
      );
495
    }
496

    
497
    return $annotations_and_sources;
498
  }
499

    
500

    
501
  /**
502
   *
503
   *
504
   * @return string
505
   *  the footnote_list_key
506
   */
507
  function original_source_footnote_list_key($key_suggestion = null) {
508
    if(!$key_suggestion){
509
      $key_suggestion = RenderHints::getFootnoteListKey();
510
    }
511
    $bibliography_settings = get_bibliography_settings();
512
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? 'BIBLIOGRAPHY' : 'BIBLIOGRAPHY-' . $key_suggestion;
513
    return $footnote_list_key;
514
  }
515

    
516
  /**
517
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
518
   *
519
   * @param $feature_block_settings
520
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
521
   */
522
  function cdm_feature_block_element_tag_name($feature_block_settings){
523
    switch ($feature_block_settings['as_list']){
524
      case 'ul':
525
      case 'ol':
526
        return 'li';
527
      case 'div':
528
        if(isset($feature_block_settings['element_tag'])){
529
          return $feature_block_settings['element_tag'];
530
        }
531
        return 'span';
532
      case 'dl':
533
        return 'dd';
534
      default:
535
        return 'div'; // should never happen, throw error instead?
536
    }
537
  }
538

    
539

    
540
/* ==================== COMPOSE FUNCTIONS =============== */
541

    
542
  /**
543
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
544
   *
545
   * The taxon profile consists of drupal block elements, one for the description elements
546
   * of a specific feature. The structure is defined by specific FeatureTree.
547
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
548
   *
549
   * The merged nodes can be obtained by making use of the
550
   * function cdm_ws_descriptions_by_featuretree().
551
   *
552
   * @see cdm_ws_descriptions_by_featuretree()
553
   *
554
   * @param $mergedFeatureNodes
555
   *
556
   * @param $taxon
557
   *
558
   * @return array
559
   *  A Drupal render array containing feature blocks and the table of content
560
   *
561
   * @ingroup compose
562
   */
563
  function compose_feature_blocks($mergedFeatureNodes, $taxon) {
564

    
565
    $block_list = array();
566

    
567
    RenderHints::pushToRenderStack('feature_nodes');
568

    
569
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
570

    
571
    // Create a drupal block for each feature
572
    foreach ($mergedFeatureNodes as $node) {
573

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

    
577
        $feature_name = cdm_term_representation($node->feature, 'Unnamed Feature');
578
        $feature_block_settings = get_feature_block_settings($node->feature->uuid);
579

    
580
        $block = feature_block($feature_name, $node->feature);
581
        $block->content = array();
582
        $block_content_is_empty = TRUE;
583
        $block_content_weight = 0;
584

    
585
        /*
586
         * Content/DISTRIBUTION.
587
         */
588

    
589
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
590
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
591
          $block_content_is_empty = FALSE;
592
        }
593
        /*
594
         * Content/COMMON_NAME.
595
         */
596
        else if ($node->feature->uuid == UUID_COMMON_NAME) {
597
          $common_names_render_array = compose_feature_block_items_feature_common_name($node->descriptionElements, $node->feature);
598
          $block->content[] = $common_names_render_array;
599
          $block_content_is_empty = FALSE;
600
        }
601

    
602
        else if ($node->feature->uuid == UUID_USE_RECORD) {
603
          $block_uses_content_html = theme('cdm_block_Uses', array('taxonUuid' => $taxon->uuid));
604
          $block->content[] = markup_to_render_array($block_uses_content_html);
605
          $block_content_is_empty = FALSE;
606
        }
607

    
608
        /*
609
         * Content/ALL OTHER FEATURES.
610
         */
611
        else {
612

    
613
          $media_list = array();
614
          $out_child_elements = '';
615

    
616
          if (isset($node->descriptionElements)) {
617
            $elements_render_array = compose_feature_block_items_generic($node->descriptionElements, $node->feature);
618
            $block_content_is_empty = empty($elements_render_array);
619
            $block->content[] = $elements_render_array;
620
          }
621

    
622
          // Content/ALL OTHER FEATURES/Subordinate Features
623
          // subordinate features are printed inline in one floating text,
624
          // it is expected hat subordinate features can "contain" TextData,
625
          // Qualitative- and Qualitative- DescriptioneElements
626
          if (isset($node->childNodes[0])) {
627

    
628
            // TODO support more than one level of children.
629
            // can this be solved by recursively calling this function?
630
            // @see http://dev.e-taxonomy.eu/trac/ticket/2393
631
            $text = '';
632
            foreach ($node->childNodes as $child) {
633

    
634
              if (isset($child->descriptionElements) && is_array($child->descriptionElements)) {
635
                foreach ($child->descriptionElements as $element) {
636

    
637
                  //TODO it would be better if we could use compose_feature_block_items_generic() directly instead of the below stuff
638

    
639
                  if (is_array($element->media)) {
640
                    // Append media of subordinate elements to list of main
641
                    // feature.
642
                    $media_list = array_merge($media_list, $element->media);
643
                  }
644

    
645
                  switch ($element->class) {
646
                    case 'TextData':
647
                      // FIXME use compose_description_element_text_data()
648
                      if(isset($element->multilanguageText_L10n->text)){
649
                        $out_child_elements = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
650
                      }
651
                      $out_child_elements = str_replace($child->feature->titleCache, '<em>' . $child->feature->representation_L10n . '</em>', $out_child_elements);
652
                      break;
653
                    case 'CategoricalData':
654
                      $out_child_elements  = '<em>' . $child->feature->representation_L10n . '</em> '
655
                        . compose_description_element_categorical_data($element, $feature_block_settings);
656
                      break;
657
                    case 'QuantitativeData':
658
                      $out_child_elements = '<em>' . $child->feature->representation_L10n . '</em> '
659
                        . compose_description_element_quantitative_data($element, $feature_block_settings);
660

    
661
                  }
662

    
663
                }
664
                $text .= " " . $out_child_elements;
665
                $out_child_elements = '';
666
              }
667
            }
668
            $block_content_is_empty = $block_content_is_empty && empty($text);
669
            $block->content[] = markup_to_render_array($text);
670
            $block_content_is_empty = $block_content_is_empty && empty($media_list);
671
          }
672

    
673
          $block->content[] = compose_feature_media_gallery($node, $media_list, $gallery_settings);
674
          /*
675
           * Footnotes for the feature block
676
           */
677
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $node->feature->uuid)));
678
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $node->feature->uuid)));
679
          $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $node->feature->uuid)));
680
        } // END all other features
681

    
682
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
683
        drupal_alter('cdm_feature_node_block_content', $block->content, $node->feature, $node->descriptionElements);
684

    
685
        if(!$block_content_is_empty){ // skip empty block content
686
          $block_list[] = $block;
687
          cdm_toc_list_add_item(cdm_term_representation($node->feature), $node->feature->uuid);
688
        } // END: skip empty block content
689
      } // END: skip empty or supressed features
690
    } // END: creating a block per feature
691

    
692
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
693

    
694
    RenderHints::popFromRenderStack();
695

    
696
    return _block_get_renderable_array($block_list);
697
  }
698

    
699
  /**
700
   * @param $node
701
   * @param $media_list
702
   * @param $gallery_settings
703
   * @return array
704
   */
705
  function compose_feature_media_gallery($node, $media_list, $gallery_settings) {
706

    
707
    if (isset($node->descriptionElements)) {
708
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
709
    }
710

    
711
    $captionElements = array('title', 'rights');
712

    
713
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
714
      $gallery = theme('cdm_media_gallerie', array(
715
        'mediaList' => $media_list,
716
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $node->feature->uuid,
717
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
718
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
719
        'captionElements' => $captionElements,
720
      ));
721
      return markup_to_render_array($gallery);
722
    }
723

    
724
    return markup_to_render_array('');
725
  }
726

    
727
  /**
728
   * Composes the distribution feature block for a taxon
729
   *
730
   * @param $taxon
731
   * @param $descriptionElements
732
   *   an associative array with two elements:
733
   *   - '#type': must be 'DTO'
734
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
735
   * @param $feature
736
   *
737
   * @return array
738
   *  A drupal render array
739
   *
740
   * @ingroup compose
741
   */
742
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
743
    $text_data_glue = '';
744
    $text_data_sortOutArray = FALSE;
745
    $text_data_enclosingTag = 'ul';
746
    $text_data_out_array = array();
747

    
748
    $distributionElements = NULL;
749
    $distribution_info_dto = NULL;
750
    $distribution_sortOutArray = FALSE;
751

    
752
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
753

    
754
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
755
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
756
      $distribution_glue = '';
757
      $distribution_enclosingTag = 'dl';
758
    } else {
759
      $distribution_glue = '';
760
      $distribution_enclosingTag = 'ul';
761
    }
762

    
763
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
764
      // skip the DISTRIBUTION section if there is no DTO type element
765
      return array(); // FIXME is it ok to return an empty array?
766
    }
767

    
768
    $block = feature_block(
769
      cdm_term_representation($feature, 'Unnamed Feature'),
770
      $feature
771
    );
772

    
773
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
774
    if (isset($descriptionElements['TextData'])) {
775
      // --- TextData
776
      foreach ($descriptionElements['TextData'] as $text_data_element) {
777
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
778
        $repr = drupal_render($text_data_render_array);
779

    
780
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
781
          $text_data_out_array[] = $repr;
782
          // TODO HINT: sorting in compose_feature_block_elements will
783
          // not work since this array contains html attributes with uuids
784
          // and what is about cases like the bibliography where
785
          // any content can be prefixed with some foot-note anchors?
786
          $text_data_sortOutArray = TRUE;
787
          $text_data_glue = '<br/> ';
788
          $text_data_enclosingTag = 'p';
789
        }
790
      }
791
    }
792

    
793

    
794
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
795
      $block->content[] = compose_feature_block_elements(
796
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
797
      );
798
    }
799

    
800
    // --- Distribution map
801
    $distribution_map_query_parameters = NULL;
802
    if (isset($descriptionElements['DistributionInfoDTO'])) {
803
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
804
    }
805
    $map_render_element = compose_distribution_map($taxon, $distribution_map_query_parameters);
806
    $block->content[] = $map_render_element;
807

    
808
    $dto_out_array = array();
809

    
810
    // --- Condensed Distribution
811
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
812
      $condensed_distribution_markup = '<p class="condensed_distribution">';
813

    
814
      $isFirst = true;
815
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
816
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
817
          if(!$isFirst){
818
            $condensed_distribution_markup .= ' ';
819
          }
820
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
821
          . $cdItem->areaStatusLabel . '</span>';
822
          $isFirst = false;
823
        }
824
      }
825

    
826
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
827
        if(!$isFirst){
828
          $condensed_distribution_markup .= ' ';
829
        }
830
        $isFirst = TRUE;
831
        $condensed_distribution_markup .= '[';
832
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
833
          if (!$isFirst) {
834
            $condensed_distribution_markup .= ' ';
835
          }
836
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
837
            . $cdItem->areaStatusLabel . '</span>';
838
          $isFirst = false;
839
        }
840
        $condensed_distribution_markup .= ']';
841
      }
842

    
843
      $condensed_distribution_markup .= '&nbsp;' . l(
844
          font_awesome_icon_markup(
845
            'fa-info-circle',
846
            array(
847
              'alt'=>'help',
848
              'class' => array('superscript')
849
            )
850
          ),
851
          'cdm_dataportal/help/condensed_distribution',
852
          array('html' => TRUE));
853
      $condensed_distribution_markup .= '</p>';
854
      $dto_out_array[] = $condensed_distribution_markup;
855
    }
856

    
857
    // --- tree or list
858
    if (isset($descriptionElements['DistributionInfoDTO'])) {
859
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
860

    
861
      // --- tree
862
      if (is_object($distribution_info_dto->tree)) {
863
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
864
        $dto_out_array[] = $distribution_tree_render_array;
865
      }
866

    
867
      // --- sorted element list
868
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
869
        foreach ($distribution_info_dto->elements as $descriptionElement) {
870
          if (is_object($descriptionElement->area)) {
871
            $sortKey = $descriptionElement->area->representation_L10n;
872
            $distributionElements[$sortKey] = $descriptionElement;
873
          }
874
        }
875
        ksort($distributionElements);
876
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
877
        $dto_out_array[] = $distribution_element_render_array;
878

    
879
      }
880
      //
881
      $block->content[] = compose_feature_block_elements(
882
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
883
      );
884
    }
885

    
886
    // --- TextData at the bottom
887
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
888
      $block->content[] = compose_feature_block_elements(
889
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
890
      );
891
    }
892

    
893
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
894
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
895
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
896

    
897
    return $block;
898
  }
899

    
900

    
901
  /**
902
   * Composes a drupal render array for single CDM TextData description element.
903
   *
904
   * @param $element
905
   *    The CDM TextData description element.
906
   *  @param $feature_uuid
907
   *
908
   * @return array
909
   *   A drupal render array with the following elements being used:
910
   *    - #tag: either 'div', 'li', ...
911
   *    ⁻ #attributes: class attributes
912
   *    - #value_prefix: (optionally) contains footnote anchors
913
   *    - #value: contains the textual content
914
   *    - #value_suffix: (optionally) contains footnote keys
915
   *
916
   * @ingroup compose
917
   */
918
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings) {
919

    
920
    $footnote_list_key_suggestion = $feature_uuid;
921

    
922
    /*
923
    // FIXME remove this hack ---------------------------
924
    $default_theme = variable_get('theme_default', NULL);
925
    if($default_theme == 'garland_cichorieae' || $default_theme == 'cyprus'
926
      || $default_theme == 'flore_afrique_centrale' || $default_theme == 'flora_malesiana' || $default_theme == 'flore_gabon' ){
927
      $asListElement = $feature_block_settings['as_list'] == 'ul';
928
    }
929
    // --------------------------------------------------
930
    */
931

    
932
    $element_markup = '';
933
    if (isset($element->multilanguageText_L10n->text)) {
934
      // TODO replacement of \n by <br> should be configurable
935
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
936
    }
937

    
938
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion);
939

    
940
    return $render_array;
941
  }
942

    
943

    
944
/**
945
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
946
 *
947
 * @param $element
948
 *  The CDM TaxonInteraction entity
949
 *
950
 * @return
951
 *  A drupal render array
952
 *
953
 * @ingroup compose
954
 */
955
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
956

    
957
  $out = '';
958
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
959

    
960
  if (isset($element->description_L10n)) {
961
    $out .=  ' ' . $element->description_L10n;
962
  }
963

    
964
  if(isset($element->taxon2)){
965
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
966
  }
967

    
968
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
969

    
970
  return $render_array;
971
}
972

    
973

    
974
/**
975
 * Renders a single instance of the type IndividualsAssociations.
976
 *
977
 * @param $element
978
 *   The CDM IndividualsAssociations entity.
979
 * @param $feature_block_settings
980
 *
981
 * @return array
982
 *   Drupal render array
983
 *
984
 * @ingroup compose
985
 */
986
function compose_description_element_individuals_association($element, $feature_block_settings) {
987

    
988
  $out = '';
989
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
990

    
991
  $render_array = compose_cdm_specimenOrObservation($element->associatedSpecimenOrObservation);
992

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

    
997
  $out .= drupal_render($render_array);
998

    
999
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1000

    
1001
  return $render_array;
1002
}
1003

    
1004
/**
1005
 * Renders a single instance of the type CategoricalData.
1006
 *
1007
 * @param $element
1008
 *  The CDM CategoricalData entity#
1009
 * @param $feature_block_settings
1010
 *
1011
 * @return string
1012
 *   a html representation of the given CategoricalData element
1013
 *
1014
 * @ingroup compose
1015
 */
1016
function compose_description_element_categorical_data($element, $feature_block_settings) {
1017

    
1018
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
1019

    
1020
  $state_data_strings = array();
1021
  if (isset($element->stateData)) {
1022
    foreach ($element->stateData as $state_data) {
1023

    
1024
      $state  = NULL;
1025

    
1026
      if (isset($state_data->state)) {
1027
        $state = cdm_term_representation($state_data->state);
1028
      }
1029

    
1030
      if (isset($state_data->modifyingText_L10n)) {
1031
        $state = ' ' . $state_data->modifyingText_L10n;
1032
      }
1033

    
1034
      $modifiers_strings = cdm_modifers_representations($state_data);
1035

    
1036
      $state_data_strings[] = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1037

    
1038
    }
1039
  }
1040

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

    
1043
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1044

    
1045
  return $render_array;
1046
}
1047

    
1048

    
1049
/**
1050
 * Theme function to render CDM DescriptionElements of the type QuantitativeData.
1051
 *
1052
 * The function renders the statisticalValues contained in the QuantitativeData
1053
 * entity according to the following scheme:
1054
 *
1055
 * (ExtremeMin)-Min-Average-Max-(ExtremeMax)
1056
 *
1057
 * All modifiers of these values are appended.
1058
 *
1059
 * If the QuantitativeData is containing more statisticalValues with further
1060
 * statisticalValue types, these additional measures will be appended to the
1061
 * above string separated by whitespace.
1062
 *
1063
 * Special cases;
1064
 * 1. Min==Max: this will be interpreted as Average
1065
 *
1066
 * @param array $variables
1067
 *   An associative array containing:
1068
 *    - element: the QuantitativeData element
1069
 *
1070
 * @return string
1071
 *   a html representation of the given QuantitativeData element
1072
 *
1073
 * @ingroup themeable
1074
 */
1075
function compose_description_element_quantitative_data($element, $feature_block_settings) {
1076
  /*
1077
   * - statisticalValues
1078
   *   - value
1079
   *   - modifiers
1080
   *   - type
1081
   * - unit->representation_L10n
1082
   * - modifyingText
1083
   * - modifiers
1084
   * - sources
1085
   */
1086

    
1087
  $out = '';
1088
  $type_representation = NULL;
1089
  $min_max = min_max_array();
1090

    
1091

    
1092
  $other_values = array();
1093

    
1094
  if (isset($element->statisticalValues)) {
1095
    $other_values_markup = array();
1096
    foreach ($element->statisticalValues as $statistical_val) {
1097

    
1098
      // compile the full value string which also may contain modifiers
1099
      if (isset($statistical_val->value)) {
1100
        $statistical_val->_value = $statistical_val->value;
1101
      }
1102
      $val_modifiers_strings = cdm_modifers_representations($statistical_val);
1103
      if ($val_modifiers_strings) {
1104
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1105
      }
1106

    
1107
      // either put into min max array or into $other_values
1108
      // for generic output to be appended to 'min-max' string
1109
      if (array_key_exists($statistical_val->type->titleCache, $min_max)) {
1110
        $min_max[$statistical_val->type->titleCache] = $statistical_val;
1111
      }
1112
      else {
1113
        $other_values[] = $statistical_val;
1114
      }
1115
    } // end of loop over statisticalValues
1116

    
1117
    // create markup
1118

    
1119
    $min_max_markup = min_max_markup($min_max);
1120

    
1121

    
1122
    foreach ($other_values as $statistical_val) {
1123
      $statistical_val_type_representation = NULL;
1124
      if (isset($statistical_val->type)) {
1125
        $statistical_val_type_representation = cdm_term_representation($statistical_val->type);
1126
        // $statistical_val->type->termType;
1127
        // $statistical_val->type->userFriendlyTypeName;
1128
      }
1129
      $value_markup = '<span class="' . html_class_attribute_ref($statistical_val) . ' ' . $statistical_val->type->termType . ' ">'
1130
        . $statistical_val->_value . '</span>';
1131
      $value_markup = $value_markup .
1132
        ($statistical_val_type_representation ? ' <span class="type">' . $statistical_val_type_representation . '</span>' : '');
1133
      $other_values_markup[] = $value_markup;
1134
    }
1135

    
1136

    
1137
    $out .= $min_max_markup . ' ' . implode($other_values_markup, ', ');
1138
  }
1139

    
1140
  if (isset($element->unit)) {
1141
    $out .= ' <span class="unit" title="'
1142
      . cdm_term_representation($element->unit) . '">'
1143
      . cdm_term_representation_abbreviated($element->unit)
1144
      . '</span>';
1145
  }
1146

    
1147
  // modifiers of the description element itself
1148
  $modifier_string = cdm_modifers_representations($element);
1149
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1150
  if (isset($element->modifyingText_L10n)) {
1151
    $out = $element->modifyingText_L10n . ' ' . $out;
1152
  }
1153

    
1154
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
1155

    
1156
  return $render_array;
1157
}
1158

    
1159

    
1160
/**
1161
 * Creates a render array for string representations of description elements for the given feature.
1162
 *
1163
 * @param array $elements
1164
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1165
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1166
 * @param  $feature :
1167
 *  The feature to which the elements given in $elements are belonging to.
1168
 * @param string $glue :
1169
 *  Defaults to empty string.
1170
 * @param bool $sort
1171
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1172
 *
1173
 * @return array|void
1174
 *
1175
 * @ingroup compose
1176
 */
1177
  function compose_feature_block_elements(array $elements, $feature, $glue = '', $sort = FALSE)
1178
  {
1179

    
1180
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1181
    $enclosing_tag = $feature_block_settings['as_list'];
1182

    
1183
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1184
      usort($elements, 'compare_description_element_render_arrays');
1185
    }
1186

    
1187
    $is_first = true;
1188
    foreach($elements as &$element_render_array){
1189
      if(!is_array($element_render_array)){
1190
        $element_render_array = markup_to_render_array($element_render_array);
1191
      }
1192
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1193

    
1194
      // add the glue!
1195
      if(!$is_first) {
1196
        if (isset($element_render_array['#value'])) {
1197
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1198
        } elseif (isset($element_render_array['#markup'])) {
1199
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1200
        }
1201
      }
1202
      $is_first = false;
1203
    }
1204

    
1205
    $render_array['elements']['children'] = $elements;
1206

    
1207
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1208
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1209

    
1210
    return $render_array;
1211
  }
1212

    
1213

    
1214
  /* compose nameInSource or originalNameString as markup
1215
   *
1216
   * @param $source
1217
   * @param $do_link_to_name_used_in_source
1218
   * @param $suppress_for_shown_taxon
1219
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1220
   *    for which the taxon page is being created, Defaults to TRUE
1221
   *
1222
   * @return array
1223
   *    A Drupal render array with an additional element, the render array is empty
1224
   *    if the source had no name in source information
1225
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1226
   *
1227
   * @ingroup compose
1228
   */
1229
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1230

    
1231
    $plaintext = NULL;
1232
    $markup = NULL;
1233
    $name_in_source_render_array = array();
1234

    
1235
    static $taxon_page_accepted_name = '';
1236
    if($suppress_for_shown_taxon && arg(1) == 'taxon' && empty($taxon_page_accepted_name)){
1237

    
1238
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, arg(2));
1239
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1240
    }
1241

    
1242
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1243
      // it is a DescriptionElementSource !
1244
      $plaintext = $source->nameUsedInSource->titleCache;
1245
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1246
        return $name_in_source_render_array; // SKIP this name
1247
      }
1248
      $markup = render_taxon_or_name($source->nameUsedInSource);
1249
      if ($do_link_to_name_used_in_source) {
1250
        $markup = l(
1251
          $markup,
1252
          path_to_name($source->nameUsedInSource->uuid),
1253
          array(
1254
            'attributes' => array(),
1255
            'absolute' => TRUE,
1256
            'html' => TRUE,
1257
          ));
1258
      }
1259
    }
1260
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1261
      // the name used in source can not be expressed as valid taxon name,
1262
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1263
      // field
1264
      // using the originalNameString as key to avoid duplicate entries
1265
      $plaintext = $source->originalNameString;
1266
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1267
        return $name_in_source_render_array; // SKIP this name
1268
      }
1269
      $markup = $source->originalNameString;
1270
    }
1271

    
1272
    if ($plaintext) { // checks if we have any content
1273
      $name_in_source_render_array = markup_to_render_array($markup);
1274
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1275
    }
1276

    
1277
    return $name_in_source_render_array;
1278
  }
1279

    
1280

    
1281

    
1282
  /**
1283
   * Return HTML for a list of description elements.
1284
   *
1285
   * Usually these are of a specific feature type.
1286
   *
1287
   * @param $descriptionElements
1288
   *   array of descriptionElements which belong to the same feature.
1289
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1290
   *   calling the function _mergeFeatureTreeDescriptions().
1291
   *   @see _mergeFeatureTreeDescriptions()
1292
   *
1293
   * @param  $feature_uuid
1294
   *
1295
   * @return
1296
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1297
   *    Footnote key or anchors are not considered to be textual content.
1298
   *
1299
   * @ingroup compose
1300
   */
1301
  function compose_feature_block_items_generic($descriptionElements, $feature) {
1302

    
1303
    $render_array = array();
1304
    $elements_out_array = array();
1305
    $distribution_tree = null;
1306

    
1307
    /*
1308
     * $feature_block_has_content will be set true if at least one of the
1309
     * $descriptionElements contains some text which makes up some content
1310
     * for the feature block. Footnote keys are not considered
1311
     * to be content in this sense.
1312
     */
1313
    $feature_block_has_content = false;
1314

    
1315
    RenderHints::pushToRenderStack($feature->uuid);
1316

    
1317
    if (is_array($descriptionElements)) {
1318
      foreach ($descriptionElements as $descriptionElement) {
1319
          /* decide based on the description element class
1320
           *
1321
           * Features handled here:
1322
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1323
           *
1324
           * TODO provide api_hook as extension point for this?
1325
           */
1326
        $feature_block_settings = get_feature_block_settings($descriptionElement->feature->uuid);
1327
        switch ($descriptionElement->class) {
1328
          case 'TextData':
1329
            $elements_out_array[] = compose_description_element_text_data($descriptionElement, $descriptionElement->feature->uuid, $feature_block_settings);
1330
            break;
1331
          case 'CategoricalData':
1332
            $elements_out_array[] = compose_description_element_categorical_data($descriptionElement, $feature_block_settings);
1333
            break;
1334
          case 'QuantitativeData':
1335
            $elements_out_array[] = compose_description_element_quantitative_data($descriptionElement, $feature_block_settings);
1336
            break;
1337
          case 'IndividualsAssociation':
1338
            $elements_out_array[] = compose_description_element_individuals_association($descriptionElement, $feature_block_settings);
1339
            break;
1340
          case 'TaxonInteraction':
1341
            $elements_out_array[] = compose_description_element_taxon_interaction($descriptionElement, $feature_block_settings);
1342
            break;
1343
          case 'Uses':
1344
            /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1345
            break;
1346
          default:
1347
            $feature_block_has_content = true;
1348
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $descriptionElement->class . '</li>');
1349
        }
1350
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1351
        // considering not empty as long as the last item added is a render array
1352
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1353
      }
1354

    
1355
      // If feature = CITATION sort the list of sources.
1356
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1357
      if (isset($descriptionElement) && $descriptionElement->feature->uuid == UUID_CITATION) {
1358
        sort($elements_out_array);
1359
      }
1360
    }
1361

    
1362
    if($feature_block_has_content){
1363
      $render_array = compose_feature_block_elements(
1364
        $elements_out_array, $feature
1365
      );
1366
    }
1367

    
1368
    RenderHints::popFromRenderStack();
1369
    return $render_array;
1370
  }
1371

    
1372
/**
1373
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1374
 *
1375
 * @parameter $elements
1376
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1377
 * @parameter $feature
1378
 *  the common feature of all $elements, must be CommonName
1379
 *
1380
 * @return
1381
 *   A drupal render array
1382
 *
1383
 * @ingroup compose
1384
 */
1385
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1386

    
1387
  $common_name_out = '';
1388
  $common_name_feature_elements = array();
1389
  $textData_commonNames = array();
1390

    
1391
  $footnote_key_suggestion = 'common-names-feature-block';
1392

    
1393
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1394

    
1395
  $element_tag_name = cdm_feature_block_element_tag_name($feature_block_settings);
1396

    
1397
  if (is_array($elements)) {
1398
    foreach ($elements as $element) {
1399

    
1400
      if ($element->class == 'CommonTaxonName') {
1401

    
1402
        // common name without a language or area, should not happen but is possible
1403
        $language_area_key = '';
1404
        if (isset($element->language->representation_L10n)) {
1405
          $language_area_key .= '<b>' . $element->language->representation_L10n . '</b>';
1406
        }
1407
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1408
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1409
        }
1410

    
1411
        if(isset($common_names[$language_area_key][$element->name])) {
1412
          // same name already exists for language and area combination, se we merge the description elements
1413
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1414
        } else{
1415
          // otherwise add as new entry
1416
          $common_names[$language_area_key][$element->name] = $element;
1417
        }
1418

    
1419
      }
1420
      elseif ($element->class == 'TextData') {
1421
        $textData_commonNames[] = $element;
1422
      }
1423
    }
1424
  }
1425
  // Handling common names.
1426
  if (isset($common_names) && count($common_names) > 0) {
1427
    // Sorting the array based on the key (language, + area if set).
1428
    // Comment @WA there are common names without a language, so this sorting
1429
    // can give strange results.
1430
    ksort($common_names);
1431

    
1432
    // loop over set of elements per language area
1433
    foreach ($common_names as $language_area_key => $elements) {
1434
      ksort($elements); // sort names alphabetically
1435
      $per_language_area_out = array();
1436
      // loop over set of individual elements
1437
      foreach ($elements as $element) {
1438
        if ($element->name) {
1439
          $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element->name, $footnote_key_suggestion);
1440
          $source_references_markup = '';
1441
          if(!empty($annotations_and_sources['source_references'])){
1442
            $source_references_markup = ' ' . join(', ', $annotations_and_sources['source_references']);
1443
          }
1444
          $per_language_area_out[] = '<' . $element_tag_name. ' class="' . html_class_attribute_ref($element) . '">'
1445
            . $element->name . $source_references_markup . $annotations_and_sources['foot_note_keys'] . '</' . $element_tag_name. '>';
1446
        }
1447
      } // End of loop over set of individual elements
1448
      $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1449
    } // End of loop over set of elements per language area
1450

    
1451

    
1452
    $common_name_feature_elements_render_array = compose_feature_block_elements(
1453
      $common_name_feature_elements, $feature, '; ', FALSE
1454
    );
1455
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1456

    
1457
  }
1458

    
1459
  // Handling commons names as text data.
1460
  $text_data_out = array();
1461

    
1462
  foreach ($textData_commonNames as $text_data_element) {
1463
    /* footnotes are not handled correctly in compose_description_element_text_data,
1464
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1465
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1466
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1467
    $text_data_out[] = drupal_render($text_data_render_array);
1468
  }
1469

    
1470
  $common_name_out_text_data = compose_feature_block_elements(
1471
    $text_data_out, $feature
1472
  );
1473

    
1474
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1475
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1476
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1477

    
1478
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1479
    '<div class="common_names_as_common_names">' . $common_name_out . '</div>'
1480
    .'<div class="common_names_as_text_data">' . drupal_render($common_name_out_text_data) . '</div>'
1481
    .$footnotes,
1482
    $weight
1483
  );
1484
}
1485

    
1486
  /**
1487
   * Composes the render array for a CDM Distribution description element
1488
   *
1489
   * @param array $description_elements
1490
   *   Array of CDM Distribution instances
1491
   * @param $enclosingTag
1492
   *   The html tag to be use for the enclosing element
1493
   *
1494
   * @return array
1495
   *   A Drupal render array
1496
   *
1497
   * @ingroup compose
1498
   */
1499
  function compose_description_elements_distribution($description_elements){
1500

    
1501
    $out = '';
1502
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1503
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1504

    
1505
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1506
    $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1507

    
1508
    foreach ($description_elements as $description_element) {
1509
      $annotations_and_sources = handle_annotations_and_sources(
1510
        $description_element,
1511
        $feature_block_settings,
1512
        $description_element->area->representation_L10n,
1513
        UUID_DISTRIBUTION
1514
      );
1515

    
1516

    
1517
      list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1518

    
1519
      $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1520
        . ' " title="' . $status_label. '">'
1521
        . $description_element->area->representation_L10n
1522
        . $status_markup;
1523
      if(!empty($annotations_and_sources['source_references'])){
1524
        $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1525
      }
1526
      $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1527
    }
1528

    
1529
    RenderHints::popFromRenderStack();
1530
    return markup_to_render_array($out);
1531
  }
1532

    
1533
  /**
1534
   * @param $descriptionElement
1535
   * @return array
1536
   */
1537
  function distribution_status_label_and_markup($descriptionElement) {
1538
    $status_markup = '';
1539
    $status_label = '';
1540

    
1541
    if (isset($descriptionElement->status)) {
1542
      $status_label = $descriptionElement->status->representation_L10n;
1543
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1544
        . $status_label . ' </span>';
1545

    
1546
    };
1547
    return array($status_label, $status_markup);
1548
  }
1549

    
1550

    
1551
  /**
1552
   * Provides the merged feature tree for a taxon profile page.
1553
   *
1554
   * The merging of the profile feature tree is actully done in
1555
   * _mergeFeatureTreeDescriptions(). See this method  for details
1556
   * on the structure of the merged tree.
1557
   *
1558
   * This method provides t hook which can be used to modify the
1559
   * merged feature tree after it has been created, see
1560
   * hook_merged_taxon_feature_tree_alter()
1561
   *
1562
   * @param $taxon
1563
   *   A CDM Taxon instance
1564
   *
1565
   * @return object
1566
   *  The merged feature tree
1567
   *
1568
   */
1569
  function merged_taxon_feature_tree($taxon) {
1570

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

    
1574

    
1575
    // 2. find the distribution feature node
1576
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1577

    
1578
    if ($distribution_node) {
1579
      // 3. get the distributionInfoDTO
1580
      $query_parameters = cdm_distribution_filter_query();
1581
      $query_parameters['part'] = array('mapUriParams');
1582
      if(variable_get(DISTRIBUTION_CONDENSED)){
1583
        $query_parameters['part'][] = 'condensedDistribution';
1584
      }
1585
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1586
        $query_parameters['part'][] = 'tree';
1587
      }
1588
      else {
1589
        $query_parameters['part'][] = 'elements';
1590
      }
1591
      $query_parameters['omitLevels'] = array();
1592
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1593
        if(is_uuid($uuid)){
1594
          $query_parameters['omitLevels'][] = $uuid;
1595
        }
1596
      }
1597
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1598
      if ($customStatusColorsJson) {
1599
        $query_parameters['statusColors'] = $customStatusColorsJson;
1600
      }
1601

    
1602
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1603
      // 4. get distribution TextData is there are any
1604
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1605
        array(
1606
          'taxon' => $taxon->uuid,
1607
          'type' => 'TextData',
1608
          'features' => UUID_DISTRIBUTION
1609
        )
1610
      );
1611

    
1612
      // 5. put all distribution data into the distribution feature node
1613
      if ($distribution_text_data //if text data exists
1614
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1615
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1616
      ) { // OR if DTO has distribution elements
1617
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1618
        if ($distribution_text_data) {
1619
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1620
        }
1621
        if ($distribution_info_dto) {
1622
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1623
        }
1624
      }
1625
    }
1626

    
1627
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1628
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1629

    
1630
    return $merged_tree;
1631
  }
1632

    
1633

    
1634
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1635

    
1636
    static $hierarchy_style;
1637
    // TODO expose $hierarchy_style to administration of provide a hook
1638
    if( !isset($hierarchy_style)){
1639
      $hierarchy_style = array(
1640
        // level 2
1641
        array(
1642
          'label_suffix' => '',
1643
          'element_glue' => ', ',
1644
          'element_set_pre' => '(',
1645
          'element_set_post' => ')'
1646
        ),
1647
        // level 1
1648
        array(
1649
          'label_suffix' => '',
1650
          'element_glue' => '; ',
1651
          'element_set_pre' => '',
1652
          'element_set_post' => ''
1653
        ),
1654
        // level 0
1655
        array(
1656
          'label_suffix' => ':',
1657
          'element_glue' => ' ',
1658
          'element_set_pre' => '',
1659
          'element_set_post' => ''
1660
        ),
1661
      );
1662
    }
1663

    
1664
    $render_array = array();
1665

    
1666
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1667
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1668

    
1669
    // Returning NULL if there are no description elements.
1670
    if ($distribution_tree == null) {
1671
      return $render_array;
1672
    }
1673
    // for now we are not using a render array internally to avoid performance problems
1674
    $markup = '';
1675
    if (isset($distribution_tree->rootElement->children)) {
1676
      $tree_nodes = $distribution_tree->rootElement->children;
1677
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1678
    }
1679

    
1680
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1681
      $markup,
1682
      0,
1683
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1684
      '</div>'
1685
    );
1686

    
1687
    return $render_array;
1688
  }
1689

    
1690
  /**
1691
   * this function should produce markup as the compose_description_elements_distribution()
1692
   * function.
1693
   *
1694
   * @see compose_description_elements_distribution()
1695
   *
1696
   * @param $distribution_tree
1697
   * @param $feature_block_settings
1698
   * @param $tree_nodes
1699
   * @param $markup
1700
   * @param $hierarchy_style
1701
   */
1702
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1703

    
1704
    $level_index++;
1705
    static $enclosingTag = "span";
1706

    
1707
    $level_style = array_pop($hierarchy_style);
1708
    if(count($hierarchy_style) == 0){
1709
      // lowest defined level style will be reused for all following levels
1710
      $hierarchy_style[] = $level_style;
1711
    }
1712

    
1713
    $node_index = -1;
1714
    $per_node_markup = array();
1715
    foreach ($tree_nodes as $node){
1716

    
1717
      $per_node_markup[++$node_index] = '';
1718

    
1719
      $label = $node->nodeId->representation_L10n;
1720

    
1721
      $distributions = $node->data;
1722
      $distribution_uuids = array();
1723
      $distribution_aggregate = NULL;
1724
        foreach($distributions as $distribution){
1725

    
1726
          $distribution_uuids[] = $distribution->uuid;
1727

    
1728
          // if there is more than one distribution we aggregate the sources and
1729
          // annotations into a synthetic distribution so that the footnote keys
1730
          // can be rendered consistently
1731
          if(!$distribution_aggregate) {
1732
            $distribution_aggregate = $distribution;
1733
            if(!isset($distribution_aggregate->sources[0])){
1734
              $distribution_aggregate->sources = array();
1735
            }
1736
            if(!isset($distribution_aggregate->annotations[0])){
1737
              $distribution_aggregate->annotations = array();
1738
            }
1739
          } else {
1740
            if(isset($distribution->sources[0])) {
1741
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1742
                $distribution->sources);
1743
            }
1744
            if(isset($distribution->annotations[0])) {
1745
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1746
                $distribution->annotations);
1747
            }
1748
          }
1749
        }
1750

    
1751
      $status_label= '';
1752
      $status_markup = '';
1753
      $annotations_and_sources =  null;
1754
      if($distribution_aggregate) {
1755
        $annotations_and_sources = handle_annotations_and_sources(
1756
          $distribution_aggregate,
1757
          $feature_block_settings,
1758
          $label,
1759
          UUID_DISTRIBUTION
1760
        );
1761

    
1762
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1763
      }
1764

    
1765
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1766
        . join(' descriptionElement-', $distribution_uuids)
1767
        . ' level_index_' . $level_index
1768
        . ' " title="' . $status_label . '">'
1769
        . '<span class="area_label">' . $label
1770
        . $level_style['label_suffix'] . ' </span>'
1771
        .  $status_markup
1772
      ;
1773

    
1774
      if(isset($annotations_and_sources)){
1775
        if(!empty($annotations_and_sources['source_references'])){
1776
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1777
        }
1778
        if($annotations_and_sources['foot_note_keys']) {
1779
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1780
        }
1781
      }
1782

    
1783
      if(isset($node->children[0])){
1784
        _compose_distribution_hierarchy(
1785
          $node->children,
1786
          $feature_block_settings,
1787
          $per_node_markup[$node_index],
1788
          $hierarchy_style,
1789
          $level_index
1790
        );
1791
      }
1792

    
1793
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1794
    }
1795
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1796
  }
1797

    
1798

    
(2-2/8)