Project

General

Profile

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

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

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

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

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

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

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

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

    
91
  return $query;
92
}
93

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

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

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

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

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

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

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

    
157
}
158

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

    
170
  return $toc_list_items;
171
}
172

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

    
200

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

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

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

    
236
  }
237

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

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

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

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

    
268

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

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

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

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

    
320

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

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

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

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

    
357

    
358

    
359
/**
360
 * @param $render_array
361
 * @param $element
362
 * @param $feature_block_settings
363
 * @param $element_markup
364
 * @param $footnote_list_key_suggestion
365
 */
366
function cdm_description_element_render_array_add_annotations_and_sources(&$render_array, $element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion)
367
{
368
  $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element_markup, $footnote_list_key_suggestion);
369

    
370
  $names_used_in_source_markup = '';
371
  if (!empty($annotations_and_sources['names_used_in_source']) && empty($element_markup)) {
372
    // $element_text ==  NULL  usually occurs only in the case of CITATIONS!!!
373
    $names_used_in_source_markup = join(', ', $annotations_and_sources['names_used_in_source']) . ': ';
374
  }
375

    
376
  $source_references_markup = '';
377
  if (!empty($annotations_and_sources['source_references'])) {
378
    $source_references_markup = '<span class="sources">' . join(' ', $annotations_and_sources['source_references']) . '<span>';
379
  }
380

    
381
  $render_array['#value'] = $names_used_in_source_markup . $element_markup . $source_references_markup;
382
  $render_array['#value_suffix'] = $annotations_and_sources['foot_note_keys'];
383
}
384

    
385

    
386
  /**
387
   * @param $element
388
   * @param $feature_block_settings
389
   * @param $element_text
390
   *   used to decide if the source references should be enclosed in brackets or not
391
   * @param $footnote_list_key_suggestion
392
   * @return array
393
   *   an associative array with the following elements:
394
   *   - foot_note_keys: all footnote keys as markup
395
   *   - source_references: an array of the source references citations
396
   *   - names used in source: an associative array of the names in source,
397
   *        the name in source strings are de-duplicated
398
   *        !!!NOTE!!!!: this field will most probably be removed soon (TODO)
399
   *
400
   *
401
   */
402
  function handle_annotations_and_sources($element, $feature_block_settings, $element_text, $footnote_list_key_suggestion) {
403
    $annotations_and_sources = array(
404
      'foot_note_keys' => NULL,
405
      'source_references' => array(),
406
      'names_used_in_source' => array()
407
    );
408

    
409
    usort($element->sources, 'compare_original_sources');
410

    
411
    if ($feature_block_settings['sources_as_content'] == 1) {
412
      foreach ($element->sources as $source) {
413

    
414
        $referenceCitation = theme('cdm_OriginalSource',
415
          array(
416
            'source' => $source,
417
            'doLink' => $feature_block_settings['link_to_reference'] == 1,
418
            'do_link_to_name_used_in_source' => $feature_block_settings['link_to_name_used_in_source'] == 1,
419
          )
420
        );
421

    
422
        if ($referenceCitation) {
423
          if (empty($element_text)) {
424
            $annotations_and_sources['source_references'][] = $referenceCitation;
425
          }
426
          else {
427
            $annotations_and_sources['source_references'][] = ' (' . $referenceCitation . ')';
428
          }
429
        }
430

    
431
        $name_in_source_render_array = compose_name_in_source(
432
          $source,
433
          $feature_block_settings['link_to_name_used_in_source'] == 1
434
        );
435

    
436
        if(!empty($name_in_source_render_array)){
437
          $annotations_and_sources['names_used_in_source'][$name_in_source_render_array['#_plaintext']] = drupal_render($name_in_source_render_array);
438
        }
439
      } // END of loop over sources
440

    
441
      // annotations footnotes separate.
442
      $annotations_and_sources['foot_note_keys'] = theme('cdm_annotations_as_footnotekeys',
443
        array(
444
          'cdmBase_list' => $element,
445
          'footnote_list_key' => $footnote_list_key_suggestion,
446
        )
447
      );
448

    
449
    } // END of references inline
450

    
451
    // put sources into bibliography if requested ...
452
    if ($feature_block_settings['sources_as_content'] !== 1 || $feature_block_settings['sources_as_content_to_bibliography'] == 1) {
453
      $annotations_and_sources['foot_note_keys'] = cdm_create_description_element_footnotes(
454
        $element, ',',
455
        $footnote_list_key_suggestion,
456
        $feature_block_settings['link_to_reference'] == 1,
457
        $feature_block_settings['link_to_name_used_in_source'] == 1
458
      );
459
    }
460

    
461
    return $annotations_and_sources;
462
  }
463

    
464

    
465
  /**
466
   *
467
   *
468
   * @return string
469
   *  the footnote_list_key
470
   */
471
  function original_source_footnote_list_key($key_suggestion = null) {
472
    if(!$key_suggestion){
473
      $key_suggestion = RenderHints::getFootnoteListKey();
474
    }
475
    $bibliography_settings = get_bibliography_settings();
476
    $footnote_list_key = $bibliography_settings['enabled'] == 1 ? 'BIBLIOGRAPHY' : 'BIBLIOGRAPHY-' . $key_suggestion;
477
    return $footnote_list_key;
478
  }
479

    
480
  /**
481
   * Provides the according tag name for the description element markup which fits the  $feature_block_settings['as_list'] value
482
   *
483
   * @param $feature_block_settings
484
   *   A feature_block_settings array, for details, please see get_feature_block_settings($feature_uuid = 'DEFAULT')
485
   */
486
  function cdm_feature_block_element_tag_name($feature_block_settings){
487
    switch ($feature_block_settings['as_list']){
488
      case 'ul':
489
      case 'ol':
490
        return 'li';
491
      case 'div':
492
        if(isset($feature_block_settings['element_tag'])){
493
          return $feature_block_settings['element_tag'];
494
        }
495
        return 'span';
496
      case 'dl':
497
        return 'dd';
498
      default:
499
        return 'div'; // should never happen, throw error instead?
500
    }
501
  }
502

    
503

    
504
/* ==================== COMPOSE FUNCTIONS =============== */
505

    
506
  /**
507
   * Returns a set of feature blocks for a taxon profile from the $mergedFeatureNodes of a given $taxon.
508
   *
509
   * The taxon profile consists of drupal block elements, one for the description elements
510
   * of a specific feature. The structure is defined by specific FeatureTree.
511
   * The chosen FeatureTree is merged with the list of description elements prior to using this method.
512
   *
513
   * The merged nodes can be obtained by making use of the
514
   * function cdm_ws_descriptions_by_featuretree().
515
   *
516
   * @see cdm_ws_descriptions_by_featuretree()
517
   *
518
   * @param $mergedFeatureNodes
519
   *
520
   * @param $taxon
521
   *
522
   * @return array
523
   *  A Drupal render array containing feature blocks and the table of content
524
   *
525
   * @ingroup compose
526
   */
527
  function compose_feature_blocks($mergedFeatureNodes, $taxon) {
528

    
529
    $block_list = array();
530

    
531
    RenderHints::pushToRenderStack('feature_nodes');
532

    
533
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME);
534

    
535
    // Create a drupal block for each feature
536
    foreach ($mergedFeatureNodes as $node) {
537

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

    
541
        $feature_name = cdm_term_representation($node->feature, 'Unnamed Feature');
542

    
543
        $block = feature_block($feature_name, $node->feature);
544
        $block->content = array();
545
        $block_content_is_empty = TRUE;
546
        $block_content_weight = 0;
547

    
548
        /*
549
         * Content/DISTRIBUTION.
550
         */
551

    
552
        if ($node->feature->uuid == UUID_DISTRIBUTION) {
553
          $block = compose_feature_block_distribution($taxon, $node->descriptionElements, $node->feature);
554
          $block_content_is_empty = FALSE;
555
        }
556
        /*
557
         * Content/COMMON_NAME.
558
         */
559
        else if ($node->feature->uuid == UUID_COMMON_NAME) {
560
          $common_names_render_array = compose_feature_block_items_feature_common_name($node->descriptionElements, $node->feature);
561
          $block->content[] = $common_names_render_array;
562
          $block_content_is_empty = FALSE;
563
        }
564

    
565
        else if ($node->feature->uuid == UUID_USE_RECORD) {
566
          $block_uses_content_html = theme('cdm_block_Uses', array('taxonUuid' => $taxon->uuid));
567
          $block->content[] = markup_to_render_array($block_uses_content_html);
568
          $block_content_is_empty = FALSE;
569
        }
570

    
571
        /*
572
         * Content/ALL OTHER FEATURES.
573
         */
574
        else {
575

    
576
          $media_list = array();
577
          $out_child_elements = '';
578

    
579
          if (isset($node->descriptionElements)) {
580
            $taxon_uuid = NULL;
581
            if(isset($taxon) ) {
582
              $taxon_uuid = $taxon->uuid;
583
            }
584
            $elements_render_array = compose_feature_block_items_generic($node->descriptionElements, $node->feature, $taxon_uuid);
585
            $block_content_is_empty = empty($elements_render_array);
586
            $block->content[] = $elements_render_array;
587
          }
588

    
589
          // Content/ALL OTHER FEATURES/Subordinate Features
590
          // subordinate features are printed inline in one floating text,
591
          // it is expected hat subordinate features can "contain" TextData,
592
          // Qualitative- and Qualitative- DescriptioneElements
593
          if (isset($node->childNodes[0])) {
594

    
595
            // TODO support more than one level of children.
596
            // can this be solved by recursively calling this function?
597
            // @see http://dev.e-taxonomy.eu/trac/ticket/2393
598
            $text = '';
599
            foreach ($node->childNodes as $child) {
600

    
601
              if (isset($child->descriptionElements) && is_array($child->descriptionElements)) {
602
                foreach ($child->descriptionElements as $element) {
603

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

    
606
                  if (is_array($element->media)) {
607
                    // Append media of subordinate elements to list of main
608
                    // feature.
609
                    $media_list = array_merge($media_list, $element->media);
610
                  }
611

    
612
                  switch ($element->class) {
613
                    case 'TextData':
614
                      // FIXME use compose_description_element_textdata()
615
                      if(isset($element->multilanguageText_L10n->text)){
616
                        $out_child_elements = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
617
                      }
618
                      $out_child_elements = str_replace($child->feature->titleCache, '<em>' . $child->feature->representation_L10n . '</em>', $out_child_elements);
619
                      break;
620
                    case 'CategoricalData':
621
                      $out_child_elements  = '<em>' . $child->feature->representation_L10n . '</em> '
622
                        . theme('cdm_descriptionElement_CategoricalData', array('element' => $element));
623
                      break;
624
                    case 'QuantitativeData':
625
                      $out_child_elements = '<em>' . $child->feature->representation_L10n . '</em> '
626
                        . theme('cdm_descriptionElement_QuantitativeData', array('element' => $element));
627

    
628
                  }
629

    
630
                }
631
                $text .= " " . $out_child_elements;
632
                $out_child_elements = '';
633
              }
634
            }
635
            $block_content_is_empty = $block_content_is_empty && empty($text);
636
            $block->content[] = markup_to_render_array($text);
637
            $block_content_is_empty = $block_content_is_empty && empty($media_list);
638
          }
639

    
640
          $block->content[] = compose_feature_media_gallery($node, $media_list, $gallery_settings);
641
          /*
642
           * Footnotes for the feature block
643
           */
644
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $node->feature->uuid)));
645
          $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => $node->feature->uuid)));
646
          $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => $node->feature->uuid)));
647
        } // END all other features
648

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

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

    
659
    drupal_alter('cdm_feature_node_blocks', $block_list, $taxon);
660

    
661
    RenderHints::popFromRenderStack();
662

    
663
    return _block_get_renderable_array($block_list);
664
  }
665

    
666
  /**
667
   * @param $node
668
   * @param $media_list
669
   * @param $gallery_settings
670
   * @return array
671
   */
672
  function compose_feature_media_gallery($node, $media_list, $gallery_settings) {
673

    
674
    if (isset($node->descriptionElements)) {
675
      $media_list = array_merge($media_list, cdm_dataportal_media_from_descriptionElements($node->descriptionElements));
676
    }
677

    
678
    $captionElements = array('title', 'rights');
679

    
680
    if (isset($media_list[0]) && isset($gallery_settings['cdm_dataportal_media_maxextend']) && isset($gallery_settings['cdm_dataportal_media_cols'])) {
681
      $gallery = theme('cdm_media_gallerie', array(
682
        'mediaList' => $media_list,
683
        'galleryName' => CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME . '_' . $node->feature->uuid,
684
        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
685
        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
686
        'captionElements' => $captionElements,
687
      ));
688
      return markup_to_render_array($gallery);
689
    }
690

    
691
    return markup_to_render_array('');
692
  }
693

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

    
715
    $distributionElements = NULL;
716
    $distribution_info_dto = NULL;
717
    $distribution_sortOutArray = FALSE;
718

    
719
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
720

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

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

    
735
    $block = feature_block(
736
      cdm_term_representation($feature, 'Unnamed Feature'),
737
      $feature
738
    );
739

    
740
    // $$descriptionElements['TextData'] is added to to the feature node in merged_taxon_feature_tree()
741
    if (isset($descriptionElements['TextData'])) {
742
      // --- TextData
743
      foreach ($descriptionElements['TextData'] as $text_data_element) {
744
        $asListElement = FALSE;
745
        $text_data_render_array = compose_description_element_textdata($text_data_element, $asListElement, $text_data_element->feature->uuid);
746
        $repr = drupal_render($text_data_render_array);
747

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

    
761

    
762
    if ($text_data_out_array && variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
763
      $block->content[] = compose_feature_block_elements(
764
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
765
      );
766
    }
767

    
768
    // --- Distribution map
769
    $distribution_map_query_parameters = NULL;
770
    if (isset($descriptionElements['DistributionInfoDTO'])) {
771
      $distribution_map_query_parameters = $descriptionElements['DistributionInfoDTO']->mapUriParams;
772
    }
773
    $map_render_element = compose_distribution_map($taxon, $distribution_map_query_parameters);
774
    $block->content[] = $map_render_element;
775

    
776
    $dto_out_array = array();
777

    
778
    // --- Condensed Distribution
779
    if(variable_get(DISTRIBUTION_CONDENSED) && isset($descriptionElements['DistributionInfoDTO']->condensedDistribution)){
780
      $condensed_distribution_markup = '<p class="condensed_distribution">';
781

    
782
      $isFirst = true;
783
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous[0])){
784
        foreach($descriptionElements['DistributionInfoDTO']->condensedDistribution->indigenous as $cdItem){
785
          if(!$isFirst){
786
            $condensed_distribution_markup .= ' ';
787
          }
788
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->idInVocabulary . '">'
789
          . $cdItem->areaStatusLabel . '</span>';
790
          $isFirst = false;
791
        }
792
      }
793

    
794
      if(isset($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign[0])) {
795
        if(!$isFirst){
796
          $condensed_distribution_markup .= ' ';
797
        }
798
        $isFirst = TRUE;
799
        $condensed_distribution_markup .= '[';
800
        foreach ($descriptionElements['DistributionInfoDTO']->condensedDistribution->foreign as $cdItem) {
801
          if (!$isFirst) {
802
            $condensed_distribution_markup .= ' ';
803
          }
804
          $condensed_distribution_markup .= '<span class="status_' . $cdItem->status->titleCache . '">'
805
            . $cdItem->areaStatusLabel . '</span>';
806
          $isFirst = false;
807
        }
808
        $condensed_distribution_markup .= ']';
809
      }
810

    
811
      $condensed_distribution_markup .= '&nbsp;' . l(
812
          font_awesome_icon_markup(
813
            'fa-info-circle',
814
            array(
815
              'alt'=>'help',
816
              'class' => array('superscript')
817
            )
818
          ),
819
          'cdm_dataportal/help/condensed_distribution',
820
          array('html' => TRUE));
821
      $condensed_distribution_markup .= '</p>';
822
      $dto_out_array[] = $condensed_distribution_markup;
823
    }
824

    
825
    // --- tree or list
826
    if (isset($descriptionElements['DistributionInfoDTO'])) {
827
      $distribution_info_dto = $descriptionElements['DistributionInfoDTO'];
828

    
829
      // --- tree
830
      if (is_object($distribution_info_dto->tree)) {
831
        $distribution_tree_render_array = compose_distribution_hierarchy($distribution_info_dto->tree, $feature_block_settings);
832
        $dto_out_array[] = drupal_render($distribution_tree_render_array);
833
      }
834

    
835
      // --- sorted element list
836
      if (is_array($distribution_info_dto->elements) && count($distribution_info_dto->elements) > 0) {
837
        foreach ($distribution_info_dto->elements as $descriptionElement) {
838
          if (is_object($descriptionElement->area)) {
839
            $sortKey = $descriptionElement->area->representation_L10n;
840
            $distributionElements[$sortKey] = $descriptionElement;
841
          }
842
        }
843
        ksort($distributionElements);
844
        $distribution_element_render_array = compose_description_elements_distribution($distributionElements);
845
        $dto_out_array[] = drupal_render($distribution_element_render_array);
846

    
847
      }
848
      //
849
      $block->content[] = compose_feature_block_elements(
850
        $dto_out_array, $feature, $distribution_glue, $distribution_sortOutArray
851
      );
852
    }
853

    
854
    // --- TextData at the bottom
855
    if ($text_data_out_array && !variable_get(DISTRIBUTION_TEXTDATA_DISPLAY_ON_TOP, 0)) {
856
      $block->content[] = compose_feature_block_elements(
857
        $text_data_out_array, $feature, $text_data_glue, $text_data_sortOutArray
858
      );
859
    }
860

    
861
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . UUID_DISTRIBUTION)));
862
    $block->content[] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
863
    $block->content[] = markup_to_render_array(theme('cdm_annotation_footnotes', array('footnoteListKey' => UUID_DISTRIBUTION)));
864

    
865
    return $block;
866
  }
867

    
868

    
869
  /**
870
   * Composes a drupal render array for single CDM TextData description element.
871
   *
872
   * @param $element
873
   *    The CDN TextData  description element.
874
   * @param $asListElement
875
   *    A boolean which determines whether the citations should
876
   *     be rendered as a list or not.
877
   *    TODO remove and replace $asListElement by $feature_block_settings['as_list']
878
   *  @param $feature_uuid
879
   *
880
   * @return array
881
   *   A drupal render array with the following elements being used:
882
   *    - #tag: either 'div', 'li', ...
883
   *    ⁻ #attributes: class attributes
884
   *    - #value_prefix: (optionally) contains footnote anchors
885
   *    - #value: contains the textual content
886
   *    - #value_suffix: (optionally) contains footnote keys
887
   *
888
   * @ingroup compose
889
   */
890
  function compose_description_element_textdata($element, $asListElement, $feature_uuid) {
891

    
892
    $footnote_list_key_suggestion = $feature_uuid;
893

    
894
    // FIXME $feature_block_settings should be passed as parameter!!!!!
895
    $feature_block_settings = get_feature_block_settings($feature_uuid);
896

    
897
    // FIXME remove this hack ---------------------------
898
    $default_theme = variable_get('theme_default', NULL);
899
    if($default_theme == 'garland_cichorieae' || $default_theme == 'cyprus'
900
      || $default_theme == 'flore_afrique_centrale' || $default_theme == 'flora_malesiana' || $default_theme == 'flore_gabon' ){
901
      $asListElement = $feature_block_settings['as_list'] == 'ul';
902
    }
903
    // --------------------------------------------------
904

    
905
    $render_array = array(
906
      '#type' => 'html_tag',
907
      '#tag' => $asListElement ? 'li' : 'span',
908
      '#attributes' => array(
909
        'class' => 'DescriptionElement DescriptionElement-' . $element->class . '
910
      ' .  html_class_attribute_ref($element)
911
      ),
912
      '#value' => '',
913
      '#value_suffix' => NULL
914
    );
915

    
916
    $element_text = '';
917
    if (isset($element->multilanguageText_L10n->text)) {
918
      // TODO replacement of \n by <br> should be configurable
919
      $element_text = str_replace("\n", "<br/>", $element->multilanguageText_L10n->text);
920
    }
921

    
922
    cdm_description_element_render_array_add_annotations_and_sources($render_array, $element, $feature_block_settings, $element_text, $footnote_list_key_suggestion);
923

    
924
    return $render_array;
925
  }
926

    
927

    
928
/**
929
 * Renders a single instance of the type IndividualsAssociations.
930
 *
931
 * @param $element
932
 *   The CDM IndividualsAssociations entity.
933
 * @param $feature_block_settings
934
 *
935
 * @return array
936
 *   Drupal render array
937
 *
938
 * @ingroup compose
939
 */
940
function compose_description_element_individuals_association($element, $feature_block_settings) {
941

    
942
  $out = '';
943
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
944

    
945
  $render_array = compose_cdm_specimenOrObservation($element->associatedSpecimenOrObservation);
946

    
947
  if (isset($element->description_L10n)) {
948
    $out .=  ' ' . $element->description_L10n;
949
  }
950

    
951
  $out .= drupal_render($render_array);
952

    
953
  $annotations_and_sources = handle_annotations_and_sources(
954
    $element,
955
    $feature_block_settings,
956
    $out, // the description element text
957
    $element->feature->uuid
958
  );
959

    
960
  if(!empty($annotations_and_sources['source_references'])){
961
    $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
962
  }
963
  return '<' . $enclosing_tag . '>' . $out . $annotations_and_sources['foot_note_keys'] . '</' . $enclosing_tag . '>';
964

    
965

    
966
}
967

    
968

    
969
/**
970
 * Creates a render array for string representations of description elements for the given feature.
971
 *
972
 * @param array $elements
973
 *   An array of strings. Can be plaintext or markup.
974
 * @param  $feature :
975
 *  The feature to which the elements given in $elements are belonging to.
976
 * @param string $glue :
977
 *  Defaults to empty string.
978
 * @param bool $sort
979
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
980
 *
981
 * @return array|void
982
 *
983
 * @ingroup compose
984
 */
985
  function compose_feature_block_elements(array $elements, $feature, $glue = '', $sort = FALSE)
986
  {
987

    
988
    $feature_block_settings = get_feature_block_settings($feature->uuid);
989
    if($feature_block_settings['as_list']){
990
      $enclosing_tag = $feature_block_settings['as_list'];
991
    } else {
992
      $out = "ERROR</body></html>";
993
      return;
994
    }
995

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

    
998
    if ($sort) {
999
      sort($elements);
1000
    }
1001

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

    
1006
    $out .= '</' . $enclosing_tag . '>';
1007
    return markup_to_render_array($out);
1008
  }
1009

    
1010

    
1011
  /* compose nameInSource or originalNameString as markup
1012
   *
1013
   * @param $source
1014
   * @param $do_link_to_name_used_in_source
1015
   * @param $suppress_for_shown_taxon
1016
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1017
   *    for which the taxon page is being created, Defaults to TRUE
1018
   *
1019
   * @return array
1020
   *    A Drupal render array with an additional element, the render array is empty
1021
   *    if the source had no name in source information
1022
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1023
   *
1024
   * @ingroup compose
1025
   */
1026
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1027

    
1028
    $plaintext = NULL;
1029
    $markup = NULL;
1030
    $name_in_source_render_array = array();
1031

    
1032
    static $taxon_page_accepted_name = '';
1033
    if($suppress_for_shown_taxon && arg(1) == 'taxon' && empty($taxon_page_accepted_name)){
1034

    
1035
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, arg(2));
1036
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1037
    }
1038

    
1039
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1040
      // it is a DescriptionElementSource !
1041
      $plaintext = $source->nameUsedInSource->titleCache;
1042
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1043
        return $name_in_source_render_array; // SKIP this name
1044
      }
1045
      $markup = render_taxon_or_name($source->nameUsedInSource);
1046
      if ($do_link_to_name_used_in_source) {
1047
        $markup = l(
1048
          $markup,
1049
          path_to_name($source->nameUsedInSource->uuid),
1050
          array(
1051
            'attributes' => array(),
1052
            'absolute' => TRUE,
1053
            'html' => TRUE,
1054
          ));
1055
      }
1056
    }
1057
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1058
      // the name used in source can not be expressed as valid taxon name,
1059
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1060
      // field
1061
      // using the originalNameString as key to avoid duplicate entries
1062
      $plaintext = $source->originalNameString;
1063
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1064
        return $name_in_source_render_array; // SKIP this name
1065
      }
1066
      $markup = $source->originalNameString;
1067
    }
1068

    
1069
    if ($plaintext) { // checks if we have any content
1070
      $name_in_source_render_array = markup_to_render_array($markup);
1071
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1072
    }
1073

    
1074
    return $name_in_source_render_array;
1075
  }
1076

    
1077

    
1078

    
1079
  /**
1080
   * Return HTML for a list of description elements.
1081
   *
1082
   * Usually these are of a specific feature type.
1083
   *
1084
   * @param $descriptionElements
1085
   *   array of descriptionElements which belong to the same feature.
1086
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1087
   *   calling the function _mergeFeatureTreeDescriptions().
1088
   *   @see _mergeFeatureTreeDescriptions()
1089
   *
1090
   * @param  $feature_uuid
1091
   *
1092
   * @return
1093
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1094
   *    Footnote key or anchors are not considered to be textual content.
1095
   *
1096
   * @ingroup compose
1097
   */
1098
  function compose_feature_block_items_generic($descriptionElements, $feature) {
1099

    
1100
    $render_array = array();
1101
    $elements_out_array = array();
1102
    $distribution_tree = null;
1103

    
1104
    /*
1105
     * $feature_block_has_content will be set true if at least one of the
1106
     * $descriptionElements contains some text which makes up some content
1107
     * for the feature block. Footnote keys are not considered
1108
     * to be content in this sense.
1109
     */
1110
    $feature_block_has_content = false;
1111

    
1112
    RenderHints::pushToRenderStack($feature->uuid);
1113

    
1114
    if (is_array($descriptionElements)) {
1115
      foreach ($descriptionElements as $descriptionElement) {
1116
          /* decide based on the description element class
1117
           *
1118
           * Features handled here:
1119
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1120
           *
1121
           *
1122
           * TODO provide api_hook as extension point for this?
1123
           */
1124
          $feature_block_settings = get_feature_block_settings($descriptionElement->feature->uuid);
1125
          $asListElement  = $feature_block_settings['as_list'] == 'ul';
1126
          switch ($descriptionElement->class) {
1127
            case 'TextData':
1128
              $text_data_render_array = compose_description_element_textdata($descriptionElement, $asListElement, $descriptionElement->feature->uuid);
1129
              $feature_block_has_content = $feature_block_has_content || !empty($text_data_render_array['#value']);
1130
              $elements_out_array[] = drupal_render($text_data_render_array);
1131
              break;
1132
            case 'CategoricalData':
1133
              $feature_block_has_content = true;
1134
              $elements_out_array[] = theme('cdm_descriptionElement_CategoricalData', array('element' => $descriptionElement));
1135
              break;
1136
            case 'QuantitativeData':
1137
              $feature_block_has_content = true;
1138
              $elements_out_array[] = theme('cdm_descriptionElement_QuantitativeData', array('element' => $descriptionElement));
1139
              break;
1140
            case 'IndividualsAssociation':
1141
              $feature_block_has_content = true;
1142
              $elements_out_array[] = compose_description_element_individuals_association($descriptionElement, $feature_block_settings);
1143
              break;
1144
            case 'TaxonInteraction':
1145
              $feature_block_has_content = true;
1146
              $elements_out_array[] = theme('cdm_descriptionElement_TaxonInteraction', array('element' => $descriptionElement));
1147
              break;
1148
            case 'Uses':
1149
              /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1150
              break;
1151
            default:
1152
              $feature_block_has_content = true;
1153
              $elements_out_array[] = '<li>No method for rendering unknown description class: ' . $descriptionElement->class . '</li>';
1154
          }
1155
      } // --- END loop over normal description element arrays
1156

    
1157
      // If feature = CITATION sort the list of sources.
1158
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1159
      if ($descriptionElement->feature->uuid == UUID_CITATION) {
1160
        sort($elements_out_array);
1161
      }
1162
    }
1163

    
1164
    if($feature_block_has_content){
1165
      $render_array = compose_feature_block_elements(
1166
        $elements_out_array, $feature
1167
      );
1168
    }
1169

    
1170
    RenderHints::popFromRenderStack();
1171
    return $render_array;
1172
  }
1173

    
1174
/**
1175
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1176
 *
1177
 * @parameter $elements
1178
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1179
 * @parameter $feature
1180
 *  the common feature of all $elements, must be CommonName
1181
 *
1182
 * @return
1183
 *   A drupal render array
1184
 *
1185
 * @ingroup compose
1186
 */
1187
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1188

    
1189
  $common_name_out = '';
1190
  $common_name_feature_elements = array();
1191
  $textData_commonNames = array();
1192

    
1193
  $footnote_key_suggestion = 'common-names-feature-block';
1194

    
1195
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1196

    
1197
  $element_tag_name = cdm_feature_block_element_tag_name($feature_block_settings);
1198

    
1199
  if (is_array($elements)) {
1200
    foreach ($elements as $element) {
1201

    
1202
      if ($element->class == 'CommonTaxonName') {
1203

    
1204
        // common name without a language or area, should not happen but is possible
1205
        $language_area_key = '';
1206
        if (isset($element->language->representation_L10n)) {
1207
          $language_area_key .= '<b>' . $element->language->representation_L10n . '</b>';
1208
        }
1209
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1210
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1211
        }
1212

    
1213
        if(isset($common_names[$language_area_key][$element->name])) {
1214
          // same name already exists for language and areae combination, se we merge the description elements
1215
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1216
        } else{
1217
          // otherwise add as new entry
1218
          $common_names[$language_area_key][$element->name] = $element;
1219
        }
1220

    
1221
      }
1222
      elseif ($element->class == 'TextData') {
1223
        $textData_commonNames[] = $element;
1224
      }
1225
    }
1226
  }
1227
  // Handling common names.
1228
  if (isset($common_names) && count($common_names) > 0) {
1229
    // Sorting the array based on the key (language, + area if set).
1230
    // Comment @WA there are common names without a language, so this sorting
1231
    // can give strange results.
1232
    ksort($common_names);
1233

    
1234
    // loop over set of elements per language area
1235
    foreach ($common_names as $language_area_key => $elements) {
1236
      ksort($elements); // sort names alphabetically
1237
      $per_language_area_out = array();
1238
      // loop over set of individual elements
1239
      foreach ($elements as $element) {
1240
        if ($element->name) {
1241
          $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element->name, $footnote_key_suggestion);
1242
          $source_references_markup = '';
1243
          if(!empty($annotations_and_sources['source_references'])){
1244
            $source_references_markup = ' ' . join(', ', $annotations_and_sources['source_references']);
1245
          }
1246
          $per_language_area_out[] = '<' . $element_tag_name. ' class="' . html_class_attribute_ref($element) . '">'
1247
            . $element->name . $source_references_markup . $annotations_and_sources['foot_note_keys'] . '</' . $element_tag_name. '>';
1248
        }
1249
      } // End of loop over set of individual elements
1250
      $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1251
    } // End of loop over set of elements per language area
1252

    
1253

    
1254
    $common_name_feature_elements_render_array = compose_feature_block_elements(
1255
      $common_name_feature_elements, $feature, '; ', FALSE
1256
    );
1257
    $common_name_out .= $common_name_feature_elements_render_array['#markup'];
1258

    
1259
  }
1260

    
1261
  // Handling commons names as text data.
1262
  $text_data_out = array();
1263

    
1264
  foreach ($textData_commonNames as $text_data_element) {
1265
    /* footnotes are not handled correctly in compose_description_element_textdata,
1266
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1267
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1268
    $text_data_render_array = compose_description_element_textdata($text_data_element, TRUE, $text_data_element->feature->uuid);
1269
    $text_data_out[] = drupal_render($text_data_render_array);
1270
  }
1271

    
1272
  $common_name_out_text_data = compose_feature_block_elements(
1273
    $text_data_out, $feature
1274
  );
1275

    
1276
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1277
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1278
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1279

    
1280
  return  markup_to_render_array(
1281
    '<div class="common_names_as_common_names">' . $common_name_out . '</div>'
1282
    .'<div class="common_names_as_text_data">' . $common_name_out_text_data['#markup'] . '</div>'
1283
    .$footnotes,
1284
    $weight
1285
  );
1286
}
1287

    
1288
  /**
1289
   * Composes the render array for a CDM Distribution description element
1290
   *
1291
   * @param array $description_elements
1292
   *   Array of CDM Distribution instances
1293
   * @param $enclosingTag
1294
   *   The html tag to be use for the enclosing element
1295
   *
1296
   * @return array
1297
   *   A Drupal render array
1298
   *
1299
   * @ingroup compose
1300
   */
1301
  function compose_description_elements_distribution($description_elements){
1302

    
1303
    $out = '';
1304
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1305
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1306

    
1307
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1308
    $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1309

    
1310
    foreach ($description_elements as $description_element) {
1311
      $annotations_and_sources = handle_annotations_and_sources(
1312
        $description_element,
1313
        $feature_block_settings,
1314
        $description_element->area->representation_L10n,
1315
        UUID_DISTRIBUTION
1316
      );
1317

    
1318

    
1319
      list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1320

    
1321
      $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1322
        . ' " title="' . $status_label. '">'
1323
        . $description_element->area->representation_L10n
1324
        . $status_markup;
1325
      if(!empty($annotations_and_sources['source_references'])){
1326
        $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1327
      }
1328
      $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1329
    }
1330

    
1331
    RenderHints::popFromRenderStack();
1332
    return markup_to_render_array($out);
1333
  }
1334

    
1335
  /**
1336
   * @param $descriptionElement
1337
   * @return array
1338
   */
1339
  function distribution_status_label_and_markup($descriptionElement) {
1340
    $status_markup = '';
1341
    $status_label = '';
1342

    
1343
    if (isset($descriptionElement->status)) {
1344
      $status_label = $descriptionElement->status->representation_L10n;
1345
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1346
        . $status_label . ' </span>';
1347

    
1348
    };
1349
    return array($status_label, $status_markup);
1350
  }
1351

    
1352

    
1353
  /**
1354
   * Provides the merged feature tree for a taxon profile page.
1355
   *
1356
   * The merging of the profile feature tree is actully done in
1357
   * _mergeFeatureTreeDescriptions(). See this method  for details
1358
   * on the structure of the merged tree.
1359
   *
1360
   * This method provides t hook which can be used to modify the
1361
   * merged feature tree after it has been created, see
1362
   * hook_merged_taxon_feature_tree_alter()
1363
   *
1364
   * @param $taxon
1365
   *   A CDM Taxon instance
1366
   *
1367
   * @return object
1368
   *  The merged feature tree
1369
   *
1370
   */
1371
  function merged_taxon_feature_tree($taxon) {
1372

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

    
1376

    
1377
    // 2. find the distribution feature node
1378
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1379

    
1380
    if ($distribution_node) {
1381
      // 3. get the distributionInfoDTO
1382
      $query_parameters = cdm_distribution_filter_query();
1383
      $query_parameters['part'] = array('mapUriParams');
1384
      if(variable_get(DISTRIBUTION_CONDENSED)){
1385
        $query_parameters['part'][] = 'condensedDistribution';
1386
      }
1387
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1388
        $query_parameters['part'][] = 'tree';
1389
      }
1390
      else {
1391
        $query_parameters['part'][] = 'elements';
1392
      }
1393
      $query_parameters['omitLevels'] = array();
1394
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1395
        if(is_uuid($uuid)){
1396
          $query_parameters['omitLevels'][] = $uuid;
1397
        }
1398
      }
1399
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1400
      if ($customStatusColorsJson) {
1401
        $query_parameters['statusColors'] = $customStatusColorsJson;
1402
      }
1403

    
1404
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1405
      // 4. get distribution TextData is there are any
1406
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1407
        array(
1408
          'taxon' => $taxon->uuid,
1409
          'type' => 'TextData',
1410
          'features' => UUID_DISTRIBUTION
1411
        )
1412
      );
1413

    
1414
      // 5. put all distribution data into the distribution feature node
1415
      if ($distribution_text_data //if text data exists
1416
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1417
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1418
      ) { // OR if DTO has distribution elements
1419
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1420
        if ($distribution_text_data) {
1421
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1422
        }
1423
        if ($distribution_info_dto) {
1424
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1425
        }
1426
      }
1427
    }
1428

    
1429
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1430
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1431

    
1432
    return $merged_tree;
1433
  }
1434

    
1435

    
1436
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1437

    
1438
    static $hierarchy_style;
1439
    // TODO expose $hierarchy_style to administration of provide a hook
1440
    if( !isset($hierarchy_style)){
1441
      $hierarchy_style = array(
1442
        // level 2
1443
        array(
1444
          'label_suffix' => '',
1445
          'element_glue' => ', ',
1446
          'element_set_pre' => '(',
1447
          'element_set_post' => ')'
1448
        ),
1449
        // level 1
1450
        array(
1451
          'label_suffix' => '',
1452
          'element_glue' => '; ',
1453
          'element_set_pre' => '',
1454
          'element_set_post' => ''
1455
        ),
1456
        // level 0
1457
        array(
1458
          'label_suffix' => ':',
1459
          'element_glue' => ' ',
1460
          'element_set_pre' => '',
1461
          'element_set_post' => ''
1462
        ),
1463
      );
1464
    }
1465

    
1466
    $render_array = array();
1467

    
1468
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1469
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1470

    
1471
    // Returning NULL if there are no description elements.
1472
    if ($distribution_tree == null) {
1473
      return $render_array;
1474
    }
1475
    // for now we are not using a render array internally to avoid performance problems
1476
    $markup = '';
1477
    if (isset($distribution_tree->rootElement->children)) {
1478
      $tree_nodes = $distribution_tree->rootElement->children;
1479
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1480
    }
1481

    
1482
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1483
      $markup,
1484
      0,
1485
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1486
      '</div>'
1487
    );
1488

    
1489
    return $render_array;
1490
  }
1491

    
1492
  /**
1493
   * this function should produce markup as the compose_description_elements_distribution()
1494
   * function.
1495
   *
1496
   * @see compose_description_elements_distribution()
1497
   *
1498
   * @param $distribution_tree
1499
   * @param $feature_block_settings
1500
   * @param $tree_nodes
1501
   * @param $markup
1502
   * @param $hierarchy_style
1503
   */
1504
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1505

    
1506
    $level_index++;
1507
    static $enclosingTag = "span";
1508

    
1509
    $level_style = array_pop($hierarchy_style);
1510
    if(count($hierarchy_style) == 0){
1511
      // lowest defined level style will be reused for all following levels
1512
      $hierarchy_style[] = $level_style;
1513
    }
1514

    
1515
    $node_index = -1;
1516
    $per_node_markup = array();
1517
    foreach ($tree_nodes as $node){
1518

    
1519
      $per_node_markup[++$node_index] = '';
1520

    
1521
      $label = $node->nodeId->representation_L10n;
1522

    
1523
      $distributions = $node->data;
1524
      $distribution_uuids = array();
1525
      $distribution_aggregate = NULL;
1526
        foreach($distributions as $distribution){
1527

    
1528
          $distribution_uuids[] = $distribution->uuid;
1529

    
1530
          // if there is more than one distribution we aggregate the sources and
1531
          // annotations into a synthetic distribution so that the footnote keys
1532
          // can be rendered consistently
1533
          if(!$distribution_aggregate) {
1534
            $distribution_aggregate = $distribution;
1535
            if(!isset($distribution_aggregate->sources[0])){
1536
              $distribution_aggregate->sources = array();
1537
            }
1538
            if(!isset($distribution_aggregate->annotations[0])){
1539
              $distribution_aggregate->annotations = array();
1540
            }
1541
          } else {
1542
            if(isset($distribution->sources[0])) {
1543
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1544
                $distribution->sources);
1545
            }
1546
            if(isset($distribution->annotations[0])) {
1547
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1548
                $distribution->annotations);
1549
            }
1550
          }
1551
        }
1552

    
1553
      $status_label= '';
1554
      $status_markup = '';
1555
      $annotations_and_sources =  null;
1556
      if($distribution_aggregate) {
1557
        $annotations_and_sources = handle_annotations_and_sources(
1558
          $distribution_aggregate,
1559
          $feature_block_settings,
1560
          $label,
1561
          UUID_DISTRIBUTION
1562
        );
1563

    
1564
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1565
      }
1566

    
1567
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1568
        . join(' descriptionElement-', $distribution_uuids)
1569
        . ' level_index_' . $level_index
1570
        . ' " title="' . $status_label . '">'
1571
        . '<span class="area_label">' . $label
1572
        . $level_style['label_suffix'] . ' </span>'
1573
        .  $status_markup
1574
      ;
1575

    
1576
      if(isset($annotations_and_sources)){
1577
        if(!empty($annotations_and_sources['source_references'])){
1578
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1579
        }
1580
        if($annotations_and_sources['foot_note_keys']) {
1581
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1582
        }
1583
      }
1584

    
1585
      if(isset($node->children[0])){
1586
        _compose_distribution_hierarchy(
1587
          $node->children,
1588
          $feature_block_settings,
1589
          $per_node_markup[$node_index],
1590
          $hierarchy_style,
1591
          $level_index
1592
        );
1593
      }
1594

    
1595
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1596
    }
1597
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1598
  }
1599

    
1600

    
(2-2/8)