Project

General

Profile

Download (80.7 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
          $protologue_links[] = ' ' . l(font_awesome_icon_markup('fa-book'), $link->uri, ['html' => true]);
509
          }
510
        }
511
      }
512
    array_setr('description', join(', ', $protologue_links), $renderTemplate);
513
  }
514

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

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

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

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

    
576

    
577

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

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

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

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

    
616
  $typified_name = null;
617

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

    
633
  }
634

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

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

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

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

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

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

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

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

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

    
716
  return $render_array;
717
}
718

    
719

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

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

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

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

    
787
  return $render_array;
788
}
789

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

    
818

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

    
837

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

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

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

    
874

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
992
      }
993

    
994

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

    
998

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

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

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

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

    
1058
  RenderHints::popFromRenderStack();
1059

    
1060
  return $out;
1061
}
1062

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1161

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

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

    
1193

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

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

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

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

    
1247
  $render_array = array();
1248

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

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

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

    
1261

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

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

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

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

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

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

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

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

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

    
1352
  $relationship_markup = null;
1353

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

    
1356
  cdm_load_tagged_full_title($other_name);
1357

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

    
1373
  return $relationship_markup;
1374
}
1375

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

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

    
1399

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1554
  if ($name_relations) {
1555

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

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

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

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

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

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

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

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

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

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

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

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

    
1653

    
1654

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

    
1667

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

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

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

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

    
1753
}
1754

    
1755

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

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

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

    
1844
  return array();
1845
}
1846

    
1847

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

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

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

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

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

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

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

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

    
1933

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

    
1944
  $type_status_order = type_status_order();
1945

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

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

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

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

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

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

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