Project

General

Profile

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

    
3
const BIBLIOGRAPHY_FOOTNOTE_KEY = PSEUDO_FEATURE_BIBLIOGRAPHY;
4

    
5

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

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

    
47
  $computed_elements = array();
48
  $other_elements = array();
49

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

    
61
  if (count($computed_elements) > 0) {
62
    return $computed_elements;
63
  }
64
  else {
65
    return $other_elements;
66
  }
67
}
68

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

    
79
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
80
  if($feature_block_settings['sort_elements'] == SORT_HIERARCHICAL){
81
    $query['distributionOrder'] = 'AREA_ORDER';
82
  }
83

    
84
  $query['recipe'] = variable_get(DISTRIBUTION_CONDENSED_RECIPE, DISTRIBUTION_CONDENSED_RECIPE_DEFAULT);
85

    
86

    
87

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

    
103
  return $query;
104
}
105

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

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

    
129
/**
130
 * Adds an entry to the end of the table of content items list
131
 *
132
 * The  table of content items are crated internally by calling
133
 * toc_list_item() the resulting item is added to the statically cached
134
 * list of toc elements
135
 *
136
 * @param string $label
137
 *   The label of toc entry
138
 * @param $class_attribute_suffix
139
 *   The suffix to be appended to the class attribute prefix:
140
 *   "feature-toc-item-"
141
 * @param string $fragment
142
 *   Optional parameter to define a url fragment different from the $label,
143
 *   if the $fragment is not defined the $label will be used
144
 * @param boolean $as_first_element
145
 *   Place the new item as fist one. This parameter is ignored when $weight is
146
 *   being set
147
 * @param integer $weight
148
 *   Defines the weight for the ordering the item in the toc list.
149
 *   The item will be placed at the end if weigth is NULL.
150
 *
151
 * @throws \Exception re-throws exception from theme()
152
 */
153
function cdm_toc_list_add_item($label, $class_attribute_suffix, $fragment = NULL, $as_first_element = FALSE, $weight = null) {
154

    
155
  $toc_list_items = &cdm_toc_list();
156

    
157
  if (!$fragment) {
158
    $fragment = $label;
159
  }
160
  $fragment = generalizeString($fragment);
161

    
162
  $class_attributes = 'feature-toc-item-' . $class_attribute_suffix;
163

    
164
  $new_item = toc_list_item(
165
    theme(
166
      'cdm_feature_name',
167
      array('feature_name' => $label)),
168
      array('class' => $class_attributes),
169
      $fragment
170
    );
171

    
172
  if ($weight === null && $as_first_element) {
173
    reset($toc_list_items);
174
    $weight = key($toc_list_items); // returns null for empty arrays
175
    $weight = $weight !== null ? $weight - FEATURE_BLOCK_WEIGHT_INCREMENT : 0;
176
  }
177
  else if($weight === null) {
178
      end($toc_list_items);
179
      $weight = key($toc_list_items); // returns null for empty arrays
180
      $weight = $weight !== null ? $weight + FEATURE_BLOCK_WEIGHT_INCREMENT : 0;
181
  }
182
  $toc_list_items[$weight] = $new_item;
183
  ksort($toc_list_items); // sort so that the last element has always the highest weight
184

    
185
}
186

    
187
/**
188
 * Returns the statically cached table of content items as render array.
189
 *
190
 * @see cdm_toc_list_add_item()
191
 *
192
 * @return array
193
 *   a render array of table of content items suitable for theme_item_list()
194
 */
195
function &cdm_toc_list(){
196

    
197
  $toc_list_items = &drupal_static('toc_list_items', array());
198

    
199
  return $toc_list_items;
200
}
201

    
202
/**
203
 * Prepares an empty Drupal block for displaying description elements of a
204
 * specific CDM Feature.
205
 *
206
 * The block can also be used for pseudo Features like a bibliography. Pseudo
207
 * features are derived from other data on the fly and so not exist as such in
208
 * the cdm data. For pseudo features the $feature can be created using
209
 * make_pseudo_feature().
210
 *
211
 * @param $feature_name
212
 *   A label describing the feature, usually the localized feature
213
 *   representation.
214
 * @param object $feature
215
 *   The CDM Feature for which the block is created.
216
 *
217
 * @return object
218
 *   A Drupal block object
219
 *
220
 * @throws \Exception re-throws exception from theme()
221
 */
222
function feature_block($feature_name, $feature) {
223
  $block = new stdclass();
224
  $block->module = 'cdm_dataportal';
225
  $block->region = NULL;
226
  $class_attribute = html_class_attribute_ref($feature);
227
  $block_delta = $feature->class !== 'PseudoFeature' ? $feature_name : $feature->label;
228
  $block->delta = generalizeString($block_delta);
229
  $block->subject = '<a name="' . $block->delta . '"></a><span class="' . $class_attribute . '">'
230
    . theme('cdm_feature_name', array('feature_name' => $feature_name))
231
    . '</span>';
232
  $block->module = "cdm_dataportal-feature";
233
  $block->content = '';
234
  return $block;
235
}
236

    
237

    
238
/**
239
 * Returns a list of a specific type of IdentificationKeys.
240
 *
241
 * The list can be restricted by a taxon.
242
 *
243
 * @param string $type
244
 *   The simple name of the cdm class implementing the interface
245
 *   IdentificationKey, valid values are:
246
 *   PolytomousKey, MediaKey, MultiAccessKey.
247
 * @param string $taxonUuid
248
 *   If given this parameter restrict the listed keys to those which have
249
 *   the taxon identified be this uuid in scope.
250
 *
251
 * @return array
252
 *   List with identification keys.
253
 */
254
function _list_IdentificationKeys($type, $taxonUuid = NULL, $pageSize = NULL, $pageNumber = NULL) {
255
  if (!$type) {
256
    drupal_set_message(t('Type parameter is missing'), 'error');
257
    return;
258
  }
259
  $cdm_ws_base_path = NULL;
260
  switch ($type) {
261
    case "PolytomousKey":
262
      $cdm_ws_base_path = CDM_WS_POLYTOMOUSKEY;
263
      break;
264

    
265
    case "MediaKey":
266
      $cdm_ws_base_path = CDM_WS_MEDIAKEY;
267
      break;
268

    
269
    case "MultiAccessKey":
270
      $cdm_ws_base_path = CDM_WS_MULTIACCESSKEY;
271
      break;
272

    
273
  }
274

    
275
  if (!$cdm_ws_base_path) {
276
    drupal_set_message(t('Type parameter is not valid: ') . $type, 'error');
277
  }
278

    
279
  $queryParameters = '';
280
  if (is_numeric($pageSize)) {
281
    $queryParameters = "pageSize=" . $pageSize;
282
  }
283
  else {
284
    $queryParameters = "pageSize=0";
285
  }
286

    
287
  if (is_numeric($pageNumber)) {
288
    $queryParameters = "pageNumber=" . $pageNumber;
289
  }
290
  else {
291
    $queryParameters = "pageNumber=0";
292
  }
293
  $queryParameters = NULL;
294
  if ($taxonUuid) {
295
    $queryParameters = "findByTaxonomicScope=$taxonUuid";
296
  }
297
  $pager = cdm_ws_get($cdm_ws_base_path, NULL, $queryParameters);
298

    
299
  if (!$pager || $pager->count == 0) {
300
    return array();
301
  }
302
  return $pager->records;
303
}
304

    
305

    
306
/**
307
 * Creates a list item for a table of content, suitable as data element for a themed list
308
 *
309
 * @see theme_list()
310
 *
311
 * @param $label
312
 * @param $http_request_params
313
 * @param $attributes
314
 * @return array
315
 */
316
function toc_list_item($label, $attributes = array(), $fragment = null) {
317

    
318
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
319
  $http_request_params = drupal_static('http_request_params', drupal_get_query_parameters());
320

    
321
  $item =  array(
322
    'data' => l(
323
      $label,
324
      $_GET['q'],
325
      array(
326
        'attributes' => array('class' => array('toc')),
327
        'fragment' => generalizeString($label),
328
        'query' => $http_request_params,
329
      )
330
    ),
331
  );
332
  $item['attributes'] = $attributes;
333
  return $item;
334
}
335

    
336
/**
337
 * Compare callback to be used in usort() to sort render arrays produced by
338
 * compose_description_element().
339
 *
340
 * @param $a
341
 * @param $b
342
 *
343
 * @return int Returns < 0 if $a['#value'].$a['#value-suffix'] from is less than
344
 * $b['#value'].$b['#value-suffix'], > 0 if it is greater than $b['#value'].$b['#value-suffix'],
345
 * and 0 if they are equal.
346
 */
347
function compare_description_element_render_arrays($a, $b){
348
  if ($a['#value'].$a['#value-suffix'] == $b['#value'].$b['#value-suffix']) {
349
    return 0;
350
  }
351
  return ($a['#value'].$a['#value-suffix'] < $b['#value'].$b['#value-suffix']) ? -1 : 1;
352

    
353
}
354

    
355

    
356
/**
357
 * @param $element
358
 * @param $feature_block_settings
359
 * @param $element_markup
360
 * @param $footnote_list_key_suggestion
361
 * @param bool $prepend_feature_label
362
 *
363
 * @return array|null
364
 */
365
function compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label = FALSE)
366
{
367

    
368
  $render_array = array(
369
    '#type' => 'html_tag',
370
    '#tag' => cdm_feature_block_element_tag_name($feature_block_settings),
371

    
372
    '#attributes' => array(
373
      'class' => array(
374
        'DescriptionElement',
375
        'DescriptionElement-' . $element->class,
376
        html_class_attribute_ref($element)
377
      )
378
    ),
379

    
380
    '#value' => '',
381
    '#value_suffix' => NULL
382

    
383
  );
384

    
385
  RenderHints::setAnnotationsAndSourceConfig(handle_annotations_and_sources_config($feature_block_settings));
386
  $annotations_and_sources = handle_annotations_and_sources(
387
    $element, $element_markup, $footnote_list_key_suggestion
388
  );
389

    
390
  $timescope_markup = '';
391
  if(isset($element->timeperiod)){
392
    $timescope_markup = ' ' . timePeriodToString($element->timeperiod, true);
393
  }
394

    
395
  // handle the special case were the TextData is used as container for original source with name
396
  // used in source information without any text stored in it.
397
  $names_used_in_source_markup = '';
398
  if ($annotations_and_sources->hasNameUsedInSource() && empty($element_markup)) {
399
    $names_used_in_source_markup = join(', ', $annotations_and_sources->getNameUsedInSource()) . ': ';
400
    // remove all <span class="nameUsedInSource">...</span> from all source_references
401
    // these are expected to be at the end of the strings
402
    $pattern = '/ <span class="nameUsedInSource">.*$/';
403
    foreach( $annotations_and_sources->getSourceReferences() as &$source_reference){
404
      $source_reference = preg_replace($pattern , '', $source_reference);
405
    }
406
  }
407

    
408
  $source_references_markup = '';
409
  if ($annotations_and_sources->hasSourceReferences()) {
410
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources->getSourceReferences()) . '<span>';
411
  }
412

    
413
  $feature_label = '';
414
  if ($prepend_feature_label) {
415
    $feature_label = '<span class="nested-feature-tree-feature-label">' . $element->feature->representation_L10n . ':</span> ';
416
  }
417
  $content_markup = $names_used_in_source_markup . $element_markup . $timescope_markup . $source_references_markup;
418

    
419
  if(!$content_markup && $feature_block_settings['sources_as_content'] !== 1){
420
    // no textual content? So skip this element completely, even if there could be an footnote key
421
    // see #4379
422
    return null;
423
  }
424

    
425
    $render_array['#value'] = $feature_label . $content_markup;
426
    $render_array['#value_suffix'] = $annotations_and_sources->footNoteKeysMarkup();
427
  return $render_array;
428
}
429

    
430
/**
431
 * Provides the according tag name for the description element markup which
432
 * fits the  $feature_block_settings['as_list'] value
433
 *
434
 * @param $feature_block_settings
435
 *   A feature_block_settings array, for details, please see
436
 *   get_feature_block_settings($feature_uuid = 'DEFAULT')
437
 *
438
 * @return mixed|string
439
 */
440
  function cdm_feature_block_element_tag_name($feature_block_settings){
441
    switch ($feature_block_settings['as_list']){
442
      case 'ul':
443
      case 'ol':
444
        return 'li';
445
      case 'div':
446
        if(isset($feature_block_settings['element_tag'])){
447
          return $feature_block_settings['element_tag'];
448
        }
449
        return 'span';
450
      case 'dl':
451
        return 'dd';
452
      default:
453
        return 'div'; // should never happen, throw error instead?
454
    }
455
  }
456

    
457

    
458
/* ==================== COMPOSE FUNCTIONS =============== */
459

    
460
  /**
461
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
462
   *
463
   * The taxon profile consists of drupal block elements, one for the description elements
464
   * of a specific feature. The structure is defined by specific FeatureTree.
465
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
466
   *
467
   * The merged nodes can be obtained by making use of the
468
   * function cdm_ws_descriptions_by_featuretree().
469
   *
470
   * @see cdm_ws_descriptions_by_featuretree()
471
   *
472
   * @param $mergedFeatureNodes
473
   *
474
   * @param $taxon
475
   *
476
   * @return array
477
   *  A Drupal render array containing feature blocks and the table of content
478
   *
479
   * @ingroup compose
480
   */
481
  function make_feature_block_list($mergedFeatureNodes, $taxon) {
482

    
483
    $block_list = array();
484

    
485
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
486

    
487
    $use_description_features = array(UUID_USE);
488

    
489

    
490
    RenderHints::pushToRenderStack('feature_block');
491
    // Create a drupal block for each feature
492
    $block_weight = - FEATURE_BLOCK_WEIGHT_INCREMENT;
493
    foreach ($mergedFeatureNodes as $feature_node) {
494

    
495
      $block_weight = $block_weight + FEATURE_BLOCK_WEIGHT_INCREMENT;
496

    
497
      if ((isset($feature_node->descriptionElements['#type']) ||
498
          has_feature_node_description_elements($feature_node)) && $feature_node->term->uuid != UUID_IMAGE) { // skip empty or suppressed features
499

    
500
        RenderHints::pushToRenderStack($feature_node->term->uuid);
501
          
502
        $feature_name = cdm_term_representation($feature_node->term, 'Unnamed Feature');
503
        $feature_block_settings = get_feature_block_settings($feature_node->term->uuid);
504
        
505

    
506
        $block = feature_block($feature_name, $feature_node->term);
507
        $block->content = array();
508
        $block_content_is_empty = TRUE;
509

    
510
        if(array_search($feature_node->term->uuid, $use_description_features) !== false) {
511
          // do not show features which belong to the UseDescriptions, these are
512
          // handled by compose_feature_block_items_use_records() where the according descriptions are
513
          // fetched again separately.
514
          // UseDescriptions are a special feature introduced for palmweb
515
          continue;
516
        }
517

    
518
        /*
519
         * Content/DISTRIBUTION.
520
         */
521
        if ($feature_node->term->uuid == UUID_DISTRIBUTION) {
522
          $block = compose_feature_block_distribution($taxon, $feature_node->descriptionElements, $feature_node->term);
523
          $block_content_is_empty = FALSE;
524
        }
525

    
526
        /*
527
         * Content/COMMON_NAME.
528
         */
529
        else if ($feature_node->term->uuid == UUID_COMMON_NAME) {
530
          $common_names_render_array = compose_feature_block_items_feature_common_name($feature_node->descriptionElements, $feature_node->term);
531
          $block->content[] = $common_names_render_array;
532
          $block_content_is_empty = FALSE;
533
        }
534

    
535
        /*
536
         * Content/Use Description (Use + UseRecord)
537
         */
538
        else if ($feature_node->term->uuid == UUID_USE_RECORD) {
539
          $block->content[] = cdm_block_use_description_content($taxon->uuid, $feature_node->term);
540
          $block_content_is_empty = FALSE;
541
        }
542

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

    
548
          $media_list = array();
549
          $elements_render_array = array();
550
          $child_elements_render_array = null;
551

    
552
          if (isset($feature_node->descriptionElements[0])) {
553
            $elements_render_array = compose_feature_block_items_generic($feature_node->descriptionElements);
554
          }
555

    
556
          // Content/ALL OTHER FEATURES/Subordinate Features
557
          // subordinate features are printed inline in one floating text,
558
          // it is expected hat subordinate features can "contain" TextData,
559
          // Qualitative- and Qualitative- DescriptionElements
560
          if (isset($feature_node->childNodes[0])) {
561
            $child_elements_render_array = compose_feature_block_items_nested($feature_node, $media_list, $feature_block_settings);
562
            $elements_render_array = array_merge($elements_render_array, $child_elements_render_array);
563
          }
564
          $block_content_is_empty = $block_content_is_empty && empty($media_list) && empty($elements_render_array);
565
          if(!$block_content_is_empty){
566
            $block->content[] = compose_feature_block_wrap_elements($elements_render_array, $feature_node->term, $feature_block_settings['glue']);
567
            $block->content[] = compose_feature_media_gallery($feature_node, $media_list, $gallery_settings);
568
            /*
569
             * Footnotes for the feature block
570
             */
571
            $block->content[] = markup_to_render_array(render_footnotes(PSEUDO_FEATURE_BIBLIOGRAPHY . '-' . $feature_node->term->uuid));
572
            $block->content[] = markup_to_render_array(render_footnotes($feature_node->term->uuid));
573
          }
574
        } // END all other features
575

    
576
        // allows modifying the block contents via a the hook_cdm_feature_node_block_content_alter
577
        drupal_alter('cdm_feature_node_block_content', $block->content, $feature_node->term, $feature_node->descriptionElements);
578

    
579
        if(!$block_content_is_empty){ // skip empty block content
580
          $block_list[$block_weight] = $block;
581
          cdm_toc_list_add_item(cdm_term_representation($feature_node->term), $feature_node->term->uuid, null, FALSE, $block_weight);
582
        } // END: skip empty block content
583
      } // END: skip empty or suppressed features
584
      RenderHints::popFromRenderStack();
585
    } // END: creating a block per feature
586

    
587
    RenderHints::popFromRenderStack();
588

    
589
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
590

    
591
    ksort($block_list);
592

    
593
    return  $block_list;
594
  }
595

    
596
/**
597
 * Creates a render array of description elements  held by child nodes of the given feature node.
598
 *
599
 * This function is called recursively!
600
 *
601
 * @param $feature_node
602
 *   The feature node.
603
 * @param array $media_list
604
 *   List of CDM Media entities. All media of subordinate elements should be passed to the main feature.ä
605
 * @param $feature_block_settings
606
 *   The feature block settings.
607
 * @param $main_feature
608
 *  Only used internally in recursive calls.
609
 *
610
 * @return array
611
 *  A Drupal render array
612
 *
613
 * @ingroup compose
614
 */
615
function compose_feature_block_items_nested($feature_node, &$media_list, $feature_block_settings, $main_feature = NULL)
616
{
617

    
618
  if(!$main_feature){
619
    $main_feature = $feature_node->term;
620
  }
621
  /*
622
   * TODO should be configurable, options; YES, NO, AUTOMATIC
623
   * (automatic will only place the label if the first word of the description element text is not the same)
624
   */
625
  $prepend_feature_label = false;
626

    
627
  $render_arrays = array();
628
  foreach ($feature_node->childNodes as $child_node) {
629
    if (isset($child_node->descriptionElements[0])) {
630
      foreach ($child_node->descriptionElements as $element) {
631

    
632
        if (isset($element->media[0])) {
633
          // Append media of subordinate elements to list of main
634
          // feature.
635
          $media_list = array_merge($media_list, $element->media);
636
        }
637

    
638
        $child_node_element = null;
639
        switch ($element->class) {
640
          case 'TextData':
641
            $child_node_element = compose_description_element_text_data($element, $element->feature->uuid, $feature_block_settings, $prepend_feature_label);
642
            break;
643
          case 'CategoricalData':
644
            $child_node_element = compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label);
645
            break;
646
          case 'QuantitativeData':
647
            $child_node_element = compose_description_element_quantitative_data($element, $feature_block_settings, $prepend_feature_label);
648

    
649
        }
650
        if (is_array($child_node_element)) {
651
          $render_arrays[] = $child_node_element;
652
        }
653
      }
654
    }
655

    
656
    if(isset($child_node->childNodes[0])){
657
      $render_arrays = array_merge($render_arrays, compose_feature_block_items_nested($child_node, $media_list, $feature_block_settings, $main_feature ));
658
    }
659
  }
660

    
661
  return $render_arrays;
662
}
663

    
664
  /**
665
   *
666
   * @param $feature_node
667
   *  The merged feature three node which potentially contains media in its description elements.
668
   * @param $media_list
669
   *    Additional media to be merged witht the media contained in the nodes description elements
670
   * @param $gallery_settings
671
   * @return array
672
   *
673
   * @ingroup compose
674
   */
675
  function compose_feature_media_gallery($feature_node, $media_list, $gallery_settings) {
676

    
677
    if (isset($feature_node->descriptionElements)) {
678
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($feature_node->descriptionElements));
679
    }
680

    
681
    $captionElements = array('title', 'rights');
682

    
683
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
684
      $gallery = compose_cdm_media_gallery(array(
685
        'mediaList' => $media_list,
686
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $feature_node->term->uuid,
687
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
688
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
689
        'captionElements' => $captionElements,
690
      ));
691
      return markup_to_render_array($gallery);
692
    }
693

    
694
    return markup_to_render_array('');
695
  }
696

    
697
  /**
698
   * Composes the distribution feature block for a taxon
699
   *
700
   * @param $taxon
701
   * @param $descriptionElements
702
   *   an associative array with two elements:
703
   *   - '#type': must be 'DTO'
704
   *   - 'DistributionInfoDTO': a CDM DistributionInfoDTO object as returned by the DistributionInfo web service
705
   * @param $feature
706
   *
707
   * @return array
708
   *  A drupal render array
709
   *
710
   * @ingroup compose
711
   */
712
  function compose_feature_block_distribution($taxon, $descriptionElements, $feature) {
713
    $text_data_glue = '';
714
    $text_data_sortOutArray = FALSE;
715
    $text_data_enclosingTag = 'ul';
716
    $text_data_out_array = array();
717

    
718
    $distributionElements = NULL;
719
    $distribution_info_dto = NULL;
720
    $distribution_sortOutArray = FALSE;
721

    
722
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
723

    
724
    // TODO use feature_block_settings instead of DISTRIBUTION_ORDER_MODE
725
    if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) != 'TREE') {
726
      $distribution_glue = '';
727
      $distribution_enclosingTag = 'dl';
728
    } else {
729
      $distribution_glue = '';
730
      $distribution_enclosingTag = 'ul';
731
    }
732

    
733
    if (!isset($descriptionElements['#type']) || !$descriptionElements['#type'] == 'DTO') {
734
      // skip the DISTRIBUTION section if there is no DTO type element
735
      return array(); // FIXME is it ok to return an empty array?
736
    }
737

    
738
    $block = feature_block(
739
      cdm_term_representation($feature, 'Unnamed Feature'),
740
      $feature
741
    );
742
    $block->content = array();
743

    
744
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
745
    if (isset($descriptionElements['TextData'])) {
746
      // --- TextData
747
      foreach ($descriptionElements['TextData'] as $text_data_element) {
748
        $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
749
        $repr = drupal_render($text_data_render_array);
750

    
751
        if (!array_search($repr, $text_data_out_array)) { // de-duplication !!
752
          $text_data_out_array[] = $repr;
753
          // TODO HINT: sorting in compose_feature_block_wrap_elements will
754
          // not work since this array contains html attributes with uuids
755
          // and what is about cases like the bibliography where
756
          // any content can be prefixed with some foot-note anchors?
757
          $text_data_sortOutArray = TRUE;
758
          $text_data_glue = '<br/> ';
759
          $text_data_enclosingTag = 'p';
760
        }
761
      }
762
    }
763

    
764

    
765
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
766
      $block->content[] = compose_feature_block_wrap_elements(
767
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
768
      );
769
    }
770

    
771
    // --- Distribution map
772
    $distribution_map_query_parameters = NULL;
773

    
774
    $map_visibility = variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT);
775
    if(variable_get(DISTRIBUTION_MAP_VISIBILITY, DISTRIBUTION_MAP_VISIBILITY_DEFAULT) == 'always' ||
776
        $map_visibility == 'automatic' && isset($descriptionElements['DistributionInfoDTO']->mapUriParams)
777
      )
778
    {
779
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
780
    }
781
    $map_render_element = compose_distribution_map($distribution_map_query_parameters);
782
    $block->content[] = $map_render_element;
783

    
784
    $dto_out_array = array();
785

    
786
    // --- Condensed Distribution
787
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
788
      $condensed_distribution_markup = '<p class="condensed_distribution">';
789

    
790
	  if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->htmlString)){
791
		$condensed_distribution_markup .= $descriptionElements['DistributionInfoDTO']->condensedDistribution->htmlString;
792
	  }
793
      
794
      $condensed_distribution_markup .= '&nbsp;' . l(
795
          font_awesome_icon_markup(
796
            'fa-info-circle',
797
            array(
798
              'alt'=>'help',
799
              'class' => array('superscript')
800
            )
801
          ),
802
          variable_get(DISTRIBUTION_CONDENSED_INFO_PATH, DISTRIBUTION_CONDENSED_INFO_PATH_DEFAULT) ,
803
          array('html' => TRUE));
804
      $condensed_distribution_markup .= '</p>';
805
      $dto_out_array[] = $condensed_distribution_markup;
806
    }
807

    
808
    // --- tree or list
809
    if (isset($descriptionElements['DistributionInfoDTO'])) {
810
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
811

    
812
      // --- tree
813
      if (is_object($distribution_info_dto->tree)) {
814
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
815
        $dto_out_array[] = $distribution_tree_render_array;
816
      }
817

    
818
      // --- sorted element list
819
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
820
        foreach ($distribution_info_dto->elements as $descriptionElement) {
821
          if (is_object($descriptionElement->area)) {
822
            $sortKey = $descriptionElement->area->representation_L10n;
823
            $distributionElements[$sortKey] = $descriptionElement;
824
          }
825
        }
826
        ksort($distributionElements);
827
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
828
        $dto_out_array[] = $distribution_element_render_array;
829

    
830
      }
831
      //
832
      $block->content[] = compose_feature_block_wrap_elements(
833
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
834
      );
835
    }
836

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

    
844
    $block->content[] = markup_to_render_array(render_footnotes('BIBLIOGRAPHY-' . UUID_DISTRIBUTION));
845
    $block->content[] = markup_to_render_array(render_footnotes(UUID_DISTRIBUTION));
846

    
847
    return $block;
848
  }
849

    
850
/**
851
 * Creates the markup for the media associated a DescriptionElement instance.
852
 *
853
 * @param $descriptionElement
854
 *    the DescriptionElement instance
855
 * @param $mimeTypePreference array
856
 *    An array of mime type strings. the order of the mimetypes is the order of preference.
857
 *    E.g.: array('application/pdf','image/jpeg')
858
 *
859
 * @return string
860
 *    The markup
861
 *
862
 * @ingroup compose
863
 */
864
function cdm_description_element_media($descriptionElement, $mimeTypePreference) {
865

    
866
  $out = '';
867

    
868
  _add_js_thickbox();
869

    
870
  $feature = $descriptionElement->feature;
871
  $medias = $descriptionElement->media;
872

    
873
  foreach ($medias as $media) {
874
    $pref_representations = cdm_preferred_media_representations($media, $mimeTypePreference, 300, 400);
875
    $media_representation = array_shift($pref_representations);
876
    if ($media_representation) {
877

    
878
      $content_type_directory = media_content_type_dir($media_representation);
879

    
880
      switch($content_type_directory){
881
        case 'image':
882
          $out .= compose_cdm_media_mime_image($media_representation, $feature);
883
          break;
884
        case 'application':
885
        case 'text':
886
        default:
887
          $out .= compose_cdm_media_mime_application($media_representation, $feature);
888
      }
889
    }
890
    else {
891
      // Media has empty or corrupt representation
892
      if(user_is_logged_in()){
893
        drupal_set_message('The media entity (' . l($media->uuid, path_to_media($media->uuid)) .') has empty or corrupt representation parts. Maybe the URI is empty.' , 'warning');
894
      }
895
    }
896
  }
897
  return $out;
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
   * @param bool $prepend_feature_label
908
   *   Used in nested feature trees to put the feature as label in front of the description element text representation.
909
   *
910
   * @return array
911
   *   A drupal render array with the following elements being used:
912
   *    - #tag: either 'div', 'li', ...
913
   *    ⁻ #attributes: class attributes
914
   *    - #value_prefix: (optionally) contains footnote anchors
915
   *    - #value: contains the textual content
916
   *    - #value_suffix: (optionally) contains footnote keys
917
   *
918
   * @ingroup compose
919
   */
920
  function compose_description_element_text_data($element, $feature_uuid, $feature_block_settings, $prepend_feature_label = FALSE) {
921

    
922
    $footnote_list_key_suggestion = $feature_uuid;
923

    
924
    $element_markup = '';
925
    if (isset($element->multilanguageText_L10n->text)) {
926
      // TODO replacement of \n by <br> should be configurable
927
      $element_markup = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
928
    }
929

    
930
    $render_array = compose_description_element($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion, $prepend_feature_label);
931

    
932
    return $render_array;
933
  }
934

    
935

    
936
/**
937
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
938
 *
939
 * @param $element
940
 *  The CDM TaxonInteraction entity
941
 *
942
 * @return
943
 *  A drupal render array
944
 *
945
 * @ingroup compose
946
 */
947
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
948

    
949
  $out = '';
950

    
951

    
952
  if (isset($element->description_L10n)) {
953
    $out .=  ' ' . $element->description_L10n;
954
  }
955

    
956
  if(isset($element->taxon2)){
957
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
958
  }
959

    
960
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
961

    
962
  return $render_array;
963
}
964

    
965

    
966
/**
967
 * Renders a single instance of the type IndividualsAssociations.
968
 *
969
 * @param $element
970
 *   The CDM IndividualsAssociations entity.
971
 * @param $feature_block_settings
972
 *
973
 * @return array
974
 *   Drupal render array
975
 *
976
 * @ingroup compose
977
 */
978
function compose_description_element_individuals_association($element, $feature_block_settings) {
979

    
980
  $out = '';
981

    
982
  $render_array = compose_cdm_specimen_or_observation($element->associatedSpecimenOrObservation);
983

    
984
  if (isset($element->description_L10n)) {
985
    $out .=  ' ' . $element->description_L10n;
986
  }
987

    
988
  $out .= drupal_render($render_array);
989

    
990
  $render_array = compose_description_element($element, $feature_block_settings, $out, $element->feature->uuid);
991

    
992
  return $render_array;
993
}
994

    
995

    
996

    
997
/**
998
 * Renders a single instance of the type CategoricalData.
999
 *
1000
 * @param $element
1001
 *  The CDM CategoricalData entity
1002
 *
1003
 * @param $feature_block_settings
1004
 *
1005
 * @param bool $prepend_feature_label
1006
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1007
 *
1008
 * @return array
1009
 *   a drupal render array for given CategoricalData element
1010
 *
1011
 * @ingroup compose
1012
 */
1013
function compose_description_element_categorical_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1014

    
1015
  $state_data_markup = render_state_data($element);
1016

    
1017
  $render_array = compose_description_element($element, $feature_block_settings, $state_data_markup, $element->feature->uuid, $prepend_feature_label);
1018

    
1019
  return $render_array;
1020
}
1021

    
1022

    
1023
/**
1024
 * Renders a single instance of the type TemporalData.
1025
 *
1026
 * @param $element
1027
 *  The CDM TemporalData entity
1028
 *
1029
 * @param $feature_block_settings
1030
 *
1031
 * @param bool $prepend_feature_label
1032
 *   Used in nested feature trees to put the feature as label in front of the description element text representation.
1033
 *
1034
 * @return array
1035
 *   a drupal render array for given TemporalData element
1036
 *
1037
 * @ingroup compose
1038
 */
1039
function compose_description_element_temporal_data($element, $feature_block_settings, $prepend_feature_label = FALSE) {
1040

    
1041
  $markup = '<span class="period-label">' . $element->period->label .'</span>';
1042
  $render_array = compose_description_element($element, $feature_block_settings, $markup, $element->feature->uuid, $prepend_feature_label);
1043
  return $render_array;
1044
}
1045

    
1046

    
1047

    
1048
/**
1049
 * @param $element
1050
 *
1051
 * @return string
1052
 * the markup
1053
 */
1054
function render_state_data($element) {
1055

    
1056
  $state_data_items = [];
1057

    
1058
  $out = '';
1059

    
1060
  if (isset($element->stateData)) {
1061
    foreach ($element->stateData as $state_data) {
1062

    
1063
      $state = NULL;
1064

    
1065
      if (isset($state_data->state)) {
1066
        $state = cdm_term_representation($state_data->state);
1067

    
1068
          $sample_count = 0;
1069
          if (isset($state_data->count)) {
1070
            $sample_count = $state_data->count;
1071
            $state .= ' [' . $state_data->count . ']';
1072
          }
1073
    
1074
          if (isset($state_data->modifyingText_L10n)) {
1075
            $state .= ' ' . $state_data->modifyingText_L10n;
1076
          }
1077
    
1078
          $modifiers_strings = cdm_modifiers_representations($state_data);
1079
          $state_data_markup = $state . ($modifiers_strings ? ' ' . $modifiers_strings : '');
1080
          // we could use strip_tags() to reduce the markup to text for the key but this is expensive
1081
          $sort_key = str_pad($sample_count, 6, '0', STR_PAD_LEFT) . '_' . $state_data_markup;
1082
          $state_data_items[$sort_key] = $state_data_markup;
1083
      }
1084

    
1085
    }
1086
    krsort($state_data_items);
1087
    $out = '<span class="' . html_class_attribute_ref($element) . '">' . join(', ', $state_data_items) .  '</span>';
1088
  }
1089
  return $out;
1090
}
1091

    
1092

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

    
1136
  $out = render_quantitative_statistics($element);
1137

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

    
1140
  return $render_array;
1141
}
1142

    
1143
/**
1144
 * Composes the HTML for quantitative statistics
1145
 * @param $element
1146
 *
1147
 * @return string
1148
 */
1149
function render_quantitative_statistics($element) {
1150

    
1151
  $out = '';
1152
  $type_representation = NULL;
1153
  $min_max = statistical_values_array();
1154
  $sample_size_markup = null;
1155

    
1156
  if (isset($element->statisticalValues)) {
1157
    $out = '<span class=\"' . html_class_attribute_ref($element) . '\">';
1158
    $other_values_markup = [];
1159
    foreach ($element->statisticalValues as $statistical_val) {
1160

    
1161
      // compile the full value string which also may contain modifiers
1162
      if (isset($statistical_val->value)) {
1163
        $statistical_val->_value = $statistical_val->value;
1164
      }
1165
      $val_modifiers_strings = cdm_modifiers_representations($statistical_val);
1166
      if ($val_modifiers_strings) {
1167
        $statistical_val->_value = ' ' . $val_modifiers_strings . ' ' . $statistical_val->_value;
1168
      }
1169

    
1170
      // either put into min max array or into $other_values
1171
      // for generic output to be appended to 'min-max' string
1172
      if (array_key_exists(statistical_measure_term2min_max_key($statistical_val->type), $min_max)) {
1173
        $min_max[statistical_measure_term2min_max_key($statistical_val->type)] = $statistical_val;
1174
      }
1175
      else {
1176
        drupal_set_message("Unsupported statistical value type: " . $statistical_val->type->uuid, "error");
1177
      }
1178
    } // end of loop over statisticalValues
1179

    
1180
    // create markup
1181
    $unit = null;
1182
    if (isset($element->unit)) {
1183
      $unit = ' <span class="unit" title="'
1184
        . cdm_term_representation($element->unit) . '">'
1185
        . cdm_term_representation_abbreviated($element->unit)
1186
        . '</span>';
1187
    }
1188
    $min_max_markup = statistical_values($min_max, $unit);
1189
    $out .= $min_max_markup . '</span>';
1190
  }
1191

    
1192
  if($sample_size_markup){
1193
    $out .= ' ' . $sample_size_markup;
1194

    
1195
  }
1196

    
1197
  // modifiers of the description element itself
1198
  $modifier_string = cdm_modifiers_representations($element);
1199
  $out .= ($modifier_string ? ' ' . $modifier_string : '');
1200
  if (isset($element->modifyingText_L10n)) {
1201
    $out = $element->modifyingText_L10n . ' ' . $out;
1202
  }
1203
  return $out;
1204
}
1205

    
1206
function statistical_measure_term2min_max_key($term){
1207
  static $uuid2key = [
1208
    UUID_STATISTICALMEASURE_MIN => 'Min',
1209
    UUID_STATISTICALMEASURE_MAX => 'Max',
1210
    UUID_STATISTICALMEASURE_AVERAGE => 'Average',
1211
    UUID_STATISTICALMEASURE_SAMPLESIZE => 'SampleSize',
1212
    UUID_STATISTICALMEASURE_VARIANCE => 'Variance',
1213
    UUID_STATISTICALMEASURE_TYPICALLOWERBOUNDARY => 'TypicalLowerBoundary',
1214
    UUID_STATISTICALMEASURE_TYPICALUPPERBOUNDARY => 'TypicalUpperBoundary',
1215
    UUID_STATISTICALMEASURE_STANDARDDEVIATION => 'StandardDeviation',
1216
    UUID_STATISTICALMEASURE_EXACTVALUE => 'ExactValue',
1217
    UUID_STATISTICALMEASURE_STATISTICALMEASUREUNKNOWNDATA => 'StatisticalMeasureUnknownData'
1218
  ];
1219
  return $uuid2key[$term->uuid];
1220
}
1221

    
1222

    
1223
/**
1224
 * Wraps the render array for the given feature into an enclosing html tag.
1225
 *
1226
 * Optionally the elements can be sorted and glued together by a separator string.
1227
 *
1228
 * @param array $description_element_render_arrays
1229
 *   An list of render arrays. Which are usually are produced by the compose_description_element()
1230
 *   function. The render arrays should be of #type=html_tag, so that they can understand the #attribute property.
1231
 * @param  $feature :
1232
 *  The feature to which the elements given in $elements are belonging to.
1233
 * @param string $glue :
1234
 *  Defaults to empty string.
1235
 * @param bool $sort
1236
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1237
 *
1238
 * @return array
1239
 *    A Drupal render array
1240
 *
1241
 * @ingroup compose
1242
 */
1243
  function compose_feature_block_wrap_elements(array $description_element_render_arrays, $feature, $glue = '', $sort = FALSE)
1244
  {
1245

    
1246
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1247
    $enclosing_tag = $feature_block_settings['as_list'];
1248

    
1249
    if ($sort) { // TODO remove parameter and replace by $feature_block_settings['sort_elements']
1250
      usort($description_element_render_arrays, 'compare_description_element_render_arrays');
1251
    }
1252

    
1253
    $is_first = true;
1254
    foreach($description_element_render_arrays as &$element_render_array){
1255
      if(!is_array($element_render_array)){
1256
        $element_render_array = markup_to_render_array($element_render_array);
1257
      }
1258
      $element_render_array['#attributes']['class'][] = "feature-block-element";
1259

    
1260
      // add the glue!
1261
      if(!$is_first) {
1262
        if (isset($element_render_array['#value'])) {
1263
          $element_render_array['#value'] = $glue . $element_render_array['#value'];
1264
        } elseif (isset($element_render_array['#markup'])) {
1265
          $element_render_array['#markup'] = $glue . $element_render_array['#markup'];
1266
        }
1267
      }
1268
      $is_first = false;
1269
    }
1270

    
1271
    $render_array['elements']['children'] = $description_element_render_arrays;
1272

    
1273
    $render_array['elements']['#prefix'] = '<' . $enclosing_tag . ' class="feature-block-elements" id="' . $feature->representation_L10n . '">';
1274
    $render_array['elements']['#suffix'] = '</' . $enclosing_tag . '>';
1275

    
1276
    return $render_array;
1277
  }
1278

    
1279

    
1280
  /* compose nameInSource or originalInfo as markup
1281
   *
1282
   * @param $source
1283
   * @param $do_link_to_name_used_in_source
1284
   * @param $suppress_for_shown_taxon
1285
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1286
   *    for which the taxon page is being created, Defaults to TRUE
1287
   *
1288
   * @return array
1289
   *    A Drupal render array with an additional element, the render array is empty
1290
   *    if the source had no name in source information
1291
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1292
   *
1293
   * @ingroup compose
1294
   */
1295
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1296

    
1297
    $plaintext = NULL;
1298
    $markup = NULL;
1299
    $name_in_source_render_array = array();
1300

    
1301
    static $taxon_page_accepted_name = '';
1302
    $taxon_uuid = get_current_taxon_uuid();
1303
    if($suppress_for_shown_taxon && $taxon_uuid && empty($taxon_page_accepted_name)){
1304

    
1305
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $taxon_uuid);
1306
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1307
    }
1308

    
1309
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1310
      // it is a DescriptionElementSource !
1311
      $plaintext = $source->nameUsedInSource->titleCache;
1312
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1313
        return $name_in_source_render_array; // SKIP this name
1314
      }
1315
      $markup = render_taxon_or_name($source->nameUsedInSource);
1316
      if ($do_link_to_name_used_in_source) {
1317
        $markup = l(
1318
          $markup,
1319
          path_to_name($source->nameUsedInSource->uuid),
1320
          array(
1321
            'attributes' => array(),
1322
            'absolute' => TRUE,
1323
            'html' => TRUE,
1324
          ));
1325
      }
1326
    }
1327
    else if (isset($source->originalInfo) && !empty($source->originalInfo)) {
1328
      // the name used in source can not be expressed as valid taxon name,
1329
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalInfo
1330
      // field
1331
      // using the originalInfo as key to avoid duplicate entries
1332
      $plaintext = $source->originalInfo;
1333
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1334
        return $name_in_source_render_array; // SKIP this name
1335
      }
1336
      $markup = $source->originalInfo;
1337
    }
1338

    
1339
    if ($plaintext) { // checks if we have any content
1340
      $name_in_source_render_array = markup_to_render_array($markup);
1341
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1342
    }
1343

    
1344
    return $name_in_source_render_array;
1345
  }
1346

    
1347

    
1348

    
1349
  /**
1350
   * Return HTML for a list of description elements.
1351
   *
1352
   * Usually these are of a specific feature type.
1353
   *
1354
   * @param $description_elements
1355
   *   array of descriptionElements which belong to the same feature.
1356
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1357
   *   calling the function _mergeFeatureTreeDescriptions().
1358
   *   @see _mergeFeatureTreeDescriptions()
1359
   *
1360
   * @return array
1361
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1362
   *    Footnote key or anchors are not considered to be textual content.
1363
   *
1364
   * @ingroup compose
1365
   */
1366
  function compose_feature_block_items_generic($description_elements) {
1367

    
1368
    $elements_out_array = [];
1369
    $distribution_tree = null;
1370

    
1371
    /*
1372
     * $feature_block_has_content will be set true if at least one of the
1373
     * $descriptionElements contains some text which makes up some content
1374
     * for the feature block. Footnote keys are not considered
1375
     * to be content in this sense.
1376
     */
1377
    $feature_block_has_content = false;
1378

    
1379
    if (is_array($description_elements)) {
1380
      foreach ($description_elements as $description_element) {
1381
          /* decide based on the description element class
1382
           *
1383
           * Features handled here:
1384
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1385
           *
1386
           * TODO provide api_hook as extension point for this?
1387
           */
1388
        $feature_block_settings = get_feature_block_settings($description_element->feature->uuid);
1389
        switch ($description_element->class) {
1390
          case 'TextData':
1391
            $elements_out_array[] = compose_description_element_text_data($description_element, $description_element->feature->uuid, $feature_block_settings);
1392
            break;
1393
          case 'CategoricalData':
1394
            $elements_out_array[] = compose_description_element_categorical_data($description_element, $feature_block_settings);
1395
            break;
1396
          case 'QuantitativeData':
1397
            $elements_out_array[] = compose_description_element_quantitative_data($description_element, $feature_block_settings);
1398
            break;
1399
          case 'IndividualsAssociation':
1400
            $elements_out_array[] = compose_description_element_individuals_association($description_element, $feature_block_settings);
1401
            break;
1402
          case 'TaxonInteraction':
1403
            $elements_out_array[] = compose_description_element_taxon_interaction($description_element, $feature_block_settings);
1404
            break;
1405
          case 'CommonTaxonName':
1406
            $elements_out_array[] = compose_description_element_common_taxon_name($description_element, $feature_block_settings);
1407
            break;
1408
          case 'TemporalData':
1409
            $elements_out_array[] = compose_description_element_temporal_data($description_element, $feature_block_settings);
1410
            break;
1411
          case 'Uses':
1412
            /* IGNORE Uses classes, these are handled completely in compose_feature_block_items_use_records()  */
1413
            break;
1414
          default:
1415
            $feature_block_has_content = true;
1416
            $elements_out_array[] = markup_to_render_array('<li>No method for rendering unknown description class: ' . $description_element->class . '</li>');
1417
        }
1418
        $elements_out_array_last_item = $elements_out_array[count($elements_out_array) - 1];
1419
        // considering not empty as long as the last item added is a render array
1420
        $feature_block_has_content = $feature_block_has_content || !empty($elements_out_array_last_item['#type']);
1421
      }
1422

    
1423
      // If feature = CITATION sort the list of sources.
1424
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1425
      if (isset($description_element) && $description_element->feature->uuid == UUID_CITATION) {
1426
        sort($elements_out_array);
1427
      }
1428
    }
1429

    
1430
    // sanitize: remove empty and NULL items from the render array
1431
    $tmp_out_array = $elements_out_array;
1432
    $elements_out_array = array();
1433
    foreach($tmp_out_array as $item){
1434
      if(is_array($item) && count($item) > 0){
1435
        $elements_out_array[] = $item;
1436
      }
1437
    }
1438

    
1439
    return $elements_out_array;
1440
  }
1441

    
1442
/**
1443
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1444
 *
1445
 * @parameter $elements
1446
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1447
 * @parameter $feature
1448
 *  the common feature of all $elements, must be CommonName
1449
 *
1450
 * @return
1451
 *   A drupal render array
1452
 *
1453
 * @ingroup compose
1454
 */
1455
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1456

    
1457
  $common_name_out = '';
1458
  $common_name_feature_elements = array();
1459
  $textData_commonNames = array();
1460

    
1461
  $footnote_key_suggestion = 'common-names-feature-block';
1462

    
1463
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1464

    
1465
  if (is_array($elements)) {
1466
    foreach ($elements as $element) {
1467

    
1468
      if ($element->class == 'CommonTaxonName') {
1469

    
1470
        // common name without a language or area, should not happen but is possible
1471
        $language_area_key = '';
1472
        if (isset($element->language->representation_L10n)) {
1473
          $language_area_key .= $element->language->representation_L10n;
1474
        }
1475
        if(isset($element->area->representation_L10n) && strlen($element->area->representation_L10n) > 0){
1476
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->representation_L10n . ')';
1477
        }
1478
        if($language_area_key){
1479
          $language_area_key = '<span class="language-area-label">' . $language_area_key . '<span class="separator">: </span></span>';
1480
        }
1481

    
1482
        if(isset($common_names[$language_area_key][$element->name])) {
1483
          // same name already exists for language and area combination, se we merge the description elements
1484
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1485
        } else{
1486
          // otherwise add as new entry
1487
          $common_names[$language_area_key][$element->name] = $element;
1488
        }
1489

    
1490
      }
1491
      elseif ($element->class == 'TextData') {
1492
        $textData_commonNames[] = $element;
1493
      }
1494
    }
1495
  }
1496
  // Handling common names.
1497
  if (isset($common_names) && count($common_names) > 0) {
1498
    // Sorting the array based on the key (language, + area if set).
1499
    // Comment @WA there are common names without a language, so this sorting
1500
    // can give strange results.
1501
    ksort($common_names);
1502

    
1503
    // loop over set of elements per language area
1504
    foreach ($common_names as $language_area_key => $elements) {
1505
      ksort($elements); // sort names alphabetically
1506
      $per_language_area_out = array();
1507

    
1508
      foreach ($elements as $element) {
1509
        $common_name_render_array = compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key_suggestion);
1510
        $common_name_markup = drupal_render($common_name_render_array);
1511
        // IMPORTANT!
1512
        // during the above drupal_render the theme_html_tag function is executed, which adds a "\n" character to the end of the markup
1513
        // this is an error and the trailing whitespace needs to be removed
1514
        if(str_endsWith($common_name_markup, "\n")){
1515
          $common_name_markup = substr($common_name_markup, 0, strlen($common_name_markup) - 1);
1516
        }
1517
        $per_language_area_out[] = $common_name_markup;
1518
      }
1519

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

    
1523

    
1524
    $common_name_feature_elements_render_array = compose_feature_block_wrap_elements(
1525
      $common_name_feature_elements, $feature, '; ', FALSE
1526
    );
1527
    $common_name_out .= drupal_render($common_name_feature_elements_render_array); // FIXME should this be a render array instead?
1528

    
1529
  }
1530

    
1531
  // Handling commons names as text data.
1532
  $text_data_out = array();
1533

    
1534
  foreach ($textData_commonNames as $text_data_element) {
1535
    /* footnotes are not handled correctly in compose_description_element_text_data,
1536
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1537
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1538
    $text_data_render_array = compose_description_element_text_data($text_data_element, $text_data_element->feature->uuid, $feature_block_settings);
1539
    $text_data_out[] = drupal_render($text_data_render_array);
1540
  }
1541

    
1542
  $common_name_out_text_data = compose_feature_block_wrap_elements(
1543
    $text_data_out, $feature
1544
  );
1545

    
1546
  $footnotes = render_footnotes('BIBLIOGRAPHY-' . $footnote_key_suggestion);
1547
  $footnotes .= render_footnotes($footnote_key_suggestion);
1548

    
1549
  return  markup_to_render_array(  // FIXME markup_to_render_array should no longer be needed
1550
    '<div class="common-taxon-name">' . $common_name_out . '</div>'
1551
    .'<div class="text-data">' . drupal_render($common_name_out_text_data) . '</div>'
1552
    .$footnotes,
1553
    $weight
1554
  );
1555
}
1556

    
1557
/**
1558
 * Renders a single instance of the type CommonTaxonName.
1559
 *
1560
 * @param $element
1561
 *   The CDM CommonTaxonName entity.
1562
 * @param $feature_block_settings
1563
 *
1564
 * @param $footnote_key
1565
 *
1566
 * @return array
1567
 *   Drupal render array
1568
 *
1569
 * @ingroup compose
1570
 */
1571
function compose_description_element_common_taxon_name($element, $feature_block_settings, $footnote_key = NULL)
1572
{
1573

    
1574
  if(!$footnote_key) {
1575
    $footnote_key = $element->feature->uuid;
1576
  }
1577

    
1578
  $name = '';
1579
  if(isset($element->name)){
1580
    $name = $element->name;
1581
  }
1582

    
1583

    
1584
  return compose_description_element($element, $feature_block_settings, $name, $footnote_key);
1585
}
1586

    
1587
/**
1588
 * Composes the render array for a CDM Distribution description element
1589
 *
1590
 * @param array $description_elements
1591
 *   Array of CDM Distribution instances
1592
 * @param $enclosingTag
1593
 *   The html tag to be use for the enclosing element
1594
 *
1595
 * @return array
1596
 *   A Drupal render array
1597
 *
1598
 * @ingroup compose
1599
 */
1600
function compose_description_elements_distribution($description_elements){
1601

    
1602
  $markup_array = array();
1603
  RenderHints::pushToRenderStack('descriptionElementDistribution');
1604
  RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1605

    
1606
  $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1607
  $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1608

    
1609
  foreach ($description_elements as $description_element) {
1610
    RenderHints::setAnnotationsAndSourceConfig(handle_annotations_and_sources_config($feature_block_settings));
1611
    $annotations_and_sources = handle_annotations_and_sources(
1612
      $description_element, $description_element->area->representation_L10n, UUID_DISTRIBUTION
1613
    );
1614

    
1615
    $status = distribution_status_label_and_markup([$description_element->status]);
1616

    
1617
    $out = '';
1618
    $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1619
      . ' " title="' . $status['label']. '">'
1620
      . $description_element->area->representation_L10n
1621
      . $status['markup'];
1622
    if($annotations_and_sources->hasSourceReferences()){
1623
      $out .= ' ' . join(' ', $annotations_and_sources->getSourceReferences());
1624
    }
1625
    $out .= $annotations_and_sources->footNoteKeysMarkup() . '</' . $enclosingTag . '>';
1626
    $markup_array[] = $out;
1627
  }
1628

    
1629
  RenderHints::popFromRenderStack();
1630
  return markup_to_render_array(join('<span class="separator">' . $feature_block_settings['glue'] . '</span>', $markup_array));
1631
}
1632

    
1633
  /**
1634
   * @param array $distribution_status
1635
   * @return array an array with following keys
1636
   *   - 'label': the plain text status label
1637
   *   - 'markup': markup for the status
1638
   */
1639
  function distribution_status_label_and_markup(array $distribution_status, $status_glue = '&#8210; ') {
1640

    
1641
    $status_markup = '';
1642
    $status_label = '';
1643

    
1644
    foreach($distribution_status as $status) {
1645
      $status_label .= ($status_label ? $status_glue : '') . $status->representation_L10n ;
1646
      $status_markup .=  '<span class="distributionStatus"> '
1647
        . ($status_markup ? $status_glue : '')
1648
        . '<span class="distributionStatus-' . $status->idInVocabulary . '">'
1649
        .  $status->representation_L10n
1650
        . '</span></span>';
1651

    
1652
    };
1653
    return ['label' => $status_label, 'markup' => $status_markup];
1654
  }
1655

    
1656

    
1657
  /**
1658
   * Provides the merged feature tree for a taxon profile page.
1659
   *
1660
   * The merging of the profile feature tree is actually done in
1661
   * _mergeFeatureTreeDescriptions(). See this method  for details
1662
   * on the structure of the merged tree.
1663
   *
1664
   * This method provides a hook which can be used to modify the
1665
   * merged feature tree after it has been created, see
1666
   * hook_merged_taxon_feature_tree_alter()
1667
   *
1668
   * @param $taxon
1669
   *    A CDM Taxon instance
1670
   *
1671
   * @return object
1672
   *    The merged feature tree
1673
   *
1674
   */
1675
  function merged_taxon_feature_tree($taxon) {
1676

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

    
1680

    
1681
    // 2. find the distribution feature node
1682
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1683

    
1684
    if ($distribution_node) {
1685
      // 3. get the distributionInfoDTO
1686
      $query_parameters = cdm_distribution_filter_query();
1687
      $query_parameters['part'] = array('mapUriParams');
1688
      if(variable_get(DISTRIBUTION_CONDENSED)){
1689
        $query_parameters['part'][] = 'condensedDistribution';
1690
      }
1691
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1692
        $query_parameters['part'][] = 'tree';
1693
      }
1694
      else {
1695
        $query_parameters['part'][] = 'elements';
1696
      }
1697
      $query_parameters['omitLevels'] = array();
1698
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1699
        if(is_uuid($uuid)){
1700
          $query_parameters['omitLevels'][] = $uuid;
1701
        }
1702
      }
1703
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1704
      if ($customStatusColorsJson) {
1705
        $query_parameters['statusColors'] = $customStatusColorsJson;
1706
      }
1707

    
1708
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1709
      // 4. get distribution TextData is there are any
1710
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1711
        array(
1712
          'taxon' => $taxon->uuid,
1713
          'type' => 'TextData',
1714
          'features' => UUID_DISTRIBUTION
1715
        )
1716
      );
1717

    
1718
      // 5. put all distribution data into the distribution feature node
1719
      if ($distribution_text_data //if text data exists
1720
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1721
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1722
      ) { // OR if DTO has distribution elements
1723
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1724
        if ($distribution_text_data) {
1725
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1726
        }
1727
        if ($distribution_info_dto) {
1728
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1729
        }
1730
      }
1731
    }
1732

    
1733
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1734
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1735

    
1736
    return $merged_tree;
1737
  }
1738

    
1739
  /**
1740
   * @param $distribution_tree
1741
   *  A tree cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
1742
   *  and Distribution items as data array. Per data array some Distributions may
1743
   *  be with status information, others only with sources, others with both.
1744
   *  Each node may also have subordinate node items in the children field.
1745
   *  TreeNode:
1746
   *   - array data
1747
   *   - array children
1748
   *   - int numberOfChildren
1749
   *   - stdClass nodeId
1750
   *
1751
   * @param $feature_block_settings
1752
   *
1753
   * @return array
1754
   * @throws \Exception
1755
   */
1756
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1757

    
1758
    static $hierarchy_style;
1759
    // TODO expose $hierarchy_style to administration or provide a hook
1760
    if( !isset($hierarchy_style)){
1761
      $hierarchy_style = get_array_variable_merged(DISTRIBUTION_HIERARCHY_STYLE, DISTRIBUTION_HIERARCHY_STYLE_DEFAULT);
1762
    }
1763

    
1764
    $render_array = array();
1765

    
1766
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1767
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1768

    
1769
    // Returning NULL if there are no description elements.
1770
    if ($distribution_tree == null) {
1771
      return $render_array;
1772
    }
1773
    // for now we are not using a render array internally to avoid performance problems
1774
    $markup = '';
1775
    if (isset($distribution_tree->rootElement->children)) {
1776
      $tree_nodes = $distribution_tree->rootElement->children;
1777
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1778
    }
1779

    
1780
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1781
      $markup,
1782
      0,
1783
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1784
      '</div>'
1785
    );
1786

    
1787
    RenderHints::popFromRenderStack();
1788

    
1789
    return $render_array;
1790
  }
1791

    
1792
/**
1793
 * this function should produce markup as the
1794
 * compose_description_elements_distribution() function.
1795
 *
1796
 * @param array $tree_nodes
1797
 *  An array of cdm TreeNode items. A TreeNode item has a NamedArea as nodeId
1798
 *  and Distribution items as data array. Per data array some Distributions may
1799
 *  be with status information, others only with sources, others with both.
1800
 *  TreeNode:
1801
 *   - array data
1802
 *   - array children
1803
 *   - int numberOfChildren
1804
 *   - stdClass nodeId
1805
 * @param array $feature_block_settings
1806
 * @param $markup
1807
 * @param $hierarchy_style
1808
 * @param int $level_index
1809
 *
1810
 * @throws \Exception
1811
 *
1812
 * @see compose_description_elements_distribution()
1813
 * @see compose_distribution_hierarchy()
1814
 *
1815
 */
1816
  function _compose_distribution_hierarchy(array $tree_nodes, array $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1817

    
1818
    $level_index++;
1819
    static $enclosingTag = "span";
1820

    
1821
    $level_style = array_shift($hierarchy_style);
1822
    if(count($hierarchy_style) == 0){
1823
      // lowest defined level style will be reused for all following levels
1824
      $hierarchy_style[] = $level_style;
1825
    }
1826

    
1827
    $node_index = -1;
1828
    $per_node_markup = array();
1829

    
1830
    foreach ($tree_nodes as $node){
1831

    
1832
      $per_node_markup[++$node_index] = '';
1833
      $label = $node->nodeId->representation_L10n;
1834

    
1835
      $distributions = $node->data;
1836
      $distribution_uuids = array();
1837
      $distribution_aggregate = NULL;
1838
      $status = ['label' => '', 'markup' => ''];
1839

    
1840
      foreach($distributions as $distribution){
1841
        $distribution_uuids[] = $distribution->uuid;
1842
        // if there is more than one distribution we aggregate the sources and
1843
        // annotations into a synthetic distribution so that the footnote keys
1844
        // can be rendered consistently
1845
        if(!$distribution_aggregate) {
1846
          $distribution_aggregate = $distribution;
1847
          if(isset($distribution->status)){
1848
            $distribution_aggregate->status = [$distribution->status];
1849
          } else {
1850
            $distribution_aggregate->status = [];
1851
          }
1852
          if(!isset($distribution_aggregate->sources[0])){
1853
            $distribution_aggregate->sources = array();
1854
          }
1855
          if(!isset($distribution_aggregate->annotations[0])){
1856
            $distribution_aggregate->annotations = array();
1857
          }
1858
        } else {
1859
          if(isset($distribution->status)){
1860
            $distribution_aggregate->status[] = $distribution->status;
1861
          }
1862
          if(isset($distribution->sources[0])) {
1863
            $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1864
              $distribution->sources);
1865
          }
1866
          if(isset($distribution->annotations[0])) {
1867
            $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1868
              $distribution->annotations);
1869
          }
1870
        }
1871
      }
1872

    
1873
      $annotations_and_sources =  null;
1874
      if($distribution_aggregate) {
1875
        RenderHints::setAnnotationsAndSourceConfig(handle_annotations_and_sources_config($feature_block_settings));
1876
        $annotations_and_sources = handle_annotations_and_sources(
1877
          $distribution_aggregate, $label, UUID_DISTRIBUTION
1878
        );
1879
        $status = distribution_status_label_and_markup($distribution_aggregate->status, $level_style['status_glue']);
1880
      }
1881

    
1882
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1883
        . join(' descriptionElement-', $distribution_uuids)
1884
        . ' level_index_' . $level_index
1885
        . ' " title="' . $status['label'] . '">'
1886
        . '<span class="area_label">' . $label
1887
        . $level_style['label_suffix'] . '</span>'
1888
        . $status['markup']
1889
      ;
1890

    
1891
      if(isset($annotations_and_sources)){
1892
        if($annotations_and_sources->hasSourceReferences()){
1893
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources->getSourceReferences());
1894
        }
1895
        if($annotations_and_sources->hasFootnoteKeys()) {
1896
          $per_node_markup[$node_index] .= $annotations_and_sources->footNoteKeysMarkup();
1897
        }
1898
      }
1899

    
1900
      if(isset($node->children[0])){
1901
        $per_node_markup[$node_index] .= $level_style['item_suffix'];
1902
        _compose_distribution_hierarchy(
1903
          $node->children,
1904
          $feature_block_settings,
1905
          $per_node_markup[$node_index],
1906
          $hierarchy_style,
1907
          $level_index
1908
        );
1909
      }
1910

    
1911
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1912
    }
1913
    $markup .= $level_style['item_group_prefix']  . join( $level_style['item_glue'], $per_node_markup) . $level_style['item_group_postfix'];
1914
  }
1915

    
1916

    
1917
/**
1918
 * Provides the content for a block of Uses Descriptions for a given taxon.
1919
 *
1920
 * Fetches the list of TaxonDescriptions tagged with the MARKERTYPE_USE
1921
 * and passes them to the theme function theme_cdm_UseDescription().
1922
 *
1923
 * @param string $taxon_uuid
1924
 *   The uuid of the Taxon
1925
 *
1926
 * @return array
1927
 *   A drupal render array
1928
 */
1929
function cdm_block_use_description_content($taxon_uuid, $feature) {
1930

    
1931
  $use_description_content = array();
1932

    
1933
  if (is_uuid($taxon_uuid )) {
1934
    $markerTypes = array();
1935
    $markerTypes['markerTypes'] = UUID_MARKERTYPE_USE;
1936
    $useDescriptions = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXON . '/' . $taxon_uuid . '/descriptions', $markerTypes);
1937
    if (!empty($useDescriptions)) {
1938
      $use_description_content = compose_feature_block_items_use_records($useDescriptions, $taxon_uuid, $feature);
1939
    }
1940
  }
1941

    
1942
  return $use_description_content;
1943
}
1944

    
1945
/**
1946
 * Creates a trunk of a feature object which can be used to build pseudo feature blocks like the Bibliography.
1947
 *
1948
 * @param $representation_L10n
1949
 * @param String $pseudo_feature_key
1950
 *    Will be set as uuid but should be one of 'BIBLIOGRAPHY', ... more to come. See also get_feature_block_settings()
1951
 *
1952
 * @return object
1953
 *  The feature object
1954
 */
1955
function make_pseudo_feature($representation_L10n, $pseudo_feature_key = null){
1956
  $feature = new stdClass;
1957
  $feature->representation_L10n = $representation_L10n;
1958
  $feature->uuid = NULL; // $pseudo_feature_key;
1959
  $feature->label = $pseudo_feature_key;
1960
  $feature->class = 'PseudoFeature';
1961

    
1962
  return $feature;
1963

    
1964
}
1965

    
1966
/**
1967
 * @param $root_nodes, for obtaining the  root nodes from a description you can
1968
 * use the function get_root_nodes_for_dataset($description);
1969
 *
1970
 * @return string
1971
 */
1972
function render_description_string($root_nodes, &$item_cnt = 0) {
1973

    
1974
  $out = '';
1975

    
1976
  $description_strings= [];
1977
  if (!empty($root_nodes)) {
1978
    foreach ($root_nodes as $root_node) {
1979
      if(isset($root_node->descriptionElements)) {
1980
        foreach ($root_node->descriptionElements as $element) {
1981
          $feature_label = $element->feature->representation_L10n;
1982
          if($item_cnt == 0){
1983
            $feature_label = ucfirst($feature_label);
1984
          }
1985
          switch ($element->class) {
1986
            case 'CategoricalData':
1987
              $state_data = render_state_data($element);
1988
              if (!empty($state_data)) {
1989
                if(is_suppress_state_present_display($element, $root_node)){
1990
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: '  . '</span>';
1991
                } else {
1992
                  $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . $state_data . '</span>;' ;
1993
                }
1994
              }
1995
              break;
1996
            case 'QuantitativeData':
1997
              $description_strings[] = '<span class="'. html_class_attribute_ref($element) .'"><span class="label">' . $feature_label . '</span>: ' . render_quantitative_statistics($element) . '</span>;';
1998
              break;
1999
          }
2000
        }
2001
        $item_cnt++;
2002
      }
2003

    
2004
      // recurse child nodes
2005
      $child_markup = render_description_string($root_node->childNodes, $item_cnt);
2006
      if($child_markup){
2007
        $description_strings[] = $child_markup;
2008
      }
2009
    }
2010
    if(count($description_strings) > 0){
2011
      // remove last semicolon
2012
      $description_strings[count($description_strings) - 1] = preg_replace('/;$/', '', $description_strings[count($description_strings) - 1]);
2013
    }
2014
    $out  = join(' ', $description_strings);
2015
  }
2016
  return $out;
2017
}
2018

    
2019
/**
2020
 * Compose a description as a table of Feature<->State
2021
 *
2022
 * @param $description_uuid
2023
 *
2024
 * @return array
2025
 *    The drupal render array for the page
2026
 *
2027
 * @ingroup compose
2028
 */
2029
function  compose_description_table($description_uuid, $descriptive_dataset_uuid = NULL) {
2030

    
2031
  RenderHints::pushToRenderStack('description_table');
2032

    
2033
  $render_array = [];
2034

    
2035
  $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, [$description_uuid]);
2036
  $dataSet = NULL;
2037
  // dataset passed as parameter
2038
  if ($descriptive_dataset_uuid != NULL) {
2039
    foreach ($description->descriptiveDataSets as $set) {
2040
      if ($set->uuid == $descriptive_dataset_uuid) {
2041
        $dataSet = $set;
2042
        break;
2043
      }
2044
    }
2045
  }
2046

    
2047
  if(!empty($description->descriptiveDataSets)) {
2048
    // only one dataset present
2049
    if (!isset($dataSet) && sizeof($description->descriptiveDataSets) == 1) {
2050
      foreach ($description->descriptiveDataSets as $dataSet) {
2051
        break;
2052
      }
2053
    }
2054

    
2055
    // generate description title
2056
    RenderHints::pushToRenderStack('title');
2057
    if (isset($dataSet)) {
2058

    
2059
      $described_entity_title = NULL;
2060
      if(isset($description->describedSpecimenOrObservation)){
2061
        $described_entity_title = $description->describedSpecimenOrObservation->titleCache;
2062
      } else if($description->taxon) {
2063
          $described_entity_title = render_taxon_or_name($description->taxon);
2064
      }
2065
      $title = 'Descriptive Data ' . $dataSet->titleCache .
2066
        ($described_entity_title ? ' for ' . $described_entity_title : '');
2067
    }
2068
    $render_array['title'] = markup_to_render_array($title, null, '<h3 class="title">', '</h3>');
2069
    RenderHints::popFromRenderStack();
2070
    // END of --- generate description title
2071

    
2072
    if (isset($description->types)) {
2073
      foreach ($description->types as $type) {
2074
        if ($type == 'CLONE_FOR_SOURCE') {
2075
          $render_array['source'] = markup_to_render_array("Aggregation source from " . $description->created, null, '<div class="date-created">', '</div>');
2076
          break;
2077
        }
2078
      }
2079
    }
2080
  }
2081
  // multiple datasets present see #8714 "Show multiple datasets per description as list of links"
2082
  else {
2083
    $items = [];
2084
    foreach ($description->descriptiveDataSets as $dataSet) {
2085
      $path = path_to_description($description->uuid, $dataSet->uuid);
2086
      $attributes['class'][] = html_class_attribute_ref($description);
2087
      $items[] = [
2088
        'data' => $dataSet->titleCache . icon_link($path),
2089
      ];
2090
    }
2091
    $render_array['description_elements'] = [
2092
      '#title' => 'Available data sets for description',
2093
      '#theme' => 'item_list',
2094
      '#type' => 'ul',
2095
      '#items' => $items,
2096
    ];
2097
  }
2098

    
2099
  $described_entities = [];
2100
  if (isset($description->describedSpecimenOrObservation)) {
2101
    $decr_entitiy = '<span class="label">Specimen:</span> ' . render_cdm_specimen_link($description->describedSpecimenOrObservation);
2102
    $described_entities['specimen'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2103
  }
2104
  if (isset($description->taxon)) {
2105
    $decr_entitiy = '<span class="label">Taxon:</span> ' . render_taxon_or_name($description->taxon, url(path_to_taxon($description->taxon->uuid)));
2106
    $described_entities['taxon'] = markup_to_render_array($decr_entitiy, null, '<div>', '</div>');
2107
  }
2108

    
2109
  if(count($described_entities)){
2110
    $render_array['described_entities'] = $described_entities;
2111
    $render_array['described_entities']['#prefix'] = '<div class="described-entities">';
2112
    $render_array['described_entities']['#suffix'] = '</div>';
2113
  }
2114

    
2115

    
2116
  $root_nodes = get_root_nodes_for_dataset($description);
2117

    
2118

    
2119
  $rows = [];
2120
  $rows = description_element_table_rows($root_nodes, $rows);
2121

    
2122
  // --- create headers
2123
  $header = [0 => [], 1 => []];
2124

    
2125
  foreach($rows as $row) {
2126
    if(array_search('Character', $row['class']) && array_search('Character', $header[0]) === false){
2127
      $header[0][] = 'Character';
2128
    } elseif (array_search('Feature', $row['class']) && array_search('Feature', $header[0]) === false){
2129
      $header[0][] = 'Feature';
2130
    }
2131
    if(array_search('has_state', $row['class']) && array_search('States', $header[1]) === false){
2132
      $header[1][] = 'States';
2133
    } elseif (array_search('has_values', $row['class']) && array_search('Values', $header[1]) === false){
2134
      $header[1][] = 'Values';
2135
    }
2136
  }
2137
  asort($header[0]);
2138
  asort($header[1]);
2139
  $header[0] = join('/', $header[0]);
2140
  $header[1] = join('/', $header[1]);
2141

    
2142
  // ---
2143

    
2144
  if (!empty($rows)) {
2145
    $render_array['table'] = markup_to_render_array(theme('table', [
2146
      'header' => $header,
2147
      'rows' => $rows,
2148
      'caption' => statistical_values_explanation(),
2149
      'title' => "Table"
2150
    ]));
2151
  }
2152

    
2153
  // --- sources
2154
  if (isset($description->sources) and !empty($description->sources)) {
2155
    $items = [];
2156
    foreach ($description->sources as $source) {
2157
      if ($source->type == 'Aggregation' and isset($source->cdmSource)){
2158
        $cdm_source_entity = $source->cdmSource;
2159
        switch($cdm_source_entity->class){
2160
          case 'Taxon':
2161
            $source_link_markup = render_taxon_or_name($cdm_source_entity) . icon_link(path_to_taxon($cdm_source_entity->uuid, false));
2162
            break;
2163
          case 'TaxonDescription':
2164
          case 'NameDescription':
2165
          case 'SpecimenDescription':
2166
            $source_link_markup = render_cdm_entity_link($cdm_source_entity);
2167
            break;
2168
          default:
2169
            $source_link_markup = '<span class="error">Unhandled CdmSource</span>';
2170
        }
2171
        $items[$cdm_source_entity->titleCache] = [
2172
          'data' => $source_link_markup
2173
        ];
2174
      }
2175
    }
2176
    ksort($items);
2177
    $render_array['sources'] = [
2178
      '#title' => 'Sources',
2179
      '#theme' => 'item_list',
2180
      '#type' => 'ul',
2181
      '#items' => $items,
2182
      '#attributes' => ['class' => 'sources']
2183
    ];
2184
    $render_array['#prefix'] = '<div class="description-table">';
2185
    $render_array['#suffix'] = '</div>';
2186
  }
2187

    
2188
  RenderHints::popFromRenderStack();
2189

    
2190
  return $render_array;
2191
}
2192

    
2193
/**
2194
 * For a given description returns the root nodes according to the
2195
 *corresponding term tree. The term tree is determined as follow:
2196
 * 1. If description is part of a descriptive data set the term tree of that
2197
 *    data set is used (FIXME handle multiple term trees)
2198
 * 2. Otherwise the portal taxon profile tree is used
2199
 * @param $description
2200
 *
2201
 * @return array
2202
 */
2203
function get_root_nodes_for_dataset($description) {
2204
  if (!empty($description->descriptiveDataSets)) {
2205
    foreach ($description->descriptiveDataSets as $dataSet) {
2206
      break;// FIXME handle multiple term trees
2207
    }
2208
    $tree = cdm_ws_get(CDM_WS_TERMTREE, $dataSet->descriptiveSystem->uuid);
2209
    $root_nodes = _mergeFeatureTreeDescriptions($tree->root->childNodes, $description->elements);
2210
  }
2211
  else {
2212
    $root_nodes = _mergeFeatureTreeDescriptions(get_profile_feature_tree()->root->childNodes, $description->elements);
2213
  }
2214
  return $root_nodes;
2215
}
2216

    
2217
/**
2218
 * Recursively creates an array of row items to be used in theme_table.
2219
 *
2220
 * The array items will have am element 'class' with information on the
2221
 * nature of the DescriptionElement ('has_values' | 'has_state') and on the
2222
 * type of the FeatureNode ('Feature' | 'Character')
2223
 *
2224
 * @param array $root_nodes
2225
 * @param array $row_items
2226
 * @param int $level
2227
 *     the depth in the hierarchy
2228
 *
2229
 * @return array
2230
 *  An array of row items to be used in theme_table
2231
 *
2232
 *
2233
 */
2234
function description_element_table_rows($root_nodes, $row_items, $level = 0) {
2235

    
2236
  $indent_string = '&nbsp;&nbsp;&nbsp;';
2237
  foreach ($root_nodes as $root_node) {
2238
    if(isset($root_node->descriptionElements)) {
2239
      foreach ($root_node->descriptionElements as $element) {
2240
        $level_indent = str_pad('', $level * strlen($indent_string), $indent_string);
2241
        switch ($element->class) {
2242
          case 'QuantitativeData':
2243
            $row_items[] = [
2244
              'data' => [
2245
                [
2246
                  'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2247
                  'class' => ['level_' . $level]
2248
                ],
2249
                render_quantitative_statistics($element)
2250
              ],
2251
              'class' => ['level_' . $level, 'has_values', $element->feature->class]
2252
            ];
2253
            break;
2254
          case 'CategoricalData':
2255
            default:
2256
            if (!empty($element->stateData)) {
2257
              $supress_state_display = is_suppress_state_present_display($element, $root_node);
2258
              if(!$supress_state_display){
2259
                $state_cell = render_state_data($element);
2260
              } else {
2261
                $state_cell = "<span> </span>";
2262
              }
2263
              $row_items[] = [
2264
                'data' => [
2265
                  [
2266
                    'data' => markup_to_render_array($level_indent . $element->feature->representation_L10n),
2267
                    'class' => ['level_' . $level]
2268
                  ],
2269
                  $state_cell,
2270
                ],
2271
                'class' => ['level_' . $level, 'has_state', $element->feature->class]
2272
              ];
2273
            }
2274
            break;
2275
        }
2276
      }
2277
    }
2278
    // recurse child nodes
2279
    $row_items = description_element_table_rows($root_node->childNodes, $row_items, $level + 1);
2280
  }
2281
  return $row_items;
2282
}
2283

    
2284
/**
2285
 * @param $element
2286
 * @param $root_node
2287
 *
2288
 * @return bool
2289
 */
2290
function is_suppress_state_present_display($element, $root_node) {
2291
  return count($element->stateData) == 1 & $element->stateData[0]->state->representation_L10n == 'present' && is_array($root_node->childNodes);
2292
}
2293

    
2294

    
2295

    
(3-3/16)