Project

General

Profile

Download (58.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
 * Theme function to render CDM DescriptionElements of the type TaxonInteraction.
930
 *
931
 * @param $element
932
 *  The CDM TaxonInteraction entity
933
 *
934
 * @return
935
 *  A drupal render array
936
 *
937
 * @ingroup compose
938
 */
939
function compose_description_element_taxon_interaction($element, $feature_block_settings) {
940

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

    
944
  if (isset($element->description_L10n)) {
945
    $out .=  ' ' . $element->description_L10n;
946
  }
947

    
948
  if(isset($element->taxon2)){
949
    $out = render_taxon_or_name($element->taxon2, url(path_to_taxon($element->taxon2->uuid)));
950
  }
951

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

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

    
964
}
965

    
966

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

    
981
  $out = '';
982
  $enclosing_tag = cdm_feature_block_element_tag_name($feature_block_settings);
983

    
984
  $render_array = compose_cdm_specimenOrObservation($element->associatedSpecimenOrObservation);
985

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

    
990
  $out .= drupal_render($render_array);
991

    
992
  $annotations_and_sources = handle_annotations_and_sources(
993
    $element,
994
    $feature_block_settings,
995
    $out, // the description element text
996
    $element->feature->uuid
997
  );
998

    
999
  if(!empty($annotations_and_sources['source_references'])){
1000
    $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1001
  }
1002
  return '<' . $enclosing_tag . '>' . $out . $annotations_and_sources['foot_note_keys'] . '</' . $enclosing_tag . '>';
1003

    
1004

    
1005
}
1006

    
1007

    
1008
/**
1009
 * Creates a render array for string representations of description elements for the given feature.
1010
 *
1011
 * @param array $elements
1012
 *   An array of strings. Can be plaintext or markup.
1013
 * @param  $feature :
1014
 *  The feature to which the elements given in $elements are belonging to.
1015
 * @param string $glue :
1016
 *  Defaults to empty string.
1017
 * @param bool $sort
1018
 *   Boolean Whether to sort the $elements alphabetically, default is FALSE
1019
 *
1020
 * @return array|void
1021
 *
1022
 * @ingroup compose
1023
 */
1024
  function compose_feature_block_elements(array $elements, $feature, $glue = '', $sort = FALSE)
1025
  {
1026

    
1027
    $feature_block_settings = get_feature_block_settings($feature->uuid);
1028
    if($feature_block_settings['as_list']){
1029
      $enclosing_tag = $feature_block_settings['as_list'];
1030
    } else {
1031
      $out = "ERROR</body></html>";
1032
      return;
1033
    }
1034

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

    
1037
    if ($sort) {
1038
      sort($elements);
1039
    }
1040

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

    
1045
    $out .= '</' . $enclosing_tag . '>';
1046
    return markup_to_render_array($out);
1047
  }
1048

    
1049

    
1050
  /* compose nameInSource or originalNameString as markup
1051
   *
1052
   * @param $source
1053
   * @param $do_link_to_name_used_in_source
1054
   * @param $suppress_for_shown_taxon
1055
   *    the nameInSource will be suppressed when it has the same name as the accepted taxon
1056
   *    for which the taxon page is being created, Defaults to TRUE
1057
   *
1058
   * @return array
1059
   *    A Drupal render array with an additional element, the render array is empty
1060
   *    if the source had no name in source information
1061
   *    - #_plaintext: contains the plaintext version of the name (custom element)
1062
   *
1063
   * @ingroup compose
1064
   */
1065
  function compose_name_in_source($source, $do_link_to_name_used_in_source, $suppress_for_shown_taxon = TRUE) {
1066

    
1067
    $plaintext = NULL;
1068
    $markup = NULL;
1069
    $name_in_source_render_array = array();
1070

    
1071
    static $taxon_page_accepted_name = '';
1072
    if($suppress_for_shown_taxon && arg(1) == 'taxon' && empty($taxon_page_accepted_name)){
1073

    
1074
      $current_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, arg(2));
1075
      $taxon_page_accepted_name = $current_taxon->name->titleCache;
1076
    }
1077

    
1078
    if (isset($source->nameUsedInSource->uuid) && isset($source->nameUsedInSource->titleCache)) {
1079
      // it is a DescriptionElementSource !
1080
      $plaintext = $source->nameUsedInSource->titleCache;
1081
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1082
        return $name_in_source_render_array; // SKIP this name
1083
      }
1084
      $markup = render_taxon_or_name($source->nameUsedInSource);
1085
      if ($do_link_to_name_used_in_source) {
1086
        $markup = l(
1087
          $markup,
1088
          path_to_name($source->nameUsedInSource->uuid),
1089
          array(
1090
            'attributes' => array(),
1091
            'absolute' => TRUE,
1092
            'html' => TRUE,
1093
          ));
1094
      }
1095
    }
1096
    else if (isset($source->originalNameString) && !empty($source->originalNameString)) {
1097
      // the name used in source can not be expressed as valid taxon name,
1098
      // so the editor has chosen to put the freetext name into ReferencedEntityBase.originalNameString
1099
      // field
1100
      // using the originalNameString as key to avoid duplicate entries
1101
      $plaintext = $source->originalNameString;
1102
      if($suppress_for_shown_taxon && $taxon_page_accepted_name == $plaintext){
1103
        return $name_in_source_render_array; // SKIP this name
1104
      }
1105
      $markup = $source->originalNameString;
1106
    }
1107

    
1108
    if ($plaintext) { // checks if we have any content
1109
      $name_in_source_render_array = markup_to_render_array($markup);
1110
      $name_in_source_render_array['#_plaintext'] = $plaintext;
1111
    }
1112

    
1113
    return $name_in_source_render_array;
1114
  }
1115

    
1116

    
1117

    
1118
  /**
1119
   * Return HTML for a list of description elements.
1120
   *
1121
   * Usually these are of a specific feature type.
1122
   *
1123
   * @param $descriptionElements
1124
   *   array of descriptionElements which belong to the same feature.
1125
   *   These descriptions elements of a Description must be ordered by the chosen feature tree by
1126
   *   calling the function _mergeFeatureTreeDescriptions().
1127
   *   @see _mergeFeatureTreeDescriptions()
1128
   *
1129
   * @param  $feature_uuid
1130
   *
1131
   * @return
1132
   *    A drupal render array for the $descriptionElements, may be an empty array if the textual content was empty.
1133
   *    Footnote key or anchors are not considered to be textual content.
1134
   *
1135
   * @ingroup compose
1136
   */
1137
  function compose_feature_block_items_generic($descriptionElements, $feature) {
1138

    
1139
    $render_array = array();
1140
    $elements_out_array = array();
1141
    $distribution_tree = null;
1142

    
1143
    /*
1144
     * $feature_block_has_content will be set true if at least one of the
1145
     * $descriptionElements contains some text which makes up some content
1146
     * for the feature block. Footnote keys are not considered
1147
     * to be content in this sense.
1148
     */
1149
    $feature_block_has_content = false;
1150

    
1151
    RenderHints::pushToRenderStack($feature->uuid);
1152

    
1153
    if (is_array($descriptionElements)) {
1154
      foreach ($descriptionElements as $descriptionElement) {
1155
          /* decide based on the description element class
1156
           *
1157
           * Features handled here:
1158
           * all except DISTRIBUTION, COMMON_NAME, USES, IMAGES,
1159
           *
1160
           *
1161
           * TODO provide api_hook as extension point for this?
1162
           */
1163
          $feature_block_settings = get_feature_block_settings($descriptionElement->feature->uuid);
1164
          $asListElement  = $feature_block_settings['as_list'] == 'ul';
1165
          switch ($descriptionElement->class) {
1166
            case 'TextData':
1167
              $text_data_render_array = compose_description_element_textdata($descriptionElement, $asListElement, $descriptionElement->feature->uuid);
1168
              $feature_block_has_content = $feature_block_has_content || !empty($text_data_render_array['#value']);
1169
              $elements_out_array[] = drupal_render($text_data_render_array);
1170
              break;
1171
            case 'CategoricalData':
1172
              $feature_block_has_content = true;
1173
              $elements_out_array[] = theme('cdm_descriptionElement_CategoricalData', array('element' => $descriptionElement));
1174
              break;
1175
            case 'QuantitativeData':
1176
              $feature_block_has_content = true;
1177
              $elements_out_array[] = theme('cdm_descriptionElement_QuantitativeData', array('element' => $descriptionElement));
1178
              break;
1179
            case 'IndividualsAssociation':
1180
              $feature_block_has_content = true;
1181
              $elements_out_array[] = compose_description_element_individuals_association($descriptionElement, $feature_block_settings);
1182
              break;
1183
            case 'TaxonInteraction':
1184
              $feature_block_has_content = true;
1185
              $elements_out_array[] = compose_description_element_taxon_interaction($descriptionElement, $feature_block_settings);
1186
              break;
1187
            case 'Uses':
1188
              /* IGNORE Uses classes, these are handled completely in theme_cdm_UseDescription */
1189
              break;
1190
            default:
1191
              $feature_block_has_content = true;
1192
              $elements_out_array[] = '<li>No method for rendering unknown description class: ' . $descriptionElement->class . '</li>';
1193
          }
1194
      } // --- END loop over normal description element arrays
1195

    
1196
      // If feature = CITATION sort the list of sources.
1197
      // This is ONLY for FLORA MALESIANA and FLORE d'AFRIQUE CENTRALE.
1198
      if ($descriptionElement->feature->uuid == UUID_CITATION) {
1199
        sort($elements_out_array);
1200
      }
1201
    }
1202

    
1203
    if($feature_block_has_content){
1204
      $render_array = compose_feature_block_elements(
1205
        $elements_out_array, $feature
1206
      );
1207
    }
1208

    
1209
    RenderHints::popFromRenderStack();
1210
    return $render_array;
1211
  }
1212

    
1213
/**
1214
 * Composes block of common names for the given DescriptionElements $elements which must be of the feature CommonName
1215
 *
1216
 * @parameter $elements
1217
 *  an array of CDM DescriptionElements either of type CommonName or TextData
1218
 * @parameter $feature
1219
 *  the common feature of all $elements, must be CommonName
1220
 *
1221
 * @return
1222
 *   A drupal render array
1223
 *
1224
 * @ingroup compose
1225
 */
1226
function compose_feature_block_items_feature_common_name($elements, $feature, $weight = FALSE) {
1227

    
1228
  $common_name_out = '';
1229
  $common_name_feature_elements = array();
1230
  $textData_commonNames = array();
1231

    
1232
  $footnote_key_suggestion = 'common-names-feature-block';
1233

    
1234
  $feature_block_settings = get_feature_block_settings(UUID_COMMON_NAME);
1235

    
1236
  $element_tag_name = cdm_feature_block_element_tag_name($feature_block_settings);
1237

    
1238
  if (is_array($elements)) {
1239
    foreach ($elements as $element) {
1240

    
1241
      if ($element->class == 'CommonTaxonName') {
1242

    
1243
        // common name without a language or area, should not happen but is possible
1244
        $language_area_key = '';
1245
        if (isset($element->language->representation_L10n)) {
1246
          $language_area_key .= '<b>' . $element->language->representation_L10n . '</b>';
1247
        }
1248
        if(isset($element->area->titleCache) && strlen($element->area->titleCache) > 0){
1249
          $language_area_key .= ($language_area_key ? ' '  : '') . '(' . $element->area->titleCache . ')';
1250
        }
1251

    
1252
        if(isset($common_names[$language_area_key][$element->name])) {
1253
          // same name already exists for language and areae combination, se we merge the description elements
1254
          cdm_merge_description_elements($common_names[$language_area_key][$element->name], $element);
1255
        } else{
1256
          // otherwise add as new entry
1257
          $common_names[$language_area_key][$element->name] = $element;
1258
        }
1259

    
1260
      }
1261
      elseif ($element->class == 'TextData') {
1262
        $textData_commonNames[] = $element;
1263
      }
1264
    }
1265
  }
1266
  // Handling common names.
1267
  if (isset($common_names) && count($common_names) > 0) {
1268
    // Sorting the array based on the key (language, + area if set).
1269
    // Comment @WA there are common names without a language, so this sorting
1270
    // can give strange results.
1271
    ksort($common_names);
1272

    
1273
    // loop over set of elements per language area
1274
    foreach ($common_names as $language_area_key => $elements) {
1275
      ksort($elements); // sort names alphabetically
1276
      $per_language_area_out = array();
1277
      // loop over set of individual elements
1278
      foreach ($elements as $element) {
1279
        if ($element->name) {
1280
          $annotations_and_sources = handle_annotations_and_sources($element, $feature_block_settings, $element->name, $footnote_key_suggestion);
1281
          $source_references_markup = '';
1282
          if(!empty($annotations_and_sources['source_references'])){
1283
            $source_references_markup = ' ' . join(', ', $annotations_and_sources['source_references']);
1284
          }
1285
          $per_language_area_out[] = '<' . $element_tag_name. ' class="' . html_class_attribute_ref($element) . '">'
1286
            . $element->name . $source_references_markup . $annotations_and_sources['foot_note_keys'] . '</' . $element_tag_name. '>';
1287
        }
1288
      } // End of loop over set of individual elements
1289
      $common_name_feature_elements[] = ($language_area_key ? $language_area_key . ': ' : '' ) . join(', ', $per_language_area_out);
1290
    } // End of loop over set of elements per language area
1291

    
1292

    
1293
    $common_name_feature_elements_render_array = compose_feature_block_elements(
1294
      $common_name_feature_elements, $feature, '; ', FALSE
1295
    );
1296
    $common_name_out .= $common_name_feature_elements_render_array['#markup'];
1297

    
1298
  }
1299

    
1300
  // Handling commons names as text data.
1301
  $text_data_out = array();
1302

    
1303
  foreach ($textData_commonNames as $text_data_element) {
1304
    /* footnotes are not handled correctly in compose_description_element_textdata,
1305
       need to set 'common-names-feature-block' as $footnote_key_suggestion */
1306
    RenderHints::setFootnoteListKey($footnote_key_suggestion);
1307
    $text_data_render_array = compose_description_element_textdata($text_data_element, TRUE, $text_data_element->feature->uuid);
1308
    $text_data_out[] = drupal_render($text_data_render_array);
1309
  }
1310

    
1311
  $common_name_out_text_data = compose_feature_block_elements(
1312
    $text_data_out, $feature
1313
  );
1314

    
1315
  $footnotes = theme('cdm_footnotes', array('footnoteListKey' => 'BIBLIOGRAPHY-' . $footnote_key_suggestion));
1316
  $footnotes .= theme('cdm_footnotes', array('footnoteListKey' => $footnote_key_suggestion)); // FIXME is this needed at all?
1317
  $footnotes .= theme('cdm_annotation_footnotes', array('footnoteListKey' => $footnote_key_suggestion));
1318

    
1319
  return  markup_to_render_array(
1320
    '<div class="common_names_as_common_names">' . $common_name_out . '</div>'
1321
    .'<div class="common_names_as_text_data">' . $common_name_out_text_data['#markup'] . '</div>'
1322
    .$footnotes,
1323
    $weight
1324
  );
1325
}
1326

    
1327
  /**
1328
   * Composes the render array for a CDM Distribution description element
1329
   *
1330
   * @param array $description_elements
1331
   *   Array of CDM Distribution instances
1332
   * @param $enclosingTag
1333
   *   The html tag to be use for the enclosing element
1334
   *
1335
   * @return array
1336
   *   A Drupal render array
1337
   *
1338
   * @ingroup compose
1339
   */
1340
  function compose_description_elements_distribution($description_elements){
1341

    
1342
    $out = '';
1343
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1344
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1345

    
1346
    $feature_block_settings = get_feature_block_settings(UUID_DISTRIBUTION);
1347
    $enclosingTag = cdm_feature_block_element_tag_name($feature_block_settings);
1348

    
1349
    foreach ($description_elements as $description_element) {
1350
      $annotations_and_sources = handle_annotations_and_sources(
1351
        $description_element,
1352
        $feature_block_settings,
1353
        $description_element->area->representation_L10n,
1354
        UUID_DISTRIBUTION
1355
      );
1356

    
1357

    
1358
      list($status_label, $status_markup) = distribution_status_label_and_markup($description_element);
1359

    
1360
      $out .= '<' . $enclosingTag . ' class="descriptionElement descriptionElement-' . $description_element->uuid
1361
        . ' " title="' . $status_label. '">'
1362
        . $description_element->area->representation_L10n
1363
        . $status_markup;
1364
      if(!empty($annotations_and_sources['source_references'])){
1365
        $out .= ' ' . join(' ', $annotations_and_sources['source_references'] );
1366
      }
1367
      $out .= $annotations_and_sources['foot_note_keys']   . ' </' . $enclosingTag . '>';
1368
    }
1369

    
1370
    RenderHints::popFromRenderStack();
1371
    return markup_to_render_array($out);
1372
  }
1373

    
1374
  /**
1375
   * @param $descriptionElement
1376
   * @return array
1377
   */
1378
  function distribution_status_label_and_markup($descriptionElement) {
1379
    $status_markup = '';
1380
    $status_label = '';
1381

    
1382
    if (isset($descriptionElement->status)) {
1383
      $status_label = $descriptionElement->status->representation_L10n;
1384
      $status_markup = '<span class="distributionStatus distributionStatus-' . $descriptionElement->status->idInVocabulary . '"> '
1385
        . $status_label . ' </span>';
1386

    
1387
    };
1388
    return array($status_label, $status_markup);
1389
  }
1390

    
1391

    
1392
  /**
1393
   * Provides the merged feature tree for a taxon profile page.
1394
   *
1395
   * The merging of the profile feature tree is actully done in
1396
   * _mergeFeatureTreeDescriptions(). See this method  for details
1397
   * on the structure of the merged tree.
1398
   *
1399
   * This method provides t hook which can be used to modify the
1400
   * merged feature tree after it has been created, see
1401
   * hook_merged_taxon_feature_tree_alter()
1402
   *
1403
   * @param $taxon
1404
   *   A CDM Taxon instance
1405
   *
1406
   * @return object
1407
   *  The merged feature tree
1408
   *
1409
   */
1410
  function merged_taxon_feature_tree($taxon) {
1411

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

    
1415

    
1416
    // 2. find the distribution feature node
1417
    $distribution_node =& cdm_feature_tree_find_node($merged_tree->root->childNodes, UUID_DISTRIBUTION);
1418

    
1419
    if ($distribution_node) {
1420
      // 3. get the distributionInfoDTO
1421
      $query_parameters = cdm_distribution_filter_query();
1422
      $query_parameters['part'] = array('mapUriParams');
1423
      if(variable_get(DISTRIBUTION_CONDENSED)){
1424
        $query_parameters['part'][] = 'condensedDistribution';
1425
      }
1426
      if (variable_get(DISTRIBUTION_ORDER_MODE, DISTRIBUTION_ORDER_MODE_DEFAULT) == 'TREE') {
1427
        $query_parameters['part'][] = 'tree';
1428
      }
1429
      else {
1430
        $query_parameters['part'][] = 'elements';
1431
      }
1432
      $query_parameters['omitLevels'] = array();
1433
      foreach(variable_get(DISTRIBUTION_TREE_OMIT_LEVELS, array()) as $uuid){
1434
        if(is_uuid($uuid)){
1435
          $query_parameters['omitLevels'][] = $uuid;
1436
        }
1437
      }
1438
      $customStatusColorsJson = variable_get(DISTRIBUTION_STATUS_COLORS, NULL);
1439
      if ($customStatusColorsJson) {
1440
        $query_parameters['statusColors'] = $customStatusColorsJson;
1441
      }
1442

    
1443
      $distribution_info_dto = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION_DISTRIBUTION_INFO_FOR, $taxon->uuid, queryString($query_parameters));
1444
      // 4. get distribution TextData is there are any
1445
      $distribution_text_data = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1446
        array(
1447
          'taxon' => $taxon->uuid,
1448
          'type' => 'TextData',
1449
          'features' => UUID_DISTRIBUTION
1450
        )
1451
      );
1452

    
1453
      // 5. put all distribution data into the distribution feature node
1454
      if ($distribution_text_data //if text data exists
1455
        || ($distribution_info_dto && isset($distribution_info_dto->tree) && $distribution_info_dto->tree->rootElement->numberOfChildren > 0) // OR if tree element has distribution elements
1456
        || ($distribution_info_dto && !empty($distribution_info_dto->elements))
1457
      ) { // OR if DTO has distribution elements
1458
        $distribution_node->descriptionElements = array('#type' => 'DTO');
1459
        if ($distribution_text_data) {
1460
          $distribution_node->descriptionElements['TextData'] = $distribution_text_data;
1461
        }
1462
        if ($distribution_info_dto) {
1463
          $distribution_node->descriptionElements['DistributionInfoDTO'] = $distribution_info_dto;
1464
        }
1465
      }
1466
    }
1467

    
1468
    // allows modifying the merged tree via a the hook_cdm_feature_node_block_content_alter
1469
    drupal_alter('merged_taxon_feature_tree', $taxon, $merged_tree);
1470

    
1471
    return $merged_tree;
1472
  }
1473

    
1474

    
1475
  function compose_distribution_hierarchy($distribution_tree, $feature_block_settings){
1476

    
1477
    static $hierarchy_style;
1478
    // TODO expose $hierarchy_style to administration of provide a hook
1479
    if( !isset($hierarchy_style)){
1480
      $hierarchy_style = array(
1481
        // level 2
1482
        array(
1483
          'label_suffix' => '',
1484
          'element_glue' => ', ',
1485
          'element_set_pre' => '(',
1486
          'element_set_post' => ')'
1487
        ),
1488
        // level 1
1489
        array(
1490
          'label_suffix' => '',
1491
          'element_glue' => '; ',
1492
          'element_set_pre' => '',
1493
          'element_set_post' => ''
1494
        ),
1495
        // level 0
1496
        array(
1497
          'label_suffix' => ':',
1498
          'element_glue' => ' ',
1499
          'element_set_pre' => '',
1500
          'element_set_post' => ''
1501
        ),
1502
      );
1503
    }
1504

    
1505
    $render_array = array();
1506

    
1507
    RenderHints::pushToRenderStack('descriptionElementDistribution');
1508
    RenderHints::setFootnoteListKey(UUID_DISTRIBUTION);
1509

    
1510
    // Returning NULL if there are no description elements.
1511
    if ($distribution_tree == null) {
1512
      return $render_array;
1513
    }
1514
    // for now we are not using a render array internally to avoid performance problems
1515
    $markup = '';
1516
    if (isset($distribution_tree->rootElement->children)) {
1517
      $tree_nodes = $distribution_tree->rootElement->children;
1518
      _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, $markup, $hierarchy_style);
1519
    }
1520

    
1521
    $render_array['distribution_hierarchy'] = markup_to_render_array(
1522
      $markup,
1523
      0,
1524
      '<div id="distribution_hierarchy" class="distribution_hierarchy">',
1525
      '</div>'
1526
    );
1527

    
1528
    return $render_array;
1529
  }
1530

    
1531
  /**
1532
   * this function should produce markup as the compose_description_elements_distribution()
1533
   * function.
1534
   *
1535
   * @see compose_description_elements_distribution()
1536
   *
1537
   * @param $distribution_tree
1538
   * @param $feature_block_settings
1539
   * @param $tree_nodes
1540
   * @param $markup
1541
   * @param $hierarchy_style
1542
   */
1543
  function _compose_distribution_hierarchy($tree_nodes, $feature_block_settings, &$markup, $hierarchy_style, $level_index = -1){
1544

    
1545
    $level_index++;
1546
    static $enclosingTag = "span";
1547

    
1548
    $level_style = array_pop($hierarchy_style);
1549
    if(count($hierarchy_style) == 0){
1550
      // lowest defined level style will be reused for all following levels
1551
      $hierarchy_style[] = $level_style;
1552
    }
1553

    
1554
    $node_index = -1;
1555
    $per_node_markup = array();
1556
    foreach ($tree_nodes as $node){
1557

    
1558
      $per_node_markup[++$node_index] = '';
1559

    
1560
      $label = $node->nodeId->representation_L10n;
1561

    
1562
      $distributions = $node->data;
1563
      $distribution_uuids = array();
1564
      $distribution_aggregate = NULL;
1565
        foreach($distributions as $distribution){
1566

    
1567
          $distribution_uuids[] = $distribution->uuid;
1568

    
1569
          // if there is more than one distribution we aggregate the sources and
1570
          // annotations into a synthetic distribution so that the footnote keys
1571
          // can be rendered consistently
1572
          if(!$distribution_aggregate) {
1573
            $distribution_aggregate = $distribution;
1574
            if(!isset($distribution_aggregate->sources[0])){
1575
              $distribution_aggregate->sources = array();
1576
            }
1577
            if(!isset($distribution_aggregate->annotations[0])){
1578
              $distribution_aggregate->annotations = array();
1579
            }
1580
          } else {
1581
            if(isset($distribution->sources[0])) {
1582
              $distribution_aggregate->sources = array_merge($distribution_aggregate->sources,
1583
                $distribution->sources);
1584
            }
1585
            if(isset($distribution->annotations[0])) {
1586
              $distribution_aggregate->annotations = array_merge($distribution_aggregate->annotations,
1587
                $distribution->annotations);
1588
            }
1589
          }
1590
        }
1591

    
1592
      $status_label= '';
1593
      $status_markup = '';
1594
      $annotations_and_sources =  null;
1595
      if($distribution_aggregate) {
1596
        $annotations_and_sources = handle_annotations_and_sources(
1597
          $distribution_aggregate,
1598
          $feature_block_settings,
1599
          $label,
1600
          UUID_DISTRIBUTION
1601
        );
1602

    
1603
        list($status_label, $status_markup) = distribution_status_label_and_markup($distribution);
1604
      }
1605

    
1606
      $per_node_markup[$node_index] .= '<' . $enclosingTag . ' class="descriptionElement'
1607
        . join(' descriptionElement-', $distribution_uuids)
1608
        . ' level_index_' . $level_index
1609
        . ' " title="' . $status_label . '">'
1610
        . '<span class="area_label">' . $label
1611
        . $level_style['label_suffix'] . ' </span>'
1612
        .  $status_markup
1613
      ;
1614

    
1615
      if(isset($annotations_and_sources)){
1616
        if(!empty($annotations_and_sources['source_references'])){
1617
          $per_node_markup[$node_index] .= ' ' . join(', ' , $annotations_and_sources['source_references']);
1618
        }
1619
        if($annotations_and_sources['foot_note_keys']) {
1620
          $per_node_markup[$node_index] .= $annotations_and_sources['foot_note_keys'];
1621
        }
1622
      }
1623

    
1624
      if(isset($node->children[0])){
1625
        _compose_distribution_hierarchy(
1626
          $node->children,
1627
          $feature_block_settings,
1628
          $per_node_markup[$node_index],
1629
          $hierarchy_style,
1630
          $level_index
1631
        );
1632
      }
1633

    
1634
      $per_node_markup[$node_index] .= '</' . $enclosingTag . '>';
1635
    }
1636
    $markup .= $level_style['element_set_pre']  . join( $level_style['element_glue'], $per_node_markup) . $level_style['element_set_post'];
1637
  }
1638

    
1639

    
(2-2/8)