Project

General

Profile

Download (80.8 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
      $microreference = NULL;
415
      if (isset($renderTemplate['referencePart']['microreference'])&& isset($taxon_name->nomenclaturalSource->citationMicroReference)) {
416
        $microreference = $taxon_name->nomenclaturalSource->citationMicroReference;
417
      }
418
      if(count($nomref_tagged_text) == 0 && isset($taxon_name->nomenclaturalSource->citation)){
419
        // TODO is this case still relevant? The tagged text should already contain all information!
420
        $citation = cdm_ws_getNomenclaturalReference($taxon_name->nomenclaturalSource->citation->uuid, $microreference);
421
        // Find preceding element of the reference.
422
        $precedingKey = get_preceding_contentElementKey('reference', $renderTemplate);
423
        if (str_beginsWith($citation, ", in")) {
424
          $citation = substr($citation, 2);
425
          $separator = ' ';
426
        }
427
        elseif (!str_beginsWith($citation, "in") && $precedingKey == 'authors') {
428
          $separator = ', ';
429
        } else {
430
          $separator = ' ';
431
        }
432
        $referenceArray['#separator'] = $separator;
433
        $referenceArray['#html'] = '<span class="reference">' . $citation . '</span>' . $registration_markup;
434
      } else {
435
        // this ist the case for taxon names
436
        $referenceArray['#html'] = cdm_tagged_text_to_markup($nomref_tagged_text);
437
      }
438

    
439

    
440
      array_setr('reference', $referenceArray, $renderTemplate);
441
    }
442

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

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

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

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

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

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

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

    
553
    }
554
    else {
555
      $out .= $separator . $partHtml;
556
    }
557
  }
558
  $out .= '</span>';
559

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

    
577

    
578

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

    
605
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
606
    return $render_array;
607
  }
608

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

    
614
    '#suffix' => '</div>'
615
  );
616

    
617
  $typified_name = null;
618

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

    
634
  }
635

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

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

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

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

    
698
  $render_array['nomenclatural_act']['footnotes'] = markup_to_render_array(render_footnotes(),100);
699

    
700
  // END of nomenclatural act block
701
  RenderHints::setFootnoteListKey($last_footnote_listkey );
702

    
703
  if($typified_name){
704
    $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);
705
  }
706

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

    
715
  $render_array['page_footnotes'] = markup_to_render_array(render_footnotes(), 110);
716

    
717
  return $render_array;
718
}
719

    
720

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

    
743
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
744
    return $render_array;
745
  }
746

    
747
  $registration_date_institute_markup = render_registration_date_and_institute($registration_dto, 'span');
748
  $identifier_markup = render_link_to_registration($registration_dto->identifier);
749

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

    
788
  return $render_array;
789
}
790

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

    
819

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

    
838

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

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

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

    
875

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

    
898
  // need to add element to render path since type designations
899
  // need other name render template
900
  RenderHints::pushToRenderStack('typedesignations');
901

    
902
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
903
  $specimen_type_designations = array();
904
  $name_type_designations = array();
905
  $textual_type_designations = array();
906
  $separator = ',';
907

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

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

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

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

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

    
957
      if (!empty($specimen_type_designation->source->citation)) {
958

    
959
        $citation_footnote_str = cdm_reference_markup($specimen_type_designation->source->citation, null, false, true);
960
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $specimen_type_designation->source->citation->uuid);
961

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

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

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

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

    
993
      }
994

    
995

    
996
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($specimen_type_designation) . '">';
997
      $out .= type_designation_status_label_markup($specimen_type_designation) . $type_citation_markup;
998

    
999

    
1000
      $derivedUnitFacadeInstance = null;
1001
      if (isset($specimen_type_designation->typeSpecimen)) {
1002
        $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $specimen_type_designation->typeSpecimen->uuid);
1003
      }
1004

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

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

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

    
1059
  RenderHints::popFromRenderStack();
1060

    
1061
  return $out;
1062
}
1063

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

    
1080
  // need to add element to render path since type designations
1081
  // need other name render template
1082
  RenderHints::pushToRenderStack('typedesignations');
1083

    
1084
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
1085
  $separator = ',';
1086

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

    
1092
      if (!empty($std_dto->source->citation)) {
1093

    
1094
        $citation_footnote_str = cdm_reference_markup($std_dto->source->citation, null, false, true);
1095
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $std_dto->source->citation->uuid);
1096

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

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

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

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

    
1129
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($std_dto) . '">';
1130
      $out .= type_designation_dto_status_label_markup($std_dto) . $type_citation_markup;
1131

    
1132
      if($show_type_specimen){
1133
        $derivedUnitFacadeInstance = null;
1134
        if (isset($std_dto->typeSpecimen)) {
1135
          $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $std_dto->typeSpecimen->uuid);
1136
        }
1137

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

    
1155
      $out .= '</'. $element_tag .'>';
1156
    }
1157
    RenderHints::popFromRenderStack();
1158
  }
1159
  return $out;
1160
}
1161

    
1162

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

    
1189
    $render_array['map'] = compose_type_designations_map($type_designations);
1190
  }
1191
  return $render_array;
1192
}
1193

    
1194

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

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

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

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

    
1248
  $render_array = array();
1249

    
1250
  $type_designation_list = array();
1251
  uksort($type_entity_refs, "compare_type_designation_status_labels");
1252
  foreach($type_entity_refs as $type_status => $type_designation_entity_refs){
1253
    foreach($type_designation_entity_refs as $type_designation_entity_ref){
1254

    
1255
      $type_designation = cdm_ws_get(CDM_WS_PORTAL_TYPEDESIGNATION, array($type_designation_entity_ref->uuid));
1256
      $type_designation_list[] = $type_designation; // collect for the map
1257

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

    
1262

    
1263
      $preferredStableUri = '';
1264
      $citation_markup = '';
1265
      $media = '';
1266

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

    
1273
      // preferredStableUri
1274
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1275
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1276
      }
1277

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

    
1307
      $citation_markup = join(', ', $source_citations);
1308

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

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

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

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

    
1353
  $relationship_markup = null;
1354

    
1355
  $other_name = get_other_name($current_name_uuid, $name_rel);
1356

    
1357
  cdm_load_tagged_full_title($other_name);
1358

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

    
1374
  return $relationship_markup;
1375
}
1376

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

    
1391
  if ($current_name_is_toName) {
1392
    $name = $name_rel->fromName;
1393
  }
1394
  else {
1395
    $name = $name_rel->toName;
1396
  }
1397
  return $name;
1398
}
1399

    
1400

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

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

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

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

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

    
1462
  RenderHints::popFromRenderStack();
1463
  return $render_array;
1464
}
1465

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

    
1490
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1491

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

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

    
1506
  $list_prefix = '<div class="relationships_list name_relationships">';
1507
  $list_suffix = '</div>';
1508
  $item_prefix = '<div class="item">';
1509
  $item_suffix = '</div>';
1510

    
1511
  $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);
1512

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

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

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

    
1555
  if ($name_relations) {
1556

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

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

    
1579
          $filtered_name_rels[] = $name_rel;
1580
        }
1581
      }
1582
    }
1583
    $name_relations = $filtered_name_rels;
1584

    
1585
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1586

    
1587
    // compose
1588
    $show_name_cache_only = FALSE;
1589
    foreach ($name_relations as $name_rel) {
1590

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

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

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

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

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

    
1630
    // orthographic variants
1631
    if (count($orthographic_variants) > 0) {
1632
      $show_name_cache_only = TRUE;
1633
      foreach ($orthographic_variants as $name_rel) {
1634

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

    
1654

    
1655

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

    
1668

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

    
1699
/**
1700
 * @todo Please document this function.
1701
 * @see http://drupal.org/node/1354
1702
 */
1703
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1704
  $res = NULL;
1705
  $precedingElement = NULL;
1706
  foreach ($renderTemplate as &$part) {
1707
    foreach ($part as $key => &$element) {
1708
      if ($key == $contentElementKey) {
1709
        return $precedingElement;
1710
      }
1711
      $precedingElement = $element;
1712
    }
1713
  }
1714
  return $res;
1715
}
1716

    
1717
/**
1718
 * @todo Please document this function.
1719
 * @see http://drupal.org/node/1354
1720
 */
1721
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1722
  $res = NULL;
1723
  $precedingKey = NULL;
1724
  foreach ($renderTemplate as &$part) {
1725
    if (is_array($part)) {
1726
      foreach ($part as $key => &$element) {
1727
        if ($key == $contentElementKey) {
1728
          return $precedingKey;
1729
        }
1730
        if (!str_beginsWith($key, '#')) {
1731
          $precedingKey = $key;
1732
        }
1733
      }
1734
    }
1735
  }
1736
  return $res;
1737
}
1738

    
1739
function nameTypeToDTYPE($dtype){
1740
  static $nameTypeLabelMap = array(
1741
    "ICNB" => "BacterialName",
1742
    "ICNAFP" => "BotanicalName",
1743
    "ICNCP" => "CultivarPlantName",
1744
    "ICZN" => "ZoologicalName",
1745
    "ICVCN" => "ViralName",
1746
    "Any taxon name" => "TaxonName",
1747
    "NonViral" => "TaxonName",
1748
    "Fungus" => "BotanicalName",
1749
    "Plant" => "BotanicalName",
1750
    "Algae" => "BotanicalName",
1751
  );
1752
  return $nameTypeLabelMap[$dtype];
1753

    
1754
}
1755

    
1756

    
1757
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1758
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1759
}
1760

    
1761
/**
1762
 * Provides an array with the different registration types covered by the passed registration.
1763
 *
1764
 * The labels in the returned array are translatable.
1765
 *
1766
 * See also https://dev.e-taxonomy.eu/redmine/issues/8016
1767
 *
1768
 * @param $registration_dto
1769
 * @return array
1770
 *    An array of the labels describing the different registration types covered by the passed registration.
1771
 */
1772
function registration_types($registration_dto){
1773
  $reg_type_labels = array();
1774
  if(isset($registration_dto->nameRef)){
1775
    $reg_type_labels["name"] = t("new name");
1776
    $reg_type_labels["taxon"] = t("new taxon");
1777
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1778
    $is_new_combination = true;
1779
    foreach($name_relations as $name_rel){
1780
      if(isset($name_rel->type->uuid)){
1781
        $name_is_from_name = $registration_dto->nameRef->uuid == $name_rel->fromName->uuid;
1782
        switch($name_rel->type->uuid) {
1783
          case UUID_NAMERELATIONSHIPTYPE_BASIONYM:
1784
            if(!$name_is_from_name){
1785
              $reg_type_labels["basionym"] = t("new combination");
1786
              $is_new_combination = true;
1787
            }
1788
            break;
1789
          case UUID_NAMERELATIONSHIPTYPE_REPLACED_SYNONYM:
1790
            if(!$name_is_from_name) {
1791
              $is_new_combination = true;
1792
            }
1793
            break;
1794
          case UUID_NAMERELATIONSHIPTYPE_VALIDATED_BY_NAME:
1795
            if(!$name_is_from_name) {
1796
              $reg_type_labels["validation"] = t("validation");
1797
            }
1798
            break;
1799
          case UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT:
1800
            if(!$name_is_from_name) {
1801
              $reg_type_labels["orth_var"] = t("orthographical correction");
1802
            }break;
1803
          default:
1804
            // NOTHING
1805
        }
1806
      }
1807
    }
1808
    if($is_new_combination){
1809
      unset($reg_type_labels["taxon"]);
1810
    }
1811
  }
1812
  if(isset($registration_dto->orderedTypeDesignationWorkingSets)){
1813
    $reg_type_labels[] = t("new nomenclatural type");
1814
  }
1815
  return $reg_type_labels;
1816
}
1817

    
1818
/**
1819
 * Collects and deduplicates the type designations associated with the passes synonyms.
1820
 *
1821
 * @param $synonymy_group
1822
 *    An array containing a homotypic or heterotypic group of names.
1823
 * @param $accepted_taxon_name_uuid
1824
 *    The uuid of the accepted taxon name. Optional parameter which is required when composing
1825
 *    the information for the homotypic group. In this case the accepted taxon is not included
1826
 *    in the $synonymy_group and must therefor passed in this second parameter.
1827
 *
1828
 * @return array
1829
 *    The CDM TypeDesignation entities
1830
 */
1831
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null)
1832
{
1833
  if (count($synonymy_group) > 0) {
1834
    $name_uuid = array_pop($synonymy_group)->name->uuid;
1835
  } else {
1836
    $name_uuid = $accepted_taxon_name_uuid;
1837
  }
1838
  if ($name_uuid) {
1839
   $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS_IN_HOMOTYPICAL_GROUP, $name_uuid);
1840
    if ($type_designations) {
1841
      return $type_designations;
1842
    }
1843
  }
1844

    
1845
  return array();
1846
}
1847

    
1848

    
1849
/**
1850
 * Compares two SpecimenTypeDesignations
1851
 *
1852
 * @param object $a
1853
 *   A SpecimenTypeDesignation.
1854
 * @param object $b
1855
 *   SpecimenTypeDesignation.
1856
 */
1857
function compare_specimen_type_designation($a, $b) {
1858

    
1859
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1860
  if($cmp_by_status !== 0){
1861
    return $cmp_by_status;
1862
  }
1863

    
1864
  $aQuantifier = FALSE;
1865
  $bQuantifier = FALSE;
1866
  if ($aQuantifier == $bQuantifier) {
1867
    // Sort alphabetically.
1868
    $a_text =  isset($a->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $a->typeSpecimen->titleCache) : '';
1869
    $b_text =  isset($b->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $b->typeSpecimen->titleCache) : '';
1870
    return strcasecmp($a_text, $b_text);
1871
  }
1872
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1873
}
1874

    
1875
/**
1876
 * Compares the status of two TypeDesignations
1877
 *
1878
 * @param object $a
1879
 *   A TypeDesignation
1880
 * @param object $b
1881
 *   TypeDesignation
1882
 */
1883
function compare_type_designations_by_status($a, $b) {
1884
  $status_a = isset($a->typeStatus) ? $a->typeStatus : null;
1885
  $status_b = isset($b->typeStatus) ? $b->typeStatus : null;
1886
  return compare_type_designation_status($status_a, $status_b);
1887
}
1888

    
1889
/**
1890
 * Compares two TypeDesignationStatusBase
1891
 *
1892
 * @param object $a
1893
 *   A TypeDesignationStatusBase.
1894
 * @param object $b
1895
 *   TypeDesignationStatusBase.
1896
 */
1897
function compare_type_designation_status($a, $b) {
1898
  $type_status_order = type_status_order();
1899
  $aQuantifier = FALSE;
1900
  $bQuantifier = FALSE;
1901
  if (isset($a->label) && isset($b->label)) {
1902
    $aQuantifier = array_search($a->label, $type_status_order);
1903
    $bQuantifier = array_search($b->label, $type_status_order);
1904
  }
1905
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1906
}
1907

    
1908
/**
1909
 * Compares the two TextualTypeDesignations
1910
 *
1911
 * @param object $a
1912
 *   A TextualTypeDesignations.
1913
 * @param object $b
1914
 *   TextualTypeDesignations.
1915
 */
1916
function compare_textual_type_designation($a, $b) {
1917

    
1918
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1919
  if($cmp_by_status !== 0){
1920
    return $cmp_by_status;
1921
  }
1922

    
1923
  $aQuantifier = FALSE;
1924
  $bQuantifier = FALSE;
1925
  if ($aQuantifier == $bQuantifier) {
1926
    // Sort alphabetically.
1927
    $a_text =  isset($a->text_L10n->text) ? $a->text_L10n->text : '';
1928
    $b_text =  isset($b->text_L10n->text) ? $b->text_L10n->text : '';
1929
    return strcasecmp($a_text, $b_text);
1930
  }
1931
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1932
}
1933

    
1934

    
1935
/**
1936
 * Compares two SpecimenTypeDesignation status labels
1937
 *
1938
 * @param string $a
1939
 *   A TypeDesignationStatus label.
1940
 * @param string $b
1941
 *   A TypeDesignationStatus label.
1942
 */
1943
function compare_type_designation_status_labels($a, $b) {
1944

    
1945
  $type_status_order = type_status_order();
1946

    
1947
  $aQuantifier = FALSE;
1948
  $bQuantifier = FALSE;
1949
  if (isset($a) && isset($b)) {
1950
    $aQuantifier = array_search(ucfirst($a), $type_status_order);
1951
    $bQuantifier = array_search(ucfirst($b), $type_status_order);
1952
  }
1953
  return ($aQuantifier < $bQuantifier) ? -1 : 1;
1954
}
1955

    
1956
/**
1957
 * Preliminary implementation of a preset to define a sort order for
1958
 * type designation status.
1959
 *
1960
 * TODO this is only preliminary and may break in future,
1961
 *      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
1962
 * @return array
1963
 *   The array of orderd type labels
1964
 */
1965
function type_status_order()
1966
{
1967
  /*
1968
    This is the desired sort order as of now: Holotype Isotype Lectotype
1969
    Isolectotype Syntype.
1970
    TODO Basically, what we are trying to do is, we define
1971
    an ordered array of TypeDesignation-states and use the index of this array
1972
    for comparison. This array has to be filled with the cdm- TypeDesignation
1973
    states and the order should be parameterisable inside the dataportal.
1974
    */
1975
  static $type_status_order = array(
1976
    'Epitype',
1977
    'Holotype',
1978
    'Isotype',
1979
    'Lectotype',
1980
    'Isolectotype',
1981
    'Syntype',
1982
    'Paratype'
1983
  );
1984
  return $type_status_order;
1985
}
1986

    
1987
/**
1988
 * Return HTML for the lectotype citation with the correct layout.
1989
 *
1990
 * This function prints the lectotype citation with the correct layout.
1991
 * Lectotypes are renderized in the synonymy tab of a taxon if they exist.
1992
 *
1993
 * @param mixed $typeDesignation
1994
 *   Object containing the lectotype citation to print.
1995
 *
1996
 * @return string
1997
 *   Valid html string.
1998
 */
1999
function type_designation_citation_layout($typeDesignation, $footnote_separator = ',') {
2000
  $res = '';
2001
  $citation = $typeDesignation->source->citation;
2002
  $pages = $typeDesignation->source->citationMicroReference;
2003
  if(isset($typeDesignation->typeStatus->uuid) && isset($typeDesignation->typeStatus->representation_L10n)) {
2004
    if ( $typeDesignation->typeStatus->uuid == UUID_NTD_ORIGINAL_DESIGNATION || $typeDesignation->typeStatus->uuid == UUID_NTD_MONOTYPY) {
2005
      $res = ' (' . $typeDesignation->typeStatus->representation_L10n . ')';
2006
      return $res;
2007
    }
2008
  }
2009

    
2010
  if ($citation) {
2011
    // $type = $typeDesignation_citation->type;
2012
    $year = isset($citation->datePublished->start) ? substr($citation->datePublished->start, 0, 4) : '';
2013
    $author = isset($citation->authorship->titleCache) ? $citation->authorship->titleCache : '';
2014
    $res .= ' (designated by ';
2015
    $res .= $author;
2016
    $res .= ($year ? ' ' . $year : '');
2017
    $res .= ($pages ? ': ' . $pages : '');
2018
    // $res .= ')';
2019

    
2020
    // footnotes should be rendered in the parent element so we
2021
    // are relying on the FootnoteListKey set there
2022
    $fkey_typeDesignation = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation->titleCache);
2023
    $res .= render_footnote_key($fkey_typeDesignation, $footnote_separator,TRUE) . ')';
2024
  }
2025
  return $res;
2026
}
2027

    
2028
/**
2029
 * 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"
2030
 *
2031
 * @param $type_designation
2032
 * @return string
2033
 */
2034
function type_designation_status_label_markup($type_designation)
2035
{
2036
  return '<span class="type-status">'
2037
    . ((isset($type_designation->typeStatus->representation_L10n)) ? ucfirst($type_designation->typeStatus->representation_L10n) : t('Type')) . '</span>'
2038
    ;
2039
}
2040

    
2041
/**
2042
 * Creates markup for the status of a type designation DTO.
2043
 * In case the status or its representation is missing the label will be set to "Type"
2044
 *
2045
 * @param $type_designation
2046
 * @return string
2047
 */
2048
function type_designation_dto_status_label_markup($type_designation)
2049
{
2050
  return '<span class="type-status">'
2051
    . ((isset($type_designation->typeStatus_L10n)) ? ucfirst($type_designation->typeStatus_L10n) : t('Type')) . '</span>'
2052
    ;
2053
}
(7-7/14)