Project

General

Profile

Download (81.5 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
  $descriptionHtml = '';
503
  if (array_setr('description', TRUE, $renderTemplate)) {
504
    $descriptions = cdm_ws_get(CDM_WS_PORTAL_NAME_DESCRIPTIONS, $taxon_name->uuid);
505
    if($descriptions){
506
      foreach ($descriptions as $description) {
507
        if (!empty($description)) {
508
          foreach ($description->elements as $description_element) {
509
            $second_citation = '';
510
            if (isset($description_element->multilanguageText_L10n) && $description_element->multilanguageText_L10n->text) {
511
              if(isset($description_element->feature) && $description_element->feature->uuid == UUID_ADDITIONAL_PUBLICATION){
512
                $prefix =  '& ';
513
              } else {
514
                $prefix = '';
515
              }
516
              $second_citation = ' [' . $prefix . $description_element->multilanguageText_L10n->text . '].';
517
            }
518
            $descriptionHtml .= $second_citation;
519
            $descriptionHtml .= cdm_description_element_media(
520
                $description_element,
521
                array(
522
                  'application/pdf',
523
                  'image/png',
524
                  'image/jpeg',
525
                  'image/gif',
526
                  'text/html',
527
                )
528
            );
529

    
530
          }
531
        }
532
      }
533
    }
534
    array_setr('description', $descriptionHtml, $renderTemplate);
535
  }
536

    
537
  // Render.
538
  $out = '';
539
  if(isset($_REQUEST['RENDER_PATH'])){
540
    // developer option to show the render path with each taxon name
541
    $out .= '<span class="render-path">' . RenderHints::getRenderPath() . '</span>';
542
  }
543
  $out .= '<span class="' . html_class_attribute_ref($taxon_name_or_taxon_base)
544
    . '" data-cdm-ref="/name/' . $taxon_name->uuid . '" data-cdm-render-path="' . RenderHints::getRenderPath() .'">';
545

    
546
  foreach ($renderTemplate as $partName => $part) {
547
    $separator = '';
548
    $partHtml = '';
549
    $uri = FALSE;
550
    if (!is_array($part)) {
551
      continue;
552
    }
553
    if (isset($part['#uri']) && is_string($part['#uri'])) {
554
      $uri = $part['#uri'];
555
      unset($part['#uri']);
556
    }
557
    foreach ($part as $part => $content) {
558
      $html = '';
559
      if (is_array($content)) {
560
        $html = $content['#html'];
561
        if(isset($content['#separator'])) {
562
          $separator = $content['#separator'];
563
        }
564
      }
565
      elseif (is_string($content)) {
566
        $html = $content;
567
      }
568
      $partHtml .= '<span class="' . $part . '">' . $html . '</span>';
569
    }
570
    if ($uri) {
571
      // cannot use l() here since the #uri already should have been processed through uri() at this point
572
      $out .= $separator . '<a href="' . $uri . '" class="' . $partName . '">' . $partHtml . '</a>';
573

    
574
    }
575
    else {
576
      $out .= $separator . $partHtml;
577
    }
578
  }
579
  $out .= '</span>';
580

    
581
  $annotations_and_sources = new AnnotationsAndSources();
582
  if($nom_status_fkey){
583
    // the nomenclatural status footnote key refers to the source citation
584
    $annotations_and_sources->addFootNoteKey($nom_status_fkey);
585
  }
586
  if ($show_taxon_name_annotations) {
587
    if($taxon_base){
588
      $annotations_and_sources = handle_annotations_and_sources($taxon_base,
589
        null, null, $annotations_and_sources);
590
    }
591
    $annotations_and_sources = handle_annotations_and_sources($taxon_name,
592
      null, null, $annotations_and_sources);
593
  }
594
  $out .= $annotations_and_sources->footNoteKeysMarkup();
595
  return $out;
596
}
597

    
598

    
599

    
600
/**
601
 * Composes information for a registration from a dto object.
602
 *
603
 * Registrations which are not yet published are suppressed.
604
 *
605
 * @param $registration_dto
606
 * @param $with_citation
607
 *   Whether to show the citation.
608
 *
609
 * @return array
610
 *    A drupal render array with the elements:
611
 *    - 'name'
612
 *    - 'name-relations'
613
 *    - 'specimen_type_designations'
614
 *    - 'name_type_designations'
615
 *    - 'citation'
616
 *    - 'registration_date_and_institute'
617
 * @ingroup compose
618
 */
619
function compose_registration_dto_full($registration_dto, $with_citation = true)
620
{
621
  $render_array = array(
622
    '#prefix' => '<div class="registration">',
623
    '#suffix' => '</div>'
624
  );
625

    
626
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
627
    return $render_array;
628
  }
629

    
630
  $render_array['sub_headline'] = markup_to_render_array(join(", ", registration_types($registration_dto)),-10, '<h3 class="registration_type">' . t('Event: '), '</h3>' );
631
  $render_array['nomenclatural_act'] = array(
632
    '#weight' => 0,
633
    '#prefix' => '<div class="nomenclatural_act">',
634

    
635
    '#suffix' => '</div>'
636
  );
637

    
638
  $typified_name = null;
639

    
640
  // Nomenclatural act block element
641
  $last_footnote_listkey = RenderHints::setFootnoteListKey("nomenclatural_act");
642
  // name
643
  $name_relations = null;
644
  if(isset($registration_dto->nameRef) && $registration_dto->nameRef){
645
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
646
    cdm_load_tagged_full_title($name);
647
    $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);
648
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
649
    // need to create the name relationships later, so that the foot notes are in correct order, see section // name relations
650
  } else {
651
    // in this case the registration must have a
652
    // typified name will be rendered later
653
    $typified_name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
654

    
655
  }
656

    
657
  // typedesignation in detail
658
  if(is_object($registration_dto->orderedTypeDesignationWorkingSets)) {
659
    $field_unit_uuids = array();
660
    $specimen_type_designation_refs = array();
661
    $name_type_designation_refs = array();
662
    foreach ((array)$registration_dto->orderedTypeDesignationWorkingSets as $workingset_ref => $obj) {
663
      $tokens = explode("#", $workingset_ref);
664
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
665

    
666
      if ($tokens[0] == 'NameTypeDesignation') {
667
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
668
          if(!isset($name_type_designation_refs[$type_status])){
669
            $name_type_designation_refs[$type_status]  = $entity_reference_list;
670
          } else {
671
            array_push($name_type_designation_refs[$type_status] ,$entity_reference_list);
672
          }
673
        }
674
      } else if ($tokens[0] == 'FieldUnit'){
675
        $field_unit_uuids[] = $tokens[1];
676
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
677
          if(!isset($specimen_type_designation_refs[$type_status])){
678
            $specimen_type_designation_refs[$type_status] =  $entity_reference_list;
679
          } else {
680
            array_push($specimen_type_designation_refs[$type_status], $entity_reference_list);
681
          }
682
        }
683
      } else {
684
        drupal_set_message("Unimplemented type: " . $tokens[0], 'error');
685
      }
686
    }
687
    // type designations which are in this nomenclatural act.
688
    if (count($name_type_designation_refs) > 0) {
689
      $render_array['nomenclatural_act']['name_type_designations'] = compose_name_type_designations($name_type_designation_refs);
690
      $render_array['nomenclatural_act']['name_type_designations']['#prefix'] = '<p class="name_type_designations">';
691
      $render_array['nomenclatural_act']['name_type_designations']['#suffix'] = '</p>';
692
      $render_array['nomenclatural_act']['name_type_designations']['#weight'] = 20;
693
    }
694
    if (count($field_unit_uuids) > 0) {
695
      $specimen_type_designations_array = compose_specimen_type_designations($specimen_type_designation_refs, true);
696
      $render_array['nomenclatural_act']['specimen_type_designations'] = $specimen_type_designations_array['type_designations'];
697
      $render_array['map'] = $specimen_type_designations_array['map'];
698
      $render_array['map']['#weight'] = $render_array['nomenclatural_act']['#weight'] + 20;
699
    }
700
  }
701

    
702
  // name relations
703
  if($name_relations){
704
    $render_array['nomenclatural_act']['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
705
    $render_array['nomenclatural_act']['name_relations']['#weight'] = 10;
706
  }
707

    
708
  // citation
709
  if ($with_citation) {
710
    $render_array['citation'] = markup_to_render_array(
711
      "<div class=\"citation nomenclatural_act_citation" . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
712
      . "<span class=\"label\">published in: </span>"
713
      . $registration_dto->bibliographicInRefCitationString
714
      . l(custom_icon_font_markup('icon-interal-link-alt-solid', array('class' => array('superscript'))), path_to_reference($registration_dto->citationUuid), array('html' => true))
715
      . "</div>",
716
      $render_array['nomenclatural_act']['#weight'] + 10 );
717
  }
718

    
719
  $render_array['nomenclatural_act']['footnotes'] = markup_to_render_array(render_footnotes(),100);
720

    
721
  // END of nomenclatural act block
722
  RenderHints::setFootnoteListKey($last_footnote_listkey );
723

    
724
  if($typified_name){
725
    $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);
726
  }
727

    
728
  // registration date and office
729
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto);
730
  if($registration_date_insitute_markup){
731
    $render_array['registration_date_and_institute'] = markup_to_render_array(
732
      $registration_date_insitute_markup . '</p>',
733
      100);
734
  }
735

    
736
  $render_array['page_footnotes'] = markup_to_render_array(render_footnotes(), 110);
737

    
738
  return $render_array;
739
}
740

    
741

    
742
/**
743
 * Composes a compact representation for a registrationDTO object
744
 *
745
 * Registrations which are not yet published are suppressed.
746
 *
747
 * @param $registration_dto
748
 * @param $style string
749
 *   The style of how to compose the 'identifier' and 'registration_date_and_institute' part with the summary
750
 *   - 'citation': Similar to the arrearance of nomenclatural acts in print media
751
 *   - 'list-item' : style suitable for result lists etc
752
 *
753
 * @return array
754
 *    A drupal render array with the elements:
755
 *    - 'registration-metadata' when $style == 'list-item'
756
 *    - 'summary'
757
 * @ingroup compose
758
 */
759
function compose_registration_dto_compact($registration_dto, $style = 'citation', $tag_enclosing_summary = 'p')
760
{
761
  $render_array = array();
762
  $media_link_map = array();
763

    
764
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
765
    return $render_array;
766
  }
767

    
768
  $registration_date_institute_markup = render_registration_date_and_institute($registration_dto, 'span');
769
  $identifier_markup = render_link_to_registration($registration_dto->identifier);
770

    
771
  $tagged_text_options = array();
772
  if(isset($registration_dto->nameRef)){
773
    $tagged_text_options[] = array(
774
      'filter-type' => 'name',
775
      'prefix' => '<span class="registered_name">',
776
      'suffix' => '</span>',
777
    );
778
  } else {
779
    $tagged_text_options[] = array(
780
      'filter-type' => 'name',
781
      'prefix' => '<span class="referenced_typified_name">',
782
      'suffix' => '</span>',
783
    );
784
  }
785
  cdm_tagged_text_add_options($registration_dto->summaryTaggedText, $tagged_text_options);
786
  tagged_text_extract_reference($registration_dto->summaryTaggedText);
787
  $tagged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
788
  foreach ($tagged_text_expanded  as $tagged_text){
789
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
790
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
791
      if(isset($mediaDTOs[0]->uri)){
792
        $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
793
        $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
794
        $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
795
      }
796
    }
797
  }
798
  $registation_markup = cdm_tagged_text_to_markup($tagged_text_expanded);
799
  foreach($media_link_map as $media_url_key => $link){
800
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
801
  }
802
  if($style == 'citation') {
803
    $registation_markup = $registation_markup . ' ' . $identifier_markup . ' ' . $registration_date_institute_markup;
804
  } else {
805
    $render_array['registration-metadata'] = markup_to_render_array('<div class="registration-metadata">' . $identifier_markup . ' ' . $registration_date_institute_markup. "</div>", -10);
806
  }
807
  $render_array['summary'] = markup_to_render_array('<' . $tag_enclosing_summary . ' class="registration-summary">' . $registation_markup . '</' . $tag_enclosing_summary . '>', 0);
808

    
809
  return $render_array;
810
}
811

    
812
/**
813
 * Renders the registrationDate and institutionTitleCache of the $registration_dto as markup.
814
 *
815
 * @param $registration_dto
816
 * @return string
817
 *    The markup or an empty string
818
 */
819
function render_registration_date_and_institute($registration_dto, $enclosing_tag = 'p') {
820
  $registration_date_institute_markup = '';
821
  if ($registration_dto->registrationDate) {
822
    $date_string = format_datetime($registration_dto->registrationDate);
823
    if (isset($registration_dto->institutionTitleCache) && $registration_dto->institutionTitleCache) {
824
      $registration_date_institute_markup =
825
        t("Registration on @date in @institution", array(
826
          '@date' => $date_string,
827
          '@institution' => $registration_dto->institutionTitleCache,
828
        ));
829
    } else {
830
      $registration_date_institute_markup =
831
        t("Registration on @date", array(
832
          '@date' => $date_string
833
        ));
834
    }
835
    $registration_date_institute_markup = '<' .$enclosing_tag . ' class="registration-date-and-institute">'. $registration_date_institute_markup . '</' .$enclosing_tag . '>';
836
  }
837
  return $registration_date_institute_markup;
838
}
839

    
840

    
841
/**
842
 * @param $registrations
843
 * @return string
844
 */
845
function render_registrations($registrations)
846
{
847
  $registration_markup = '';
848
  $registration_markup_array = array();
849
  if ($registrations) {
850
    foreach ($registrations as $reg) {
851
      $registration_markup_array[] = render_registration($reg);
852
    }
853
    $registration_markup = " Registration" . (count($registration_markup_array) > 1 ? 's: ' : ': ')
854
      . join(', ', $registration_markup_array);
855
  }
856
  return $registration_markup;
857
}
858

    
859

    
860
/**
861
 * Renders a registration
862
 *
863
 * TODO replace by compose_registration_dto_compact
864
 * @param $registration
865
 */
866
function render_registration($registration){
867
  $markup = '';
868

    
869
  if(isset($registration->identifier) && $registration->status == 'PUBLISHED'){
870
    $office_class_attribute = '';
871
    if(isset($registration->institution->titleCache)){
872
      $office_class_attribute = registration_institution_class_attribute($registration);
873
    }
874
    $markup = "<span class=\"registration $office_class_attribute\">" . render_link_to_registration($registration->identifier) . ', '
875
      .  preg_replace('/^([^T]*)(.*)$/', '${1}', $registration->registrationDate)
876
      . '</span>';
877
  }
878
  return $markup;
879
}
880

    
881
/**
882
 * @param $registration
883
 * @return string
884
 */
885
function registration_institution_class_attribute($registration_dto)
886
{
887
  if(isset($registration_dto->institutionTitleCache)){
888
    $institutionTitleCache = $registration_dto->institutionTitleCache;
889
  } else {
890
    // fall back option to also support cdm entities
891
    $institutionTitleCache = @$registration_dto->institution->titleCache;
892
  }
893
  return $institutionTitleCache ? 'registration-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $institutionTitleCache)) : '';
894
}
895

    
896

    
897
/**
898
 * Renders and array of CDM TypeDesignations
899
 *
900
 *  - NameTypeDesignation
901
 *  - SpecimenTypeDesignation
902
 *  - TextualTypeDesignation
903
 *
904
 * @param object $type_designations an array of cdm TypeDesignation entities
905
 *  to render
906
 * @param string $enclosing_tag the tag element type to enclose the whole list
907
 *  of type designation with. By default this DOM element is <ul>
908
 * @param string $element_tag the tag element type to be used for each
909
 *  type designation item.
910
 * @param bool $link_to_specimen_page whether a specimen in type designation element
911
 *  should be a link or not.
912
 *
913
 * @return string The markup.
914
 *
915
 * @InGroup Render
916
 */
917
function render_type_designations($type_designations, $enclosing_tag = 'ul', $element_tag =  'li', $link_to_specimen_page = true) {
918

    
919
  // need to add element to render path since type designations
920
  // need other name render template
921
  RenderHints::pushToRenderStack('typedesignations');
922

    
923
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
924
  $specimen_type_designations = array();
925
  $name_type_designations = array();
926
  $textual_type_designations = array();
927
  $separator = ',';
928

    
929
  foreach ($type_designations as $type_designation) {
930
    switch ($type_designation->class) {
931
      case 'SpecimenTypeDesignation':
932
        $specimen_type_designations[] = $type_designation;
933
        break;
934
      case 'NameTypeDesignation':
935
        $name_type_designations[] = $type_designation;
936
        break;
937
      case 'TextualTypeDesignation':
938
        $textual_type_designations[] = $type_designation;
939
        break;
940
      default:  throw new Exception('Unknown type designation class: ' . $type_designation->class);
941
    }
942
  }
943

    
944
  // NameTypeDesignation ..................................
945
  if(!empty($name_type_designations)){
946
    usort($name_type_designations, "compare_type_designations_by_status");
947
    foreach($name_type_designations as $name_type_designation){
948
      if ($name_type_designation->notDesignated) {
949
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation)  . ': '
950
          . t('not designated') . '</'. $element_tag .'>';
951
      }
952
      elseif (isset($name_type_designation->typeName)) {
953
        $link_to_name_page = url(path_to_name($name_type_designation->typeName->uuid));
954
        $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($name_type_designation) . '">' .  type_designation_status_label_markup($name_type_designation) ;
955

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

    
959
        }
960
        $referenceUri = '';
961
        if (isset($name_type_designation->typeName->nomenclaturalSource->citation)) {
962
          $referenceUri = url(path_to_reference($name_type_designation->typeName->nomenclaturalSource->citation->uuid));
963
        }
964
        $out .= ': ' . render_taxon_or_name($name_type_designation->typeName, $link_to_name_page, $referenceUri, TRUE, TRUE);
965
      }
966
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
967
      $annotations_and_sources = handle_annotations_and_sources($name_type_designation);
968
      $out .= $annotations_and_sources->footNoteKeysMarkup();
969
    }
970
  } // END NameTypeDesignation
971

    
972
  // SpecimenTypeDesignation ...................................
973
  if (!empty($specimen_type_designations)) {
974
    usort($specimen_type_designations, "compare_specimen_type_designation");
975
    foreach ($specimen_type_designations as $specimen_type_designation) {
976
      $type_citation_markup = '';
977

    
978
      if (!empty($specimen_type_designation->source->citation)) {
979

    
980
        $citation_footnote_str = cdm_reference_markup($specimen_type_designation->source->citation, null, false, true);
981
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $specimen_type_designation->source->citation->uuid);
982

    
983
        if (!empty($author_team->titleCache)) {
984
          $year = @timePeriodToString($specimen_type_designation->source->citation->datePublished, true, 'YYYY');
985
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
986
          if ($authorteam_str == $specimen_type_designation->source->citation->titleCache) {
987
            $citation_footnote_str = '';
988
          }
989
        } else {
990
          $authorteam_str = $citation_footnote_str;
991
          // no need for a footnote in case in case it is used as replacement for missing author teams
992
          $citation_footnote_str = '';
993
        }
994

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

    
1000
        $footnote_key_markup = '';
1001
        if ($citation_footnote_str) {
1002
          // footnotes should be rendered in the parent element so we
1003
          // are relying on the FootnoteListKey set there
1004
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
1005
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
1006
        }
1007

    
1008
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
1009
        if (!empty($specimen_type_designation->source->citationMicroReference)) {
1010
          $type_citation_markup .= ': ' . trim($specimen_type_designation->source->citationMicroReference);
1011
        }
1012
        $type_citation_markup .= $footnote_key_markup . ')';
1013

    
1014
      }
1015

    
1016

    
1017
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($specimen_type_designation) . '">';
1018
      $out .= type_designation_status_label_markup($specimen_type_designation) . $type_citation_markup;
1019

    
1020

    
1021
      $derivedUnitFacadeInstance = null;
1022
      if (isset($specimen_type_designation->typeSpecimen)) {
1023
        $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $specimen_type_designation->typeSpecimen->uuid);
1024
      }
1025

    
1026
      if (!empty($derivedUnitFacadeInstance->titleCache)) {
1027
        $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1028
        if($link_to_specimen_page && isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1029
          $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($specimen_type_designation->typeSpecimen->uuid)), $specimen_markup);
1030
        }
1031
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1032
        $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1033
        $out .= ': <span class="' . html_class_attribute_ref($specimen_type_designation->typeSpecimen) . '">'
1034
          . $specimen_markup
1035
          . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1036
        if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1037
          $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1038
        }
1039
        $out .= $annotations_and_sources->footNoteKeysMarkup();
1040
      }
1041
      $out .= '</'. $element_tag .'>';
1042
    }
1043
  } // END Specimen type designations
1044

    
1045
  // TextualTypeDesignation .........................
1046
  usort($textual_type_designations, 'compare_textual_type_designation');
1047
  if(!empty($textual_type_designations)) {
1048
      RenderHints::setAnnotationsAndSourceConfig([
1049
          // these settings differ from those provided by annotations_and_sources_config_typedesignations()
1050
          // TODO is this by purpose? please document the reason for the difference
1051
          'sources_as_content' => false, // as footnotes
1052
          'link_to_name_used_in_source' => false,
1053
          'link_to_reference' => true,
1054
          'add_footnote_keys' => true,
1055
          'bibliography_aware' => false
1056
        ]
1057
      );
1058
    foreach ($textual_type_designations as $textual_type_designation) {
1059
      $annotations_and_sources = handle_annotations_and_sources($textual_type_designation);
1060
      $encasement =  $textual_type_designation->verbatim ? '"' : '';
1061
      $out .= '<' . $element_tag . ' class="' . html_class_attribute_ref($textual_type_designation) . '">' . type_designation_status_label_markup(null)
1062
        . ': ' .  $encasement . trim($textual_type_designation->text_L10n->text) . $encasement .  $annotations_and_sources->footNoteKeysMarkup() .'</' . $element_tag . '>';
1063
//      if($annotations_and_sources->hasSourceReferences())){
1064
//        $citation_markup = join(', ', getSourceReferences());
1065
//      }
1066
//      $out .= $citation_markup;
1067
    }
1068
  }
1069

    
1070
  // Footnotes for citations, collection acronyms.
1071
  // footnotes should be rendered in the parent element so we
1072
  // are relying on the FootnoteListKey set there
1073
  $_fkey = FootnoteManager::addNewFootnote(
1074
    RenderHints::getFootnoteListKey(),
1075
    (isset($derivedUnitFacadeInstance->collection->titleCache) ? $derivedUnitFacadeInstance->collection->titleCache : FALSE)
1076
  );
1077
  $out .= render_footnote_key($_fkey, $separator);
1078
  $out .= '</' . $enclosing_tag .'>';
1079

    
1080
  RenderHints::popFromRenderStack();
1081

    
1082
  return $out;
1083
}
1084

    
1085
/**
1086
 * Creates markup for a list of SpecimenTypedesignationDTO
1087
 *
1088
 * @param array $specimen_typedesignation_dtos
1089
 *  The SpecimenTypedesignationDTOs to be rendered
1090
 *
1091
 * @param bool $show_type_specimen
1092
 *
1093
 * @param string $enclosing_tag
1094
 * @param string $element_tag
1095
 *
1096
 * @return string
1097
 *   The markup.
1098
 */
1099
function render_specimen_typedesignation_dto($specimen_typedesignation_dtos, $show_type_specimen = FALSE, $enclosing_tag = 'ul', $element_tag = 'li'){
1100

    
1101
  // need to add element to render path since type designations
1102
  // need other name render template
1103
  RenderHints::pushToRenderStack('typedesignations');
1104

    
1105
  $out = '<' . $enclosing_tag .' class="typeDesignations">';
1106
  $separator = ',';
1107

    
1108
  if (!empty($specimen_typedesignation_dtos)) {
1109
    // usort($specimen_type_designations, "compare_specimen_type_designation"); // FIXME create compare function for SpecimenTypedesignationDTO
1110
    foreach ($specimen_typedesignation_dtos as $std_dto) {
1111
      $type_citation_markup = '';
1112

    
1113
      if (!empty($std_dto->source->citation)) {
1114

    
1115
        $citation_footnote_str = cdm_reference_markup($std_dto->source->citation, null, false, true);
1116
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $std_dto->source->citation->uuid);
1117

    
1118
        if (!empty($author_team->titleCache)) {
1119
          $year = @timePeriodToString($std_dto->source->citation->datePublished, true, 'YYYY');
1120
          $authorteam_str = $author_team->titleCache . ($year ? ' ' : '') . $year;
1121
          if ($authorteam_str == $std_dto->source->citation->titleCache) {
1122
            $citation_footnote_str = '';
1123
          }
1124
        } else {
1125
          $authorteam_str = $citation_footnote_str;
1126
          // no need for a footnote in case in case it is used as replacement for missing author teams
1127
          $citation_footnote_str = '';
1128
        }
1129

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

    
1135
        $footnote_key_markup = '';
1136
        if ($citation_footnote_str) {
1137
          // footnotes should be rendered in the parent element so we
1138
          // are relying on the FootnoteListKey set there
1139
          $_fkey2 = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation_footnote_str);
1140
          $footnote_key_markup = render_footnote_key($_fkey2, $separator, TRUE);
1141
        }
1142

    
1143
        $type_citation_markup .= '&nbsp;(' . t('designated by') . '&nbsp;<span class="typeReference">' . $authorteam_str . '</span>';
1144
        if (!empty($std_dto->source->citationMicroReference)) {
1145
          $type_citation_markup .= ': ' . trim($std_dto->source->citationMicroReference);
1146
        }
1147
        $type_citation_markup .= $footnote_key_markup . ')';
1148
      }
1149

    
1150
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($std_dto) . '">';
1151
      $out .= type_designation_dto_status_label_markup($std_dto) . $type_citation_markup;
1152

    
1153
      if($show_type_specimen){
1154
        $derivedUnitFacadeInstance = null;
1155
        if (isset($std_dto->typeSpecimen)) {
1156
          $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $std_dto->typeSpecimen->uuid);
1157
        }
1158

    
1159
        if (!empty($derivedUnitFacadeInstance->titleCache)) {
1160
          $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1161
          if(isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1162
            $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($std_dto->typeSpecimen->uuid)), $specimen_markup);
1163
          }
1164
          RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1165
          $annotations_and_sources = handle_annotations_and_sources($derivedUnitFacadeInstance);
1166
          $out .= ': <span class="' . html_class_attribute_ref($std_dto->typeSpecimen) . '">'
1167
            . $specimen_markup
1168
            . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1169
          if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1170
            $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1171
          }
1172
          $out .= $annotations_and_sources->footNoteKeysMarkup();
1173
        }
1174
      }
1175

    
1176
      $out .= '</'. $element_tag .'>';
1177
    }
1178
    RenderHints::popFromRenderStack();
1179
  }
1180
  return $out;
1181
}
1182

    
1183

    
1184
/**
1185
 * Composes the textual representation for the type designation of taxon name identified by the uuid in with a map for the location data.
1186
 *
1187
 * @param $taxon_name_uuid
1188
 * @param $show_specimen_details
1189
 * @return array
1190
 *    A drupal render array with the following elements:
1191
 *    - 'type_designations'
1192
 *    - 'map'
1193
 *    - 'specimens'
1194
 *
1195
 * @ingroup compose
1196
 */
1197
function compose_type_designations($taxon_name_uuid, $show_specimen_details = false)
1198
{
1199
  $render_array = array(
1200
    'type_designations' => array(),
1201
    'map' => array(),
1202
    );
1203
  $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name_uuid);
1204
  if ($type_designations) {
1205
    usort($type_designations, 'compare_specimen_type_designation');
1206
    $render_array['type_designations'] = markup_to_render_array(
1207
      render_type_designations($type_designations, 'div', 'div')
1208
    );
1209

    
1210
    $render_array['map'] = compose_type_designations_map($type_designations);
1211
  }
1212
  return $render_array;
1213
}
1214

    
1215

    
1216
/**
1217
 * Composes the TypedEntityReference to name type designations passed as associatve array.
1218
 *
1219
 * @param $type_entity_refs_by_status array
1220
 *   an associative array of name type type => TypedEntityReference for name type designations as
1221
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1222
 *
1223
 * @ingroup compose
1224
 */
1225
function compose_name_type_designations($type_entity_refs_by_status){
1226
  $render_array = array();
1227
  $preferredStableUri = '';
1228
  foreach($type_entity_refs_by_status as $type_status => $name_type_entityRefs){
1229
    foreach ($name_type_entityRefs as $name_type_entity_ref){
1230
      $type_designation = cdm_ws_get(CDM_WS_TYPEDESIGNATION, array($name_type_entity_ref->uuid, 'preferredUri'));
1231
      $footnote_keys = '';
1232

    
1233
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1234
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1235
      }
1236
      // annotations and sources for the $derived_unit_facade_dto
1237
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1238
      $annotations_and_sources = handle_annotations_and_sources($name_type_entity_ref);
1239

    
1240
      $render_array[] = markup_to_render_array('<div class="name_type_designation ' . html_class_attribute_ref($name_type_entity_ref)  .
1241
        '"><span class="type-status">'. ucfirst($type_status) . "</span>: "
1242
        . $name_type_entity_ref->label
1243
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1244
        . $annotations_and_sources->footNoteKeysMarkup()
1245
        . '</div>');
1246
      }
1247
  }
1248
  return $render_array;
1249
}
1250

    
1251
/**
1252
 * Composes the specimen type designations with map from the the $type_entity_refs
1253
 *
1254
 * @param $type_entity_refs array
1255
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
1256
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1257
 *
1258
 * @param $show_media_specimen
1259
 * @return array
1260
 *    A drupal render array with the following elements:
1261
 *    - 'type_designations'
1262
 *    - 'map'
1263
 *
1264
 * @ingroup compose
1265
 *
1266
 */
1267
function compose_specimen_type_designations($type_entity_refs, $show_media_specimen){
1268

    
1269
  $render_array = array();
1270

    
1271
  $type_designation_list = array();
1272
  uksort($type_entity_refs, "compare_type_designation_status_labels");
1273
  foreach($type_entity_refs as $type_status => $type_designation_entity_refs){
1274
    foreach($type_designation_entity_refs as $type_designation_entity_ref){
1275

    
1276
      $type_designation = cdm_ws_get(CDM_WS_PORTAL_TYPEDESIGNATION, array($type_designation_entity_ref->uuid));
1277
      $type_designation_list[] = $type_designation; // collect for the map
1278

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

    
1283

    
1284
      $preferredStableUri = '';
1285
      $citation_markup = '';
1286
      $media = '';
1287

    
1288
      // annotations and sources for the $derived_unit_facade_dto
1289
      RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1290
      $annotations_and_sources = handle_annotations_and_sources($derived_unit_facade_dto);
1291
      $source_citations = $annotations_and_sources->getSourceReferences();
1292
      $foot_note_keys = $annotations_and_sources->footNoteKeysMarkup();
1293

    
1294
      // preferredStableUri
1295
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1296
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1297
      }
1298

    
1299
      if($show_media_specimen && $mediaSpecimen){
1300
        // compose output
1301
        // mediaURI
1302
        if(isset($mediaSpecimen->representations[0])) {
1303
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
1304
          $captionElements = array(
1305
            '#uri' => t('open media'),
1306
            'elements' => array('-none-'),
1307
            'sources_as_content' => true
1308
          );
1309
          $media = compose_cdm_media_gallerie(array(
1310
            'mediaList' => array($mediaSpecimen),
1311
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $type_designation_entity_ref->uuid,
1312
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
1313
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
1314
            'captionElements' => $captionElements,
1315
          ));
1316
        }
1317
        // citation and detail for the media specimen
1318
        RenderHints::setAnnotationsAndSourceConfig(annotations_and_sources_config_typedesignations());
1319
        $annotations_and_sources = handle_annotations_and_sources($mediaSpecimen);
1320
        if($annotations_and_sources->hasSourceReferences()){
1321
          $source_citations = array_merge($source_citations, $annotations_and_sources->getSourceReferences());
1322
        }
1323
        if($annotations_and_sources->hasFootnoteKeys()){
1324
          $foot_note_keys .= ', ' . $annotations_and_sources->footNoteKeysMarkup();
1325
        }
1326
      }
1327

    
1328
      $citation_markup = join(', ', $source_citations);
1329

    
1330
      $specimen_markup = $derived_unit_facade_dto->titleCache;
1331
      if(isset($derived_unit_facade_dto->specimenLabel) && $derived_unit_facade_dto->specimenLabel){
1332
        $specimen_markup = str_replace(
1333
          $derived_unit_facade_dto->specimenLabel,
1334
          l($derived_unit_facade_dto->specimenLabel, path_to_specimen($type_designation->typeSpecimen->uuid)), $specimen_markup);
1335
      }
1336

    
1337
      $type_designation_render_array = markup_to_render_array(
1338
        '<div class="type_designation_entity_ref ' . html_class_attribute_ref($type_designation_entity_ref)  . '">
1339
          <span class="type-status">' . ucfirst($type_status) . "</span>: "
1340
        . $specimen_markup . $foot_note_keys
1341
        . ($citation_markup ? ' '. $citation_markup : '')
1342
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1343
        . $media
1344
        . '</div>');
1345

    
1346
      $render_array['type_designations'][] = $type_designation_render_array;
1347
    }
1348
  }
1349
  if(count($type_designation_list) > 0 ){
1350
    $render_array['map'] = compose_type_designations_map($type_designation_list);
1351
  } else {
1352
    $render_array['map'] = array();
1353
  }
1354
  return $render_array;
1355
}
1356

    
1357
/**
1358
 * Creates the markup for the given name relationship.
1359
 *
1360
 * For the footnotes see handle_annotations_and_sources().
1361
 *
1362
 * @param $other_name
1363
 *      The other name from the NameRelationship see get_other_name()
1364
 * @param $current_taxon_uuid
1365
 * @param $show_name_cache_only
1366
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
1367
 * @return null|string
1368
 *    The markup or null
1369
 *
1370
 * @see \get_other_name
1371
 */
1372
function name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only = false){
1373

    
1374
  $relationship_markup = null;
1375

    
1376
  $other_name = get_other_name($current_name_uuid, $name_rel);
1377

    
1378
  cdm_load_tagged_full_title($other_name);
1379

    
1380
  $highlited_synonym_uuid = isset ($other_name->taxonBases[0]->uuid) ? $other_name->taxonBases[0]->uuid : '';
1381
  if($show_name_cache_only){
1382
    $relationship_markup = l(
1383
      '<span class="' . html_class_attribute_ref($other_name) . '"">' . $other_name->nameCache . '</span>',
1384
      path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
1385
      array('html' => true)
1386
    );
1387
    $annotations_and_sources = handle_annotations_and_sources($other_name);
1388
    $relationship_markup .= $annotations_and_sources->footNoteKeysMarkup();
1389
  } else {
1390
    $relationship_markup = render_taxon_or_name($other_name,
1391
      url(path_to_name($other_name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
1392
    );
1393
  }
1394

    
1395
  return $relationship_markup;
1396
}
1397

    
1398
/**
1399
 * Determined the other name which is contained in the NameRelationship entity.
1400
 *
1401
 * @param $current_name_uuid
1402
 *   The uuid of this name.
1403
 * @param $name_rel
1404
 *   The cdm NameRelationship entity
1405
 *
1406
 * @return object
1407
 *   The other cdm Name entity.
1408
 */
1409
function get_other_name($current_name_uuid, $name_rel) {
1410
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
1411

    
1412
  if ($current_name_is_toName) {
1413
    $name = $name_rel->fromName;
1414
  }
1415
  else {
1416
    $name = $name_rel->toName;
1417
  }
1418
  return $name;
1419
}
1420

    
1421

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

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

    
1462
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
1463
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1464
  foreach ($selected_name_rel_uuids as $uuid){
1465
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1466
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
1467
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
1468
    }
1469
  }
1470

    
1471
  $list_prefix = '<span class="name_relationships">[';
1472
  $list_suffix = ']</span>';
1473
  $item_prefix = '<span class="item">';
1474
  $item_suffix = '</span> ';
1475
  $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);
1476

    
1477
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1478
  $items_ctn = count($render_array['list']['items']);
1479
  if($items_ctn){
1480
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1481
  }
1482

    
1483
  RenderHints::popFromRenderStack();
1484
  return $render_array;
1485
}
1486

    
1487
/**
1488
 * Composes an list representation of the name relationships.
1489
 *
1490
 * The output of this function will be usually appended to taxon name representations.
1491
 *
1492
 * Related issues:
1493
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1494
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1495
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1496
 *
1497
 * @param $name_relations
1498
 *    The list of CDM NameRelationsips
1499
 * @param $current_name_uuid
1500
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1501
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1502
 * @param $current_taxon_uuid
1503
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1504
 * @return array
1505
 *    A drupal render array
1506
 *
1507
 * @ingroup Compose
1508
 */
1509
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1510

    
1511
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1512

    
1513
  $key = 'name_relationships';
1514
  RenderHints::pushToRenderStack($key);
1515
  if(RenderHints::isUnsetFootnoteListKey()){
1516
    RenderHints::setFootnoteListKey($key);
1517
  }
1518
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1519

    
1520
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, cdm_vocabulary_as_defaults(UUID_NAME_RELATIONSHIP_TYPE));
1521
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1522
  foreach ($selected_name_rel_uuids as $uuid){
1523
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1524
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1525
  }
1526

    
1527
  $list_prefix = '<div class="relationships_list name_relationships">';
1528
  $list_suffix = '</div>';
1529
  $item_prefix = '<div class="item">';
1530
  $item_suffix = '</div>';
1531

    
1532
  $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);
1533

    
1534
  RenderHints::popFromRenderStack();
1535
  if(RenderHints::getFootnoteListKey() == $key) {
1536
    $render_array['footnotes'] = markup_to_render_array(render_footnotes(RenderHints::getFootnoteListKey()));
1537
    RenderHints::clearFootnoteListKey();
1538
  }
1539
  return $render_array;
1540
}
1541

    
1542
/**
1543
 * @param $name_relations
1544
 * @param $name_rel_type_filter
1545
 *   Associative array with two keys:
1546
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1547
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1548
 * @param $current_name_uuid
1549
 * @param $current_taxon_uuid
1550
 * @param $list_prefix
1551
 * @param $list_suffix
1552
 * @param $item_prefix
1553
 * @param $item_suffix
1554
 * @return array
1555
 *
1556
 * @ingroup Compose
1557
 */
1558
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1559
                                    $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1560
{
1561
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1562
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1563
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1564
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1565
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1566

    
1567
  $render_array = array(
1568
    'list' => array(
1569
      '#prefix' => $list_prefix,
1570
      '#suffix' => $list_suffix,
1571
      'items' => array()
1572
    ),
1573
    'footnotes' => array()
1574
  );
1575

    
1576
  if ($name_relations) {
1577

    
1578
    // remove all relations which are not selected in the settings and
1579
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1580
    // for special handling
1581
    $filtered_name_rels = array();
1582
    $non_nec_name_rels = array();
1583
    $orthographic_variants = array();
1584
    foreach ($name_relations as $name_rel) {
1585
      $rel_type_uuid = $name_rel->type->uuid;
1586
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1587
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1588
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1589

    
1590
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1591
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1592
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1593
          )
1594
        ){
1595
          $non_nec_name_rels[] = $name_rel;
1596
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1597
          $orthographic_variants[] = $name_rel;
1598
        } else {
1599

    
1600
          $filtered_name_rels[] = $name_rel;
1601
        }
1602
      }
1603
    }
1604
    $name_relations = $filtered_name_rels;
1605

    
1606
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1607

    
1608
    // compose
1609
    $show_name_cache_only = FALSE;
1610
    foreach ($name_relations 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 = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1618
      $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup . ' ';
1619
      $relationship_markup = $symbol_markup . $relationship_markup;
1620
      if ($relationship_markup) {
1621
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1622
          null,
1623
          $item_prefix,
1624
          $item_suffix);
1625
      }
1626
    }
1627

    
1628
    // name relationships to be displayed as non nec
1629
    if (count($non_nec_name_rels) > 0) {
1630
      $non_nec_markup = '';
1631
      $show_name_cache_only = FALSE;
1632
      foreach ($non_nec_name_rels 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

    
1639
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1640
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1641
        $non_nec_markup .= $symbol_markup . $relationship_markup;
1642
      }
1643
      if ($non_nec_markup) {
1644
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1645
          null,
1646
          $item_prefix,
1647
          $item_suffix);
1648
      }
1649
    }
1650

    
1651
    // orthographic variants
1652
    if (count($orthographic_variants) > 0) {
1653
      $show_name_cache_only = TRUE;
1654
      foreach ($orthographic_variants as $name_rel) {
1655

    
1656
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1657
        $rel_footnote_key_markup = render_footnote_key(handle_name_relationship_as_footnote($name_rel),'');
1658
        $relationship_markup = name_relationship_markup($current_name_uuid, $name_rel, $current_taxon_uuid, $show_name_cache_only);
1659
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1660
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1661
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1662
        $relationship_markup = $symbol_markup . $relationship_markup;
1663
      }
1664
      if (isset($relationship_markup) && $relationship_markup) {
1665
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1666
          null,
1667
          $item_prefix,
1668
          $item_suffix);
1669
      }
1670
    }
1671
  }
1672
  return $render_array;
1673
}
1674

    
1675

    
1676

    
1677
/**
1678
 * @param $taxon
1679
 * @return array
1680
 */
1681
function cdm_name_relationships_for_taxon($taxon)
1682
{
1683
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1684
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1685
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1686
  return $name_relations;
1687
}
1688

    
1689

    
1690
/**
1691
 * Recursively searches the array for the $key and sets the given value.
1692
 *
1693
 * @param mixed $key
1694
 *   Key to search for.
1695
 * @param mixed $value
1696
 *   Value to set.'
1697
 * @param array $array
1698
 *   Array to search in.
1699
 *
1700
 * @return bool
1701
 *   True if the key has been found.
1702
 */
1703
function &array_setr($key, $value, array &$array) {
1704
  $res = NULL;
1705
  foreach ($array as $k => &$v) {
1706
    if ($key == $k) {
1707
      $v = $value;
1708
      return $array;
1709
    }
1710
    elseif (is_array($v)) {
1711
      $innerArray = array_setr($key, $value, $v);
1712
      if ($innerArray) {
1713
        return $array;
1714
      }
1715
    }
1716
  }
1717
  return $res;
1718
}
1719

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

    
1738
/**
1739
 * @todo Please document this function.
1740
 * @see http://drupal.org/node/1354
1741
 */
1742
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1743
  $res = NULL;
1744
  $precedingKey = NULL;
1745
  foreach ($renderTemplate as &$part) {
1746
    if (is_array($part)) {
1747
      foreach ($part as $key => &$element) {
1748
        if ($key == $contentElementKey) {
1749
          return $precedingKey;
1750
        }
1751
        if (!str_beginsWith($key, '#')) {
1752
          $precedingKey = $key;
1753
        }
1754
      }
1755
    }
1756
  }
1757
  return $res;
1758
}
1759

    
1760
function nameTypeToDTYPE($dtype){
1761
  static $nameTypeLabelMap = array(
1762
    "ICNB" => "BacterialName",
1763
    "ICNAFP" => "BotanicalName",
1764
    "ICNCP" => "CultivarPlantName",
1765
    "ICZN" => "ZoologicalName",
1766
    "ICVCN" => "ViralName",
1767
    "Any taxon name" => "TaxonName",
1768
    "NonViral" => "TaxonName",
1769
    "Fungus" => "BotanicalName",
1770
    "Plant" => "BotanicalName",
1771
    "Algae" => "BotanicalName",
1772
  );
1773
  return $nameTypeLabelMap[$dtype];
1774

    
1775
}
1776

    
1777

    
1778
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1779
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1780
}
1781

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

    
1839
/**
1840
 * Collects and deduplicates the type designations associated with the passes synonyms.
1841
 *
1842
 * @param $synonymy_group
1843
 *    An array containing a homotypic or heterotypic group of names.
1844
 * @param $accepted_taxon_name_uuid
1845
 *    The uuid of the accepted taxon name. Optional parameter which is required when composing
1846
 *    the information for the homotypic group. In this case the accepted taxon is not included
1847
 *    in the $synonymy_group and must therefor passed in this second parameter.
1848
 *
1849
 * @return array
1850
 *    The CDM TypeDesignation entities
1851
 */
1852
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null)
1853
{
1854
  if (count($synonymy_group) > 0) {
1855
    $name_uuid = array_pop($synonymy_group)->name->uuid;
1856
  } else {
1857
    $name_uuid = $accepted_taxon_name_uuid;
1858
  }
1859
  if ($name_uuid) {
1860
   $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS_IN_HOMOTYPICAL_GROUP, $name_uuid);
1861
    if ($type_designations) {
1862
      return $type_designations;
1863
    }
1864
  }
1865

    
1866
  return array();
1867
}
1868

    
1869

    
1870
/**
1871
 * Compares two SpecimenTypeDesignations
1872
 *
1873
 * @param object $a
1874
 *   A SpecimenTypeDesignation.
1875
 * @param object $b
1876
 *   SpecimenTypeDesignation.
1877
 */
1878
function compare_specimen_type_designation($a, $b) {
1879

    
1880
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1881
  if($cmp_by_status !== 0){
1882
    return $cmp_by_status;
1883
  }
1884

    
1885
  $aQuantifier = FALSE;
1886
  $bQuantifier = FALSE;
1887
  if ($aQuantifier == $bQuantifier) {
1888
    // Sort alphabetically.
1889
    $a_text =  isset($a->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $a->typeSpecimen->titleCache) : '';
1890
    $b_text =  isset($b->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $b->typeSpecimen->titleCache) : '';
1891
    return strcasecmp($a_text, $b_text);
1892
  }
1893
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1894
}
1895

    
1896
/**
1897
 * Compares the status of two TypeDesignations
1898
 *
1899
 * @param object $a
1900
 *   A TypeDesignation
1901
 * @param object $b
1902
 *   TypeDesignation
1903
 */
1904
function compare_type_designations_by_status($a, $b) {
1905
  $status_a = isset($a->typeStatus) ? $a->typeStatus : null;
1906
  $status_b = isset($b->typeStatus) ? $b->typeStatus : null;
1907
  return compare_type_designation_status($status_a, $status_b);
1908
}
1909

    
1910
/**
1911
 * Compares two TypeDesignationStatusBase
1912
 *
1913
 * @param object $a
1914
 *   A TypeDesignationStatusBase.
1915
 * @param object $b
1916
 *   TypeDesignationStatusBase.
1917
 */
1918
function compare_type_designation_status($a, $b) {
1919
  $type_status_order = type_status_order();
1920
  $aQuantifier = FALSE;
1921
  $bQuantifier = FALSE;
1922
  if (isset($a->label) && isset($b->label)) {
1923
    $aQuantifier = array_search($a->label, $type_status_order);
1924
    $bQuantifier = array_search($b->label, $type_status_order);
1925
  }
1926
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1927
}
1928

    
1929
/**
1930
 * Compares the two TextualTypeDesignations
1931
 *
1932
 * @param object $a
1933
 *   A TextualTypeDesignations.
1934
 * @param object $b
1935
 *   TextualTypeDesignations.
1936
 */
1937
function compare_textual_type_designation($a, $b) {
1938

    
1939
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1940
  if($cmp_by_status !== 0){
1941
    return $cmp_by_status;
1942
  }
1943

    
1944
  $aQuantifier = FALSE;
1945
  $bQuantifier = FALSE;
1946
  if ($aQuantifier == $bQuantifier) {
1947
    // Sort alphabetically.
1948
    $a_text =  isset($a->text_L10n->text) ? $a->text_L10n->text : '';
1949
    $b_text =  isset($b->text_L10n->text) ? $b->text_L10n->text : '';
1950
    return strcasecmp($a_text, $b_text);
1951
  }
1952
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1953
}
1954

    
1955

    
1956
/**
1957
 * Compares two SpecimenTypeDesignation status labels
1958
 *
1959
 * @param string $a
1960
 *   A TypeDesignationStatus label.
1961
 * @param string $b
1962
 *   A TypeDesignationStatus label.
1963
 */
1964
function compare_type_designation_status_labels($a, $b) {
1965

    
1966
  $type_status_order = type_status_order();
1967

    
1968
  $aQuantifier = FALSE;
1969
  $bQuantifier = FALSE;
1970
  if (isset($a) && isset($b)) {
1971
    $aQuantifier = array_search(ucfirst($a), $type_status_order);
1972
    $bQuantifier = array_search(ucfirst($b), $type_status_order);
1973
  }
1974
  return ($aQuantifier < $bQuantifier) ? -1 : 1;
1975
}
1976

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

    
2008
/**
2009
 * Return HTML for the lectotype citation with the correct layout.
2010
 *
2011
 * This function prints the lectotype citation with the correct layout.
2012
 * Lectotypes are renderized in the synonymy tab of a taxon if they exist.
2013
 *
2014
 * @param mixed $typeDesignation
2015
 *   Object containing the lectotype citation to print.
2016
 *
2017
 * @return string
2018
 *   Valid html string.
2019
 */
2020
function type_designation_citation_layout($typeDesignation, $footnote_separator = ',') {
2021
  $res = '';
2022
  $citation = $typeDesignation->source->citation;
2023
  $pages = $typeDesignation->source->citationMicroReference;
2024
  if(isset($typeDesignation->typeStatus->uuid) && isset($typeDesignation->typeStatus->representation_L10n)) {
2025
    if ( $typeDesignation->typeStatus->uuid == UUID_NTD_ORIGINAL_DESIGNATION || $typeDesignation->typeStatus->uuid == UUID_NTD_MONOTYPY) {
2026
      $res = ' (' . $typeDesignation->typeStatus->representation_L10n . ')';
2027
      return $res;
2028
    }
2029
  }
2030

    
2031
  if ($citation) {
2032
    // $type = $typeDesignation_citation->type;
2033
    $year = isset($citation->datePublished->start) ? substr($citation->datePublished->start, 0, 4) : '';
2034
    $author = isset($citation->authorship->titleCache) ? $citation->authorship->titleCache : '';
2035
    $res .= ' (designated by ';
2036
    $res .= $author;
2037
    $res .= ($year ? ' ' . $year : '');
2038
    $res .= ($pages ? ': ' . $pages : '');
2039
    // $res .= ')';
2040

    
2041
    // footnotes should be rendered in the parent element so we
2042
    // are relying on the FootnoteListKey set there
2043
    $fkey_typeDesignation = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $citation->titleCache);
2044
    $res .= render_footnote_key($fkey_typeDesignation, $footnote_separator,TRUE) . ')';
2045
  }
2046
  return $res;
2047
}
2048

    
2049
/**
2050
 * 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"
2051
 *
2052
 * @param $type_designation
2053
 * @return string
2054
 */
2055
function type_designation_status_label_markup($type_designation)
2056
{
2057
  return '<span class="type-status">'
2058
    . ((isset($type_designation->typeStatus->representation_L10n)) ? ucfirst($type_designation->typeStatus->representation_L10n) : t('Type')) . '</span>'
2059
    ;
2060
}
2061

    
2062
/**
2063
 * Creates markup for the status of a type designation DTO.
2064
 * In case the status or its representation is missing the label will be set to "Type"
2065
 *
2066
 * @param $type_designation
2067
 * @return string
2068
 */
2069
function type_designation_dto_status_label_markup($type_designation)
2070
{
2071
  return '<span class="type-status">'
2072
    . ((isset($type_designation->typeStatus_L10n)) ? ucfirst($type_designation->typeStatus_L10n) : t('Type')) . '</span>'
2073
    ;
2074
}
(7-7/14)