Project

General

Profile

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

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

    
33

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

    
75
  static $default_render_templates = NULL;
76
  static $split_render_templates = NULL;
77

    
78

    
79
  if (!isset($default_render_templates)) {
80
    $default_render_templates = unserialize(CDM_NAME_RENDER_TEMPLATES_DEFAULT);
81
  }
82
  if($split_render_templates == NULL) {
83
    $render_templates = variable_get(CDM_NAME_RENDER_TEMPLATES, $default_render_templates);
84
    // needs to be converted to an array
85
    $render_templates = (object_to_array($render_templates));
86

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

    
100
  // get the base element of the renderPath
101
  if (($separatorPos = strpos($render_path, '.')) > 0) {
102
    $renderPath_base = substr($render_path, 0, $separatorPos);
103
  } else {
104
    $renderPath_base = $render_path;
105
  }
106

    
107
  $template = NULL;
108
  // 1. try to find a template using the render path base element
109
  if(array_key_exists($renderPath_base, $split_render_templates)){
110
    $template = (array)$split_render_templates[$renderPath_base];
111
  }
112

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

    
127

    
128
  // 3. Otherwise get default RenderTemplate from theme.
129
  if (!is_array($template)) {
130
    $template = $split_render_templates['#DEFAULT'];
131
  }
132

    
133
  // --- set the link uris to the according template fields if they exist
134
  if(isset($template['nameAuthorPart']) && isset($template['nameAuthorPart']['#uri'])) {
135
    if ($nameLink) {
136
      $template['nameAuthorPart']['#uri'] = $nameLink;
137
    }
138
    else {
139
      unset($template['nameAuthorPart']['#uri']);
140
    }
141
  }
142

    
143
  if ($nameLink && isset($template['namePart']['#uri'])) {
144
    $template['namePart']['#uri'] = $nameLink;
145
  }
146
  else {
147
    unset($template['namePart']['#uri']);
148
  }
149

    
150
  if ($referenceLink && isset($template['referencePart']['#uri'])) {
151
    $template['referencePart']['#uri'] = $referenceLink;
152
  }
153
  else {
154
    unset($template['referencePart']['#uri']);
155
  }
156

    
157
  return $template;
158
}
159

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

    
225
  static $default_part_definitions = null;
226
  if (!isset($default_part_definitions)) {
227
    $default_part_definitions= unserialize(CDM_PART_DEFINITIONS_DEFAULT);
228
  }
229

    
230
  static $part_definitions = null;
231
  if (!isset($part_definitions)) {
232
    $part_definitions = object_to_array(variable_get(CDM_PART_DEFINITIONS, $default_part_definitions));
233
  }
234

    
235
  $dtype = nameTypeToDTYPE($taxonNameType);
236
  if (array_key_exists($taxonNameType, $part_definitions)) {
237
    return $part_definitions[$taxonNameType];
238
  } else if (array_key_exists($dtype, $part_definitions)) {
239
    return $part_definitions[$dtype];
240
  } else {
241
    return $part_definitions['#DEFAULT']; // covers ViralNames and general NonViralNames
242
  }
243

    
244
}
245

    
246

    
247
/**
248
 * Renders the markup for a CDM TaxonName instance.
249
 *
250
 * The layout of the name representation is configured by the
251
 * part_definitions and render_templates (see get_partDefinition() and
252
 * get_nameRenderTemplate())
253
 *
254
 * @param $taxonName
255
 *    cdm TaxonName instance
256
 * @param $name_link
257
 *    URI to the taxon, @see path_to_taxon(), must be processed by url() before passing to this method
258
 * @param $reference_link
259
 *    URI to the reference, @see path_to_reference(), must be processed by url() before passing to this method
260
 * @param $show_annotations
261
 *    turns the display of annotations on
262
 * @param $is_type_designation
263
 *    To indicate that the supplied taxon name is a name type designation.
264
 * @param $skiptags
265
 *    an array of name elements tags like 'name', 'rank' to skip. The name part
266
 *          'authors' will not ber affected by this filter. This part is managed though the render template
267
 *          mechanism.
268
 * @param $is_invalid
269
 *   Indicates that this taxon is invalid. In this case the name part will be shown in double quotes.
270
 *   This is useful when rendering taxon relation ships.
271
 *
272
 * @return string
273
 *  The markup for a taxon name.
274
 *
275
 */
276
function render_taxon_or_name($taxon_name_or_taxon_base, $name_link = NULL, $reference_link = NULL,
277
  $show_annotations = true, $is_type_designation = false, $skiptags = array(), $is_invalid = false) {
278

    
279
  $is_doubtful = false;
280

    
281
  if($taxon_name_or_taxon_base->class == 'Taxon' || $taxon_name_or_taxon_base->class == 'Synonym'){
282
    if(isset($taxon_name_or_taxon_base->name)){
283
      $taxonName = $taxon_name_or_taxon_base->name;
284
    } else {
285
      $taxonName = cdm_ws_get(CDM_WS_TAXON . '/$0/name', array($taxon_name_or_taxon_base->uuid));
286
    }
287
    $is_doubtful = $taxon_name_or_taxon_base->doubtful;
288
    // use the TaxonBase.tagged_title so we have the secRef
289
    $tagged_title = $taxon_name_or_taxon_base->taggedTitle;
290
  } else {
291
    // assuming this is a TaxonName
292
    $taxonName = $taxon_name_or_taxon_base;
293
    if(isset($taxonName->taggedFullTitle)){
294
      $tagged_title = $taxon_name_or_taxon_base->taggedFullTitle;
295
    } else {
296
      $tagged_title = $taxon_name_or_taxon_base->taggedName;
297
    }
298
  }
299

    
300

    
301
  $renderTemplate = get_nameRenderTemplate(RenderHints::getRenderPath(), $name_link, $reference_link);
302
  $partDefinition = get_partDefinition($taxonName->nameType);
303

    
304
  // Apply definitions to template.
305
  foreach ($renderTemplate as $part => $uri) {
306

    
307
    if (isset($partDefinition[$part])) {
308
      $renderTemplate[$part] = $partDefinition[$part];
309
    }
310
    if (is_array($uri) && isset($uri['#uri'])) {
311
      $renderTemplate[$part]['#uri'] = $uri['#uri'];
312
    }
313
  }
314

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

    
321
  normalize_tagged_text($tagged_title);
322

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

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

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

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

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

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

    
356

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

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

    
387

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

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

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

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

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

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

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

    
440

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

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

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

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

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

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

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

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

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

    
576
    }
577
    else {
578
      $out .= $separator . $partHtml;
579
    }
580
  }
581
  $out .= '</span>';
582
  if ($show_annotations) {
583
    // $out .= render_entities_annotations_as_footnote_keys([$taxonName]);
584
  }
585
  return $out;
586
}
587

    
588

    
589

    
590
/**
591
 * Composes information for a registration from a dto object.
592
 *
593
 * Registrations which are not yet published are suppressed.
594
 *
595
 * @param $registration_dto
596
 * @param $with_citation
597
 *   Whether to show the citation.
598
 *
599
 * @return array
600
 *    A drupal render array with the elements:
601
 *    - 'name'
602
 *    - 'name-relations'
603
 *    - 'specimen_type_designations'
604
 *    - 'name_type_designations'
605
 *    - 'citation'
606
 *    - 'registration_date_and_institute'
607
 * @ingroup compose
608
 */
609
function compose_registration_dto_full($registration_dto, $with_citation = true)
610
{
611
  $render_array = array(
612
    '#prefix' => '<div class="registration">',
613
    '#suffix' => '</div>'
614
  );
615

    
616
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
617
    return $render_array;
618
  }
619

    
620
  $render_array['sub_headline'] = markup_to_render_array(join(", ", registration_types($registration_dto)),-10, '<h3 class="registration_type">' . t('Event: '), '</h3>' );
621
  $render_array['nomenclatural_act'] = array(
622
    '#weight' => 0,
623
    '#prefix' => '<div class="nomenclatural_act">',
624

    
625
    '#suffix' => '</div>'
626
  );
627

    
628
  // name
629
  $name_relations = null;
630
  if($registration_dto->nameRef){
631
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
632
    cdm_load_tagged_full_title($name);
633
    $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);
634
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
635
    // need to create the name relationships later, so that the foot notes are in correct order, see section // name relations
636
  } else {
637
    // in this case the registration must have a
638
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
639
    $render_array['typified_name'] = markup_to_render_array('<p class="typified-name">for ' . render_taxon_or_name($name, url(path_to_name($name->uuid))) . '</p>', 40);
640
  }
641

    
642
  // typedesignation in detail
643
  if(is_object($registration_dto->orderdTypeDesignationWorkingSets)) {
644
    $field_unit_uuids = array();
645
    $specimen_type_designation_refs = array();
646
    $name_type_designation_refs = array();
647
    foreach ((array)$registration_dto->orderdTypeDesignationWorkingSets as $workingset_ref => $obj) {
648
      $tokens = explode("#", $workingset_ref);
649
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
650

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

    
687
  // name relations
688
  if($name_relations){
689
    $render_array['nomenclatural_act']['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
690
    $render_array['nomenclatural_act']['name_relations']['#weight'] = 10;
691
  }
692

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

    
704
  $render_array['nomenclatural_act']['footnotes'] = markup_to_render_array(render_cdm_footnotes(),
705
    100
706
  );
707

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

    
716

    
717
  return $render_array;
718
}
719

    
720

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

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

    
747
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto, 'span');
748
  $itentifier_markup = l($registration_dto->identifier, path_to_registration($registration_dto->identifier), array('attributes' => array('class' => array('identifier'))));
749

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

    
787
  return $render_array;
788
}
789

    
790

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

    
819

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

    
838

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

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

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

    
875

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

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

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

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

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

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

    
938
        }
939
        $referenceUri = '';
940
        if (isset($name_type_designation->typeName->nomenclaturalReference)) {
941
          $referenceUri = url(path_to_reference($name_type_designation->typeName->nomenclaturalReference->uuid));
942
        }
943
        $out .= ': ' . render_taxon_or_name($name_type_designation->typeName, $link_to_name_page, $referenceUri, TRUE, TRUE);
944
      }
945
      $annotations_and_sources = handle_annotations_and_sources(
946
        $name_type_designation,
947
        typedesignations_annotations_and_sources_config(),
948
        '',
949
        RenderHints::getFootnoteListKey());
950
      $out .= $annotations_and_sources['foot_note_keys'];
951
    }
952
  } // END NameTypeDesignation
953

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

    
960
      if (!empty($specimen_type_designation->citation)) {
961

    
962
        $citation_footnote_str = cdm_reference_markup($specimen_type_designation->citation, null, false, true);
963
        $author_team = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $specimen_type_designation->citation->uuid);
964

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

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

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

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

    
996
      }
997

    
998

    
999
      $out .= '<'. $element_tag .' class="' . html_class_attribute_ref($specimen_type_designation) . '">';
1000
      $out .= type_designation_status_label_markup($specimen_type_designation) . $type_citation_markup;
1001

    
1002

    
1003
      $derivedUnitFacadeInstance = null;
1004
      if (isset($specimen_type_designation->typeSpecimen)) {
1005
        $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, $specimen_type_designation->typeSpecimen->uuid);
1006
      }
1007

    
1008
      if (!empty($derivedUnitFacadeInstance->titleCache)) {
1009
        $specimen_markup = $derivedUnitFacadeInstance->titleCache;
1010
        if($link_to_specimen_page && isset($derivedUnitFacadeInstance->specimenLabel) && $derivedUnitFacadeInstance->specimenLabel){
1011
          $specimen_markup = str_replace($derivedUnitFacadeInstance->specimenLabel, l($derivedUnitFacadeInstance->specimenLabel, path_to_specimen($specimen_type_designation->typeSpecimen->uuid)), $specimen_markup);
1012
        }
1013
        $annotations_and_sources = handle_annotations_and_sources(
1014
          $derivedUnitFacadeInstance,
1015
          typedesignations_annotations_and_sources_config(),
1016
          '',
1017
          RenderHints::getFootnoteListKey()
1018
        );
1019
        $out .= ': <span class="' . html_class_attribute_ref($specimen_type_designation->typeSpecimen) . '">'
1020
          . $specimen_markup
1021
          . '</span>'; // . ': ' . theme('cdm_specimen', array('specimenTypeDesignation' => $derivedUnitFacadeInstance));
1022
        if(!empty($derivedUnitFacadeInstance->preferredStableUri)){
1023
          $out .= ' ' . l($derivedUnitFacadeInstance->preferredStableUri, $derivedUnitFacadeInstance->preferredStableUri, array('absolute' => true));
1024
        }
1025
        $out .= $annotations_and_sources['foot_note_keys'];
1026
      }
1027

    
1028

    
1029
      $out .= '</'. $element_tag .'>';
1030

    
1031
    }
1032
  } // END Specimen type designations
1033

    
1034
  // TextualTypeDesignation .........................
1035
  usort($textual_type_designations, 'compare_textual_type_designation');
1036
  if(!empty($textual_type_designations)) {
1037
    foreach ($textual_type_designations as $textual_type_designation) {
1038
      $annotations_and_sources = handle_annotations_and_sources(
1039
        $textual_type_designation,
1040
        array(
1041
          'sources_as_content' => false, // as footnotes
1042
          'link_to_name_used_in_source' => false,
1043
          'link_to_reference' => true,
1044
          'add_footnote_keys' => true,
1045
          'bibliography_aware' => false
1046
        ),
1047
        '',
1048
        RenderHints::getFootnoteListKey() // passing a defined key to avoid a separate annotation footnote key see https://dev.e-taxonomy.eu/redmine/issues/8543
1049
      );
1050
      $encasement =  $textual_type_designation->verbatim ? '"' : '';
1051
      $out .= '<' . $element_tag . ' class="' . html_class_attribute_ref($textual_type_designation) . '">' . type_designation_status_label_markup(null)
1052
        . ': ' .  $encasement . trim($textual_type_designation->text_L10n->text) . $encasement .  $annotations_and_sources['foot_note_keys'] .'</' . $element_tag . '>';
1053
//      if(is_array( $annotations_and_sources['source_references'])){
1054
//        $citation_markup = join(', ', $annotations_and_sources['source_references']);
1055
//      }
1056
//      $out .= $citation_markup;
1057
    }
1058
  }
1059

    
1060
  // Footnotes for citations, collection acronyms.
1061
  // footnotes should be rendered in the parent element so we
1062
  // are relying on the FootnoteListKey set there
1063
  $_fkey = FootnoteManager::addNewFootnote(
1064
    RenderHints::getFootnoteListKey(),
1065
    (isset($derivedUnitFacadeInstance->collection->titleCache) ? $derivedUnitFacadeInstance->collection->titleCache : FALSE)
1066
  );
1067
  $out .= render_footnote_key($_fkey, $separator);
1068
  $out .= '</' . $enclosing_tag .'>';
1069

    
1070
  RenderHints::popFromRenderStack();
1071

    
1072
  return $out;
1073
}
1074

    
1075

    
1076
/**
1077
 * Composes the textual representation for the type designation of taxon name identified by the uuid in with a map for the location data.
1078
 *
1079
 * @param $taxon_name_uuid
1080
 * @param $show_specimen_details
1081
 * @return array
1082
 *    A drupal render array with the following elements:
1083
 *    - 'type_designations'
1084
 *    - 'map'
1085
 *    - 'specimens'
1086
 *
1087
 * @ingroup compose
1088
 */
1089
function compose_type_designations($taxon_name_uuid, $show_specimen_details = false)
1090
{
1091
  $render_array = array(
1092
    'type_designations' => array(),
1093
    'map' => array(),
1094
    );
1095
  $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name_uuid);
1096
  if ($type_designations) {
1097
    usort($type_designations, 'compare_specimen_type_designation');
1098
    $render_array['type_designations'] = markup_to_render_array(
1099
      render_type_designations($type_designations, 'div', 'div')
1100
    );
1101

    
1102
    $render_array['map'] = compose_type_designations_map($type_designations);
1103
  }
1104
  return $render_array;
1105
}
1106

    
1107

    
1108
/**
1109
 * Composes the TypedEntityReference to name type designations passed as associatve array.
1110
 *
1111
 * @param $type_entity_refs_by_status array
1112
 *   an associative array of name type type => TypedEntityReference for name type designations as
1113
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1114
 *
1115
 * @ingroup compose
1116
 */
1117
function compose_name_type_designations($type_entity_refs_by_status){
1118
  $render_array = array();
1119
  $preferredStableUri = '';
1120
  foreach($type_entity_refs_by_status as $type_status => $name_type_entityRefs){
1121
    foreach ($name_type_entityRefs as $name_type_entity_ref){
1122
      $type_designation = cdm_ws_get(CDM_WS_TYPEDESIGNATION, array($name_type_entity_ref->uuid, 'preferredUri'));
1123
      $footnote_keys = '';
1124

    
1125
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1126
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1127
      }
1128
      // annotations and sources for the $derived_unit_facade_dto
1129
      $annotations_and_sources = handle_annotations_and_sources(
1130
        $name_type_entity_ref,
1131
        typedesignations_annotations_and_sources_config(),
1132
        '',
1133
        RenderHints::getFootnoteListKey()
1134
      );
1135

    
1136
      $render_array[] = markup_to_render_array('<div class="name_type_designation ' . html_class_attribute_ref($name_type_entity_ref)  . '"><span class="type-status">'. ucfirst($type_status) . "</span>: "
1137
        . $name_type_entity_ref->label
1138
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1139
        . $annotations_and_sources['foot_note_keys']
1140
        . '</div>');
1141
      }
1142
  }
1143
  return $render_array;
1144
}
1145

    
1146
/**
1147
 * Composes the specimen type designations with map from the the $type_entity_refs
1148
 *
1149
 * @param $type_entity_refs array
1150
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
1151
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
1152
 *
1153
 * @param $show_media_specimen
1154
 * @return array
1155
 *    A drupal render array with the following elements:
1156
 *    - 'type_designations'
1157
 *    - 'map'
1158
 *
1159
 * @ingroup compose
1160
 *
1161
 */
1162
function compose_specimen_type_designations($type_entity_refs, $show_media_specimen){
1163

    
1164
  $render_array = array();
1165

    
1166
  $type_designation_list = array();
1167
  uksort($type_entity_refs, "compare_type_designation_status_labels");
1168
  foreach($type_entity_refs as $type_status => $type_designation_entity_refs){
1169
    foreach($type_designation_entity_refs as $type_designation_entity_ref){
1170

    
1171
      $type_designation = cdm_ws_get(CDM_WS_PORTAL_TYPEDESIGNATION, array($type_designation_entity_ref->uuid));
1172
      $type_designation_list[] = $type_designation; // collect for the map
1173

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

    
1178

    
1179
      $preferredStableUri = '';
1180
      $citation_markup = '';
1181
      $media = '';
1182

    
1183
      // annotations and sources for the $derived_unit_facade_dto
1184
      $annotations_and_sources = handle_annotations_and_sources(
1185
        $derived_unit_facade_dto,
1186
        typedesignations_annotations_and_sources_config(),
1187
        '',
1188
        RenderHints::getFootnoteListKey()
1189
      );
1190
      $source_citations = $annotations_and_sources['source_references'];
1191
      $foot_note_keys = $annotations_and_sources['foot_note_keys'];
1192

    
1193
      // preferredStableUri
1194
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
1195
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
1196
      }
1197

    
1198
      if($show_media_specimen && $mediaSpecimen){
1199
        // compose output
1200
        // mediaURI
1201
        if(isset($mediaSpecimen->representations[0])) {
1202
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
1203
          $captionElements = array(
1204
            '#uri' => t('open media'),
1205
            'elements' => array('-none-'),
1206
            'sources_as_content' => true
1207
          );
1208
          $media = compose_cdm_media_gallerie(array(
1209
            'mediaList' => array($mediaSpecimen),
1210
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $type_designation_entity_ref->uuid,
1211
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
1212
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
1213
            'captionElements' => $captionElements,
1214
          ));
1215
        }
1216
        // citation and detail for the media specimen
1217
        $annotations_and_sources = handle_annotations_and_sources(
1218
          $mediaSpecimen,
1219
          typedesignations_annotations_and_sources_config(),
1220
          '',
1221
          null
1222
        );
1223
        if(is_array( $annotations_and_sources['source_references'])){
1224
          $source_citations = array_merge($source_citations, $annotations_and_sources['source_references']);
1225
        }
1226
        if($annotations_and_sources['foot_note_keys']){
1227
          $foot_note_keys .= ', ' . $annotations_and_sources['foot_note_keys'];
1228
        }
1229
      }
1230

    
1231
      $citation_markup = join(', ', $source_citations);
1232

    
1233
      $specimen_markup = $derived_unit_facade_dto->titleCache;
1234
      if(isset($derived_unit_facade_dto->specimenLabel) && $derived_unit_facade_dto->specimenLabel){
1235
        $specimen_markup = str_replace(
1236
          $derived_unit_facade_dto->specimenLabel,
1237
          l($derived_unit_facade_dto->specimenLabel, path_to_specimen($type_designation->typeSpecimen->uuid)), $specimen_markup);
1238
      }
1239

    
1240
      $type_designation_render_array = markup_to_render_array(
1241
        '<div class="type_designation_entity_ref ' . html_class_attribute_ref($type_designation_entity_ref)  . '">
1242
          <span class="type-status">' . ucfirst($type_status) . "</span>: "
1243
        . $specimen_markup . $foot_note_keys
1244
        . ($citation_markup ? ' '. $citation_markup : '')
1245
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1246
        . $media
1247
        . '</div>');
1248

    
1249
      $render_array['type_designations'][] = $type_designation_render_array;
1250
    }
1251
  }
1252
  if(count($type_designation_list) > 0 ){
1253
    $render_array['map'] = compose_type_designations_map($type_designation_list);
1254
  } else {
1255
    $render_array['map'] = array();
1256
  }
1257
  return $render_array;
1258
}
1259

    
1260
/**
1261
 * Provides the default configuration for typedesignations which
1262
 * are passed to the handle_annotations_and_sources()
1263
 * function:
1264
 * - 'sources_as_content' => TRUE,
1265
 * - 'link_to_name_used_in_source' => FALSE,
1266
 * - 'link_to_reference' => TRUE,
1267
 * - 'add_footnote_keys' => FALSE,
1268
 * - 'bibliography_aware' => FALSE
1269
 *
1270
 * @return array
1271
 */
1272
function typedesignations_annotations_and_sources_config() {
1273
  static $annotations_and_sources_config = [
1274
    'sources_as_content' => TRUE,
1275
    'link_to_name_used_in_source' => FALSE,
1276
    'link_to_reference' => TRUE,
1277
    'add_footnote_keys' => FALSE,
1278
    'bibliography_aware' => FALSE
1279
  ];
1280
  return $annotations_and_sources_config;
1281
}
1282

    
1283
/**
1284
 * @param $name_rel
1285
 * @param $current_name_uuid
1286
 * @param $current_taxon_uuid
1287
 * @param $suppress_if_current_name_is_source // FIXME UNUSED !!!!
1288
 * @param $show_name_cache_only
1289
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
1290
 * @return null|string
1291
 *    The markup or null
1292
 */
1293
function name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, $show_name_cache_only = false){
1294

    
1295
  $relationship_markup = null;
1296

    
1297
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
1298

    
1299
  if($current_name_is_toName){
1300
    $name = $name_rel->fromName;
1301
  } else {
1302
    $name = $name_rel->toName;
1303
  }
1304

    
1305
  cdm_load_tagged_full_title($name);
1306

    
1307
  $highlited_synonym_uuid = isset ($name->taxonBases[0]->uuid) ? $name->taxonBases[0]->uuid : '';
1308
  if(!$show_name_cache_only){
1309
    $relationship_markup = render_taxon_or_name($name,
1310
      url(path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
1311
    );
1312
  } else {
1313
    $relationship_markup = l(
1314
      '<span class="' . html_class_attribute_ref($name) . '"">' . $name->nameCache . '</span>',
1315
      path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
1316
      array('html' => true)
1317
    );
1318
  }
1319

    
1320
  return $relationship_markup;
1321
}
1322

    
1323

    
1324
/**
1325
 * Composes an inline representation of selected name relationships
1326
 *
1327
 * The output of this function will be usually appended to taxon name representations.
1328
 * Only the following types are displayed: LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR, ORTHOGRAPHIC_VARIANT
1329
 *
1330
 * LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR are displayed as
1331
 * non {titleCache} nec {titleCache} nec {titleCache} whereas the related names
1332
 * are ordered alphabetically.
1333
 *
1334
 * ORTHOGRAPHIC_VARIANT is displayed as 'ort. var. {nameCache}'
1335
 *
1336
 * Related issues:
1337
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1338
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1339
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1340
 *   - https://dev.e-taxonomy.eu/redmine/issues/2001 "[Cichorieae Portal] Name Relationship -> blocking name are not shown"
1341
 *
1342
 * @param $name_relations
1343
 *    The list of CDM NameRelationsips
1344
 * @param $current_name_uuid
1345
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1346
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1347
 * @param $suppress_if_current_name_is_source
1348
 *    The display of the relation will be
1349
 *    suppressed is the current name is on the source of the relation edge.
1350
 *    That is if it is on the from side of the relation. Except for 'blocking name for' which is
1351
 *    an inverse relation. For this relation type the toName is taken in to account.
1352
 * @param $current_taxon_uuid
1353
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1354
 * @return array
1355
 *    A drupal render array
1356
 *
1357
 * @ingroup Compose
1358
 */
1359
function compose_name_relationships_inline($name_relations, $current_name_uuid, $current_taxon_uuid, $suppress_if_current_name_is_source = true) {
1360

    
1361
  RenderHints::pushToRenderStack('homonym');
1362
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1363

    
1364
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
1365
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1366
  foreach ($selected_name_rel_uuids as $uuid){
1367
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1368
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
1369
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
1370
    }
1371
  }
1372

    
1373
  $list_prefix = '<span class="name_relationships">[';
1374
  $list_suffix = ']</span>';
1375
  $item_prefix = '<span class="item">';
1376
  $item_suffix = '</span> ';
1377
  $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);
1378

    
1379
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1380
  $items_ctn = count($render_array['list']['items']);
1381
  if($items_ctn){
1382
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1383
  }
1384

    
1385
  RenderHints::popFromRenderStack();
1386
  return $render_array;
1387
}
1388

    
1389
/**
1390
 * Composes an list representation of the name relationships.
1391
 *
1392
 * The output of this function will be usually appended to taxon name representations.
1393
 *
1394
 * Related issues:
1395
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1396
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1397
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1398
 *
1399
 * @param $name_relations
1400
 *    The list of CDM NameRelationsips
1401
 * @param $current_name_uuid
1402
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1403
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1404
 * @param $current_taxon_uuid
1405
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1406
 * @return array
1407
 *    A drupal render array
1408
 *
1409
 * @ingroup Compose
1410
 */
1411
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1412

    
1413
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1414

    
1415
  $key = 'name_relationships';
1416
  RenderHints::pushToRenderStack($key);
1417
  if(!RenderHints::getFootnoteListKey()){
1418
    RenderHints::setFootnoteListKey($key);
1419
  }
1420
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1421

    
1422
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, cdm_vocabulary_as_defaults(UUID_NAME_RELATIONSHIP_TYPE));
1423
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1424
  foreach ($selected_name_rel_uuids as $uuid){
1425
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1426
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1427
  }
1428

    
1429
  $list_prefix = '<div class="relationships_list name_relationships">';
1430
  $list_suffix = '</div>';
1431
  $item_prefix = '<div class="item">';
1432
  $item_suffix = '</div>';
1433

    
1434
  $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);
1435

    
1436
  RenderHints::popFromRenderStack();
1437
  if(RenderHints::getFootnoteListKey() == $key) {
1438
    $render_array['footnotes'] = markup_to_render_array(render_footnotes(RenderHints::getFootnoteListKey()));
1439
    RenderHints::clearFootnoteListKey();
1440
  }
1441
  return $render_array;
1442
}
1443

    
1444
/**
1445
 * @param $name_relations
1446
 * @param $name_rel_type_filter
1447
 *   Associative array with two keys:
1448
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1449
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1450
 * @param $current_name_uuid
1451
 * @param $current_taxon_uuid
1452
 * @param $list_prefix
1453
 * @param $list_suffix
1454
 * @param $item_prefix
1455
 * @param $item_suffix
1456
 * @return array
1457
 *
1458
 * @ingroup Compose
1459
 */
1460
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1461
                                    $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1462
{
1463
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1464
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1465
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1466
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1467
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1468

    
1469
  $render_array = array(
1470
    'list' => array(
1471
      '#prefix' => $list_prefix,
1472
      '#suffix' => $list_suffix,
1473
      'items' => array()
1474
    ),
1475
    'footnotes' => array()
1476
  );
1477

    
1478
  if ($name_relations) {
1479

    
1480
    // remove all relations which are not selected in the settings and
1481
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1482
    // for special handling
1483
    $filtered_name_rels = array();
1484
    $non_nec_name_rels = array();
1485
    $orthographic_variants = array();
1486
    foreach ($name_relations as $name_rel) {
1487
      $rel_type_uuid = $name_rel->type->uuid;
1488
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1489
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1490
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1491

    
1492
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1493
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1494
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1495
          )
1496
        ){
1497
          $non_nec_name_rels[] = $name_rel;
1498
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1499
          $orthographic_variants[] = $name_rel;
1500
        } else {
1501

    
1502
          $filtered_name_rels[] = $name_rel;
1503
        }
1504
      }
1505
    }
1506
    $name_relations = $filtered_name_rels;
1507

    
1508
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1509

    
1510
    // compose
1511
    foreach ($name_relations as $name_rel) {
1512

    
1513
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1514

    
1515
      $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1516
      $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1517

    
1518
      $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1519
      $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1520
      $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup . ' ';
1521
      $relationship_markup = $symbol_markup . $relationship_markup;
1522
      if ($relationship_markup) {
1523
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1524
          null,
1525
          $item_prefix,
1526
          $item_suffix);
1527
      }
1528
    }
1529

    
1530
    // name relationships to be displayed as non nec
1531
    if (count($non_nec_name_rels) > 0) {
1532
      $non_nec_markup = '';
1533
      foreach ($non_nec_name_rels as $name_rel) {
1534
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1535
        $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1536
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1537
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1538
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1539
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1540
        $non_nec_markup .= $symbol_markup . $relationship_markup;
1541
      }
1542
      if ($non_nec_markup) {
1543
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1544
          null,
1545
          $item_prefix,
1546
          $item_suffix);
1547
      }
1548
    }
1549

    
1550
    // orthographic variants
1551
    if (count($orthographic_variants) > 0) {
1552
      foreach ($orthographic_variants as $name_rel) {
1553

    
1554
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1555
        $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1556
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, TRUE);
1557
        $nomref_footnote_key_markup = nomenclatural_reference_footnote_key_markup($name_rel->toName);
1558
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1559
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1560
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1561
        $relationship_markup = $symbol_markup . $relationship_markup . $nomref_footnote_key_markup;
1562
      }
1563
      if (isset($relationship_markup) && $relationship_markup) {
1564
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1565
          null,
1566
          $item_prefix,
1567
          $item_suffix);
1568
      }
1569
    }
1570
  }
1571
  return $render_array;
1572
}
1573

    
1574
/**
1575
 * @param $name_rel
1576
 * @return string
1577
 */
1578
function name_relationship_footnote_markup($name_rel)
1579
{
1580
  $footnote_markup = '';
1581
  $footnote_key_markup = '';
1582
  if (isset($name_rel->ruleConsidered) && $name_rel->ruleConsidered) {
1583
    $footnote_markup = '<span class="rule_considered">' . $name_rel->ruleConsidered . '</span> ';
1584
  }
1585
  if (isset($name_rel->citation)) {
1586
    $footnote_markup .= '<span class="reference">' . $name_rel->citation->titleCache . '</span>';
1587
  }
1588
  if (isset($name_rel->citationMicroReference) && $name_rel->citationMicroReference) {
1589
    $footnote_markup .= (isset($name_rel->citation) ? ':' : '') . ' <span class="reference_detail">' . $name_rel->citationMicroReference . '</span>';
1590
  }
1591
  if ($footnote_markup) {
1592
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1593
    $footnote_key_markup = render_footnote_key($fnkey,',',TRUE);
1594
  }
1595
  return $footnote_key_markup;
1596
}
1597

    
1598
/**
1599
 * @param $nom_status
1600
 * @return string
1601
 */
1602
function nomenclatural_status_footnote_markup($nom_status)
1603
{
1604
  // NomenclaturalStatus is a subclass of ReferencedEntityBase
1605
  // and has the same structure as TaxonNameRelationship
1606
  return name_relationship_footnote_markup($nom_status);
1607
}
1608

    
1609
/**
1610
 * @param $name
1611
 * @return string
1612
 */
1613
function nomenclatural_reference_footnote_key_markup($name)
1614
{
1615
  $footnote_markup = '';
1616
  $footnote_key_markup = '';
1617
  if (isset($name->nomenclaturalReference) && $name->nomenclaturalReference) {
1618
    $footnote_markup .= '<span class="reference">' . $name->nomenclaturalReference->titleCache . '</span>';
1619
  }
1620
  if (isset($name->nomenclaturalMicroReference)) {
1621
    $footnote_markup .= ($footnote_key_markup ? ':' : '') . '<span class="reference_detail">' . $name->nomenclaturalMicroReference . '</span>';
1622
  }
1623
  if ($footnote_markup) {
1624
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1625
    $footnote_key_markup = render_footnote_key($fnkey, ',',TRUE);
1626
  }
1627
  return $footnote_key_markup;
1628
}
1629

    
1630

    
1631
/**
1632
 * @param $taxon
1633
 * @return array
1634
 */
1635
function cdm_name_relationships_for_taxon($taxon)
1636
{
1637
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1638
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1639
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1640
  return $name_relations;
1641
}
1642

    
1643

    
1644
/**
1645
 * Recursively searches the array for the $key and sets the given value.
1646
 *
1647
 * @param mixed $key
1648
 *   Key to search for.
1649
 * @param mixed $value
1650
 *   Value to set.'
1651
 * @param array $array
1652
 *   Array to search in.
1653
 *
1654
 * @return bool
1655
 *   True if the key has been found.
1656
 */
1657
function &array_setr($key, $value, array &$array) {
1658
  $res = NULL;
1659
  foreach ($array as $k => &$v) {
1660
    if ($key == $k) {
1661
      $v = $value;
1662
      return $array;
1663
    }
1664
    elseif (is_array($v)) {
1665
      $innerArray = array_setr($key, $value, $v);
1666
      if ($innerArray) {
1667
        return $array;
1668
      }
1669
    }
1670
  }
1671
  return $res;
1672
}
1673

    
1674
/**
1675
 * @todo Please document this function.
1676
 * @see http://drupal.org/node/1354
1677
 */
1678
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1679
  $res = NULL;
1680
  $precedingElement = NULL;
1681
  foreach ($renderTemplate as &$part) {
1682
    foreach ($part as $key => &$element) {
1683
      if ($key == $contentElementKey) {
1684
        return $precedingElement;
1685
      }
1686
      $precedingElement = $element;
1687
    }
1688
  }
1689
  return $res;
1690
}
1691

    
1692
/**
1693
 * @todo Please document this function.
1694
 * @see http://drupal.org/node/1354
1695
 */
1696
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1697
  $res = NULL;
1698
  $precedingKey = NULL;
1699
  foreach ($renderTemplate as &$part) {
1700
    if (is_array($part)) {
1701
      foreach ($part as $key => &$element) {
1702
        if ($key == $contentElementKey) {
1703
          return $precedingKey;
1704
        }
1705
        if (!str_beginsWith($key, '#')) {
1706
          $precedingKey = $key;
1707
        }
1708
      }
1709
    }
1710
  }
1711
  return $res;
1712
}
1713

    
1714
function nameTypeToDTYPE($dtype){
1715
  static $nameTypeLabelMap = array(
1716
    "ICNB" => "BacterialName",
1717
    "ICNAFP" => "BotanicalName",
1718
    "ICNCP" => "CultivarPlantName",
1719
    "ICZN" => "ZoologicalName",
1720
    "ICVCN" => "ViralName",
1721
    "Any taxon name" => "TaxonName",
1722
    "NonViral" => "TaxonName",
1723
    "Fungus" => "BotanicalName",
1724
    "Plant" => "BotanicalName",
1725
    "Algae" => "BotanicalName",
1726
  );
1727
  return $nameTypeLabelMap[$dtype];
1728

    
1729
}
1730

    
1731

    
1732
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1733
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1734
}
1735

    
1736
/**
1737
 * Provides an array with the different registration types covered by the passed registration.
1738
 *
1739
 * The labels in the returned array are translatable.
1740
 *
1741
 * See also https://dev.e-taxonomy.eu/redmine/issues/8016
1742
 *
1743
 * @param $registration_dto
1744
 * @return array
1745
 *    An array of the labels describing the different registration types covered by the passed registration.
1746
 */
1747
function registration_types($registration_dto){
1748
  $reg_type_labels = array();
1749
  if(isset($registration_dto->nameRef)){
1750
    $reg_type_labels["name"] = t("new name");
1751
    $reg_type_labels["taxon"] = t("new taxon");
1752
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1753
    $is_new_combination = true;
1754
    foreach($name_relations as $name_rel){
1755
      if(isset($name_rel->type->uuid)){
1756
        $name_is_from_name = $registration_dto->nameRef->uuid == $name_rel->fromName->uuid;
1757
        switch($name_rel->type->uuid) {
1758
          case UUID_NAMERELATIONSHIPTYPE_BASIONYM:
1759
            if(!$name_is_from_name){
1760
              $reg_type_labels["basionym"] = t("new combination");
1761
              $is_new_combination = true;
1762
            }
1763
            break;
1764
          case UUID_NAMERELATIONSHIPTYPE_REPLACED_SYNONYM:
1765
            if(!$name_is_from_name) {
1766
              $is_new_combination = true;
1767
            }
1768
            break;
1769
          case UUID_NAMERELATIONSHIPTYPE_VALIDATED_BY_NAME:
1770
            if(!$name_is_from_name) {
1771
              $reg_type_labels["validation"] = t("validation");
1772
            }
1773
            break;
1774
          case UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT:
1775
            if(!$name_is_from_name) {
1776
              $reg_type_labels["orth_var"] = t("orthographical correction");
1777
            }break;
1778
          default:
1779
            // NOTHING
1780
        }
1781
      }
1782
    }
1783
    if($is_new_combination){
1784
      unset($reg_type_labels["taxon"]);
1785
    }
1786
  }
1787
  if(isset($registration_dto->orderdTypeDesignationWorkingSets)){
1788
    $reg_type_labels[] = t("new nomenclatural type");
1789
  }
1790
  return $reg_type_labels;
1791
}
1792

    
1793
/**
1794
 * Collects and deduplicates the type designations associated with the passes synonyms.
1795
 *
1796
 * @param $synonymy_group
1797
 *    An array containing a homotypic or heterotypic group of names.
1798
 * @param $accepted_taxon_name_uuid
1799
 *    The uuid of the accepted taxon name. Optional parameter which is required when composing
1800
 *    the information for the homotypic group. In this case the accepted taxon is not included
1801
 *    in the $synonymy_group and must therefor passed in this second parameter.
1802
 *
1803
 * @return array
1804
 *    The type designations
1805
 */
1806
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null)
1807
{
1808
  if (count($synonymy_group) > 0) {
1809
    $name_uuid = array_pop($synonymy_group)->name->uuid;
1810
  } else {
1811
    $name_uuid = $accepted_taxon_name_uuid;
1812
  }
1813
  if ($name_uuid) {
1814
   $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS_IN_HOMOTYPICAL_GROUP, $name_uuid);
1815
    if ($type_designations) {
1816
      return $type_designations;
1817
    }
1818
  }
1819

    
1820
  return array();
1821
}
1822

    
1823

    
1824
/**
1825
 * Compares two SpecimenTypeDesignations
1826
 *
1827
 * @param object $a
1828
 *   A SpecimenTypeDesignation.
1829
 * @param object $b
1830
 *   SpecimenTypeDesignation.
1831
 */
1832
function compare_specimen_type_designation($a, $b) {
1833

    
1834
  $cmp_by_status = compare_type_designations_by_status($a,$b);
1835
  if($cmp_by_status !== 0){
1836
    return $cmp_by_status;
1837
  }
1838

    
1839
  $aQuantifier = FALSE;
1840
  $bQuantifier = FALSE;
1841
  if ($aQuantifier == $bQuantifier) {
1842
    // Sort alphabetically.
1843
    $a_text =  isset($a->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $a->typeSpecimen->titleCache) : '';
1844
    $b_text =  isset($b->typeSpecimen->titleCache) ? preg_replace('/[\[\]\"]/', '', $b->typeSpecimen->titleCache) : '';
1845
    return strcasecmp($a_text, $b_text);
1846
  }
1847
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1848
}
1849

    
1850
/**
1851
 * Compares the status of two TypeDesignations
1852
 *
1853
 * @param object $a
1854
 *   A TypeDesignation
1855
 * @param object $b
1856
 *   TypeDesignation
1857
 */
1858
function compare_type_designations_by_status($a, $b) {
1859
  $status_a = isset($a->typeStatus) ? $a->typeStatus : null;
1860
  $status_b = isset($b->typeStatus) ? $b->typeStatus : null;
1861
  return compare_type_designation_status($status_a, $status_b);
1862
}
1863

    
1864
/**
1865
 * Compares two TypeDesignationStatusBase
1866
 *
1867
 * @param object $a
1868
 *   A TypeDesignationStatusBase.
1869
 * @param object $b
1870
 *   TypeDesignationStatusBase.
1871
 */
1872
function compare_type_designation_status($a, $b) {
1873
  $type_status_order = type_status_order();
1874
  $aQuantifier = FALSE;
1875
  $bQuantifier = FALSE;
1876
  if (isset($a->label) && isset($b->label)) {
1877
    $aQuantifier = array_search($a->label, $type_status_order);
1878
    $bQuantifier = array_search($b->label, $type_status_order);
1879
  }
1880
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1881
}
1882

    
1883
/**
1884
 * Compares the two TextualTypeDesignations
1885
 *
1886
 * @param object $a
1887
 *   A TextualTypeDesignations.
1888
 * @param object $b
1889
 *   TextualTypeDesignations.
1890
 */
1891
function compare_textual_type_designation($a, $b) {
1892

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

    
1898
  $aQuantifier = FALSE;
1899
  $bQuantifier = FALSE;
1900
  if ($aQuantifier == $bQuantifier) {
1901
    // Sort alphabetically.
1902
    $a_text =  isset($a->text_L10n->text) ? $a->text_L10n->text : '';
1903
    $b_text =  isset($b->text_L10n->text) ? $b->text_L10n->text : '';
1904
    return strcasecmp($a_text, $b_text);
1905
  }
1906
  return ($aQuantifier < $bQuantifier) ? -1 : (($aQuantifier > $bQuantifier) ? 1 : 0);
1907
}
1908

    
1909

    
1910
/**
1911
 * Compares two SpecimenTypeDesignation status labels
1912
 *
1913
 * @param string $a
1914
 *   A TypeDesignationStatus label.
1915
 * @param string $b
1916
 *   A TypeDesignationStatus label.
1917
 */
1918
function compare_type_designation_status_labels($a, $b) {
1919

    
1920
  $type_status_order = type_status_order();
1921

    
1922
  $aQuantifier = FALSE;
1923
  $bQuantifier = FALSE;
1924
  if (isset($a) && isset($b)) {
1925
    $aQuantifier = array_search($a, $type_status_order);
1926
    $bQuantifier = array_search($b, $type_status_order);
1927
  }
1928
  return ($aQuantifier < $bQuantifier) ? -1 : 1;
1929
}
1930

    
1931
/**
1932
 * @return array
1933
 */
1934
function type_status_order()
1935
{
1936
  /*
1937
    This is the desired sort order as of now: Holotype Isotype Lectotype
1938
    Isolectotype Syntype.
1939
    TODO Basically, what we are trying to do is, we define
1940
    an ordered array of TypeDesignation-states and use the index of this array
1941
    for comparison. This array has to be filled with the cdm- TypeDesignation
1942
    states and the order should be parameterisable inside the dataportal.
1943
    */
1944
  // Make that static for now.
1945
  $type_status_order = array(
1946
    'Epitype',
1947
    'Holotype',
1948
    'Isotype',
1949
    'Lectotype',
1950
    'Isolectotype',
1951
    'Syntype',
1952
    'Paratype'
1953
  );
1954
  return $type_status_order;
1955
}
1956

    
1957
/**
1958
 * Return HTML for the lectotype citation with the correct layout.
1959
 *
1960
 * This function prints the lectotype citation with the correct layout.
1961
 * Lectotypes are renderized in the synonymy tab of a taxon if they exist.
1962
 *
1963
 * @param mixed $typeDesignation
1964
 *   Object containing the lectotype citation to print.
1965
 *
1966
 * @return string
1967
 *   Valid html string.
1968
 */
1969
function type_designation_citation_layout($typeDesignation, $footnote_separator = ',') {
1970
  $res = '';
1971
  $citation = $typeDesignation->citation;
1972
  $pages = $typeDesignation->citationMicroReference;
1973
  if(isset($typeDesignation->typeStatus->uuid) && isset($typeDesignation->typeStatus->representation_L10n)) {
1974
    if ( $typeDesignation->typeStatus->uuid == UUID_NTD_ORIGINAL_DESIGNATION || $typeDesignation->typeStatus->uuid == UUID_NTD_MONOTYPY) {
1975
      $res = ' (' . $typeDesignation->typeStatus->representation_L10n . ')';
1976
      return $res;
1977
    }
1978
  }
1979

    
1980
  if ($citation) {
1981
    // $type = $typeDesignation_citation->type;
1982
    $year = isset($citation->datePublished->start) ? substr($citation->datePublished->start, 0, 4) : '';
1983
    $author = isset($citation->authorship->titleCache) ? $citation->authorship->titleCache : '';
1984
    $res .= ' (designated by ';
1985
    $res .= $author;
1986
    $res .= ($year ? ' ' . $year : '');
1987
    $res .= ($pages ? ': ' . $pages : '');
1988
    // $res .= ')';
1989

    
1990
    // footnotes should be rendered in the parent element so we
1991
    // are relying on the FootnoteListKey set there
1992
    $fkey_typeDesignation = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $typeDesignation->citation->titleCache);
1993
    $res .= render_footnote_key($fkey_typeDesignation, $footnote_separator,TRUE) . ')';
1994
  }
1995
  return $res;
1996
}
1997

    
1998
/**
1999
 * 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"
2000
 *
2001
 * @param $type_designation
2002
 * @return string
2003
 */
2004
function type_designation_status_label_markup($type_designation)
2005
{
2006
  return '<span class="type-status">'
2007
    . ((isset($type_designation->typeStatus->representation_L10n)) ? ucfirst($type_designation->typeStatus->representation_L10n) : t('Type')) . '</span>'
2008
    ;
2009
}
(7-7/14)