Project

General

Profile

Download (81.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'])) {
414
      if(count($nomref_tagged_text) == 0 && isset($taxon_name->nomenclaturalSource->nomenclaturalCitation)){
415
        $citation = $taxon_name->nomenclaturalSource->nomenclaturalCitation;
416
        // Find preceding element of the reference.
417
        $precedingKey = get_preceding_contentElementKey('reference', $renderTemplate);
418
        if (str_beginsWith($citation, ", in")) {
419
          $citation = substr($citation, 2);
420
          $separator = ' ';
421
        }
422
        elseif (!str_beginsWith($citation, "in") && $precedingKey == 'authors') {
423
          $separator = ', ';
424
        } else {
425
          $separator = ' ';
426
        }
427
        $referenceArray['#separator'] = $separator;
428
        $referenceArray['#html'] = '<span class="reference">' . $citation . '</span>' . $registration_markup;
429
      } else {
430
        // this is the case for taxon names
431
        $referenceArray['#html'] = cdm_tagged_text_to_markup($nomref_tagged_text);
432
      }
433

    
434
      array_setr('reference', $referenceArray, $renderTemplate);
435
    }
436

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

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

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

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

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

    
511
  // Render.
512
  $out = '';
513
  if(isset($_REQUEST['RENDER_PATH'])){
514
    // developer option to show the render path with each taxon name
515
    $out .= '<span class="render-path">' . RenderHints::getRenderPath() . '</span>';
516
  }
517
  $out .= '<span class="' . html_class_attribute_ref($taxon_name_or_taxon_base)
518
    . '" data-cdm-ref="/name/' . $taxon_name->uuid . '" data-cdm-render-path="' . RenderHints::getRenderPath() .'">';
519

    
520
  foreach ($renderTemplate as $partName => $part) {
521
    $separator = '';
522
    $partHtml = '';
523
    $uri = FALSE;
524
    if (!is_array($part)) {
525
      continue;
526
    }
527
    if (isset($part['#uri']) && is_string($part['#uri'])) {
528
      $uri = $part['#uri'];
529
      unset($part['#uri']);
530
    }
531
    foreach ($part as $part => $content) {
532
      $html = '';
533
      if (is_array($content)) {
534
        $html = $content['#html'];
535
        if(isset($content['#separator'])) {
536
          $separator = $content['#separator'];
537
        }
538
      }
539
      elseif (is_string($content)) {
540
        $html = $content;
541
      }
542
      if($html){ // skip empty elements
543
        $partHtml .= '<span class="' . $part . '">' . $html . '</span>';
544
      }
545
    }
546
    if ($uri) {
547
      // cannot use l() here since the #uri already should have been processed through uri() at this point
548
      $out .= $separator . '<a href="' . $uri . '" class="' . $partName . '">' . $partHtml . '</a>';
549

    
550
    }
551
    else {
552
      $out .= $separator . $partHtml;
553
    }
554
  }
555
  $out .= '</span>';
556

    
557
  $annotations_and_sources = new AnnotationsAndSources();
558
  if($nom_status_fkey){
559
    // the nomenclatural status footnote key refers to the source citation
560
    $annotations_and_sources->addFootNoteKey($nom_status_fkey);
561
  }
562
  if ($show_taxon_name_annotations) {
563
    if($taxon_base){
564
      $annotations_and_sources = handle_annotations_and_sources($taxon_base,
565
        null, null, $annotations_and_sources);
566
    }
567
    $annotations_and_sources = handle_annotations_and_sources($taxon_name,
568
      null, null, $annotations_and_sources);
569
  }
570
  $out .= $annotations_and_sources->footNoteKeysMarkup();
571
  return $out;
572
}
573

    
574

    
575

    
576
/**
577
 * Composes information for a registration from a dto object.
578
 *
579
 * Registrations which are not yet published are suppressed.
580
 *
581
 * @param $registration_dto
582
 * @param $with_citation
583
 *   Whether to show the citation.
584
 *
585
 * @return array
586
 *    A drupal render array with the elements:
587
 *    - 'name'
588
 *    - 'name-relations'
589
 *    - 'specimen_type_designations'
590
 *    - 'name_type_designations'
591
 *    - 'citation'
592
 *    - 'registration_date_and_institute'
593
 * @ingroup compose
594
 */
595
function compose_registration_dto_full($registration_dto, $with_citation = true)
596
{
597
  $render_array = array(
598
    '#prefix' => '<div class="registration">',
599
    '#suffix' => '</div>'
600
  );
601

    
602
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
603
    return $render_array;
604
  }
605

    
606
  $render_array['sub_headline'] = markup_to_render_array(join(", ", registration_types($registration_dto)),-10, '<h3 class="registration_type">' . t('Event: '), '</h3>' );
607
  $render_array['nomenclatural_act'] = array(
608
    '#weight' => 0,
609
    '#prefix' => '<div class="nomenclatural_act">',
610

    
611
    '#suffix' => '</div>'
612
  );
613

    
614
  $typified_name = null;
615

    
616
  // Nomenclatural act block element
617
  $last_footnote_listkey = RenderHints::setFootnoteListKey("nomenclatural_act");
618
  // name
619
  $name_relations = null;
620
  if(isset($registration_dto->nameRef) && $registration_dto->nameRef){
621
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
622
    cdm_load_tagged_full_title($name);
623
    $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);
624
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
625
    // need to create the name relationships later, so that the foot notes are in correct order, see section // name relations
626
  } else {
627
    // in this case the registration must have a
628
    // typified name will be rendered later
629
    $typified_name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
630

    
631
  }
632

    
633
  // typedesignation in detail
634
  if(is_object($registration_dto->orderedTypeDesignationWorkingSets)) {
635
    $field_unit_uuids = array();
636
    $specimen_type_designation_refs = array();
637
    $name_type_designation_refs = array();
638
    foreach ((array)$registration_dto->orderedTypeDesignationWorkingSets as $workingset_ref => $obj) {
639
      $tokens = explode("#", $workingset_ref);
640
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
641

    
642
      if ($tokens[0] == 'NameTypeDesignation') {
643
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
644
          if(!isset($name_type_designation_refs[$type_status])){
645
            $name_type_designation_refs[$type_status]  = $entity_reference_list;
646
          } else {
647
            array_push($name_type_designation_refs[$type_status] ,$entity_reference_list);
648
          }
649
        }
650
      } else if ($tokens[0] == 'FieldUnit'){
651
        $field_unit_uuids[] = $tokens[1];
652
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
653
          if(!isset($specimen_type_designation_refs[$type_status])){
654
            $specimen_type_designation_refs[$type_status] =  $entity_reference_list;
655
          } else {
656
            array_push($specimen_type_designation_refs[$type_status], $entity_reference_list);
657
          }
658
        }
659
      } else {
660
        drupal_set_message("Unimplemented type: " . $tokens[0], 'error');
661
      }
662
    }
663
    // type designations which are in this nomenclatural act.
664
    if (count($name_type_designation_refs) > 0) {
665
      $render_array['nomenclatural_act']['name_type_designations'] = compose_name_type_designations($name_type_designation_refs);
666
      $render_array['nomenclatural_act']['name_type_designations']['#prefix'] = '<p class="name_type_designations">';
667
      $render_array['nomenclatural_act']['name_type_designations']['#suffix'] = '</p>';
668
      $render_array['nomenclatural_act']['name_type_designations']['#weight'] = 20;
669
    }
670
    if (count($field_unit_uuids) > 0) {
671
      $specimen_type_designations_array = compose_specimen_type_designations($specimen_type_designation_refs, true);
672
      $render_array['nomenclatural_act']['specimen_type_designations'] = $specimen_type_designations_array['type_designations'];
673
      $render_array['map'] = $specimen_type_designations_array['map'];
674
      $render_array['map']['#weight'] = $render_array['nomenclatural_act']['#weight'] + 20;
675
    }
676
  }
677

    
678
  // name relations
679
  if($name_relations){
680
    $render_array['nomenclatural_act']['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
681
    $render_array['nomenclatural_act']['name_relations']['#weight'] = 10;
682
  }
683

    
684
  // citation
685
  if ($with_citation) {
686
    $render_array['citation'] = markup_to_render_array(
687
      "<div class=\"citation nomenclatural_act_citation" . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
688
      . "<span class=\"label\">published in: </span>"
689
      . $registration_dto->bibliographicInRefCitationString
690
      . l(custom_icon_font_markup('icon-interal-link-alt-solid', array('class' => array('superscript'))), path_to_reference($registration_dto->citationUuid), array('html' => true))
691
      . "</div>",
692
      $render_array['nomenclatural_act']['#weight'] + 10 );
693
  }
694

    
695
  $render_array['nomenclatural_act']['footnotes'] = markup_to_render_array(render_footnotes(),100);
696

    
697
  // END of nomenclatural act block
698
  RenderHints::setFootnoteListKey($last_footnote_listkey );
699

    
700
  if($typified_name){
701
    $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);
702
  }
703

    
704
  // registration date and office
705
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto);
706
  if($registration_date_insitute_markup){
707
    $render_array['registration_date_and_institute'] = markup_to_render_array(
708
      $registration_date_insitute_markup . '</p>',
709
      100);
710
  }
711

    
712
  $render_array['page_footnotes'] = markup_to_render_array(render_footnotes(), 110);
713

    
714
  return $render_array;
715
}
716

    
717

    
718
/**
719
 * Composes a compact representation for a registrationDTO object
720
 *
721
 * Registrations which are not yet published are suppressed.
722
 *
723
 * @param $registration_dto
724
 * @param $style string
725
 *   The style of how to compose the 'identifier' and 'registration_date_and_institute' part with the summary
726
 *   - 'citation': Similar to the arrearance of nomenclatural acts in print media
727
 *   - 'list-item' : style suitable for result lists etc
728
 *
729
 * @return array
730
 *    A drupal render array with the elements:
731
 *    - 'registration-metadata' when $style == 'list-item'
732
 *    - 'summary'
733
 * @ingroup compose
734
 */
735
function compose_registration_dto_compact($registration_dto, $style = 'citation', $tag_enclosing_summary = 'p')
736
{
737
  $render_array = array();
738
  $media_link_map = array();
739

    
740
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
741
    return $render_array;
742
  }
743

    
744
  $registration_date_institute_markup = render_registration_date_and_institute($registration_dto, 'span');
745
  $identifier_markup = render_link_to_registration($registration_dto->identifier);
746

    
747
  $tagged_text_options = array();
748
  if(isset($registration_dto->nameRef)){
749
    $tagged_text_options[] = array(
750
      'filter-type' => 'name',
751
      'prefix' => '<span class="registered_name">',
752
      'suffix' => '</span>',
753
    );
754
  } else {
755
    $tagged_text_options[] = array(
756
      'filter-type' => 'name',
757
      'prefix' => '<span class="referenced_typified_name">',
758
      'suffix' => '</span>',
759
    );
760
  }
761
  cdm_tagged_text_add_options($registration_dto->summaryTaggedText, $tagged_text_options);
762
  tagged_text_extract_reference($registration_dto->summaryTaggedText);
763
  $tagged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
764
  foreach ($tagged_text_expanded  as $tagged_text){
765
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
766
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
767
      if(isset($mediaDTOs[0]->uri)){
768
        $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
769
        $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
770
        $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
771
      }
772
    }
773
  }
774
  $registation_markup = cdm_tagged_text_to_markup($tagged_text_expanded);
775
  foreach($media_link_map as $media_url_key => $link){
776
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
777
  }
778
  if($style == 'citation') {
779
    $registation_markup = $registation_markup . ' ' . $identifier_markup . ' ' . $registration_date_institute_markup;
780
  } else {
781
    $render_array['registration-metadata'] = markup_to_render_array('<div class="registration-metadata">' . $identifier_markup . ' ' . $registration_date_institute_markup. "</div>", -10);
782
  }
783
  $render_array['summary'] = markup_to_render_array('<' . $tag_enclosing_summary . ' class="registration-summary">' . $registation_markup . '</' . $tag_enclosing_summary . '>', 0);
784

    
785
  return $render_array;
786
}
787

    
788
/**
789
 * Renders the registrationDate and institutionTitleCache of the $registration_dto as markup.
790
 *
791
 * @param $registration_dto
792
 * @return string
793
 *    The markup or an empty string
794
 */
795
function render_registration_date_and_institute($registration_dto, $enclosing_tag = 'p') {
796
  $registration_date_institute_markup = '';
797
  if ($registration_dto->registrationDate) {
798
    $date_string = format_datetime($registration_dto->registrationDate);
799
    if (isset($registration_dto->institutionTitleCache) && $registration_dto->institutionTitleCache) {
800
      $registration_date_institute_markup =
801
        t("Registration on @date in @institution", array(
802
          '@date' => $date_string,
803
          '@institution' => $registration_dto->institutionTitleCache,
804
        ));
805
    } else {
806
      $registration_date_institute_markup =
807
        t("Registration on @date", array(
808
          '@date' => $date_string
809
        ));
810
    }
811
    $registration_date_institute_markup = '<' .$enclosing_tag . ' class="registration-date-and-institute">'. $registration_date_institute_markup . '</' .$enclosing_tag . '>';
812
  }
813
  return $registration_date_institute_markup;
814
}
815

    
816

    
817
/**
818
 * @param $registrations
819
 * @return string
820
 */
821
function render_registrations($registrations)
822
{
823
  $registration_markup = '';
824
  $registration_markup_array = array();
825
  if ($registrations) {
826
    foreach ($registrations as $reg) {
827
      $registration_markup_array[] = render_registration($reg);
828
    }
829
    $registration_markup = " Registration" . (count($registration_markup_array) > 1 ? 's: ' : ': ')
830
      . join(', ', $registration_markup_array);
831
  }
832
  return $registration_markup;
833
}
834

    
835

    
836
/**
837
 * Renders a registration
838
 *
839
 * TODO replace by compose_registration_dto_compact
840
 * @param $registration
841
 */
842
function render_registration($registration){
843
  $markup = '';
844

    
845
  if(isset($registration->identifier) && $registration->status == 'PUBLISHED'){
846
    $office_class_attribute = '';
847
    if(isset($registration->institution->titleCache)){
848
      $office_class_attribute = registration_institution_class_attribute($registration);
849
    }
850
    $markup = "<span class=\"registration $office_class_attribute\">" . render_link_to_registration($registration->identifier) . ', '
851
      .  preg_replace('/^([^T]*)(.*)$/', '${1}', $registration->registrationDate)
852
      . '</span>';
853
  }
854
  return $markup;
855
}
856

    
857
/**
858
 * @param $registration
859
 * @return string
860
 */
861
function registration_institution_class_attribute($registration_dto)
862
{
863
  if(isset($registration_dto->institutionTitleCache)){
864
    $institutionTitleCache = $registration_dto->institutionTitleCache;
865
  } else {
866
    // fall back option to also support cdm entities
867
    $institutionTitleCache = @$registration_dto->institution->titleCache;
868
  }
869
  return $institutionTitleCache ? 'registration-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $institutionTitleCache)) : '';
870
}
871

    
872

    
873
/**
874
 * Renders and array of CDM TypeDesignations
875
 *
876
 *  - NameTypeDesignation
877
 *  - SpecimenTypeDesignation
878
 *  - TextualTypeDesignation
879
 *
880
 * @param object $type_designations an array of cdm TypeDesignation entities
881
 *  to render
882
 * @param string $enclosing_tag the tag element type to enclose the whole list
883
 *  of type designation with. By default this DOM element is <ul>
884
 * @param string $element_tag the tag element type to be used for each
885
 *  type designation item.
886
 * @param bool $link_to_specimen_page whether a specimen in type designation element
887
 *  should be a link or not.
888
 *
889
 * @return string The markup.
890
 *
891
 * @InGroup Render
892
 */
893
function render_type_designations($type_designations, $enclosing_tag = 'ul', $element_tag =  'li', $link_to_specimen_page = true) {
894

    
895
  // need to add element to render path since type designations
896
  // need other name render template
897
  RenderHints::pushToRenderStack('typedesignations');
898

    
899
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
900
  $specimen_type_designations = array();
901
  $name_type_designations = array();
902
  $textual_type_designations = array();
903
  $separator = ',';
904

    
905
  foreach ($type_designations as $type_designation) {
906
    switch ($type_designation->class) {
907
      case 'SpecimenTypeDesignation':
908
        $specimen_type_designations[] = $type_designation;
909
        break;
910
      case 'NameTypeDesignation':
911
        $name_type_designations[] = $type_designation;
912
        break;
913
      case 'TextualTypeDesignation':
914
        $textual_type_designations[] = $type_designation;
915
        break;
916
      default:  throw new Exception('Unknown type designation class: ' . $type_designation->class);
917
    }
918
  }
919

    
920
  // NameTypeDesignation ..................................
921
  if(!empty($name_type_designations)){
922
    usort($name_type_designations, "compare_type_designations_by_status");
923
    foreach($name_type_designations as $name_type_designation){
924
      if ($name_type_designation->notDesignated) {
925
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation)  . ': '
926
          . t('not designated') . '</'. $element_tag .'>';
927
      }
928
      elseif (isset($name_type_designation->typeName)) {
929
        $link_to_name_page = url(path_to_name($name_type_designation->typeName->uuid));
930
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation) ;
931

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

    
935
        }
936
        $referenceUri = '';
937
        if (isset($name_type_designation->typeName->nomenclaturalSource->citation)) {
938
          $referenceUri = url(path_to_reference($name_type_designation->typeName->nomenclaturalSource->citation->uuid));
939
        }
940
        $out .= ': ' . render_taxon_or_name($name_type_designation->typeName, $link_to_name_page, $referenceUri, TRUE, TRUE);
941
      }
942
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
943
      $annotations_and_sources = handle_annotations_and_sources($name_type_designation);
944
      $out .= $annotations_and_sources->footNoteKeysMarkup();
945
    }
946
  } // END NameTypeDesignation
947

    
948
  // SpecimenTypeDesignation ...................................
949
  if (!empty($specimen_type_designations)) {
950
    usort($specimen_type_designations, "compare_specimen_type_designation");
951
    foreach ($specimen_type_designations as $specimen_type_designation) {
952
      $type_citation_markup = '';
953

    
954
      if (!empty($specimen_type_designation->source->citation)) {
955

    
956
        $citation_footnote_str = cdm_reference_markup($specimen_type_designation->source->citation, null, false, true);
957
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $specimen_type_designation->source->citation->uuid);
958

    
959
        if (!empty($author_team->titleCache)) {
960
          $year = @timePeriodToString($specimen_type_designation->source->citation->datePublished, true, 'YYYY');
961
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
962
          if ($authorteam_str == $specimen_type_designation->source->citation->titleCache) {
963
            $citation_footnote_str = '';
964
          }
965
        } else {
966
          $authorteam_str = $citation_footnote_str;
967
          // no need for a footnote in case in case it is used as replacement for missing author teams
968
          $citation_footnote_str = '';
969
        }
970

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

    
976
        $footnote_key_markup = '';
977
        if ($citation_footnote_str) {
978
          // footnotes should be rendered in the parent element so we
979
          // are relying on the FootnoteListKey set there
980
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
981
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
982
        }
983

    
984
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
985
        if (!empty($specimen_type_designation->source->citationMicroReference)) {
986
          $type_citation_markup .= ': ' . trim($specimen_type_designation->source->citationMicroReference);
987
        }
988
        $type_citation_markup .= $footnote_key_markup . ')';
989

    
990
      }
991

    
992

    
993
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($specimen_type_designation) . '">';
994
      $out .= type_designation_status_label_markup($specimen_type_designation) . $type_citation_markup;
995

    
996

    
997
      $derivedUnitFacadeInstance = null;
998
      if (isset($specimen_type_designation->typeSpecimen)) {
999
        $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $specimen_type_designation->typeSpecimen->uuid);
1000
      }
1001

    
1002
      if (!empty($derivedUnitFacadeInstance->titleCache)) {
1003
        $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1004
        if($link_to_specimen_page && isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1005
          $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($specimen_type_designation->typeSpecimen->uuid)), $specimen_markup);
1006
        }
1007
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1008
        $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1009
        $out .= ': <span class="' . html_class_attribute_ref($specimen_type_designation->typeSpecimen) . '">'
1010
          . $specimen_markup
1011
          . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1012
        if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1013
          $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1014
        }
1015
        $out .= $annotations_and_sources->footNoteKeysMarkup();
1016
      }
1017
      $out .= '</'. $element_tag .'>';
1018
    }
1019
  } // END Specimen type designations
1020

    
1021
  // TextualTypeDesignation .........................
1022
  usort($textual_type_designations, 'compare_textual_type_designation');
1023
  if(!empty($textual_type_designations)) {
1024
      RenderHints::setAnnotationsAndSourceConfig([
1025
          // these settings differ from those provided by annotations_and_sources_config_typedesignations()
1026
          // TODO is this by purpose? please document the reason for the difference
1027
          'sources_as_content' => false, // as footnotes
1028
          'link_to_name_used_in_source' => false,
1029
          'link_to_reference' => true,
1030
          'add_footnote_keys' => true,
1031
          'bibliography_aware' => false
1032
        ]
1033
      );
1034
    foreach ($textual_type_designations as $textual_type_designation) {
1035
      $annotations_and_sources = handle_annotations_and_sources($textual_type_designation);
1036
      $encasement =  $textual_type_designation->verbatim ? '"' : '';
1037
      $out .= '<' . $element_tag . ' class="' . html_class_attribute_ref($textual_type_designation) . '">' . type_designation_status_label_markup(null)
1038
        . ': ' .  $encasement . trim($textual_type_designation->text_L10n->text) . $encasement .  $annotations_and_sources->footNoteKeysMarkup() .'</' . $element_tag . '>';
1039
//      if($annotations_and_sources->hasSourceReferences())){
1040
//        $citation_markup = join(', ', getSourceReferences());
1041
//      }
1042
//      $out .= $citation_markup;
1043
    }
1044
  }
1045

    
1046
  // Footnotes for citations, collection acronyms.
1047
  // footnotes should be rendered in the parent element so we
1048
  // are relying on the FootnoteListKey set there
1049
  $_fkey = FootnoteManager::addNewFootnote(
1050
    RenderHints::getFootnoteListKey(),
1051
    (isset($derivedUnitFacadeInstance->collection->titleCache) ? $derivedUnitFacadeInstance->collection->titleCache : FALSE)
1052
  );
1053
  $out .= render_footnote_key($_fkey, $separator);
1054
  $out .= '</' . $enclosing_tag .'>';
1055

    
1056
  RenderHints::popFromRenderStack();
1057

    
1058
  return $out;
1059
}
1060

    
1061
/**
1062
 * Creates markup for a list of SpecimenTypedesignationDTO
1063
 *
1064
 * @param array $specimen_typedesignation_dtos
1065
 *  The SpecimenTypedesignationDTOs to be rendered
1066
 *
1067
 * @param bool $show_type_specimen
1068
 *
1069
 * @param string $enclosing_tag
1070
 * @param string $element_tag
1071
 *
1072
 * @return string
1073
 *   The markup.
1074
 */
1075
function render_specimen_typedesignation_dto($specimen_typedesignation_dtos, $show_type_specimen = FALSE, $enclosing_tag = 'ul', $element_tag = 'li'){
1076

    
1077
  // need to add element to render path since type designations
1078
  // need other name render template
1079
  RenderHints::pushToRenderStack('typedesignations');
1080

    
1081
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
1082
  $separator = ',';
1083

    
1084
  if (!empty($specimen_typedesignation_dtos)) {
1085
    // usort($specimen_type_designations, "compare_specimen_type_designation"); // FIXME create compare function for SpecimenTypedesignationDTO
1086
    foreach ($specimen_typedesignation_dtos as $std_dto) {
1087
      $type_citation_markup = '';
1088

    
1089
      if (!empty($std_dto->source->citation)) {
1090

    
1091
        $citation_footnote_str = cdm_reference_markup($std_dto->source->citation, null, false, true);
1092
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $std_dto->source->citation->uuid);
1093

    
1094
        if (!empty($author_team->titleCache)) {
1095
          $year = @timePeriodToString($std_dto->source->citation->datePublished, true, 'YYYY');
1096
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
1097
          if ($authorteam_str == $std_dto->source->citation->titleCache) {
1098
            $citation_footnote_str = '';
1099
          }
1100
        } else {
1101
          $authorteam_str = $citation_footnote_str;
1102
          // no need for a footnote in case in case it is used as replacement for missing author teams
1103
          $citation_footnote_str = '';
1104
        }
1105

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

    
1111
        $footnote_key_markup = '';
1112
        if ($citation_footnote_str) {
1113
          // footnotes should be rendered in the parent element so we
1114
          // are relying on the FootnoteListKey set there
1115
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
1116
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
1117
        }
1118

    
1119
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
1120
        if (!empty($std_dto->source->citationMicroReference)) {
1121
          $type_citation_markup .= ': ' . trim($std_dto->source->citationMicroReference);
1122
        }
1123
        $type_citation_markup .= $footnote_key_markup . ')';
1124
      }
1125

    
1126
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($std_dto) . '">';
1127
      $out .= type_designation_dto_status_label_markup($std_dto) . $type_citation_markup;
1128

    
1129
      if($show_type_specimen){
1130
        $derivedUnitFacadeInstance = null;
1131
        if (isset($std_dto->typeSpecimen)) {
1132
          $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $std_dto->typeSpecimen->uuid);
1133
        }
1134

    
1135
        if (!empty($derivedUnitFacadeInstance->titleCache)) {
1136
          $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1137
          if(isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1138
            $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($std_dto->typeSpecimen->uuid)), $specimen_markup);
1139
          }
1140
          RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1141
          $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1142
          $out .= ': <span class="' . html_class_attribute_ref($std_dto->typeSpecimen) . '">'
1143
            . $specimen_markup
1144
            . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1145
          if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1146
            $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1147
          }
1148
          $out .= $annotations_and_sources->footNoteKeysMarkup();
1149
        }
1150
      }
1151

    
1152
      $out .= '</'. $element_tag .'>';
1153
    }
1154
    RenderHints::popFromRenderStack();
1155
  }
1156
  return $out;
1157
}
1158

    
1159

    
1160
/**
1161
 * Composes the textual representation for the type designation of taxon name identified by the uuid in with a map for the location data.
1162
 *
1163
 * @param $taxon_name_uuid
1164
 * @param $show_specimen_details
1165
 * @return array
1166
 *    A drupal render array with the following elements:
1167
 *    - 'type_designations'
1168
 *    - 'map'
1169
 *    - 'specimens'
1170
 *
1171
 * @ingroup compose
1172
 */
1173
function compose_type_designations($taxon_name_uuid, $show_specimen_details = false)
1174
{
1175
  $render_array = array(
1176
    'type_designations' => array(),
1177
    'map' => array(),
1178
    );
1179
  $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name_uuid);
1180
  if ($type_designations) {
1181
    usort($type_designations, 'compare_specimen_type_designation');
1182
    $render_array['type_designations'] = markup_to_render_array(
1183
      render_type_designations($type_designations, 'div', 'div')
1184
    );
1185

    
1186
    $render_array['map'] = compose_type_designations_map($type_designations);
1187
  }
1188
  return $render_array;
1189
}
1190

    
1191

    
1192
/**
1193
 * Composes the TypedEntityReference to name type designations passed as associatve array.
1194
 *
1195
 * @param $type_entity_refs_by_status array
1196
 *   an associative array of name type type => TypedEntityReference for name type designations as
1197
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1198
 *
1199
 * @ingroup compose
1200
 */
1201
function compose_name_type_designations($type_entity_refs_by_status){
1202
  $render_array = array();
1203
  $preferredStableUri = '';
1204
  foreach($type_entity_refs_by_status as $type_status => $name_type_entityRefs){
1205
    foreach ($name_type_entityRefs as $name_type_entity_ref){
1206
      $type_designation = cdm_ws_get(CDM_WS_TYPEDESIGNATION, array($name_type_entity_ref->uuid, 'preferredUri'));
1207
      $footnote_keys = '';
1208

    
1209
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1210
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1211
      }
1212
      // annotations and sources for the $derived_unit_facade_dto
1213
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1214
      $annotations_and_sources = handle_annotations_and_sources($name_type_entity_ref);
1215

    
1216
      $render_array[] = markup_to_render_array('<div class="name_type_designation ' . html_class_attribute_ref($name_type_entity_ref)  .
1217
        '"><span class="type-status">'. ucfirst($type_status) . "</span>: "
1218
        . $name_type_entity_ref->label
1219
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1220
        . $annotations_and_sources->footNoteKeysMarkup()
1221
        . '</div>');
1222
      }
1223
  }
1224
  return $render_array;
1225
}
1226

    
1227
/**
1228
 * Composes the specimen type designations with map from the the $type_entity_refs
1229
 *
1230
 * @param $type_entity_refs array
1231
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
1232
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1233
 *
1234
 * @param $show_media_specimen
1235
 * @return array
1236
 *    A drupal render array with the following elements:
1237
 *    - 'type_designations'
1238
 *    - 'map'
1239
 *
1240
 * @ingroup compose
1241
 *
1242
 */
1243
function compose_specimen_type_designations($type_entity_refs, $show_media_specimen){
1244

    
1245
  $render_array = array();
1246

    
1247
  $type_designation_list = array();
1248
  uksort($type_entity_refs, "compare_type_designation_status_labels");
1249
  foreach($type_entity_refs as $type_status => $type_designation_entity_refs){
1250
    foreach($type_designation_entity_refs as $type_designation_entity_ref){
1251

    
1252
      $type_designation = cdm_ws_get(CDM_WS_PORTAL_TYPEDESIGNATION, array($type_designation_entity_ref->uuid));
1253
      $type_designation_list[] = $type_designation; // collect for the map
1254

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

    
1259

    
1260
      $preferredStableUri = '';
1261
      $citation_markup = '';
1262
      $media = '';
1263

    
1264
      // annotations and sources for the $derived_unit_facade_dto
1265
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1266
      $annotations_and_sources = handle_annotations_and_sources($derived_unit_facade_dto);
1267
      $source_citations = $annotations_and_sources->getSourceReferences();
1268
      $foot_note_keys = $annotations_and_sources->footNoteKeysMarkup();
1269

    
1270
      // preferredStableUri
1271
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1272
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1273
      }
1274

    
1275
      if($show_media_specimen && $mediaSpecimen){
1276
        // compose output
1277
        // mediaURI
1278
        if(isset($mediaSpecimen->representations[0])) {
1279
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
1280
          $captionElements = array(
1281
            '#uri' => t('open media'),
1282
            'elements' => array('-none-'),
1283
            'sources_as_content' => true
1284
          );
1285
          $media = compose_cdm_media_gallerie(array(
1286
            'mediaList' => array($mediaSpecimen),
1287
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $type_designation_entity_ref->uuid,
1288
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
1289
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
1290
            'captionElements' => $captionElements,
1291
          ));
1292
        }
1293
        // citation and detail for the media specimen
1294
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1295
        $annotations_and_sources = handle_annotations_and_sources($mediaSpecimen);
1296
        if($annotations_and_sources->hasSourceReferences()){
1297
          $source_citations = array_merge($source_citations, $annotations_and_sources->getSourceReferences());
1298
        }
1299
        if($annotations_and_sources->hasFootnoteKeys()){
1300
          $foot_note_keys .= ', ' . $annotations_and_sources->footNoteKeysMarkup();
1301
        }
1302
      }
1303

    
1304
      $citation_markup = join(', ', $source_citations);
1305

    
1306
      $specimen_markup = $derived_unit_facade_dto->titleCache;
1307
      if(isset($derived_unit_facade_dto->specimenLabel) && $derived_unit_facade_dto->specimenLabel){
1308
        $specimen_markup = str_replace(
1309
          $derived_unit_facade_dto->specimenLabel,
1310
          l($derived_unit_facade_dto->specimenLabel, path_to_specimen($type_designation->typeSpecimen->uuid)), $specimen_markup);
1311
      }
1312

    
1313
      $type_designation_render_array = markup_to_render_array(
1314
        '<div class="type_designation_entity_ref ' . html_class_attribute_ref($type_designation_entity_ref)  . '">
1315
          <span class="type-status">' . ucfirst($type_status) . "</span>: "
1316
        . $specimen_markup . $foot_note_keys
1317
        . ($citation_markup ? ' '. $citation_markup : '')
1318
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1319
        . $media
1320
        . '</div>');
1321

    
1322
      $render_array['type_designations'][] = $type_designation_render_array;
1323
    }
1324
  }
1325
  if(count($type_designation_list) > 0 ){
1326
    $render_array['map'] = compose_type_designations_map($type_designation_list);
1327
  } else {
1328
    $render_array['map'] = array();
1329
  }
1330
  return $render_array;
1331
}
1332

    
1333
/**
1334
 * Creates the markup for the given name relationship.
1335
 *
1336
 * For the footnotes see handle_annotations_and_sources().
1337
 *
1338
 * @param $other_name
1339
 *      The other name from the NameRelationship see get_other_name()
1340
 * @param $current_taxon_uuid
1341
 * @param $show_name_cache_only
1342
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
1343
 * @return null|string
1344
 *    The markup or null
1345
 *
1346
 * @see \get_other_name
1347
 */
1348
function name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only = false){
1349

    
1350
  $relationship_markup = null;
1351

    
1352
  $other_name = get_other_name($current_name_uuid, $name_rel);
1353

    
1354
  cdm_load_tagged_full_title($other_name);
1355

    
1356
  $highlited_synonym_uuid = isset ($other_name->taxonBases[0]->uuid) ? $other_name->taxonBases[0]->uuid : '';
1357
  if($show_name_cache_only){
1358
    $relationship_markup = l(
1359
      '<span class="' . html_class_attribute_ref($other_name) . '"">' . $other_name->nameCache . '</span>',
1360
      path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
1361
      array('html' => true)
1362
    );
1363
    $annotations_and_sources = handle_annotations_and_sources($other_name);
1364
    $relationship_markup .= $annotations_and_sources->footNoteKeysMarkup();
1365
  } else {
1366
    $relationship_markup = render_taxon_or_name($other_name,
1367
      url(path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
1368
    );
1369
  }
1370

    
1371
  return $relationship_markup;
1372
}
1373

    
1374
/**
1375
 * Determined the other name which is contained in the NameRelationship entity.
1376
 *
1377
 * @param $current_name_uuid
1378
 *   The uuid of this name.
1379
 * @param $name_rel
1380
 *   The cdm NameRelationship entity
1381
 *
1382
 * @return object
1383
 *   The other cdm Name entity.
1384
 */
1385
function get_other_name($current_name_uuid, $name_rel) {
1386
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
1387

    
1388
  if ($current_name_is_toName) {
1389
    $name = $name_rel->fromName;
1390
  }
1391
  else {
1392
    $name = $name_rel->toName;
1393
  }
1394
  return $name;
1395
}
1396

    
1397

    
1398
/**
1399
 * Composes an inline representation of selected name relationships
1400
 *
1401
 * The output of this function will be usually appended to taxon name representations.
1402
 * Only the following types are displayed: LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR, ORTHOGRAPHIC_VARIANT
1403
 *
1404
 * LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR are displayed as
1405
 * non {titleCache} nec {titleCache} nec {titleCache} whereas the related names
1406
 * are ordered alphabetically.
1407
 *
1408
 * ORTHOGRAPHIC_VARIANT is displayed as 'ort. var. {nameCache}'
1409
 *
1410
 * Related issues:
1411
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1412
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1413
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1414
 *   - https://dev.e-taxonomy.eu/redmine/issues/2001 "[Cichorieae Portal] Name Relationship -> blocking name are not shown"
1415
 *
1416
 * @param $name_relations
1417
 *    The list of CDM NameRelationsips
1418
 * @param $current_name_uuid
1419
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1420
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1421
 * @param $suppress_if_current_name_is_source
1422
 *    The display of the relation will be
1423
 *    suppressed is the current name is on the source of the relation edge.
1424
 *    That is if it is on the from side of the relation. Except for 'blocking name for' which is
1425
 *    an inverse relation. For this relation type the toName is taken in to account.
1426
 * @param $current_taxon_uuid
1427
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1428
 * @return array
1429
 *    A drupal render array
1430
 *
1431
 * @ingroup Compose
1432
 */
1433
function compose_name_relationships_inline($name_relations, $current_name_uuid, $current_taxon_uuid, $suppress_if_current_name_is_source = true) {
1434

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

    
1438
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
1439
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1440
  foreach ($selected_name_rel_uuids as $uuid){
1441
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1442
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
1443
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
1444
    }
1445
  }
1446

    
1447
  $list_prefix = '<span class="name_relationships">[';
1448
  $list_suffix = ']</span>';
1449
  $item_prefix = '<span class="item">';
1450
  $item_suffix = '</span> ';
1451
  $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);
1452

    
1453
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1454
  $items_ctn = count($render_array['list']['items']);
1455
  if($items_ctn){
1456
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1457
  }
1458

    
1459
  RenderHints::popFromRenderStack();
1460
  return $render_array;
1461
}
1462

    
1463
/**
1464
 * Composes an list representation of the name relationships.
1465
 *
1466
 * The output of this function will be usually appended to taxon name representations.
1467
 *
1468
 * Related issues:
1469
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1470
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1471
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1472
 *
1473
 * @param $name_relations
1474
 *    The list of CDM NameRelationsips
1475
 * @param $current_name_uuid
1476
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1477
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1478
 * @param $current_taxon_uuid
1479
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1480
 * @return array
1481
 *    A drupal render array
1482
 *
1483
 * @ingroup Compose
1484
 */
1485
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1486

    
1487
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1488

    
1489
  $key = 'name_relationships';
1490
  RenderHints::pushToRenderStack($key);
1491
  if(RenderHints::isUnsetFootnoteListKey()){
1492
    RenderHints::setFootnoteListKey($key);
1493
  }
1494
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1495

    
1496
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, cdm_vocabulary_as_defaults(UUID_NAME_RELATIONSHIP_TYPE));
1497
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1498
  foreach ($selected_name_rel_uuids as $uuid){
1499
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1500
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1501
  }
1502

    
1503
  $list_prefix = '<div class="relationships_list name_relationships">';
1504
  $list_suffix = '</div>';
1505
  $item_prefix = '<div class="item">';
1506
  $item_suffix = '</div>';
1507

    
1508
  $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);
1509

    
1510
  RenderHints::popFromRenderStack();
1511
  if(RenderHints::getFootnoteListKey() == $key) {
1512
    $render_array['footnotes'] = markup_to_render_array(render_footnotes(RenderHints::getFootnoteListKey()));
1513
    RenderHints::clearFootnoteListKey();
1514
  }
1515
  return $render_array;
1516
}
1517

    
1518
/**
1519
 * @param $name_relations
1520
 * @param $name_rel_type_filter
1521
 *   Associative array with two keys:
1522
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1523
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1524
 * @param $current_name_uuid
1525
 * @param $current_taxon_uuid
1526
 * @param $list_prefix
1527
 * @param $list_suffix
1528
 * @param $item_prefix
1529
 * @param $item_suffix
1530
 * @return array
1531
 *
1532
 * @ingroup Compose
1533
 */
1534
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1535
                                    $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1536
{
1537
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1538
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1539
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1540
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1541
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1542

    
1543
  $render_array = array(
1544
    'list' => array(
1545
      '#prefix' => $list_prefix,
1546
      '#suffix' => $list_suffix,
1547
      'items' => array()
1548
    ),
1549
    'footnotes' => array()
1550
  );
1551

    
1552
  if ($name_relations) {
1553

    
1554
    // remove all relations which are not selected in the settings and
1555
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1556
    // for special handling
1557
    $filtered_name_rels = array();
1558
    $non_nec_name_rels = array();
1559
    $orthographic_variants = array();
1560
    foreach ($name_relations as $name_rel) {
1561
      $rel_type_uuid = $name_rel->type->uuid;
1562
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1563
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1564
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1565

    
1566
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1567
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1568
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1569
          )
1570
        ){
1571
          $non_nec_name_rels[] = $name_rel;
1572
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1573
          $orthographic_variants[] = $name_rel;
1574
        } else {
1575

    
1576
          $filtered_name_rels[] = $name_rel;
1577
        }
1578
      }
1579
    }
1580
    $name_relations = $filtered_name_rels;
1581

    
1582
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1583

    
1584
    // compose
1585
    $show_name_cache_only = FALSE;
1586
    foreach ($name_relations as $name_rel) {
1587

    
1588
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1589
      $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1590
      $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1591
      $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1592

    
1593
      $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1594
      $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup . ' ';
1595
      $relationship_markup = $symbol_markup . $relationship_markup;
1596
      if ($relationship_markup) {
1597
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1598
          null,
1599
          $item_prefix,
1600
          $item_suffix);
1601
      }
1602
    }
1603

    
1604
    // name relationships to be displayed as non nec
1605
    if (count($non_nec_name_rels) > 0) {
1606
      $non_nec_markup = '';
1607
      $show_name_cache_only = FALSE;
1608
      foreach ($non_nec_name_rels as $name_rel) {
1609

    
1610
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1611
        $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1612
        $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1613
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1614

    
1615
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1616
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1617
        $non_nec_markup .= $symbol_markup . $relationship_markup;
1618
      }
1619
      if ($non_nec_markup) {
1620
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1621
          null,
1622
          $item_prefix,
1623
          $item_suffix);
1624
      }
1625
    }
1626

    
1627
    // orthographic variants
1628
    if (count($orthographic_variants) > 0) {
1629
      $show_name_cache_only = TRUE;
1630
      foreach ($orthographic_variants as $name_rel) {
1631

    
1632
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1633
        $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1634
        $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1635
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1636
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1637
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1638
        $relationship_markup = $symbol_markup . $relationship_markup;
1639
      }
1640
      if (isset($relationship_markup) && $relationship_markup) {
1641
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1642
          null,
1643
          $item_prefix,
1644
          $item_suffix);
1645
      }
1646
    }
1647
  }
1648
  return $render_array;
1649
}
1650

    
1651

    
1652

    
1653
/**
1654
 * @param $taxon
1655
 * @return array
1656
 */
1657
function cdm_name_relationships_for_taxon($taxon)
1658
{
1659
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1660
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1661
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1662
  return $name_relations;
1663
}
1664

    
1665

    
1666
/**
1667
 * Recursively searches the array for the $key and sets the given value.
1668
 *
1669
 * Expects the key to be used only once in nested array structures.
1670
 *
1671
 * @param mixed $key
1672
 *   Key to search for.
1673
 * @param mixed $value
1674
 *   Value to set.'
1675
 * @param array $array
1676
 *   Array to search in.
1677
 *
1678
 * @return array
1679
 *   The array the key has been found.
1680
 */
1681
function &array_setr($key, $value, array &$array) {
1682
  $res = NULL;
1683
  foreach ($array as $k => &$v) {
1684
    if ($key == $k) {
1685
      $v = $value;
1686
      return $array;
1687
    }
1688
    elseif (is_array($v)) {
1689
      $innerArray = array_setr($key, $value, $v);
1690
      if ($innerArray) {
1691
        return $array;
1692
      }
1693
    }
1694
  }
1695
  return $res;
1696
}
1697

    
1698
/**
1699
 * Recursively searches the array for the $key and sets is to $new_key
1700
 *
1701
 * Expects the key to be used only once in nested array structures.
1702
 *
1703
 * @param mixed $key
1704
 *   Key to search for.
1705
 * @param mixed $new_key
1706
 *   The new key to use
1707
 * @param array $array
1708
 *   Array to search in.
1709
 *
1710
 * @return bool
1711
 *   True if the key has been found.
1712
 */
1713
function array_replace_keyr($key, $new_key, array &$array) {
1714
  $res = NULL;
1715
  if(array_key_exists($key, $array)){
1716
    $value = $array[$key];
1717
    unset($array[$key]);
1718
    $array[$new_key] = $value;
1719
    return true;
1720
  } else {
1721
    // search in next level
1722
    foreach ($array as &$v) {
1723
        if (is_array($v)) {
1724
          array_replace_keyr($key, $new_key, $v);
1725
        }
1726
      }
1727
  }
1728

    
1729
  return false;
1730
}
1731

    
1732
/**
1733
 * @todo Please document this function.
1734
 * @see http://drupal.org/node/1354
1735
 */
1736
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1737
  $res = NULL;
1738
  $precedingElement = NULL;
1739
  foreach ($renderTemplate as &$part) {
1740
    foreach ($part as $key => &$element) {
1741
      if ($key == $contentElementKey) {
1742
        return $precedingElement;
1743
      }
1744
      $precedingElement = $element;
1745
    }
1746
  }
1747
  return $res;
1748
}
1749

    
1750
/**
1751
 * @todo Please document this function.
1752
 * @see http://drupal.org/node/1354
1753
 */
1754
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1755
  $res = NULL;
1756
  $precedingKey = NULL;
1757
  foreach ($renderTemplate as &$part) {
1758
    if (is_array($part)) {
1759
      foreach ($part as $key => &$element) {
1760
        if ($key == $contentElementKey) {
1761
          return $precedingKey;
1762
        }
1763
        if (!str_beginsWith($key, '#')) {
1764
          $precedingKey = $key;
1765
        }
1766
      }
1767
    }
1768
  }
1769
  return $res;
1770
}
1771

    
1772
function nameTypeToDTYPE($dtype){
1773
  static $nameTypeLabelMap = array(
1774
    "ICNB" => "BacterialName",
1775
    "ICNAFP" => "BotanicalName",
1776
    "ICNCP" => "CultivarPlantName",
1777
    "ICZN" => "ZoologicalName",
1778
    "ICVCN" => "ViralName",
1779
    "Any taxon name" => "TaxonName",
1780
    "NonViral" => "TaxonName",
1781
    "Fungus" => "BotanicalName",
1782
    "Plant" => "BotanicalName",
1783
    "Algae" => "BotanicalName",
1784
  );
1785
  return $nameTypeLabelMap[$dtype];
1786

    
1787
}
1788

    
1789

    
1790
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1791
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1792
}
1793

    
1794
/**
1795
 * Provides an array with the different registration types covered by the passed registration.
1796
 *
1797
 * The labels in the returned array are translatable.
1798
 *
1799
 * See also https://dev.e-taxonomy.eu/redmine/issues/8016
1800
 *
1801
 * @param $registration_dto
1802
 * @return array
1803
 *    An array of the labels describing the different registration types covered by the passed registration.
1804
 */
1805
function registration_types($registration_dto){
1806
  $reg_type_labels = array();
1807
  if(isset($registration_dto->nameRef)){
1808
    $reg_type_labels["name"] = t("new name");
1809
    $reg_type_labels["taxon"] = t("new taxon");
1810
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1811
    $is_new_combination = true;
1812
    foreach($name_relations as $name_rel){
1813
      if(isset($name_rel->type->uuid)){
1814
        $name_is_from_name = $registration_dto->nameRef->uuid == $name_rel->fromName->uuid;
1815
        switch($name_rel->type->uuid) {
1816
          case UUID_NAMERELATIONSHIPTYPE_BASIONYM:
1817
            if(!$name_is_from_name){
1818
              $reg_type_labels["basionym"] = t("new combination");
1819
              $is_new_combination = true;
1820
            }
1821
            break;
1822
          case UUID_NAMERELATIONSHIPTYPE_REPLACED_SYNONYM:
1823
            if(!$name_is_from_name) {
1824
              $is_new_combination = true;
1825
            }
1826
            break;
1827
          case UUID_NAMERELATIONSHIPTYPE_VALIDATED_BY_NAME:
1828
            if(!$name_is_from_name) {
1829
              $reg_type_labels["validation"] = t("validation");
1830
            }
1831
            break;
1832
          case UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT:
1833
            if(!$name_is_from_name) {
1834
              $reg_type_labels["orth_var"] = t("orthographical correction");
1835
            }break;
1836
          default:
1837
            // NOTHING
1838
        }
1839
      }
1840
    }
1841
    if($is_new_combination){
1842
      unset($reg_type_labels["taxon"]);
1843
    }
1844
  }
1845
  if(isset($registration_dto->orderedTypeDesignationWorkingSets)){
1846
    $reg_type_labels[] = t("new nomenclatural type");
1847
  }
1848
  return $reg_type_labels;
1849
}
1850

    
1851
/**
1852
 * Collects and deduplicates the type designations associated with the passes synonyms.
1853
 *
1854
 * @param $synonymy_group
1855
 *    An array containing a homotypic or heterotypic group of names.
1856
 * @param $accepted_taxon_name_uuid
1857
 *    The uuid of the accepted taxon name. Optional parameter which is required when composing
1858
 *    the information for the homotypic group. In this case the accepted taxon is not included
1859
 *    in the $synonymy_group and must therefor passed in this second parameter.
1860
 *
1861
 * @return array
1862
 *    The CDM TypeDesignation entities
1863
 */
1864
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null)
1865
{
1866
  if (count($synonymy_group) > 0) {
1867
    $name_uuid = array_pop($synonymy_group)->name->uuid;
1868
  } else {
1869
    $name_uuid = $accepted_taxon_name_uuid;
1870
  }
1871
  if ($name_uuid) {
1872
   $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS_IN_HOMOTYPICAL_GROUP, $name_uuid);
1873
    if ($type_designations) {
1874
      return $type_designations;
1875
    }
1876
  }
1877

    
1878
  return array();
1879
}
1880

    
1881

    
1882
/**
1883
 * Compares two SpecimenTypeDesignations
1884
 *
1885
 * @param object $a
1886
 *   A SpecimenTypeDesignation.
1887
 * @param object $b
1888
 *   SpecimenTypeDesignation.
1889
 */
1890
function compare_specimen_type_designation($a, $b) {
1891

    
1892
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1893
  if($cmp_by_status !== 0){
1894
    return $cmp_by_status;
1895
  }
1896

    
1897
  $aQuantifier = FALSE;
1898
  $bQuantifier = FALSE;
1899
  if ($aQuantifier == $bQuantifier) {
1900
    // Sort alphabetically.
1901
    $a_text =  isset($a->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $a->typeSpecimen->titleCache) : '';
1902
    $b_text =  isset($b->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $b->typeSpecimen->titleCache) : '';
1903
    return strcasecmp($a_text, $b_text);
1904
  }
1905
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1906
}
1907

    
1908
/**
1909
 * Compares the status of two TypeDesignations
1910
 *
1911
 * @param object $a
1912
 *   A TypeDesignation
1913
 * @param object $b
1914
 *   TypeDesignation
1915
 */
1916
function compare_type_designations_by_status($a, $b) {
1917
  $status_a = isset($a->typeStatus) ? $a->typeStatus : null;
1918
  $status_b = isset($b->typeStatus) ? $b->typeStatus : null;
1919
  return compare_type_designation_status($status_a, $status_b);
1920
}
1921

    
1922
/**
1923
 * Compares two TypeDesignationStatusBase
1924
 *
1925
 * @param object $a
1926
 *   A TypeDesignationStatusBase.
1927
 * @param object $b
1928
 *   TypeDesignationStatusBase.
1929
 */
1930
function compare_type_designation_status($a, $b) {
1931
  $type_status_order = type_status_order();
1932
  $aQuantifier = FALSE;
1933
  $bQuantifier = FALSE;
1934
  if (isset($a->label) && isset($b->label)) {
1935
    $aQuantifier = array_search($a->label, $type_status_order);
1936
    $bQuantifier = array_search($b->label, $type_status_order);
1937
  }
1938
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1939
}
1940

    
1941
/**
1942
 * Compares the two TextualTypeDesignations
1943
 *
1944
 * @param object $a
1945
 *   A TextualTypeDesignations.
1946
 * @param object $b
1947
 *   TextualTypeDesignations.
1948
 */
1949
function compare_textual_type_designation($a, $b) {
1950

    
1951
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1952
  if($cmp_by_status !== 0){
1953
    return $cmp_by_status;
1954
  }
1955

    
1956
  $aQuantifier = FALSE;
1957
  $bQuantifier = FALSE;
1958
  if ($aQuantifier == $bQuantifier) {
1959
    // Sort alphabetically.
1960
    $a_text =  isset($a->text_L10n->text) ? $a->text_L10n->text : '';
1961
    $b_text =  isset($b->text_L10n->text) ? $b->text_L10n->text : '';
1962
    return strcasecmp($a_text, $b_text);
1963
  }
1964
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1965
}
1966

    
1967

    
1968
/**
1969
 * Compares two SpecimenTypeDesignation status labels
1970
 *
1971
 * @param string $a
1972
 *   A TypeDesignationStatus label.
1973
 * @param string $b
1974
 *   A TypeDesignationStatus label.
1975
 */
1976
function compare_type_designation_status_labels($a, $b) {
1977

    
1978
  $type_status_order = type_status_order();
1979

    
1980
  $aQuantifier = FALSE;
1981
  $bQuantifier = FALSE;
1982
  if (isset($a) && isset($b)) {
1983
    $aQuantifier = array_search(ucfirst($a), $type_status_order);
1984
    $bQuantifier = array_search(ucfirst($b), $type_status_order);
1985
  }
1986
  return ($aQuantifier < $bQuantifier) ? -1 : 1;
1987
}
1988

    
1989
/**
1990
 * Preliminary implementation of a preset to define a sort order for
1991
 * type designation status.
1992
 *
1993
 * TODO this is only preliminary and may break in future,
1994
 *      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
1995
 * @return array
1996
 *   The array of orderd type labels
1997
 */
1998
function type_status_order()
1999
{
2000
  /*
2001
    This is the desired sort order as of now: Holotype Isotype Lectotype
2002
    Isolectotype Syntype.
2003
    TODO Basically, what we are trying to do is, we define
2004
    an ordered array of TypeDesignation-states and use the index of this array
2005
    for comparison. This array has to be filled with the cdm- TypeDesignation
2006
    states and the order should be parameterisable inside the dataportal.
2007
    */
2008
  static $type_status_order = array(
2009
    'Epitype',
2010
    'Holotype',
2011
    'Isotype',
2012
    'Lectotype',
2013
    'Isolectotype',
2014
    'Syntype',
2015
    'Paratype'
2016
  );
2017
  return $type_status_order;
2018
}
2019

    
2020
/**
2021
 * Return HTML for the lectotype citation with the correct layout.
2022
 *
2023
 * This function prints the lectotype citation with the correct layout.
2024
 * Lectotypes are renderized in the synonymy tab of a taxon if they exist.
2025
 *
2026
 * @param mixed $typeDesignation
2027
 *   Object containing the lectotype citation to print.
2028
 *
2029
 * @return string
2030
 *   Valid html string.
2031
 */
2032
function type_designation_citation_layout($typeDesignation, $footnote_separator = ',') {
2033
  $res = '';
2034
  $citation = $typeDesignation->source->citation;
2035
  $pages = $typeDesignation->source->citationMicroReference;
2036
  if(isset($typeDesignation->typeStatus->uuid) && isset($typeDesignation->typeStatus->representation_L10n)) {
2037
    if ( $typeDesignation->typeStatus->uuid == UUID_NTD_ORIGINAL_DESIGNATION || $typeDesignation->typeStatus->uuid == UUID_NTD_MONOTYPY) {
2038
      $res = ' (' . $typeDesignation->typeStatus->representation_L10n . ')';
2039
      return $res;
2040
    }
2041
  }
2042

    
2043
  if ($citation) {
2044
    // $type = $typeDesignation_citation->type;
2045
    $year = isset($citation->datePublished->start) ? substr($citation->datePublished->start, 0, 4) : '';
2046
    $author = isset($citation->authorship->titleCache) ? $citation->authorship->titleCache : '';
2047
    $res .= ' (designated by ';
2048
    $res .= $author;
2049
    $res .= ($year ? ' ' . $year : '');
2050
    $res .= ($pages ? ': ' . $pages : '');
2051
    // $res .= ')';
2052

    
2053
    // footnotes should be rendered in the parent element so we
2054
    // are relying on the FootnoteListKey set there
2055
    $fkey_typeDesignation = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation->titleCache);
2056
    $res .= render_footnote_key($fkey_typeDesignation, $footnote_separator,TRUE) . ')';
2057
  }
2058
  return $res;
2059
}
2060

    
2061
/**
2062
 * 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"
2063
 *
2064
 * @param $type_designation
2065
 * @return string
2066
 */
2067
function type_designation_status_label_markup($type_designation)
2068
{
2069
  return '<span class="type-status">'
2070
    . ((isset($type_designation->typeStatus->representation_L10n)) ? ucfirst($type_designation->typeStatus->representation_L10n) : t('Type')) . '</span>'
2071
    ;
2072
}
2073

    
2074
/**
2075
 * Creates markup for the status of a type designation DTO.
2076
 * In case the status or its representation is missing the label will be set to "Type"
2077
 *
2078
 * @param $type_designation
2079
 * @return string
2080
 */
2081
function type_designation_dto_status_label_markup($type_designation)
2082
{
2083
  return '<span class="type-status">'
2084
    . ((isset($type_designation->typeStatus_L10n)) ? ucfirst($type_designation->typeStatus_L10n) : t('Type')) . '</span>'
2085
    ;
2086
}
(7-7/14)