Project

General

Profile

Download (83.3 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Functions for dealing with CDM entities from the package model.name
5
 *
6
 * @copyright
7
 *   (C) 2007-2015 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 */
18

    
19
/**
20
 * @defgroup compose Compose functions
21
 * @{
22
 * Functions which are composing Drupal render arays
23
 *
24
 * The cdm_dataportal module needs to compose rather complex render arrays from
25
 * the data returned by the CDM REST service. The compose functions are
26
 * responsible for creating the render arrays.
27
 *
28
 * All these functions are also implementations of the compose_hook()
29
 * which is used in the proxy_content() function.
30
 * @}
31
 */
32

    
33

    
34
/**
35
 * Provides the name render template to be used within the page elements identified the the $renderPath.
36
 *
37
 * The render templates arrays contains one or more name render templates to be used within the page elements identified the the
38
 * renderPath. The renderPath is the key of the subelements whereas the value is the name render template.
39
 *
40
 * The render paths used for a cdm_dataportal page can be visualized by supplying the HTTP query parameter RENDER_PATH=1.
41
 *
42
 * It will be tried to find  the best matching default RenderTemplate by stripping the dot separated render path
43
 * element by element. If no matching template is found the DEFAULT will be used:
44
 *
45
 * - related_taxon.heterotypicSynonymyGroup.taxon_page_synonymy
46
 * - related_taxon.heterotypicSynonymyGroup.taxon_page_synonymy
47
 * - related_taxon.heterotypicSynonymyGroup.taxon_page_synonymy
48
 *
49
 * A single render template can be used for multiple render paths. In this case the according key of the render templates
50
 * array element should be the list of these render paths concatenated by ONLY a comma character without any whitespace.
51
 *
52
 * A render template is an associative array. The keys of this array are referring to the keys as defined in the part
53
 * definitions array.
54
 * @see get_partDefinition($taxonNameType) for more information
55
 *
56
 * The value of the render template element must be set to TRUE in order to let this part being rendered.
57
 * The namePart, nameAuthorPart and referencePart can also hold an associative array with a single
58
 * element: array('#uri' => TRUE). The value of the #uri element will be replaced by the according
59
 * links if the parameters $nameLink or $refenceLink are set.
60
 *
61
 * @param string $render_path
62
 *   The render path can consist of multiple dot separated elements
63
 *   @see RenderHints::getRenderPath()
64
 * @param string $nameLink
65
 *   The link path or URL to be used for name parts if a link is forseen in the template
66
 *   matching the given $renderPath.
67
 * @param string $referenceLink
68
 *   The link path ot URL to be used for nomenclatural reference parts if a link is forseen
69
 *   in the template matching the given $renderPath.
70
 * @return array
71
 *   An associative array, the render template
72
 */
73
function get_nameRenderTemplate($render_path, $nameLink = NULL, $referenceLink = NULL) {
74

    
75
  static $split_render_templates = NULL;
76

    
77
  if($split_render_templates == NULL) {
78
    $render_templates = variable_get(NameRenderConfiguration::CDM_NAME_RENDER_TEMPLATES, NameRenderConfiguration::CDM_NAME_RENDER_TEMPLATES_DEFAULT);
79
    // needs to be converted to an array
80
    $render_templates = (object_to_array($render_templates));
81

    
82
    // separate render templates which are combined with a comma
83
    $split_render_templates = array();
84
    foreach($render_templates as $key => $template){
85
      if(strpos($key, ',')){
86
        foreach(explode(',', $key) as $path){
87
          $split_render_templates[$path] = $template;
88
        }
89
      } else {
90
        $split_render_templates[$key] = $template;
91
      }
92
    }
93
  }
94

    
95
  // get the base element of the renderPath
96
  if (($separatorPos = strpos($render_path, '.')) > 0) {
97
    $renderPath_base = substr($render_path, 0, $separatorPos);
98
  } else {
99
    $renderPath_base = $render_path;
100
  }
101

    
102
  $template = NULL;
103
  // 1. try to find a template using the render path base element
104
  if(array_key_exists($renderPath_base, $split_render_templates)){
105
    $template = (array)$split_render_templates[$renderPath_base];
106
  }
107

    
108
  // 2. Find best matching default RenderTemplate
109
  // by stripping the dot separated render path element by element
110
  // if no matching template is found the DEFAULT will be used.
111
  while (!is_array($template) && strlen($render_path) > 0) {
112
    foreach ($split_render_templates as $path => $t) {
113
      if ($path == $render_path) {
114
        $template = $t;
115
        break;
116
      }
117
    }
118
    // shorten by one element
119
    $render_path = substr($render_path, strrpos($render_path, '.') + 1, strlen($render_path));
120
  }
121

    
122

    
123
  // 3. Otherwise get default RenderTemplate from theme.
124
  if (!is_array($template)) {
125
    $template = $split_render_templates['#DEFAULT'];
126
  }
127

    
128
  // --- set the link uris to the according template fields if they exist
129
  if(isset($template['nameAuthorPart']) && isset($template['nameAuthorPart']['#uri'])) {
130
    if ($nameLink) {
131
      $template['nameAuthorPart']['#uri'] = $nameLink;
132
    }
133
    else {
134
      unset($template['nameAuthorPart']['#uri']);
135
    }
136
  }
137

    
138
  if ($nameLink && isset($template['namePart']['#uri'])) {
139
    $template['namePart']['#uri'] = $nameLink;
140
  }
141
  else {
142
    unset($template['namePart']['#uri']);
143
  }
144

    
145
  if ($referenceLink && isset($template['referencePart']['#uri'])) {
146
    $template['referencePart']['#uri'] = $referenceLink;
147
  }
148
  else {
149
    unset($template['referencePart']['#uri']);
150
  }
151

    
152
  return $template;
153
}
154

    
155
/**
156
 * The part definitions define the specific parts of which a rendered taxon name plus additional information will consist.
157
 *
158
 * A full taxon name plus additional information can consist of the following elements:
159
 *
160
 *   - name: the taxon name inclugin rank nbut without author
161
 *   - authorTeam:  The authors of a reference, also used in taxon names
162
 *   - authors:  The authors of a reference, also used in taxon names
163
 *   - reference: the nomenclatural reference,
164
 *   - microreference:  Volume, page number etc.
165
 *   - status:  The nomenclatural status of a name
166
 *   - description: name descriptions like protologues etc ...
167
 *
168
 * These elements are combined in the part definitions array to from the specific parts to be rendered.
169
 * Usually the following parts are formed:
170
 *
171
 * The name "Lapsana communis L., Sp. Pl.: 811. 1753" shall be an example here:
172
 *  - namePart: the name and rank (in example: "Lapsana communis")
173
 *  - authorshipPart: the author (in example: "L.")
174
 *  - nameAuthorPart: the combination of name and author part (in example: "Lapsana communis L.").
175
 *     This is useful for zoological names where the authorshipPart belongs to the name and both should
176
 *     be combined when a link to the taxon is rendered.
177
 *  - referencePart: the nomencaltural reference (in example: "Sp. Pl. 1753")
178
 *  - microreferencePart: usually the page number (in example ": 811.")
179
 *  - statusPart: the nomenclatorical status
180
 *  - descriptionPart:
181
 *
182
 * Each set of parts is dedicated to render a specific TaxonName type, the type names are used as keys for the
183
 * specific parts part definitions:
184
 *
185
 *  - BotanicalName
186
 *  - ZoologicalName
187
 *  - #DEFAULT:  covers ViralNames and general NonViralNames
188
 *
189
 * An example:
190
 * @code
191
 * array(
192
 *    'ZoologicalName' => array(
193
 *        'namePart' => array('name' => TRUE),
194
 *        'referencePart' => array('authorTeam' => TRUE),
195
 *        'microreferencePart' => array('microreference' => TRUE),
196
 *        'statusPart' => array('status' => TRUE),
197
 *        'descriptionPart' => array('description' => TRUE),
198
 *    ),
199
 *    'BotanicalName' => array(
200
 *        'namePart' => array(
201
 *            'name' => TRUE,
202
 *            'authors' => TRUE,
203
 *        ),
204
 *        'referencePart' => array(
205
 *            'reference' => TRUE,
206
 *            'microreference' => TRUE,
207
 *        ),
208
 *        'statusPart' => array('status' => TRUE),
209
 *        'descriptionPart' => array('description' => TRUE),
210
 *    ),
211
 *  );
212
 * @endcode
213
 *
214
 * @param object $taxonNameType
215
 *    A cdm TaxonNameType entity
216
 *
217
 */
218
function get_partDefinition($taxonNameType) {
219

    
220
  static $part_definitions = null;
221
  if (!isset($part_definitions)) {
222
    $part_definitions = object_to_array(variable_get(NameRenderConfiguration::CDM_PART_DEFINITIONS, NameRenderConfiguration::CDM_PART_DEFINITIONS_DEFAULT));
223
  }
224

    
225
  $dtype = nameTypeToDTYPE($taxonNameType);
226
  if (array_key_exists($taxonNameType, $part_definitions)) {
227
    return $part_definitions[$taxonNameType];
228
  } else if (array_key_exists($dtype, $part_definitions)) {
229
    return $part_definitions[$dtype];
230
  } else {
231
    return $part_definitions['#DEFAULT']; // covers ViralNames and general NonViralNames
232
  }
233

    
234
}
235

    
236

    
237
/**
238
 * Renders the markup for a CDM TaxonName instance.
239
 *
240
 * The layout of the name representation is configured by the
241
 * part_definitions and render_templates (see get_partDefinition() and
242
 * get_nameRenderTemplate())
243
 *
244
 * @param $taxon_name_or_taxon_base
245
 *    A cdm TaxonBase or TaxonName entity
246
 * @param $name_link
247
 *    URI to the taxon, @param $reference_link
248
 *    URI to the reference,
249
 * @param bool $show_taxon_name_annotations
250
 *    Enable the display of footnotes for annotations on the taxon and name
251
 *    (default: true)
252
 * @param bool $is_type_designation
253
 *    To indicate that the supplied taxon name is a name type designation.
254
 *    (default: false)
255
 * @param array $skip_render_template_parts
256
 *    The render template elements matching these part names will bes skipped.
257
 *    This parameter should only be used in rare cases like for suppressing
258
 *    the sec reference of synonyms. Normally the configuration of the
259
 *    name appearance should only be done via the render templates themselves. (default: [])
260
 * @param bool $is_invalid
261
 *   Indicates that this taxon is invalid. In this case the name part will be shown in double quotes.
262
 *   This is useful when rendering taxon relation ships. (default: false)
263
 *
264
 * @return string
265
 *  The markup for a taxon name.
266
 * @see path_to_taxon(), must be processed by url() before passing to this method
267
 * @see path_to_reference(), must be processed by url() before passing to this method
268
 */
269
function render_taxon_or_name($taxon_name_or_taxon_base, $name_link = NULL, $reference_link = NULL,
270
  $show_taxon_name_annotations = true, $is_type_designation = false, $skip_render_template_parts = [], $is_invalid = false) {
271

    
272
  $is_doubtful = false;
273
  $taxon_base = null;
274
  $nom_status_fkey = null; // FootNoteKey
275
  if($taxon_name_or_taxon_base->class == 'Taxon' || $taxon_name_or_taxon_base->class == 'Synonym'){
276
    $taxon_base = $taxon_name_or_taxon_base;
277
    if(isset($taxon_name_or_taxon_base->name)){
278
      $taxon_name = $taxon_name_or_taxon_base->name;
279
    } else {
280
      $taxon_name = cdm_ws_get(CDM_WS_TAXON . '/$0/name', array($taxon_name_or_taxon_base->uuid));
281
    }
282
    $is_doubtful = $taxon_name_or_taxon_base->doubtful;
283
    // use the TaxonBase.tagged_title so we have the secRef
284
    $tagged_title = $taxon_name_or_taxon_base->taggedTitle;
285
  } else {
286
    // assuming this is a TaxonName
287
    $taxon_name = $taxon_name_or_taxon_base;
288
    if(isset($taxon_name->taggedFullTitle)){
289
      $tagged_title = $taxon_name_or_taxon_base->taggedFullTitle;
290
    } else {
291
      $tagged_title = $taxon_name_or_taxon_base->taggedName;
292
    }
293
  }
294

    
295

    
296
  $renderTemplate = get_nameRenderTemplate(RenderHints::getRenderPath(), $name_link, $reference_link);
297
  $partDefinition = get_partDefinition($taxon_name->nameType);
298

    
299
  // Apply definitions to template.
300
  foreach ($renderTemplate as $part => $uri) {
301

    
302
    if (isset($partDefinition[$part])) {
303
      $renderTemplate[$part] = $partDefinition[$part];
304
    }
305
    if (is_array($uri) && isset($uri['#uri'])) {
306
      $renderTemplate[$part]['#uri'] = $uri['#uri'];
307
    }
308
  }
309

    
310
  foreach($skip_render_template_parts as $part){
311
    unset($renderTemplate[$part]);
312
  }
313

    
314
  $secref_tagged_text = tagged_text_extract_reference_and_detail($tagged_title);
315
  // taxon names will have the nomenclatural reference in the tagged full title:
316
  $nomref_tagged_text = tagged_text_extract_reference($tagged_title);
317
  $nom_status_tagged_text = tagged_text_extract_nomstatus($tagged_title);
318
  $appended_phrase_tagged_text = array(); // this is filled later
319

    
320
  normalize_tagged_text($tagged_title);
321

    
322
  $is_valid_tagged_title =
323
    isset($tagged_title)
324
    && is_array($tagged_title)
325
    && isset($tagged_title[0]->text)
326
    && is_string($tagged_title[0]->text)
327
    && $tagged_title[0]->text != ''
328
    && isset($tagged_title[0]->type);
329
  $lastAuthorElementString = FALSE;
330

    
331
  $name_encasement = $is_invalid ? '"' : '';
332
  $doubtful_marker = $is_doubtful ? '?&#8239;' : ''; // 	&#8239; =  NARROW NO-BREAK SPACE
333
  $doubtful_marker_markup = '';
334

    
335
  if($doubtful_marker){
336
    $doubtful_marker_markup = '<span class="doubtful">' . $doubtful_marker . '</span>';
337
    if($tagged_title[0]->text == '?' ){
338
      // remove the first tagged text element
339
      unset($tagged_title[0]);
340
    }
341
  }
342

    
343
  // split off all appendedPhrase item  from the end of the array (usually there only should  be one)
344
  while($tagged_title[count($tagged_title)-1]->type == "appendedPhrase"){
345
    $appended_phrase_tagged_text[] = array_pop($tagged_title);
346
  }
347

    
348
  // Got to use second entry as first one, see ToDo comment below ...
349
  if ($is_valid_tagged_title) {
350

    
351
    $taggedName = $tagged_title;
352
    $hasNamePart_with_Authors = isset($renderTemplate['namePart']) && isset($renderTemplate['namePart']['authors']);
353
    $hasNameAuthorPart_with_Authors = isset($renderTemplate['nameAuthorPart']) && isset($renderTemplate['nameAuthorPart']['authors']);
354

    
355

    
356
    if (!(($hasNamePart_with_Authors) || ($hasNameAuthorPart_with_Authors))) {
357
      // Find author and split off from name.
358
      // TODO expecting to find the author as the last element.
359
      /*
360
      if($taggedName[count($taggedName)- 1]->type == 'authors'){
361
        $authorTeam = $taggedName[count($taggedName)- 1]->text;
362
        unset($taggedName[count($taggedName)- 1]);
363
      }
364
      */
365

    
366
      // Remove all authors.
367
      $taggedNameNew = array();
368
      foreach ($taggedName as $element) {
369
        if ($element->type != 'authors') {
370
          $taggedNameNew[] = $element;
371
        }
372
        else {
373
          $lastAuthorElementString = $element->text;
374
        }
375
      }
376
      $taggedName = $taggedNameNew;
377
      unset($taggedNameNew);
378
    }
379
    $name = '<span class="' . $taxon_name->class . '">' . $doubtful_marker_markup . $name_encasement . cdm_tagged_text_to_markup($taggedName) . $name_encasement . '</span>';
380
  }
381
  else {
382
    // use titleCache instead
383
    $name = '<span class="' . $taxon_name->class . '_titleCache">' . $doubtful_marker_markup . $name_encasement . $taxon_name->titleCache . $name_encasement . '</span>';
384
  }
385

    
386

    
387
  if(isset($appended_phrase_tagged_text[0])){
388
    $name .= ' <span class="appended-phrase">'. cdm_tagged_text_to_markup($appended_phrase_tagged_text) . '</span>';
389
  }
390

    
391
  // Fill name into $renderTemplate.
392
  array_setr('name', $name , $renderTemplate);
393

    
394
  // Fill with authorTeam.
395
  /*
396
  if($authorTeam){
397
    $authorTeamHtml = ' <span class="authorTeam">'.$authorTeam.'</span>';
398
    array_setr('authorTeam', $authorTeamHtml, $renderTemplate);
399
  }
400
  */
401

    
402
  // Fill with reference.
403
  if (isset($renderTemplate['referencePart']) && !$is_type_designation) {
404

    
405
    $registrations = cdm_ws_get(CDM_WS_NAME, array($taxon_name->uuid, "registrations"));
406
    $registration_markup = render_registrations($registrations);
407

    
408
    // default separator
409
    $separator = '';
410

    
411
    // [Eckhard]:"Komma nach dem Taxonnamen ist grundsätzlich falsch,
412
    // Komma nach dem Autornamen ist überall dort falsch, wo ein "in" folgt."
413
    if (isset($renderTemplate['referencePart']['reference']) && isset($taxon_name->nomenclaturalSource)) {
414
      $microreference = $taxon_name->nomenclaturalSource->citationMicroReference;
415
      if(count($nomref_tagged_text) == 0 && isset($taxon_name->nomenclaturalSource->citation)){
416
        // TODO is this case still relevant? The tagged text should already contain all information!
417
        $citation = cdm_ws_getNomenclaturalReference($taxon_name->nomenclaturalSource->citation->uuid, $microreference);
418
        // Find preceding element of the reference.
419
        $precedingKey = get_preceding_contentElementKey('reference', $renderTemplate);
420
        if (str_beginsWith($citation, ", in")) {
421
          $citation = substr($citation, 2);
422
          $separator = ' ';
423
        }
424
        elseif (!str_beginsWith($citation, "in") && $precedingKey == 'authors') {
425
          $separator = ', ';
426
        } else {
427
          $separator = ' ';
428
        }
429
        $referenceArray['#separator'] = $separator;
430
        $referenceArray['#html'] = '<span class="reference">' . $citation . '</span>' . $registration_markup;
431
      } else {
432
        // this is the case for taxon names
433
        $referenceArray['#html'] = cdm_tagged_text_to_markup($nomref_tagged_text);
434
      }
435

    
436
      array_setr('reference', $referenceArray, $renderTemplate);
437
    }
438

    
439
    // If authors have been removed from the name part the last named authorteam
440
    // should be added to the reference citation, otherwise, keep the separator
441
    // out of the reference.
442
    if (isset($renderTemplate['referencePart']['authors']) && $lastAuthorElementString) {
443
      // If the nomenclaturalReference citation is not included in the
444
      // reference part but display of the microreference
445
      // is wanted, append the microreference to the authorTeam.
446
      $citation = '';
447
      if (!isset($renderTemplate['referencePart']['reference']) && isset($renderTemplate['referencePart']['microreference'])) {
448
        $separator = ": ";
449
        $citation = $taxon_name->nomenclaturalMicroReference;
450
      }
451
      $referenceArray['#html'] = ' <span class="reference">' . $lastAuthorElementString . $separator . $citation . '</span>';
452
      array_setr('authors', $referenceArray, $renderTemplate);
453
    }
454
  }
455

    
456
  $is_reference_year = false;
457
  if (isset($renderTemplate['referenceYearPart']['reference.year'])) {
458
    if(isset($taxon_name->nomenclaturalSource->citation->datePublished)){
459
      $referenceArray['#html'] = ' <span class="reference">' . timePeriodToString($taxon_name->nomenclaturalSource->citation->datePublished) . '</span>';
460
      array_setr('reference.year', $referenceArray, $renderTemplate);
461
      $is_reference_year = true;
462
    }
463
  }
464

    
465
  // Fill with status.
466
  if(isset($renderTemplate['statusPart']['status'])){
467
    if (isset($nom_status_tagged_text[0])) {
468
        $tt_to_markup_options = array('html' => false);
469
        foreach ($nom_status_tagged_text as &$tt){
470
         if($tt->type == 'nomStatus'&& isset($tt->entityReference)) {
471
           $nom_status = cdm_ws_get(CDM_WS_NOMENCLATURALSTATUS, array($tt->entityReference->uuid));
472
           $nom_status_fkey = handle_nomenclatural_status_as_footnote($nom_status);
473
           $tt_to_markup_options['html'] = true;
474
         }
475
        }
476
        array_setr(
477
          'status',
478
          '<span class="nomenclatural_status">' . cdm_tagged_text_to_markup($nom_status_tagged_text, array('postSeparator'), 'span', $tt_to_markup_options) . '</span>',
479
          $renderTemplate);
480
    }
481
  }
482

    
483
  if (isset($renderTemplate['secReferencePart'])){
484
    if(isset($secref_tagged_text[1])){
485
      $post_separator_markup = $is_reference_year ? '.': '';
486
      if(isset($nom_status_tagged_text[count($nom_status_tagged_text) - 1]) && ($nom_status_tagged_text[count($nom_status_tagged_text) - 1]->type ==  'postSeparator')){
487
        $post_separator_markup = cdm_tagged_text_to_markup(array($nom_status_tagged_text[count($nom_status_tagged_text) - 1 ]));
488
      };
489
      array_setr('secReference',
490
        $post_separator_markup
491
          . ' <span class="sec_reference">'
492
          . join('', cdm_tagged_text_values($secref_tagged_text))
493
          . '</span>', $renderTemplate);
494
    }
495
  }
496

    
497
  // Fill with protologues etc...
498
  $protologue_links = [];
499
  if (array_setr('description', TRUE, $renderTemplate)) {
500
    $external_links = cdm_ws_get(CDM_WS_NAME_PROTOLOGUE_LINKS, $taxon_name->uuid);
501
    if($external_links){
502
      foreach ($external_links as $link) {
503
        if (!empty($link->uri)) {
504
          // for the link see also cdm_external_uri()
505
          $protologue_links[] = l(font_awesome_icon_markup('fa-book'), $link->uri, ['html' => true]);
506
          }
507
        }
508
      }
509

    
510
    // ---------------
511

    
512
    $additional_pub_markup = '';
513
      $descriptions = cdm_ws_get(CDM_WS_PORTAL_NAME_DESCRIPTIONS, $taxon_name->uuid);
514
      if($descriptions) {
515
        foreach ($descriptions as $description) {
516
          if (!empty($description)) {
517
            $additional_citations = [];
518
            $additional_data = [];
519
            foreach ($description->elements as $description_element) {
520
              if (isset($description_element->multilanguageText_L10n) && $description_element->multilanguageText_L10n->text) {
521
                $element_media = cdm_description_element_media(
522
                  $description_element,
523
                  [
524
                    'application/pdf',
525
                    'image/png',
526
                    'image/jpeg',
527
                    'image/gif',
528
                    'text/html',
529
                  ]
530
                );
531
                // FIXME handle annotations and sources
532
                if (isset($description_element->feature) && $description_element->feature->uuid == UUID_ADDITIONAL_PUBLICATION) {
533
                   $additional_citations[] = ' [& ' . $description_element->multilanguageText_L10n->text . $element_media . ']';
534
                } else {
535
                  $additional_data[] = ' [' . $description_element->multilanguageText_L10n->text . $element_media . ']';
536
                }
537
              }
538
            }
539
            // merge
540
            $additional_citations = array_merge($additional_citations, $additional_data);
541
            $additional_pub_markup .= join(',', $additional_citations);
542
          }
543
        }
544
      }
545
      if($additional_pub_markup){
546
        $additional_pub_markup = ' ' . $additional_pub_markup . '. '; // surround with space etc.
547
      }
548
      array_setr('description', $additional_pub_markup . join(', ', $protologue_links), $renderTemplate);
549
      array_replace_keyr('description', 'protologue', $renderTemplate); // in preparation for #9319
550
  }
551

    
552
  // Render.
553
  $out = '';
554
  if(isset($_REQUEST['RENDER_PATH'])){
555
    // developer option to show the render path with each taxon name
556
    $out .= '<span class="render-path">' . RenderHints::getRenderPath() . '</span>';
557
  }
558
  $out .= '<span class="' . html_class_attribute_ref($taxon_name_or_taxon_base)
559
    . '" data-cdm-ref="/name/' . $taxon_name->uuid . '" data-cdm-render-path="' . RenderHints::getRenderPath() .'">';
560

    
561
  foreach ($renderTemplate as $partName => $part) {
562
    $separator = '';
563
    $partHtml = '';
564
    $uri = FALSE;
565
    if (!is_array($part)) {
566
      continue;
567
    }
568
    if (isset($part['#uri']) && is_string($part['#uri'])) {
569
      $uri = $part['#uri'];
570
      unset($part['#uri']);
571
    }
572
    foreach ($part as $part => $content) {
573
      $html = '';
574
      if (is_array($content)) {
575
        $html = $content['#html'];
576
        if(isset($content['#separator'])) {
577
          $separator = $content['#separator'];
578
        }
579
      }
580
      elseif (is_string($content)) {
581
        $html = $content;
582
      }
583
      if($html){ // skip empty elements
584
        $partHtml .= '<span class="' . $part . '">' . $html . '</span>';
585
      }
586
    }
587
    if ($uri) {
588
      // cannot use l() here since the #uri already should have been processed through uri() at this point
589
      $out .= $separator . '<a href="' . $uri . '" class="' . $partName . '">' . $partHtml . '</a>';
590

    
591
    }
592
    else {
593
      $out .= $separator . $partHtml;
594
    }
595
  }
596
  $out .= '</span>';
597

    
598
  $annotations_and_sources = new AnnotationsAndSources();
599
  if($nom_status_fkey){
600
    // the nomenclatural status footnote key refers to the source citation
601
    $annotations_and_sources->addFootNoteKey($nom_status_fkey);
602
  }
603
  if ($show_taxon_name_annotations) {
604
    if($taxon_base){
605
      $annotations_and_sources = handle_annotations_and_sources($taxon_base,
606
        null, null, $annotations_and_sources);
607
    }
608
    $annotations_and_sources = handle_annotations_and_sources($taxon_name,
609
      null, null, $annotations_and_sources);
610
  }
611
  $out .= $annotations_and_sources->footNoteKeysMarkup();
612
  return $out;
613
}
614

    
615

    
616

    
617
/**
618
 * Composes information for a registration from a dto object.
619
 *
620
 * Registrations which are not yet published are suppressed.
621
 *
622
 * @param $registration_dto
623
 * @param $with_citation
624
 *   Whether to show the citation.
625
 *
626
 * @return array
627
 *    A drupal render array with the elements:
628
 *    - 'name'
629
 *    - 'name-relations'
630
 *    - 'specimen_type_designations'
631
 *    - 'name_type_designations'
632
 *    - 'citation'
633
 *    - 'registration_date_and_institute'
634
 * @ingroup compose
635
 */
636
function compose_registration_dto_full($registration_dto, $with_citation = true)
637
{
638
  $render_array = array(
639
    '#prefix' => '<div class="registration">',
640
    '#suffix' => '</div>'
641
  );
642

    
643
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
644
    return $render_array;
645
  }
646

    
647
  $render_array['sub_headline'] = markup_to_render_array(join(", ", registration_types($registration_dto)),-10, '<h3 class="registration_type">' . t('Event: '), '</h3>' );
648
  $render_array['nomenclatural_act'] = array(
649
    '#weight' => 0,
650
    '#prefix' => '<div class="nomenclatural_act">',
651

    
652
    '#suffix' => '</div>'
653
  );
654

    
655
  $typified_name = null;
656

    
657
  // Nomenclatural act block element
658
  $last_footnote_listkey = RenderHints::setFootnoteListKey("nomenclatural_act");
659
  // name
660
  $name_relations = null;
661
  if(isset($registration_dto->nameRef) && $registration_dto->nameRef){
662
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
663
    cdm_load_tagged_full_title($name);
664
    $render_array['nomenclatural_act']['published_name'] = markup_to_render_array('<div class="published-name">' . render_taxon_or_name($name, url(path_to_name($name->uuid))) . '</div>', 0);
665
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
666
    // need to create the name relationships later, so that the foot notes are in correct order, see section // name relations
667
  } else {
668
    // in this case the registration must have a
669
    // typified name will be rendered later
670
    $typified_name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
671

    
672
  }
673

    
674
  // typedesignation in detail
675
  if(is_object($registration_dto->orderedTypeDesignationWorkingSets)) {
676
    $field_unit_uuids = array();
677
    $specimen_type_designation_refs = array();
678
    $name_type_designation_refs = array();
679
    foreach ((array)$registration_dto->orderedTypeDesignationWorkingSets as $workingset_ref => $obj) {
680
      $tokens = explode("#", $workingset_ref);
681
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
682

    
683
      if ($tokens[0] == 'NameTypeDesignation') {
684
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
685
          if(!isset($name_type_designation_refs[$type_status])){
686
            $name_type_designation_refs[$type_status]  = $entity_reference_list;
687
          } else {
688
            array_push($name_type_designation_refs[$type_status] ,$entity_reference_list);
689
          }
690
        }
691
      } else if ($tokens[0] == 'FieldUnit'){
692
        $field_unit_uuids[] = $tokens[1];
693
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
694
          if(!isset($specimen_type_designation_refs[$type_status])){
695
            $specimen_type_designation_refs[$type_status] =  $entity_reference_list;
696
          } else {
697
            array_push($specimen_type_designation_refs[$type_status], $entity_reference_list);
698
          }
699
        }
700
      } else {
701
        drupal_set_message("Unimplemented type: " . $tokens[0], 'error');
702
      }
703
    }
704
    // type designations which are in this nomenclatural act.
705
    if (count($name_type_designation_refs) > 0) {
706
      $render_array['nomenclatural_act']['name_type_designations'] = compose_name_type_designations($name_type_designation_refs);
707
      $render_array['nomenclatural_act']['name_type_designations']['#prefix'] = '<p class="name_type_designations">';
708
      $render_array['nomenclatural_act']['name_type_designations']['#suffix'] = '</p>';
709
      $render_array['nomenclatural_act']['name_type_designations']['#weight'] = 20;
710
    }
711
    if (count($field_unit_uuids) > 0) {
712
      $specimen_type_designations_array = compose_specimen_type_designations($specimen_type_designation_refs, true);
713
      $render_array['nomenclatural_act']['specimen_type_designations'] = $specimen_type_designations_array['type_designations'];
714
      $render_array['map'] = $specimen_type_designations_array['map'];
715
      $render_array['map']['#weight'] = $render_array['nomenclatural_act']['#weight'] + 20;
716
    }
717
  }
718

    
719
  // name relations
720
  if($name_relations){
721
    $render_array['nomenclatural_act']['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
722
    $render_array['nomenclatural_act']['name_relations']['#weight'] = 10;
723
  }
724

    
725
  // citation
726
  if ($with_citation) {
727
    $render_array['citation'] = markup_to_render_array(
728
      "<div class=\"citation nomenclatural_act_citation" . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
729
      . "<span class=\"label\">published in: </span>"
730
      . $registration_dto->bibliographicInRefCitationString
731
      . l(custom_icon_font_markup('icon-interal-link-alt-solid', array('class' => array('superscript'))), path_to_reference($registration_dto->citationUuid), array('html' => true))
732
      . "</div>",
733
      $render_array['nomenclatural_act']['#weight'] + 10 );
734
  }
735

    
736
  $render_array['nomenclatural_act']['footnotes'] = markup_to_render_array(render_footnotes(),100);
737

    
738
  // END of nomenclatural act block
739
  RenderHints::setFootnoteListKey($last_footnote_listkey );
740

    
741
  if($typified_name){
742
    $render_array['typified_name'] = markup_to_render_array('<p class="typified-name">for ' . render_taxon_or_name($typified_name, url(path_to_name($typified_name->uuid))) . '</p>', 40);
743
  }
744

    
745
  // registration date and office
746
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto);
747
  if($registration_date_insitute_markup){
748
    $render_array['registration_date_and_institute'] = markup_to_render_array(
749
      $registration_date_insitute_markup . '</p>',
750
      100);
751
  }
752

    
753
  $render_array['page_footnotes'] = markup_to_render_array(render_footnotes(), 110);
754

    
755
  return $render_array;
756
}
757

    
758

    
759
/**
760
 * Composes a compact representation for a registrationDTO object
761
 *
762
 * Registrations which are not yet published are suppressed.
763
 *
764
 * @param $registration_dto
765
 * @param $style string
766
 *   The style of how to compose the 'identifier' and 'registration_date_and_institute' part with the summary
767
 *   - 'citation': Similar to the appearance of nomenclatural acts in print media
768
 *   - 'list-item' : style suitable for result lists etc
769
 *
770
 * @return array
771
 *    A drupal render array with the elements:
772
 *    - 'registration-metadata' when $style == 'list-item'
773
 *    - 'summary'
774
 * @ingroup compose
775
 */
776
function compose_registration_dto_compact($registration_dto, $style = 'citation', $tag_enclosing_summary = 'p')
777
{
778
  $render_array = array();
779
  $media_link_map = array();
780

    
781
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
782
    return $render_array;
783
  }
784

    
785
  $registration_date_institute_markup = render_registration_date_and_institute($registration_dto, 'span');
786
  $identifier_markup = render_link_to_registration($registration_dto->identifier);
787

    
788
  $tagged_text_options = array();
789
  if(isset($registration_dto->nameRef)){
790
    $tagged_text_options[] = array(
791
      'filter-type' => 'name',
792
      'prefix' => '<span class="registered_name">',
793
      'suffix' => '</span>',
794
    );
795
  } else {
796
    $tagged_text_options[] = array(
797
      'filter-type' => 'name',
798
      'prefix' => '<span class="referenced_typified_name">',
799
      'suffix' => '</span>',
800
    );
801
  }
802
  cdm_tagged_text_add_options($registration_dto->summaryTaggedText, $tagged_text_options);
803
  tagged_text_extract_reference($registration_dto->summaryTaggedText);
804
  $tagged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
805
  foreach ($tagged_text_expanded  as $tagged_text){
806
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
807
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
808
      if(isset($mediaDTOs[0]->uri)){
809
        $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
810
        $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
811
        $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
812
      }
813
    }
814
  }
815
  $registation_markup = cdm_tagged_text_to_markup($tagged_text_expanded);
816
  foreach($media_link_map as $media_url_key => $link){
817
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
818
  }
819
  if($style == 'citation') {
820
    $registation_markup = $registation_markup . ' ' . $identifier_markup . ' ' . $registration_date_institute_markup;
821
  } else {
822
    $render_array['registration-metadata'] = markup_to_render_array('<div class="registration-metadata">' . $identifier_markup . ' ' . $registration_date_institute_markup. "</div>", -10);
823
  }
824
  $render_array['summary'] = markup_to_render_array('<' . $tag_enclosing_summary . ' class="registration-summary">' . $registation_markup . '</' . $tag_enclosing_summary . '>', 0);
825

    
826
  return $render_array;
827
}
828

    
829
/**
830
 * Renders the registrationDate and institutionTitleCache of the $registration_dto as markup.
831
 *
832
 * @param $registration_dto
833
 * @return string
834
 *    The markup or an empty string
835
 */
836
function render_registration_date_and_institute($registration_dto, $enclosing_tag = 'p') {
837
  $registration_date_institute_markup = '';
838
  if ($registration_dto->registrationDate) {
839
    $date_string = format_datetime($registration_dto->registrationDate);
840
    if (isset($registration_dto->institutionTitleCache) && $registration_dto->institutionTitleCache) {
841
      $registration_date_institute_markup =
842
        t("Registration on @date in @institution", array(
843
          '@date' => $date_string,
844
          '@institution' => $registration_dto->institutionTitleCache,
845
        ));
846
    } else {
847
      $registration_date_institute_markup =
848
        t("Registration on @date", array(
849
          '@date' => $date_string
850
        ));
851
    }
852
    $registration_date_institute_markup = '<' .$enclosing_tag . ' class="registration-date-and-institute">'. $registration_date_institute_markup . '</' .$enclosing_tag . '>';
853
  }
854
  return $registration_date_institute_markup;
855
}
856

    
857

    
858
/**
859
 * @param $registrations
860
 * @return string
861
 */
862
function render_registrations($registrations)
863
{
864
  $registration_markup = '';
865
  $registration_markup_array = array();
866
  if ($registrations) {
867
    foreach ($registrations as $reg) {
868
      $registration_markup_array[] = render_registration($reg);
869
    }
870
    $registration_markup = " Registration" . (count($registration_markup_array) > 1 ? 's: ' : ': ')
871
      . join(', ', $registration_markup_array);
872
  }
873
  return $registration_markup;
874
}
875

    
876

    
877
/**
878
 * Renders a registration
879
 *
880
 * TODO replace by compose_registration_dto_compact
881
 * @param $registration
882
 */
883
function render_registration($registration){
884
  $markup = '';
885

    
886
  if(isset($registration->identifier) && $registration->status == 'PUBLISHED'){
887
    $office_class_attribute = '';
888
    if(isset($registration->institution->titleCache)){
889
      $office_class_attribute = registration_institution_class_attribute($registration);
890
    }
891
    $markup = "<span class=\"registration $office_class_attribute\">" . render_link_to_registration($registration->identifier) . ', '
892
      .  preg_replace('/^([^T]*)(.*)$/', '${1}', $registration->registrationDate)
893
      . '</span>';
894
  }
895
  return $markup;
896
}
897

    
898
/**
899
 * @param $registration
900
 * @return string
901
 */
902
function registration_institution_class_attribute($registration_dto)
903
{
904
  if(isset($registration_dto->institutionTitleCache)){
905
    $institutionTitleCache = $registration_dto->institutionTitleCache;
906
  } else {
907
    // fall back option to also support cdm entities
908
    $institutionTitleCache = @$registration_dto->institution->titleCache;
909
  }
910
  return $institutionTitleCache ? 'registration-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $institutionTitleCache)) : '';
911
}
912

    
913

    
914
/**
915
 * Renders and array of CDM TypeDesignations
916
 *
917
 *  - NameTypeDesignation
918
 *  - SpecimenTypeDesignation
919
 *  - TextualTypeDesignation
920
 *
921
 * @param object $type_designations an array of cdm TypeDesignation entities
922
 *  to render
923
 * @param string $enclosing_tag the tag element type to enclose the whole list
924
 *  of type designation with. By default this DOM element is <ul>
925
 * @param string $element_tag the tag element type to be used for each
926
 *  type designation item.
927
 * @param bool $link_to_specimen_page whether a specimen in type designation element
928
 *  should be a link or not.
929
 *
930
 * @return string The markup.
931
 *
932
 * @InGroup Render
933
 */
934
function render_type_designations($type_designations, $enclosing_tag = 'ul', $element_tag =  'li', $link_to_specimen_page = true) {
935

    
936
  // need to add element to render path since type designations
937
  // need other name render template
938
  RenderHints::pushToRenderStack('typedesignations');
939

    
940
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
941
  $specimen_type_designations = array();
942
  $name_type_designations = array();
943
  $textual_type_designations = array();
944
  $separator = ',';
945

    
946
  foreach ($type_designations as $type_designation) {
947
    switch ($type_designation->class) {
948
      case 'SpecimenTypeDesignation':
949
        $specimen_type_designations[] = $type_designation;
950
        break;
951
      case 'NameTypeDesignation':
952
        $name_type_designations[] = $type_designation;
953
        break;
954
      case 'TextualTypeDesignation':
955
        $textual_type_designations[] = $type_designation;
956
        break;
957
      default:  throw new Exception('Unknown type designation class: ' . $type_designation->class);
958
    }
959
  }
960

    
961
  // NameTypeDesignation ..................................
962
  if(!empty($name_type_designations)){
963
    usort($name_type_designations, "compare_type_designations_by_status");
964
    foreach($name_type_designations as $name_type_designation){
965
      if ($name_type_designation->notDesignated) {
966
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation)  . ': '
967
          . t('not designated') . '</'. $element_tag .'>';
968
      }
969
      elseif (isset($name_type_designation->typeName)) {
970
        $link_to_name_page = url(path_to_name($name_type_designation->typeName->uuid));
971
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation) ;
972

    
973
        if (!empty($name_type_designation->source->citation)) {
974
          $out .= type_designation_citation_layout($name_type_designation, $separator); // TODO type_designation_citation_layout() needs most probably to be replaced
975

    
976
        }
977
        $referenceUri = '';
978
        if (isset($name_type_designation->typeName->nomenclaturalSource->citation)) {
979
          $referenceUri = url(path_to_reference($name_type_designation->typeName->nomenclaturalSource->citation->uuid));
980
        }
981
        $out .= ': ' . render_taxon_or_name($name_type_designation->typeName, $link_to_name_page, $referenceUri, TRUE, TRUE);
982
      }
983
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
984
      $annotations_and_sources = handle_annotations_and_sources($name_type_designation);
985
      $out .= $annotations_and_sources->footNoteKeysMarkup();
986
    }
987
  } // END NameTypeDesignation
988

    
989
  // SpecimenTypeDesignation ...................................
990
  if (!empty($specimen_type_designations)) {
991
    usort($specimen_type_designations, "compare_specimen_type_designation");
992
    foreach ($specimen_type_designations as $specimen_type_designation) {
993
      $type_citation_markup = '';
994

    
995
      if (!empty($specimen_type_designation->source->citation)) {
996

    
997
        $citation_footnote_str = cdm_reference_markup($specimen_type_designation->source->citation, null, false, true);
998
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $specimen_type_designation->source->citation->uuid);
999

    
1000
        if (!empty($author_team->titleCache)) {
1001
          $year = @timePeriodToString($specimen_type_designation->source->citation->datePublished, true, 'YYYY');
1002
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
1003
          if ($authorteam_str == $specimen_type_designation->source->citation->titleCache) {
1004
            $citation_footnote_str = '';
1005
          }
1006
        } else {
1007
          $authorteam_str = $citation_footnote_str;
1008
          // no need for a footnote in case in case it is used as replacement for missing author teams
1009
          $citation_footnote_str = '';
1010
        }
1011

    
1012
        // for being registered a typedesignation MUST HAVE a citation, so it is save to handle the
1013
        // Registration output in if condition checking if the citation is present
1014
        $registration_markup = render_registrations($specimen_type_designation->registrations);
1015
        $citation_footnote_str .= ($citation_footnote_str ? ' ' : '') . $registration_markup;
1016

    
1017
        $footnote_key_markup = '';
1018
        if ($citation_footnote_str) {
1019
          // footnotes should be rendered in the parent element so we
1020
          // are relying on the FootnoteListKey set there
1021
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
1022
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
1023
        }
1024

    
1025
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
1026
        if (!empty($specimen_type_designation->source->citationMicroReference)) {
1027
          $type_citation_markup .= ': ' . trim($specimen_type_designation->source->citationMicroReference);
1028
        }
1029
        $type_citation_markup .= $footnote_key_markup . ')';
1030

    
1031
      }
1032

    
1033

    
1034
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($specimen_type_designation) . '">';
1035
      $out .= type_designation_status_label_markup($specimen_type_designation) . $type_citation_markup;
1036

    
1037

    
1038
      $derivedUnitFacadeInstance = null;
1039
      if (isset($specimen_type_designation->typeSpecimen)) {
1040
        $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $specimen_type_designation->typeSpecimen->uuid);
1041
      }
1042

    
1043
      if (!empty($derivedUnitFacadeInstance->titleCache)) {
1044
        $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1045
        if($link_to_specimen_page && isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1046
          $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($specimen_type_designation->typeSpecimen->uuid)), $specimen_markup);
1047
        }
1048
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1049
        $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1050
        $out .= ': <span class="' . html_class_attribute_ref($specimen_type_designation->typeSpecimen) . '">'
1051
          . $specimen_markup
1052
          . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1053
        if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1054
          $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1055
        }
1056
        $out .= $annotations_and_sources->footNoteKeysMarkup();
1057
      }
1058
      $out .= '</'. $element_tag .'>';
1059
    }
1060
  } // END Specimen type designations
1061

    
1062
  // TextualTypeDesignation .........................
1063
  usort($textual_type_designations, 'compare_textual_type_designation');
1064
  if(!empty($textual_type_designations)) {
1065
      RenderHints::setAnnotationsAndSourceConfig([
1066
          // these settings differ from those provided by annotations_and_sources_config_typedesignations()
1067
          // TODO is this by purpose? please document the reason for the difference
1068
          'sources_as_content' => false, // as footnotes
1069
          'link_to_name_used_in_source' => false,
1070
          'link_to_reference' => true,
1071
          'add_footnote_keys' => true,
1072
          'bibliography_aware' => false
1073
        ]
1074
      );
1075
    foreach ($textual_type_designations as $textual_type_designation) {
1076
      $annotations_and_sources = handle_annotations_and_sources($textual_type_designation);
1077
      $encasement =  $textual_type_designation->verbatim ? '"' : '';
1078
      $out .= '<' . $element_tag . ' class="' . html_class_attribute_ref($textual_type_designation) . '">' . type_designation_status_label_markup(null)
1079
        . ': ' .  $encasement . trim($textual_type_designation->text_L10n->text) . $encasement .  $annotations_and_sources->footNoteKeysMarkup() .'</' . $element_tag . '>';
1080
//      if($annotations_and_sources->hasSourceReferences())){
1081
//        $citation_markup = join(', ', getSourceReferences());
1082
//      }
1083
//      $out .= $citation_markup;
1084
    }
1085
  }
1086

    
1087
  // Footnotes for citations, collection acronyms.
1088
  // footnotes should be rendered in the parent element so we
1089
  // are relying on the FootnoteListKey set there
1090
  $_fkey = FootnoteManager::addNewFootnote(
1091
    RenderHints::getFootnoteListKey(),
1092
    (isset($derivedUnitFacadeInstance->collection->titleCache) ? $derivedUnitFacadeInstance->collection->titleCache : FALSE)
1093
  );
1094
  $out .= render_footnote_key($_fkey, $separator);
1095
  $out .= '</' . $enclosing_tag .'>';
1096

    
1097
  RenderHints::popFromRenderStack();
1098

    
1099
  return $out;
1100
}
1101

    
1102
/**
1103
 * Creates markup for a list of SpecimenTypedesignationDTO
1104
 *
1105
 * @param array $specimen_typedesignation_dtos
1106
 *  The SpecimenTypedesignationDTOs to be rendered
1107
 *
1108
 * @param bool $show_type_specimen
1109
 *
1110
 * @param string $enclosing_tag
1111
 * @param string $element_tag
1112
 *
1113
 * @return string
1114
 *   The markup.
1115
 */
1116
function render_specimen_typedesignation_dto($specimen_typedesignation_dtos, $show_type_specimen = FALSE, $enclosing_tag = 'ul', $element_tag = 'li'){
1117

    
1118
  // need to add element to render path since type designations
1119
  // need other name render template
1120
  RenderHints::pushToRenderStack('typedesignations');
1121

    
1122
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
1123
  $separator = ',';
1124

    
1125
  if (!empty($specimen_typedesignation_dtos)) {
1126
    // usort($specimen_type_designations, "compare_specimen_type_designation"); // FIXME create compare function for SpecimenTypedesignationDTO
1127
    foreach ($specimen_typedesignation_dtos as $std_dto) {
1128
      $type_citation_markup = '';
1129

    
1130
      if (!empty($std_dto->source->citation)) {
1131

    
1132
        $citation_footnote_str = cdm_reference_markup($std_dto->source->citation, null, false, true);
1133
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $std_dto->source->citation->uuid);
1134

    
1135
        if (!empty($author_team->titleCache)) {
1136
          $year = @timePeriodToString($std_dto->source->citation->datePublished, true, 'YYYY');
1137
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
1138
          if ($authorteam_str == $std_dto->source->citation->titleCache) {
1139
            $citation_footnote_str = '';
1140
          }
1141
        } else {
1142
          $authorteam_str = $citation_footnote_str;
1143
          // no need for a footnote in case in case it is used as replacement for missing author teams
1144
          $citation_footnote_str = '';
1145
        }
1146

    
1147
        // for being registered a typedesignation MUST HAVE a citation, so it is save to handle the
1148
        // Registration output in the conditional block which has been checked that the citation is present
1149
        $registration_markup = render_registrations($std_dto->registrations);
1150
        $citation_footnote_str .= ($citation_footnote_str ? ' ' : '') . $registration_markup;
1151

    
1152
        $footnote_key_markup = '';
1153
        if ($citation_footnote_str) {
1154
          // footnotes should be rendered in the parent element so we
1155
          // are relying on the FootnoteListKey set there
1156
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
1157
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
1158
        }
1159

    
1160
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
1161
        if (!empty($std_dto->source->citationMicroReference)) {
1162
          $type_citation_markup .= ': ' . trim($std_dto->source->citationMicroReference);
1163
        }
1164
        $type_citation_markup .= $footnote_key_markup . ')';
1165
      }
1166

    
1167
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($std_dto) . '">';
1168
      $out .= type_designation_dto_status_label_markup($std_dto) . $type_citation_markup;
1169

    
1170
      if($show_type_specimen){
1171
        $derivedUnitFacadeInstance = null;
1172
        if (isset($std_dto->typeSpecimen)) {
1173
          $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $std_dto->typeSpecimen->uuid);
1174
        }
1175

    
1176
        if (!empty($derivedUnitFacadeInstance->titleCache)) {
1177
          $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1178
          if(isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1179
            $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($std_dto->typeSpecimen->uuid)), $specimen_markup);
1180
          }
1181
          RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1182
          $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1183
          $out .= ': <span class="' . html_class_attribute_ref($std_dto->typeSpecimen) . '">'
1184
            . $specimen_markup
1185
            . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1186
          if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1187
            $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1188
          }
1189
          $out .= $annotations_and_sources->footNoteKeysMarkup();
1190
        }
1191
      }
1192

    
1193
      $out .= '</'. $element_tag .'>';
1194
    }
1195
    RenderHints::popFromRenderStack();
1196
  }
1197
  return $out;
1198
}
1199

    
1200

    
1201
/**
1202
 * Composes the textual representation for the type designation of taxon name identified by the uuid in with a map for the location data.
1203
 *
1204
 * @param $taxon_name_uuid
1205
 * @param $show_specimen_details
1206
 * @return array
1207
 *    A drupal render array with the following elements:
1208
 *    - 'type_designations'
1209
 *    - 'map'
1210
 *    - 'specimens'
1211
 *
1212
 * @ingroup compose
1213
 */
1214
function compose_type_designations($taxon_name_uuid, $show_specimen_details = false)
1215
{
1216
  $render_array = array(
1217
    'type_designations' => array(),
1218
    'map' => array(),
1219
    );
1220
  $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name_uuid);
1221
  if ($type_designations) {
1222
    usort($type_designations, 'compare_specimen_type_designation');
1223
    $render_array['type_designations'] = markup_to_render_array(
1224
      render_type_designations($type_designations, 'div', 'div')
1225
    );
1226

    
1227
    $render_array['map'] = compose_type_designations_map($type_designations);
1228
  }
1229
  return $render_array;
1230
}
1231

    
1232

    
1233
/**
1234
 * Composes the TypedEntityReference to name type designations passed as associatve array.
1235
 *
1236
 * @param $type_entity_refs_by_status array
1237
 *   an associative array of name type type => TypedEntityReference for name type designations as
1238
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1239
 *
1240
 * @ingroup compose
1241
 */
1242
function compose_name_type_designations($type_entity_refs_by_status){
1243
  $render_array = array();
1244
  $preferredStableUri = '';
1245
  foreach($type_entity_refs_by_status as $type_status => $name_type_entityRefs){
1246
    foreach ($name_type_entityRefs as $name_type_entity_ref){
1247
      $type_designation = cdm_ws_get(CDM_WS_TYPEDESIGNATION, array($name_type_entity_ref->uuid, 'preferredUri'));
1248
      $footnote_keys = '';
1249

    
1250
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1251
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1252
      }
1253
      // annotations and sources for the $derived_unit_facade_dto
1254
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1255
      $annotations_and_sources = handle_annotations_and_sources($name_type_entity_ref);
1256

    
1257
      $render_array[] = markup_to_render_array('<div class="name_type_designation ' . html_class_attribute_ref($name_type_entity_ref)  .
1258
        '"><span class="type-status">'. ucfirst($type_status) . "</span>: "
1259
        . cdm_tagged_text_to_markup($name_type_entity_ref->taggedText)
1260
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1261
        . $annotations_and_sources->footNoteKeysMarkup()
1262
        . '</div>');
1263
      }
1264
  }
1265
  return $render_array;
1266
}
1267

    
1268
/**
1269
 * Composes the specimen type designations with map from the the $type_entity_refs
1270
 *
1271
 * @param $type_entity_refs array
1272
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
1273
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1274
 *
1275
 * @param $show_media_specimen
1276
 * @return array
1277
 *    A drupal render array with the following elements:
1278
 *    - 'type_designations'
1279
 *    - 'map'
1280
 *
1281
 * @ingroup compose
1282
 *
1283
 */
1284
function compose_specimen_type_designations($type_entity_refs, $show_media_specimen){
1285

    
1286
  $render_array = array();
1287

    
1288
  $type_designation_list = array();
1289
  uksort($type_entity_refs, "compare_type_designation_status_labels");
1290
  foreach($type_entity_refs as $type_status => $type_designation_entity_refs){
1291
    foreach($type_designation_entity_refs as $type_designation_entity_ref){
1292

    
1293
      $type_designation = cdm_ws_get(CDM_WS_PORTAL_TYPEDESIGNATION, array($type_designation_entity_ref->uuid));
1294
      $type_designation_list[] = $type_designation; // collect for the map
1295

    
1296
      $derived_unit_facade_dto = cdm_ws_get(CDM_WS_PORTAL_DERIVEDUNIT_FACADE, $type_designation->typeSpecimen->uuid);
1297
      // the media specimen is not contained in the $type_designation returned by CDM_PORTAL_TYPEDESIGNATION, so we need to fetch it separately
1298
      $mediaSpecimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($type_designation->typeSpecimen->uuid, 'mediaSpecimen'));
1299

    
1300

    
1301
      $preferredStableUri = '';
1302
      $citation_markup = '';
1303
      $media = '';
1304

    
1305
      // annotations and sources for the $derived_unit_facade_dto
1306
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1307
      $annotations_and_sources = handle_annotations_and_sources($derived_unit_facade_dto);
1308
      $source_citations = $annotations_and_sources->getSourceReferences();
1309
      $foot_note_keys = $annotations_and_sources->footNoteKeysMarkup();
1310

    
1311
      // preferredStableUri
1312
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1313
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1314
      }
1315

    
1316
      if($show_media_specimen && $mediaSpecimen){
1317
        // compose output
1318
        // mediaURI
1319
        if(isset($mediaSpecimen->representations[0])) {
1320
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
1321
          $captionElements = array(
1322
            '#uri' => t('open media'),
1323
            'elements' => array('-none-'),
1324
            'sources_as_content' => true
1325
          );
1326
          $media = compose_cdm_media_gallerie(array(
1327
            'mediaList' => array($mediaSpecimen),
1328
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $type_designation_entity_ref->uuid,
1329
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
1330
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
1331
            'captionElements' => $captionElements,
1332
          ));
1333
        }
1334
        // citation and detail for the media specimen
1335
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1336
        $annotations_and_sources = handle_annotations_and_sources($mediaSpecimen);
1337
        if($annotations_and_sources->hasSourceReferences()){
1338
          $source_citations = array_merge($source_citations, $annotations_and_sources->getSourceReferences());
1339
        }
1340
        if($annotations_and_sources->hasFootnoteKeys()){
1341
          $foot_note_keys .= ', ' . $annotations_and_sources->footNoteKeysMarkup();
1342
        }
1343
      }
1344

    
1345
      $citation_markup = join(', ', $source_citations);
1346

    
1347
      $specimen_markup = $derived_unit_facade_dto->titleCache;
1348
      if(isset($derived_unit_facade_dto->specimenLabel) && $derived_unit_facade_dto->specimenLabel){
1349
        $specimen_markup = str_replace(
1350
          $derived_unit_facade_dto->specimenLabel,
1351
          l($derived_unit_facade_dto->specimenLabel, path_to_specimen($type_designation->typeSpecimen->uuid)), $specimen_markup);
1352
      }
1353

    
1354
      $type_designation_render_array = markup_to_render_array(
1355
        '<div class="type_designation_entity_ref ' . html_class_attribute_ref($type_designation_entity_ref)  . '">
1356
          <span class="type-status">' . ucfirst($type_status) . "</span>: "
1357
        . $specimen_markup . $foot_note_keys
1358
        . ($citation_markup ? ' '. $citation_markup : '')
1359
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1360
        . $media
1361
        . '</div>');
1362

    
1363
      $render_array['type_designations'][] = $type_designation_render_array;
1364
    }
1365
  }
1366
  if(count($type_designation_list) > 0 ){
1367
    $render_array['map'] = compose_type_designations_map($type_designation_list);
1368
  } else {
1369
    $render_array['map'] = array();
1370
  }
1371
  return $render_array;
1372
}
1373

    
1374
/**
1375
 * Creates the markup for the given name relationship.
1376
 *
1377
 * For the footnotes see handle_annotations_and_sources().
1378
 *
1379
 * @param $other_name
1380
 *      The other name from the NameRelationship see get_other_name()
1381
 * @param $current_taxon_uuid
1382
 * @param $show_name_cache_only
1383
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
1384
 * @return null|string
1385
 *    The markup or null
1386
 *
1387
 * @see \get_other_name
1388
 */
1389
function name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only = false){
1390

    
1391
  $relationship_markup = null;
1392

    
1393
  $other_name = get_other_name($current_name_uuid, $name_rel);
1394

    
1395
  cdm_load_tagged_full_title($other_name);
1396

    
1397
  $highlited_synonym_uuid = isset ($other_name->taxonBases[0]->uuid) ? $other_name->taxonBases[0]->uuid : '';
1398
  if($show_name_cache_only){
1399
    $relationship_markup = l(
1400
      '<span class="' . html_class_attribute_ref($other_name) . '"">' . $other_name->nameCache . '</span>',
1401
      path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
1402
      array('html' => true)
1403
    );
1404
    $annotations_and_sources = handle_annotations_and_sources($other_name);
1405
    $relationship_markup .= $annotations_and_sources->footNoteKeysMarkup();
1406
  } else {
1407
    $relationship_markup = render_taxon_or_name($other_name,
1408
      url(path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
1409
    );
1410
  }
1411

    
1412
  return $relationship_markup;
1413
}
1414

    
1415
/**
1416
 * Determined the other name which is contained in the NameRelationship entity.
1417
 *
1418
 * @param $current_name_uuid
1419
 *   The uuid of this name.
1420
 * @param $name_rel
1421
 *   The cdm NameRelationship entity
1422
 *
1423
 * @return object
1424
 *   The other cdm Name entity.
1425
 */
1426
function get_other_name($current_name_uuid, $name_rel) {
1427
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
1428

    
1429
  if ($current_name_is_toName) {
1430
    $name = $name_rel->fromName;
1431
  }
1432
  else {
1433
    $name = $name_rel->toName;
1434
  }
1435
  return $name;
1436
}
1437

    
1438

    
1439
/**
1440
 * Composes an inline representation of selected name relationships
1441
 *
1442
 * The output of this function will be usually appended to taxon name representations.
1443
 * Only the following types are displayed: LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR, ORTHOGRAPHIC_VARIANT
1444
 *
1445
 * LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR are displayed as
1446
 * non {titleCache} nec {titleCache} nec {titleCache} whereas the related names
1447
 * are ordered alphabetically.
1448
 *
1449
 * ORTHOGRAPHIC_VARIANT is displayed as 'ort. var. {nameCache}'
1450
 *
1451
 * Related issues:
1452
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1453
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1454
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1455
 *   - https://dev.e-taxonomy.eu/redmine/issues/2001 "[Cichorieae Portal] Name Relationship -> blocking name are not shown"
1456
 *
1457
 * @param $name_relations
1458
 *    The list of CDM NameRelationsips
1459
 * @param $current_name_uuid
1460
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1461
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1462
 * @param $suppress_if_current_name_is_source
1463
 *    The display of the relation will be
1464
 *    suppressed is the current name is on the source of the relation edge.
1465
 *    That is if it is on the from side of the relation. Except for 'blocking name for' which is
1466
 *    an inverse relation. For this relation type the toName is taken in to account.
1467
 * @param $current_taxon_uuid
1468
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1469
 * @return array
1470
 *    A drupal render array
1471
 *
1472
 * @ingroup Compose
1473
 */
1474
function compose_name_relationships_inline($name_relations, $current_name_uuid, $current_taxon_uuid, $suppress_if_current_name_is_source = true) {
1475

    
1476
  RenderHints::pushToRenderStack('homonym');
1477
  // the render stack element homonyms is being used in the default render templates !!!, see NameRenderConfiguration::CDM_NAME_RENDER_TEMPLATES_DEFAULT
1478

    
1479
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
1480
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1481
  foreach ($selected_name_rel_uuids as $uuid){
1482
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1483
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
1484
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
1485
    }
1486
  }
1487

    
1488
  $list_prefix = '<span class="name_relationships">[';
1489
  $list_suffix = ']</span>';
1490
  $item_prefix = '<span class="item">';
1491
  $item_suffix = '</span> ';
1492
  $render_array = compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid, $list_prefix, $list_suffix, $item_prefix, $item_suffix);
1493

    
1494
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1495
  $items_ctn = count($render_array['list']['items']);
1496
  if($items_ctn){
1497
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1498
  }
1499

    
1500
  RenderHints::popFromRenderStack();
1501
  return $render_array;
1502
}
1503

    
1504
/**
1505
 * Composes an list representation of the name relationships.
1506
 *
1507
 * The output of this function will be usually appended to taxon name representations.
1508
 *
1509
 * Related issues:
1510
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1511
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1512
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1513
 *
1514
 * @param $name_relations
1515
 *    The list of CDM NameRelationsips
1516
 * @param $current_name_uuid
1517
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1518
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1519
 * @param $current_taxon_uuid
1520
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1521
 * @return array
1522
 *    A drupal render array
1523
 *
1524
 * @ingroup Compose
1525
 */
1526
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1527

    
1528
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1529

    
1530
  $key = 'name_relationships';
1531
  RenderHints::pushToRenderStack($key);
1532
  if(RenderHints::isUnsetFootnoteListKey()){
1533
    RenderHints::setFootnoteListKey($key);
1534
  }
1535
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1536

    
1537
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, cdm_vocabulary_as_defaults(UUID_NAME_RELATIONSHIP_TYPE));
1538
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1539
  foreach ($selected_name_rel_uuids as $uuid){
1540
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1541
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1542
  }
1543

    
1544
  $list_prefix = '<div class="relationships_list name_relationships">';
1545
  $list_suffix = '</div>';
1546
  $item_prefix = '<div class="item">';
1547
  $item_suffix = '</div>';
1548

    
1549
  $render_array = compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid, $list_prefix, $list_suffix, $item_prefix, $item_suffix);
1550

    
1551
  RenderHints::popFromRenderStack();
1552
  if(RenderHints::getFootnoteListKey() == $key) {
1553
    $render_array['footnotes'] = markup_to_render_array(render_footnotes(RenderHints::getFootnoteListKey()));
1554
    RenderHints::clearFootnoteListKey();
1555
  }
1556
  return $render_array;
1557
}
1558

    
1559
/**
1560
 * @param $name_relations
1561
 * @param $name_rel_type_filter
1562
 *   Associative array with two keys:
1563
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1564
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1565
 * @param $current_name_uuid
1566
 * @param $current_taxon_uuid
1567
 * @param $list_prefix
1568
 * @param $list_suffix
1569
 * @param $item_prefix
1570
 * @param $item_suffix
1571
 * @return array
1572
 *
1573
 * @ingroup Compose
1574
 */
1575
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1576
                                    $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1577
{
1578
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1579
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1580
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1581
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1582
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1583

    
1584
  $render_array = array(
1585
    'list' => array(
1586
      '#prefix' => $list_prefix,
1587
      '#suffix' => $list_suffix,
1588
      'items' => array()
1589
    ),
1590
    'footnotes' => array()
1591
  );
1592

    
1593
  if ($name_relations) {
1594

    
1595
    // remove all relations which are not selected in the settings and
1596
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1597
    // for special handling
1598
    $filtered_name_rels = array();
1599
    $non_nec_name_rels = array();
1600
    $orthographic_variants = array();
1601
    foreach ($name_relations as $name_rel) {
1602
      $rel_type_uuid = $name_rel->type->uuid;
1603
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1604
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1605
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1606

    
1607
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1608
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1609
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1610
          )
1611
        ){
1612
          $non_nec_name_rels[] = $name_rel;
1613
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1614
          $orthographic_variants[] = $name_rel;
1615
        } else {
1616

    
1617
          $filtered_name_rels[] = $name_rel;
1618
        }
1619
      }
1620
    }
1621
    $name_relations = $filtered_name_rels;
1622

    
1623
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1624

    
1625
    // compose
1626
    $show_name_cache_only = FALSE;
1627
    foreach ($name_relations as $name_rel) {
1628

    
1629
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1630
      $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1631
      $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1632
      $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1633

    
1634
      $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1635
      $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup . ' ';
1636
      $relationship_markup = $symbol_markup . $relationship_markup;
1637
      if ($relationship_markup) {
1638
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1639
          null,
1640
          $item_prefix,
1641
          $item_suffix);
1642
      }
1643
    }
1644

    
1645
    // name relationships to be displayed as non nec
1646
    if (count($non_nec_name_rels) > 0) {
1647
      $non_nec_markup = '';
1648
      $show_name_cache_only = FALSE;
1649
      foreach ($non_nec_name_rels as $name_rel) {
1650

    
1651
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1652
        $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1653
        $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1654
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1655

    
1656
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1657
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1658
        $non_nec_markup .= $symbol_markup . $relationship_markup;
1659
      }
1660
      if ($non_nec_markup) {
1661
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1662
          null,
1663
          $item_prefix,
1664
          $item_suffix);
1665
      }
1666
    }
1667

    
1668
    // orthographic variants
1669
    if (count($orthographic_variants) > 0) {
1670
      $show_name_cache_only = TRUE;
1671
      foreach ($orthographic_variants as $name_rel) {
1672

    
1673
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1674
        $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1675
        $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1676
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1677
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1678
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1679
        $relationship_markup = $symbol_markup . $relationship_markup;
1680
      }
1681
      if (isset($relationship_markup) && $relationship_markup) {
1682
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1683
          null,
1684
          $item_prefix,
1685
          $item_suffix);
1686
      }
1687
    }
1688
  }
1689
  return $render_array;
1690
}
1691

    
1692

    
1693

    
1694
/**
1695
 * @param $taxon
1696
 * @return array
1697
 */
1698
function cdm_name_relationships_for_taxon($taxon)
1699
{
1700
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1701
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1702
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1703
  return $name_relations;
1704
}
1705

    
1706

    
1707
/**
1708
 * Recursively searches the array for the $key and sets the given value.
1709
 *
1710
 * Expects the key to be used only once in nested array structures.
1711
 *
1712
 * @param mixed $key
1713
 *   Key to search for.
1714
 * @param mixed $value
1715
 *   Value to set.'
1716
 * @param array $array
1717
 *   Array to search in.
1718
 *
1719
 * @return array
1720
 *   The array the key has been found.
1721
 */
1722
function &array_setr($key, $value, array &$array) {
1723
  $res = NULL;
1724
  foreach ($array as $k => &$v) {
1725
    if ($key == $k) {
1726
      $v = $value;
1727
      return $array;
1728
    }
1729
    elseif (is_array($v)) {
1730
      $innerArray = array_setr($key, $value, $v);
1731
      if ($innerArray) {
1732
        return $array;
1733
      }
1734
    }
1735
  }
1736
  return $res;
1737
}
1738

    
1739
/**
1740
 * Recursively searches the array for the $key and sets is to $new_key
1741
 *
1742
 * Expects the key to be used only once in nested array structures.
1743
 *
1744
 * @param mixed $key
1745
 *   Key to search for.
1746
 * @param mixed $new_key
1747
 *   The new key to use
1748
 * @param array $array
1749
 *   Array to search in.
1750
 *
1751
 * @return bool
1752
 *   True if the key has been found.
1753
 */
1754
function array_replace_keyr($key, $new_key, array &$array) {
1755
  $res = NULL;
1756
  if(array_key_exists($key, $array)){
1757
    $value = $array[$key];
1758
    unset($array[$key]);
1759
    $array[$new_key] = $value;
1760
    return true;
1761
  } else {
1762
    // search in next level
1763
    foreach ($array as &$v) {
1764
        if (is_array($v)) {
1765
          array_replace_keyr($key, $new_key, $v);
1766
        }
1767
      }
1768
  }
1769

    
1770
  return false;
1771
}
1772

    
1773
/**
1774
 * @todo Please document this function.
1775
 * @see http://drupal.org/node/1354
1776
 */
1777
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1778
  $res = NULL;
1779
  $precedingElement = NULL;
1780
  foreach ($renderTemplate as &$part) {
1781
    foreach ($part as $key => &$element) {
1782
      if ($key == $contentElementKey) {
1783
        return $precedingElement;
1784
      }
1785
      $precedingElement = $element;
1786
    }
1787
  }
1788
  return $res;
1789
}
1790

    
1791
/**
1792
 * @todo Please document this function.
1793
 * @see http://drupal.org/node/1354
1794
 */
1795
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1796
  $res = NULL;
1797
  $precedingKey = NULL;
1798
  foreach ($renderTemplate as &$part) {
1799
    if (is_array($part)) {
1800
      foreach ($part as $key => &$element) {
1801
        if ($key == $contentElementKey) {
1802
          return $precedingKey;
1803
        }
1804
        if (!str_beginsWith($key, '#')) {
1805
          $precedingKey = $key;
1806
        }
1807
      }
1808
    }
1809
  }
1810
  return $res;
1811
}
1812

    
1813
function nameTypeToDTYPE($dtype){
1814
  static $nameTypeLabelMap = array(
1815
    "ICNB" => "BacterialName",
1816
    "ICNAFP" => "BotanicalName",
1817
    "ICNCP" => "CultivarPlantName",
1818
    "ICZN" => "ZoologicalName",
1819
    "ICVCN" => "ViralName",
1820
    "Any taxon name" => "TaxonName",
1821
    "NonViral" => "TaxonName",
1822
    "Fungus" => "BotanicalName",
1823
    "Plant" => "BotanicalName",
1824
    "Algae" => "BotanicalName",
1825
  );
1826
  return $nameTypeLabelMap[$dtype];
1827

    
1828
}
1829

    
1830

    
1831
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1832
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1833
}
1834

    
1835
/**
1836
 * Provides an array with the different registration types covered by the passed registration.
1837
 *
1838
 * The labels in the returned array are translatable.
1839
 *
1840
 * See also https://dev.e-taxonomy.eu/redmine/issues/8016
1841
 *
1842
 * @param $registration_dto
1843
 * @return array
1844
 *    An array of the labels describing the different registration types covered by the passed registration.
1845
 */
1846
function registration_types($registration_dto){
1847
  $reg_type_labels = array();
1848
  if(isset($registration_dto->nameRef)){
1849
    $reg_type_labels["name"] = t("new name");
1850
    $reg_type_labels["taxon"] = t("new taxon");
1851
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1852
    $is_new_combination = true;
1853
    foreach($name_relations as $name_rel){
1854
      if(isset($name_rel->type->uuid)){
1855
        $name_is_from_name = $registration_dto->nameRef->uuid == $name_rel->fromName->uuid;
1856
        switch($name_rel->type->uuid) {
1857
          case UUID_NAMERELATIONSHIPTYPE_BASIONYM:
1858
            if(!$name_is_from_name){
1859
              $reg_type_labels["basionym"] = t("new combination");
1860
              $is_new_combination = true;
1861
            }
1862
            break;
1863
          case UUID_NAMERELATIONSHIPTYPE_REPLACED_SYNONYM:
1864
            if(!$name_is_from_name) {
1865
              $is_new_combination = true;
1866
            }
1867
            break;
1868
          case UUID_NAMERELATIONSHIPTYPE_VALIDATED_BY_NAME:
1869
            if(!$name_is_from_name) {
1870
              $reg_type_labels["validation"] = t("validation");
1871
            }
1872
            break;
1873
          case UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT:
1874
            if(!$name_is_from_name) {
1875
              $reg_type_labels["orth_var"] = t("orthographical correction");
1876
            }break;
1877
          default:
1878
            // NOTHING
1879
        }
1880
      }
1881
    }
1882
    if($is_new_combination){
1883
      unset($reg_type_labels["taxon"]);
1884
    }
1885
  }
1886
  if(isset($registration_dto->orderedTypeDesignationWorkingSets)){
1887
    $reg_type_labels[] = t("new nomenclatural type");
1888
  }
1889
  return $reg_type_labels;
1890
}
1891

    
1892
/**
1893
 * Collects and deduplicates the type designations associated with the passes synonyms.
1894
 *
1895
 * @param $synonymy_group
1896
 *    An array containing a homotypic or heterotypic group of names.
1897
 * @param $accepted_taxon_name_uuid
1898
 *    The uuid of the accepted taxon name. Optional parameter which is required when composing
1899
 *    the information for the homotypic group. In this case the accepted taxon is not included
1900
 *    in the $synonymy_group and must therefor passed in this second parameter.
1901
 *
1902
 * @return array
1903
 *    The CDM TypeDesignation entities
1904
 */
1905
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null)
1906
{
1907
  if (count($synonymy_group) > 0) {
1908
    $name_uuid = array_pop($synonymy_group)->name->uuid;
1909
  } else {
1910
    $name_uuid = $accepted_taxon_name_uuid;
1911
  }
1912
  if ($name_uuid) {
1913
   $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS_IN_HOMOTYPICAL_GROUP, $name_uuid);
1914
    if ($type_designations) {
1915
      return $type_designations;
1916
    }
1917
  }
1918

    
1919
  return array();
1920
}
1921

    
1922

    
1923
/**
1924
 * Compares two SpecimenTypeDesignations
1925
 *
1926
 * @param object $a
1927
 *   A SpecimenTypeDesignation.
1928
 * @param object $b
1929
 *   SpecimenTypeDesignation.
1930
 */
1931
function compare_specimen_type_designation($a, $b) {
1932

    
1933
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1934
  if($cmp_by_status !== 0){
1935
    return $cmp_by_status;
1936
  }
1937

    
1938
  $aQuantifier = FALSE;
1939
  $bQuantifier = FALSE;
1940
  if ($aQuantifier == $bQuantifier) {
1941
    // Sort alphabetically.
1942
    $a_text =  isset($a->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $a->typeSpecimen->titleCache) : '';
1943
    $b_text =  isset($b->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $b->typeSpecimen->titleCache) : '';
1944
    return strcasecmp($a_text, $b_text);
1945
  }
1946
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1947
}
1948

    
1949
/**
1950
 * Compares the status of two TypeDesignations
1951
 *
1952
 * @param object $a
1953
 *   A TypeDesignation
1954
 * @param object $b
1955
 *   TypeDesignation
1956
 */
1957
function compare_type_designations_by_status($a, $b) {
1958
  $status_a = isset($a->typeStatus) ? $a->typeStatus : null;
1959
  $status_b = isset($b->typeStatus) ? $b->typeStatus : null;
1960
  return compare_type_designation_status($status_a, $status_b);
1961
}
1962

    
1963
/**
1964
 * Compares two TypeDesignationStatusBase
1965
 *
1966
 * @param object $a
1967
 *   A TypeDesignationStatusBase.
1968
 * @param object $b
1969
 *   TypeDesignationStatusBase.
1970
 */
1971
function compare_type_designation_status($a, $b) {
1972
  $type_status_order = type_status_order();
1973
  $aQuantifier = FALSE;
1974
  $bQuantifier = FALSE;
1975
  if (isset($a->label) && isset($b->label)) {
1976
    $aQuantifier = array_search($a->label, $type_status_order);
1977
    $bQuantifier = array_search($b->label, $type_status_order);
1978
  }
1979
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1980
}
1981

    
1982
/**
1983
 * Compares the two TextualTypeDesignations
1984
 *
1985
 * @param object $a
1986
 *   A TextualTypeDesignations.
1987
 * @param object $b
1988
 *   TextualTypeDesignations.
1989
 */
1990
function compare_textual_type_designation($a, $b) {
1991

    
1992
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1993
  if($cmp_by_status !== 0){
1994
    return $cmp_by_status;
1995
  }
1996

    
1997
  $aQuantifier = FALSE;
1998
  $bQuantifier = FALSE;
1999
  if ($aQuantifier == $bQuantifier) {
2000
    // Sort alphabetically.
2001
    $a_text =  isset($a->text_L10n->text) ? $a->text_L10n->text : '';
2002
    $b_text =  isset($b->text_L10n->text) ? $b->text_L10n->text : '';
2003
    return strcasecmp($a_text, $b_text);
2004
  }
2005
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
2006
}
2007

    
2008

    
2009
/**
2010
 * Compares two SpecimenTypeDesignation status labels
2011
 *
2012
 * @param string $a
2013
 *   A TypeDesignationStatus label.
2014
 * @param string $b
2015
 *   A TypeDesignationStatus label.
2016
 */
2017
function compare_type_designation_status_labels($a, $b) {
2018

    
2019
  $type_status_order = type_status_order();
2020

    
2021
  $aQuantifier = FALSE;
2022
  $bQuantifier = FALSE;
2023
  if (isset($a) && isset($b)) {
2024
    $aQuantifier = array_search(ucfirst($a), $type_status_order);
2025
    $bQuantifier = array_search(ucfirst($b), $type_status_order);
2026
  }
2027
  return ($aQuantifier < $bQuantifier) ? -1 : 1;
2028
}
2029

    
2030
/**
2031
 * Preliminary implementation of a preset to define a sort order for
2032
 * type designation status.
2033
 *
2034
 * TODO this is only preliminary and may break in future,
2035
 *      see https://dev.e-taxonomy.eu/redmine/issues/8402?issue_count=96&issue_position=4&next_issue_id=8351&prev_issue_id=7966#note-4
2036
 * @return array
2037
 *   The array of orderd type labels
2038
 */
2039
function type_status_order()
2040
{
2041
  /*
2042
    This is the desired sort order as of now: Holotype Isotype Lectotype
2043
    Isolectotype Syntype.
2044
    TODO Basically, what we are trying to do is, we define
2045
    an ordered array of TypeDesignation-states and use the index of this array
2046
    for comparison. This array has to be filled with the cdm- TypeDesignation
2047
    states and the order should be parameterisable inside the dataportal.
2048
    */
2049
  static $type_status_order = array(
2050
    'Epitype',
2051
    'Holotype',
2052
    'Isotype',
2053
    'Lectotype',
2054
    'Isolectotype',
2055
    'Syntype',
2056
    'Paratype'
2057
  );
2058
  return $type_status_order;
2059
}
2060

    
2061
/**
2062
 * Return HTML for the lectotype citation with the correct layout.
2063
 *
2064
 * This function prints the lectotype citation with the correct layout.
2065
 * Lectotypes are renderized in the synonymy tab of a taxon if they exist.
2066
 *
2067
 * @param mixed $typeDesignation
2068
 *   Object containing the lectotype citation to print.
2069
 *
2070
 * @return string
2071
 *   Valid html string.
2072
 */
2073
function type_designation_citation_layout($typeDesignation, $footnote_separator = ',') {
2074
  $res = '';
2075
  $citation = $typeDesignation->source->citation;
2076
  $pages = $typeDesignation->source->citationMicroReference;
2077
  if(isset($typeDesignation->typeStatus->uuid) && isset($typeDesignation->typeStatus->representation_L10n)) {
2078
    if ( $typeDesignation->typeStatus->uuid == UUID_NTD_ORIGINAL_DESIGNATION || $typeDesignation->typeStatus->uuid == UUID_NTD_MONOTYPY) {
2079
      $res = ' (' . $typeDesignation->typeStatus->representation_L10n . ')';
2080
      return $res;
2081
    }
2082
  }
2083

    
2084
  if ($citation) {
2085
    // $type = $typeDesignation_citation->type;
2086
    $year = isset($citation->datePublished->start) ? substr($citation->datePublished->start, 0, 4) : '';
2087
    $author = isset($citation->authorship->titleCache) ? $citation->authorship->titleCache : '';
2088
    $res .= ' (designated by ';
2089
    $res .= $author;
2090
    $res .= ($year ? ' ' . $year : '');
2091
    $res .= ($pages ? ': ' . $pages : '');
2092
    // $res .= ')';
2093

    
2094
    // footnotes should be rendered in the parent element so we
2095
    // are relying on the FootnoteListKey set there
2096
    $fkey_typeDesignation = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation->titleCache);
2097
    $res .= render_footnote_key($fkey_typeDesignation, $footnote_separator,TRUE) . ')';
2098
  }
2099
  return $res;
2100
}
2101

    
2102
/**
2103
 * Creates markup for the status of a type designation. In case the status or its representation is missing the label will be set to "Type"
2104
 *
2105
 * @param $type_designation
2106
 * @return string
2107
 */
2108
function type_designation_status_label_markup($type_designation)
2109
{
2110
  return '<span class="type-status">'
2111
    . ((isset($type_designation->typeStatus->representation_L10n)) ? ucfirst($type_designation->typeStatus->representation_L10n) : t('Type')) . '</span>'
2112
    ;
2113
}
2114

    
2115
/**
2116
 * Creates markup for the status of a type designation DTO.
2117
 * In case the status or its representation is missing the label will be set to "Type"
2118
 *
2119
 * @param $type_designation
2120
 * @return string
2121
 */
2122
function type_designation_dto_status_label_markup($type_designation)
2123
{
2124
  return '<span class="type-status">'
2125
    . ((isset($type_designation->typeStatus_L10n)) ? ucfirst($type_designation->typeStatus_L10n) : t('Type')) . '</span>'
2126
    ;
2127
}
(7-7/14)