Project

General

Profile

Download (59.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 ot 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 $nameLink
257
 *    URI to the taxon, @see path_to_taxon(), must be processed by url() before passing to this method
258
 * @param $refenceLink
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, $nameLink = NULL, $refenceLink = 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
    $taxonName = $taxon_name_or_taxon_base->name;
283
    $is_doubtful = $taxon_name_or_taxon_base->doubtful;
284
    // use the TaxonBase.tagged_title so we have the secRef
285
    $tagged_title = $taxon_name_or_taxon_base->taggedTitle;
286
  } else {
287
    // assuming this is a TaxonName
288
    $taxonName = $taxon_name_or_taxon_base;
289
    if(isset($taxonName->taggedFullTitle)){
290
      $tagged_title = $taxon_name_or_taxon_base->taggedFullTitle;
291
    } else {
292
      $tagged_title = $taxon_name_or_taxon_base->taggedName;
293
    }
294
  }
295

    
296

    
297
  $renderTemplate = get_nameRenderTemplate(RenderHints::getRenderPath(), $nameLink, $refenceLink);
298
  $partDefinition = get_partDefinition($taxonName->nameType);
299

    
300
  // Apply definitions to template.
301
  foreach ($renderTemplate as $part => $uri) {
302

    
303
    if (isset($partDefinition[$part])) {
304
      $renderTemplate[$part] = $partDefinition[$part];
305
    }
306
    if (is_array($uri) && isset($uri['#uri'])) {
307
      $renderTemplate[$part]['#uri'] = $uri['#uri'];
308
    }
309
  }
310

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

    
317
  normalize_tagged_text($tagged_title);
318

    
319
  $firstEntryIsValidNamePart =
320
    isset($tagged_title)
321
    && is_array($tagged_title)
322
    && isset($tagged_title[0]->text)
323
    && is_string($tagged_title[0]->text)
324
    && $tagged_title[0]->text != ''
325
    && isset($tagged_title[0]->type)
326
    && $tagged_title[0]->type == 'name';
327
  $lastAuthorElementString = FALSE;
328

    
329
  $name_encasement = $is_invalid ? '"' : '';
330
  $doubtful_marker = $is_doubtful ? '?&#8239;' : ''; // 	&#8239; =  NARROW NO-BREAK SPACE
331
  $doubtful_marker_markup = '';
332

    
333
  if($doubtful_marker){
334
    $doubtful_marker_markup = '<span class="doubtful">' . $doubtful_marker . '</span>';
335
  }
336

    
337
  // split off all appendedPhrase item  from the end of the array (usually there only should  be one)
338
  while($tagged_title[count($tagged_title)-1]->type == "appendedPhrase"){
339
    $appended_phrase_tagged_text[] = array_pop($tagged_title);
340
  }
341

    
342
  // Got to use second entry as first one, see ToDo comment below ...
343
  if ($firstEntryIsValidNamePart) {
344

    
345
    $taggedName = $tagged_title;
346
    $hasNamePart_with_Authors = isset($renderTemplate['namePart']) && isset($renderTemplate['namePart']['authors']);
347
    $hasNameAuthorPart_with_Authors = isset($renderTemplate['nameAuthorPart']) && isset($renderTemplate['nameAuthorPart']['authors']);
348

    
349

    
350
    if (!(($hasNamePart_with_Authors) || ($hasNameAuthorPart_with_Authors))) {
351
      // Find author and split off from name.
352
      // TODO expecting to find the author as the last element.
353
      /*
354
      if($taggedName[count($taggedName)- 1]->type == 'authors'){
355
        $authorTeam = $taggedName[count($taggedName)- 1]->text;
356
        unset($taggedName[count($taggedName)- 1]);
357
      }
358
      */
359

    
360
      // Remove all authors.
361
      $taggedNameNew = array();
362
      foreach ($taggedName as $element) {
363
        if ($element->type != 'authors') {
364
          $taggedNameNew[] = $element;
365
        }
366
        else {
367
          $lastAuthorElementString = $element->text;
368
        }
369
      }
370
      $taggedName = $taggedNameNew;
371
      unset($taggedNameNew);
372
    }
373
    $name = '<span class="' . $taxonName->class . '">' . $doubtful_marker_markup . $name_encasement . cdm_tagged_text_to_markup($taggedName, $skiptags) . $name_encasement . '</span>';
374
  }
375
  else {
376
    $name = '<span class="' . $taxonName->class . '_titleCache">' . $doubtful_marker_markup . $name_encasement . $taxonName->titleCache . $name_encasement . '</span>';
377
  }
378

    
379

    
380
  if(isset($appended_phrase_tagged_text[0])){
381
    $name .= ' <span class="appended-phrase">'. cdm_tagged_text_to_markup($appended_phrase_tagged_text) . '</span>';
382
  }
383

    
384
  // Fill name into $renderTemplate.
385
  array_setr('name', $name , $renderTemplate);
386

    
387
  // Fill with authorTeam.
388
  /*
389
  if($authorTeam){
390
    $authorTeamHtml = ' <span class="authorTeam">'.$authorTeam.'</span>';
391
    array_setr('authorTeam', $authorTeamHtml, $renderTemplate);
392
  }
393
  */
394

    
395
  // Fill with reference.
396
  if (isset($renderTemplate['referencePart']) && !$is_type_designation) {
397

    
398
    $registrations = cdm_ws_get(CDM_WS_NAME, array($taxonName->uuid, "registrations"));
399
    $registration_markup = render_registrations($registrations);
400

    
401
    // default separator
402
    $separator = '';
403

    
404
    // [Eckhard]:"Komma nach dem Taxonnamen ist grunsätzlich falsch,
405
    // Komma nach dem Autornamen ist überall dort falsch, wo ein "in" folgt."
406
    if (isset($renderTemplate['referencePart']['reference']) && isset($taxonName->nomenclaturalReference)) {
407
      $microreference = NULL;
408
      if (isset($renderTemplate['referencePart']['microreference'])&& isset($taxonName->nomenclaturalMicroReference)) {
409
        $microreference = $taxonName->nomenclaturalMicroReference;
410
      }
411
      if(count($nomref_tagged_text) == 0){
412
        $citation = cdm_ws_getNomenclaturalReference($taxonName->nomenclaturalReference->uuid, $microreference);
413
        // Find preceding element of the reference.
414
        $precedingKey = get_preceding_contentElementKey('reference', $renderTemplate);
415
        if (str_beginsWith($citation, ", in")) {
416
          $citation = substr($citation, 2);
417
          $separator = ' ';
418
        }
419
        elseif (!str_beginsWith($citation, "in") && $precedingKey == 'authors') {
420
          $separator = ', ';
421
        } else {
422
          $separator = ' ';
423
        }
424
        $referenceArray['#separator'] = $separator;
425
        $referenceArray['#html'] = '<span class="reference">' . $citation . '</span>' . $registration_markup;
426
      } else {
427
        // this ist the case for taxon names
428
        $referenceArray['#html'] = cdm_tagged_text_to_markup($nomref_tagged_text);
429
      }
430

    
431

    
432
      array_setr('reference', $referenceArray, $renderTemplate);
433
    }
434

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

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

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

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

    
493
  // Fill with protologues etc...
494
  $descriptionHtml = '';
495
  if (array_setr('description', TRUE, $renderTemplate)) {
496
    $descriptions = cdm_ws_get(CDM_WS_PORTAL_NAME_DESCRIPTIONS, $taxonName->uuid);
497
    foreach ($descriptions as $description) {
498
      if (!empty($description)) {
499
        foreach ($description->elements as $description_element) {
500
          $second_citation = '';
501
          if (isset($description_element->multilanguageText_L10n) && $description_element->multilanguageText_L10n->text) {
502
            $second_citation = '[& ' . $description_element->multilanguageText_L10n->text . '].';
503
          }
504
          $descriptionHtml .= $second_citation;
505
          $descriptionHtml .= cdm_description_element_media(
506
              $description_element,
507
              array(
508
                'application/pdf',
509
                'image/png',
510
                'image/jpeg',
511
                'image/gif',
512
                'text/html',
513
              )
514
          );
515

    
516
        }
517
      }
518
    }
519
    array_setr('description', $descriptionHtml, $renderTemplate);
520
  }
521

    
522
  // Render.
523
  $out = '';
524
  if(isset($_REQUEST['RENDER_PATH'])){
525
    // developer option to show the render path with each taxon name
526
    $out .= '<span class="render-path">' . RenderHints::getRenderPath() . '</span>';
527
  }
528
  $out .= '<span class="' . html_class_attribute_ref($taxon_name_or_taxon_base)
529
    . '" data-cdm-ref="/name/' . $taxonName->uuid . '" data-cdm-render-path="' . RenderHints::getRenderPath() .'">';
530

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

    
559
    }
560
    else {
561
      $out .= $separator . $partHtml;
562
    }
563
  }
564
  $out .= '</span>';
565
  if ($show_annotations) {
566
    // $out .= theme('cdm_annotations_as_footnotekeys', $taxonName);
567
  }
568
  return $out;
569
}
570

    
571

    
572

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

    
599
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
600
    return $render_array;
601
  }
602

    
603
  $render_array['sub_headline'] = markup_to_render_array(join(", ", registration_types($registration_dto)),-10, '<h3 class="regsitration_type">' . t('Event: '), '</h3>' );
604

    
605
  // name and typedesignation in detail
606
  if($registration_dto->nameRef){
607
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
608
    cdm_load_tagged_full_title($name);
609
    $render_array['published_name'] = markup_to_render_array('<p class="published-name">' . render_taxon_or_name($name, url(path_to_name($name->uuid))) . '</p>', 0);
610
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
611
    $render_array['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
612
    $render_array['name_relations']['#weight'] = 10;
613
  } else {
614
    // in this case the registration must have a
615
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
616
    $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);
617
  }
618
  if(is_object($registration_dto->orderdTypeDesignationWorkingSets)) {
619
    $field_unit_uuids = array();
620
    $specimen_type_designation_refs = array();
621
    $name_type_designation_refs = array();
622
    foreach ((array)$registration_dto->orderdTypeDesignationWorkingSets as $workingset_ref => $obj) {
623
      $tokens = explode("#", $workingset_ref);
624
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
625

    
626
      if ($tokens[0] == 'NameTypeDesignation') {
627
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
628
          if(!isset($name_type_designation_refs[$type_status])){
629
            $name_type_designation_refs[$type_status]  = $entity_reference_list;
630
          } else {
631
            array_push($name_type_designation_refs[$type_status] ,$entity_reference_list);
632
          }
633
        }
634
      } else if ($tokens[0] == 'FieldUnit'){
635
        $field_unit_uuids[] = $tokens[1];
636
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
637
          if(!isset($specimen_type_designation_refs[$type_status])){
638
            $specimen_type_designation_refs[$type_status] =  $entity_reference_list;
639
          } else {
640
            array_push($specimen_type_designation_refs[$type_status], $entity_reference_list);
641
          }
642
        }
643
      } else {
644
        drupal_set_message("Unimplemented type: " . $tokens[0], 'error');
645
      }
646
    }
647
    // type designations wich are in this nomenclatural act.
648
    if (count($name_type_designation_refs) > 0) {
649
      $render_array['name_type_designations'] = compose_name_type_designations($name_type_designation_refs);
650
      $render_array['name_type_designations']['#prefix'] = '<p class="name_type_designations">';
651
      $render_array['name_type_designations']['#suffix'] = '</p>';
652
      $render_array['name_type_designations']['#weight'] = 20;
653
    }
654
    if (count($field_unit_uuids) > 0) {
655
      $specimen_type_designations_array = compose_specimen_type_designations($specimen_type_designation_refs);
656
      $render_array['specimen_type_designations'] = $specimen_type_designations_array['type_designations'];
657
      $render_array['map'] = $specimen_type_designations_array['map'];
658
    }
659
  }
660

    
661
  // citation
662
  if ($with_citation) {
663
    $render_array['citation'] = markup_to_render_array(
664
      "<p class=\"citation " . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
665
      . $registration_dto->bibliographicInRefCitationString
666
      . l(custom_icon_font_markup('icon-interal-link-alt-solid', array('class' => array('superscript'))), path_to_reference($registration_dto->citationUuid), array('html' => true))
667
      . "</p>",
668
      50);
669
  }
670

    
671
  // registration date and office
672
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto);
673
  if($registration_date_insitute_markup){
674
    $render_array['registration_date_and_institute'] = markup_to_render_array(
675
      $registration_date_insitute_markup . '</p>',
676
      100);
677
  }
678

    
679
  return $render_array;
680
}
681

    
682

    
683
/**
684
 * Composes a compact representation for a registrationDTO object
685
 *
686
 * Registrations which are not yet published are suppressed.
687
 *
688
 * @param $registration_dto
689
 * @param $style string
690
 *   The style of how to compose the 'identifier' and 'registration_date_and_institute' part with the summary
691
 *   - 'citation': Similar to the arrearance of nomenclatural acts in print media
692
 *   - 'list-item' : style suitable for result lists etc
693
 *
694
 * @return array
695
 *    A drupal render array with the elements:
696
 *    - 'registration-metadata' when $style == 'list-item'
697
 *    - 'summary'
698
 * @ingroup compose
699
 */
700
function compose_registration_dto_compact($registration_dto, $style = 'citation', $tag_enclosing_summary = 'p')
701
{
702
  $render_array = array();
703
  $media_link_map = array();
704

    
705
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
706
    return $render_array;
707
  }
708

    
709
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto, 'span');
710
  $itentifier_markup = l($registration_dto->identifier, path_to_registration($registration_dto->identifier), array('attributes' => array('class' => array('identifier'))));
711

    
712
  $tagged_text_options = array();
713
  if(isset($registration_dto->nameRef)){
714
    $tagged_text_options[] = array(
715
      'filter-type' => 'name',
716
      'prefix' => '<span class="registered_name">',
717
      'suffix' => '</span>',
718
    );
719
  } else {
720
    $tagged_text_options[] = array(
721
      'filter-type' => 'name',
722
      'prefix' => '<span class="referenced_typified_name">',
723
      'suffix' => '</span>',
724
    );
725
  }
726
  cdm_tagged_text_add_options($registration_dto->summaryTaggedText, $tagged_text_options);
727
  $taggged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
728
  foreach ($taggged_text_expanded  as $tagged_text){
729
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
730
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
731
      if(isset($mediaDTOs[0]->uri)){
732
        $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
733
        $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
734
        $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
735
      }
736
    }
737
  }
738
  $registation_markup = cdm_tagged_text_to_markup($taggged_text_expanded);
739
  foreach($media_link_map as $media_url_key => $link){
740
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
741
  }
742
  if($style == 'citation') {
743
    $registation_markup = $registation_markup . ' ' . $itentifier_markup . ' ' . $registration_date_insitute_markup;
744
  } else {
745
    $render_array['registration-metadata'] = markup_to_render_array('<div class="registration-metadata">' . $itentifier_markup . ' ' . $registration_date_insitute_markup. "</div>", -10);
746
  }
747
  $render_array['summary'] = markup_to_render_array('<' . $tag_enclosing_summary . ' class="registration-summary">' . $registation_markup . '</' . $tag_enclosing_summary . '>', 0);
748

    
749
  return $render_array;
750
}
751

    
752

    
753
/**
754
 * Renders the registrationDate and institutionTitleCache of the $registration_dto as markup.
755
 *
756
 * @param $registration_dto
757
 * @return string
758
 *    The markup or an empty string
759
 */
760
function render_registration_date_and_institute($registration_dto, $enclosing_tag = 'p') {
761
  $registration_date_institute_markup = '';
762
  if ($registration_dto->registrationDate) {
763
    $date_string = format_datetime($registration_dto->registrationDate);
764
    if (isset($registration_dto->institutionTitleCache) && $registration_dto->institutionTitleCache) {
765
      $registration_date_institute_markup =
766
        t("Registration on @date in @institution", array(
767
          '@date' => $date_string,
768
          '@institution' => $registration_dto->institutionTitleCache,
769
        ));
770
    } else {
771
      $registration_date_institute_markup =
772
        t("Registration on @date", array(
773
          '@date' => $date_string
774
        ));
775
    }
776
    $registration_date_institute_markup = '<' .$enclosing_tag . ' class="registration-date-and-institute">'. $registration_date_institute_markup . '</' .$enclosing_tag . '>';
777
  }
778
  return $registration_date_institute_markup;
779
}
780

    
781

    
782
/**
783
 * @param $registrations
784
 * @return string
785
 */
786
function render_registrations($registrations)
787
{
788
  $registration_markup = '';
789
  $registration_markup_array = array();
790
  if ($registrations) {
791
    foreach ($registrations as $reg) {
792
      $registration_markup_array[] = render_registration($reg);
793
    }
794
    $registration_markup = " Registration" . (count($registration_markup_array) > 1 ? 's: ' : ': ')
795
      . join(', ', $registration_markup_array);
796
  }
797
  return $registration_markup;
798
}
799

    
800

    
801
/**
802
 * Renders a registration
803
 *
804
 * TODO replace by compose_registration_dto_compact
805
 * @param $registration
806
 */
807
function render_registration($registration){
808
  $markup = '';
809

    
810
  if(isset($registration->identifier) && $registration->status == 'PUBLISHED'){
811
    $office_class_attribute = '';
812
    if(isset($registration->institution->titleCache)){
813
      $office_class_attribute = registration_intitute_class_attribute($registration);
814
    }
815
    $markup = "<span class=\"registration $office_class_attribute\">" . l($registration->identifier, path_to_registration($registration->identifier)) . ', '
816
      .  preg_replace('/^([^T]*)(.*)$/', '${1}', $registration->registrationDate)
817
      . '</span>';
818
  }
819
  return $markup;
820
}
821

    
822
/**
823
 * @param $registration
824
 * @return string
825
 */
826
function registration_intitute_class_attribute($registration_dto)
827
{
828
  if(isset($registration_dto->institutionTitleCache)){
829
    $institutionTitleCache = $registration_dto->institutionTitleCache;
830
  } else {
831
    // fall back option to also support cdm entities
832
    $institutionTitleCache = @$registration_dto->institution->titleCache;
833
  }
834
  return $institutionTitleCache ? 'registration-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $institutionTitleCache)) : '';
835
}
836

    
837

    
838
/**
839
 * Composes the textual representation for the type designation of taxon name identified by the uuid in with a map for the location data.
840
 *
841
 * @param $taxon_name_uuid
842
 * @return array
843
 *    A drupal render array wtit the following elements:
844
 *    - 'type_designations'
845
 *    - 'map'
846
 *
847
 * @ingroup compose
848
 */
849
function compose_type_designations($taxon_name_uuid)
850
{
851
  $render_array = array(
852
    'type_designations' => array(),
853
    'map' => array(),
854
    );
855
  $type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name_uuid);
856
  if ($type_designations) {
857
    $render_array['type_designations'] = markup_to_render_array(
858
      theme('cdm_typedesignations', array('typeDesignations' => $type_designations, 'enclosing_tag' => 'div', 'element_tag' => 'div'))
859
    );
860

    
861
    $render_array['map'] = compose_type_designations_map($type_designations);
862
  }
863
  return $render_array;
864
}
865

    
866
/**
867
 * Composes a map with the location points of the passed $type_designations.
868
 *
869
 * @param $type_designations
870
 *
871
 * @return array
872
 *     A drupal render array or an empty array in case there are no point to show.
873
 *
874
 * @ingroup compose
875
 */
876
function compose_type_designations_map($type_designations)
877
{
878
  $points = array();
879
  $map_render_array = array();
880
  foreach ($type_designations as $td) {
881
    if ($td->class == "SpecimenTypeDesignation") {
882
      $derived_unit_facade = cdm_ws_get(CDM_WS_PORTAL_DERIVEDUNIT_FACADE, array($td->typeSpecimen->uuid));
883
      if (isset($derived_unit_facade->exactLocation)) {
884
        $points[] = $derived_unit_facade->exactLocation->latitude . ',' . $derived_unit_facade->exactLocation->longitude;
885
      }
886
    }
887
  }
888

    
889
  if (count($points) > 0) {
890
    // os=1:c/ff0000/10/noLabel&od=1:52.52079,13.57781|-43.46333333333333,172.60355&legend=0
891
    $occurrence_query = 'os=1:c/ff0000/10/noLabel&od=1:' . join('|', $points) . '&legend=0';
892
    // $occurrence_query = 'os=1:c/ff0000/10/noLabel&od=1:52.52079,13.57781|-43.46333333333333,172.60355&legend=0';
893
    $legend_format_query = null;
894
    $distribution_query = NULL;
895
    $map_render_array = compose_map('specimens', $occurrence_query, $distribution_query, $legend_format_query, array());
896
  }
897
  return $map_render_array;
898
}
899

    
900
/**
901
 * Composes the TypedEntityReference to name type designations passed as associatve array.
902
 *
903
 * @param $$type_entity_refs array
904
 *   an associative array of name type type => TypedEntityReference for name type designations as
905
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
906
 *
907
 * @ingroup compose
908
 */
909
function compose_name_type_designations($type_entity_refs){
910
  $render_array = array();
911
  $preferredStableUri = '';
912
  foreach($type_entity_refs as $type_status => $name_types){
913
    foreach ($name_types as $name_type){
914
      $type_designation = cdm_ws_get(CDM_TYPEDESIGNATION, array($name_type->uuid, 'preferredUri'));
915
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
916
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
917
      }
918
      $render_array[] = markup_to_render_array('<div class="name_type_designation ' . html_class_attribute_ref($name_type)  . '"><span class="type_status">'. ucfirst($type_status) . "</span>: "
919
        . $name_type->label
920
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
921
        . '</div>');
922
      }
923
  }
924
  return $render_array;
925
}
926

    
927
/**
928
 * Composes the specimen type designations with map from the the $type_entity_refs
929
 *
930
 * @param $type_entity_refs array
931
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
932
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
933
 *
934
 * @return array
935
 *    A drupal render array wtit the following elements:
936
 *    - 'type_designations'
937
 *    - 'map'
938
 *
939
 * @ingroup compose
940
 *
941
 * @ingroup compose
942
 */
943
function compose_specimen_type_designations($type_entity_refs){
944

    
945
  $render_array = array();
946

    
947
  $type_designation_list = array();
948
  foreach($type_entity_refs as $type_status => $specimen_types){
949
    foreach($specimen_types as $specimen_type){
950

    
951
      $type_designation = cdm_ws_get(CDM_PORTAL_TYPEDESIGNATION, array($specimen_type->uuid));
952
      $type_designation_list[] = $type_designation; // collect for the map
953

    
954
      $preferredStableUri = '';
955
      $citation_markup = '';
956
      $media = '';
957

    
958
      // preferredStableUri
959
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
960
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
961
      }
962

    
963
      $mediaSpecimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($type_designation->typeSpecimen->uuid, 'mediaSpecimen'));
964
      $derivedUnitFacadeInstance = cdm_ws_get(CDM_WS_PORTAL_DERIVEDUNIT_FACADE, $type_designation->typeSpecimen->uuid);
965
      if($mediaSpecimen){
966
        // compose output
967
        // mediaURI
968
        if(isset($mediaSpecimen->representations[0])) {
969
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
970
          $captionElements = array(
971
            '#uri' => t('open media'),
972
            'elements' => array('-none-'),
973
            'sources_as_content' => true
974
          );
975
          $media = compose_cdm_media_gallerie(array(
976
            'mediaList' => array($mediaSpecimen),
977
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $specimen_type->uuid,
978
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
979
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
980
            'captionElements' => $captionElements,
981
          ));
982
        }
983
        // citation and detail
984
        $annotations_and_sources = handle_annotations_and_sources(
985
            $mediaSpecimen,
986
            array(
987
                'sources_as_content' => true,
988
                'link_to_name_used_in_source' => false,
989
                'link_to_reference' => true,
990
                'add_footnote_keys' => false,
991
                'bibliography_aware' => false),
992
            '',
993
            null
994
        );
995
        if(is_array( $annotations_and_sources['source_references'])){
996
          $citation_markup = join(', ', $annotations_and_sources['source_references']);
997
        }
998
      }
999

    
1000
      $render_array['type_designations'][] = markup_to_render_array('<div class="specimen_type_designation ' . html_class_attribute_ref($specimen_type)  . '">
1001
          <span class="type_status">' . ucfirst($type_status) . "</span>: "
1002
        . $derivedUnitFacadeInstance->titleCache
1003
        . ($citation_markup ? ' '. $citation_markup : '')
1004
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
1005
        . $media
1006
        . '</div>');
1007
    }
1008
  }
1009
  if(count($type_designation_list) > 0 ){
1010
    $render_array['map'] = compose_type_designations_map($type_designation_list);
1011
  } else {
1012
    $render_array['map'] = array();
1013
  }
1014
  return $render_array;
1015
}
1016

    
1017
/**
1018
 * @param $name_rel
1019
 * @param $current_name_uuid
1020
 * @param $current_taxon_uuid
1021
 * @param $suppress_if_current_name_is_source // FIXME UNUSED !!!!
1022
 * @param $show_name_cache_only
1023
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
1024
 * @return null|string
1025
 */
1026
function name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, $show_name_cache_only = false){
1027

    
1028
  $relationship_markup = null;
1029

    
1030
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
1031

    
1032
  if($current_name_is_toName){
1033
    $name = $name_rel->fromName;
1034
  } else {
1035
    $name = $name_rel->toName;
1036
  }
1037

    
1038
  cdm_load_tagged_full_title($name);
1039

    
1040
  $highlited_synonym_uuid = isset ($name->taxonBases[0]->uuid) ? $name->taxonBases[0]->uuid : '';
1041
  if(!$show_name_cache_only){
1042
    $relationship_markup = render_taxon_or_name($name,
1043
      url(path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
1044
    );
1045
  } else {
1046
    $relationship_markup = l(
1047
      '<span class="' . html_class_attribute_ref($name) . '"">' . $name->nameCache . '</span>',
1048
      path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
1049
      array('html' => true)
1050
    );
1051
  }
1052

    
1053
  return $relationship_markup;
1054
}
1055

    
1056

    
1057
/**
1058
 * Composes an inline representation of selected name relationships
1059
 *
1060
 * The output of this function will be usually appended to taxon name representations.
1061
 * Only the following types are displayed: LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR, ORTHOGRAPHIC_VARIANT
1062
 *
1063
 * LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR are displayed as
1064
 * non {titleCache} nec {titleCache} nec {titleCache} whereas the related names
1065
 * are ordered alphabetically.
1066
 *
1067
 * ORTHOGRAPHIC_VARIANT is displayed as 'ort. var. {nameCache}'
1068
 *
1069
 * Related issues:
1070
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1071
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1072
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1073
 *   - https://dev.e-taxonomy.eu/redmine/issues/2001 "[Cichorieae Portal] Name Relationship -> blocking name are not shown"
1074
 *
1075
 * @param $name_relations
1076
 *    The list of CDM NameRelationsips
1077
 * @param $current_name_uuid
1078
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1079
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1080
 * @param $suppress_if_current_name_is_source
1081
 *    The display of the relation will be
1082
 *    suppressed is the current name is on the source of the relation edge.
1083
 *    That is if it is on the from side of the relation. Except for 'blocking name for' which is
1084
 *    an inverse relation. For this relation type the toName is taken in to account.
1085
 * @param $current_taxon_uuid
1086
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1087
 * @return array
1088
 *    A drupal render array
1089
 *
1090
 * @ingroup Compose
1091
 */
1092
function compose_name_relationships_inline($name_relations, $current_name_uuid, $current_taxon_uuid, $suppress_if_current_name_is_source = true) {
1093

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

    
1097
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
1098
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1099
  foreach ($selected_name_rel_uuids as $uuid){
1100
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1101
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
1102
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
1103
    }
1104
  }
1105

    
1106
  $list_prefix = '<span class="name_relationships">[';
1107
  $list_suffix = ']</span>';
1108
  $item_prefix = '<span class="item">';
1109
  $item_suffix = '</span> ';
1110
  $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);
1111

    
1112
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1113
  $items_ctn = count($render_array['list']['items']);
1114
  if($items_ctn){
1115
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1116
  }
1117

    
1118
  RenderHints::popFromRenderStack();
1119
  return $render_array;
1120
}
1121

    
1122
/**
1123
 * Composes an list representation of the name relationships.
1124
 *
1125
 * The output of this function will be usually appended to taxon name representations.
1126
 *
1127
 * Related issues:
1128
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1129
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1130
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1131
 *
1132
 * @param $name_relations
1133
 *    The list of CDM NameRelationsips
1134
 * @param $current_name_uuid
1135
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1136
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1137
 * @param $current_taxon_uuid
1138
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1139
 * @return array
1140
 *    A drupal render array
1141
 *
1142
 * @ingroup Compose
1143
 */
1144
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1145

    
1146
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1147

    
1148
  $key = 'name_relationships';
1149
  RenderHints::pushToRenderStack($key);
1150
  if(!RenderHints::getFootnoteListKey()){
1151
    RenderHints::setFootnoteListKey($key);
1152
  }
1153
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1154

    
1155
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, unserialize(CDM_NAME_RELATIONSHIP_LIST_TYPES_DEFAULT));
1156
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1157
  foreach ($selected_name_rel_uuids as $uuid){
1158
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1159
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1160
  }
1161

    
1162
  $list_prefix = '<div class="relationships_list name_relationships">';
1163
  $list_suffix = '</div>';
1164
  $item_prefix = '<div class="item">';
1165
  $item_suffix = '</div>';
1166

    
1167
  $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);
1168

    
1169
  RenderHints::popFromRenderStack();
1170
  $render_array['footnotes'] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => RenderHints::getFootnoteListKey())));
1171
  if(RenderHints::getFootnoteListKey() == $key) {
1172
    RenderHints::clearFootnoteListKey();
1173
  }
1174
  return $render_array;
1175
}
1176

    
1177
/**
1178
 * @param $name_relations
1179
 * @param $name_rel_type_filter
1180
 *   Associative array with two keys:
1181
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1182
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1183
 * @param $current_name_uuid
1184
 * @param $current_taxon_uuid
1185
 * @param $list_prefix
1186
 * @param $list_suffix
1187
 * @param $item_prefix
1188
 * @param $item_suffix
1189
 * @return array
1190
 *
1191
 * @ingroup Compose
1192
 */
1193
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1194
                                    $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1195
{
1196
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1197
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1198
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1199
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1200
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1201

    
1202
  $render_array = array(
1203
    'list' => array(
1204
      '#prefix' => $list_prefix,
1205
      '#suffix' => $list_suffix,
1206
      'items' => array()
1207
    ),
1208
    'footnotes' => array()
1209
  );
1210

    
1211
  if ($name_relations) {
1212

    
1213
    // remove all relations which are not selected in the settings and
1214
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1215
    // for special handling
1216
    $filtered_name_rels = array();
1217
    $non_nec_name_rels = array();
1218
    $orthographic_variants = array();
1219
    foreach ($name_relations as $name_rel) {
1220
      $rel_type_uuid = $name_rel->type->uuid;
1221
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1222
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1223
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1224

    
1225
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1226
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1227
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1228
          )
1229
        ){
1230
          $non_nec_name_rels[] = $name_rel;
1231
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1232
          $orthographic_variants[] = $name_rel;
1233
        } else {
1234

    
1235
          $filtered_name_rels[] = $name_rel;
1236
        }
1237
      }
1238
    }
1239
    $name_relations = $filtered_name_rels;
1240

    
1241
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1242

    
1243
    // compose
1244
    foreach ($name_relations as $name_rel) {
1245

    
1246
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1247

    
1248
      $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1249
      $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1250

    
1251
      $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1252
      $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1253
      $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup . ' ';
1254
      $relationship_markup = $symbol_markup . $relationship_markup;
1255
      if ($relationship_markup) {
1256
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1257
          null,
1258
          $item_prefix,
1259
          $item_suffix);
1260
      }
1261
    }
1262

    
1263
    // name relationships to be displayed as non nec
1264
    if (count($non_nec_name_rels) > 0) {
1265
      $non_nec_markup = '';
1266
      foreach ($non_nec_name_rels as $name_rel) {
1267
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1268
        $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1269
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1270
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1271
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1272
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1273
        $non_nec_markup .= $symbol_markup . $relationship_markup;
1274
      }
1275
      if ($non_nec_markup) {
1276
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1277
          null,
1278
          $item_prefix,
1279
          $item_suffix);
1280
      }
1281
    }
1282

    
1283
    // orthographic variants
1284
    if (count($orthographic_variants) > 0) {
1285
      foreach ($orthographic_variants as $name_rel) {
1286

    
1287
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1288
        $rel_footnote_key_markup = name_relationship_footnote_markup($name_rel);
1289
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, TRUE);
1290
        $nomref_footnote_key_markup = nomenclatural_reference_footnote_key_markup($name_rel->toName);
1291
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1292
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1293
        $symbol_markup = '<span class="symbol" title="' . $label . '">' . $symbol . '</span>' . $rel_footnote_key_markup .  ' ';
1294
        $relationship_markup = $symbol_markup . $relationship_markup . $nomref_footnote_key_markup;
1295
      }
1296
      if ($relationship_markup) {
1297
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1298
          null,
1299
          $item_prefix,
1300
          $item_suffix);
1301
      }
1302
    }
1303
  }
1304
  return $render_array;
1305
}
1306

    
1307
/**
1308
 * @param $name_rel
1309
 * @return string
1310
 */
1311
function name_relationship_footnote_markup($name_rel)
1312
{
1313
  $footnote_markup = '';
1314
  $footnote_key_markup = '';
1315
  if (isset($name_rel->ruleConsidered) && $name_rel->ruleConsidered) {
1316
    $footnote_markup = '<span class="rule_considered">' . $name_rel->ruleConsidered . '</span> ';
1317
  }
1318
  if (isset($name_rel->citation)) {
1319
    $footnote_markup .= '<span class="reference">' . $name_rel->citation->titleCache . '</span>';
1320
  }
1321
  if (isset($name_rel->citationMicroReference) && $name_rel->citationMicroReference) {
1322
    $footnote_markup .= (isset($name_rel->citation) ? ':' : '') . '<span class="reference_detail">' . $name_rel->citationMicroReference . '</span>';
1323
  }
1324
  if ($footnote_markup) {
1325
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1326
    $footnote_key_markup = theme('cdm_footnote_key', array(
1327
      'footnoteKey' => $fnkey,
1328
      'separator' => ',',
1329
      'highlightable' => TRUE,
1330
      'separator_off' => TRUE,
1331
    ));
1332
  }
1333
  return $footnote_key_markup;
1334
}
1335

    
1336
/**
1337
 * @param $nom_status
1338
 * @return string
1339
 */
1340
function nomenclatural_status_footnote_markup($nom_status)
1341
{
1342
  // NomenclaturalStatus is a subclass of ReferencedEntityBase
1343
  // and has the same structure as TaxonNameRelationship
1344
  return name_relationship_footnote_markup($nom_status);
1345
}
1346

    
1347
/**
1348
 * @param $name
1349
 * @return string
1350
 */
1351
function nomenclatural_reference_footnote_key_markup($name)
1352
{
1353
  $footnote_markup = '';
1354
  $footnote_key_markup = '';
1355
  if (isset($name->nomenclaturalReference) && $name->nomenclaturalReference) {
1356
    $footnote_markup .= '<span class="reference">' . $name->nomenclaturalReference->titleCache . '</span>';
1357
  }
1358
  if (isset($name->nomenclaturalMicroReference)) {
1359
    $footnote_markup .= ($footnote_key_markup ? ':' : '') . '<span class="reference_detail">' . $name->nomenclaturalMicroReference . '</span>';
1360
  }
1361
  if ($footnote_markup) {
1362
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1363
    $footnote_key_markup = theme('cdm_footnote_key', array(
1364
      'footnoteKey' => $fnkey,
1365
      'separator' => ',',
1366
      'highlightable' => TRUE,
1367
      'separator_off' => TRUE,
1368
    ));
1369
  }
1370
  return $footnote_key_markup;
1371
}
1372

    
1373

    
1374
/**
1375
 * @param $taxon
1376
 * @return array
1377
 */
1378
function cdm_name_relationships_for_taxon($taxon)
1379
{
1380
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1381
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1382
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1383
  return $name_relations;
1384
}
1385

    
1386

    
1387
/**
1388
 * Recursively searches the array for the $key and sets the given value.
1389
 *
1390
 * @param mixed $key
1391
 *   Key to search for.
1392
 * @param mixed $value
1393
 *   Value to set.'
1394
 * @param array $array
1395
 *   Array to search in.
1396
 *
1397
 * @return bool
1398
 *   True if the key has been found.
1399
 */
1400
function &array_setr($key, $value, array &$array) {
1401
  $res = NULL;
1402
  foreach ($array as $k => &$v) {
1403
    if ($key == $k) {
1404
      $v = $value;
1405
      return $array;
1406
    }
1407
    elseif (is_array($v)) {
1408
      $innerArray = array_setr($key, $value, $v);
1409
      if ($innerArray) {
1410
        return $array;
1411
      }
1412
    }
1413
  }
1414
  return $res;
1415
}
1416

    
1417
/**
1418
 * @todo Please document this function.
1419
 * @see http://drupal.org/node/1354
1420
 */
1421
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1422
  $res = NULL;
1423
  $precedingElement = NULL;
1424
  foreach ($renderTemplate as &$part) {
1425
    foreach ($part as $key => &$element) {
1426
      if ($key == $contentElementKey) {
1427
        return $precedingElement;
1428
      }
1429
      $precedingElement = $element;
1430
    }
1431
  }
1432
  return $res;
1433
}
1434

    
1435
/**
1436
 * @todo Please document this function.
1437
 * @see http://drupal.org/node/1354
1438
 */
1439
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1440
  $res = NULL;
1441
  $precedingKey = NULL;
1442
  foreach ($renderTemplate as &$part) {
1443
    if (is_array($part)) {
1444
      foreach ($part as $key => &$element) {
1445
        if ($key == $contentElementKey) {
1446
          return $precedingKey;
1447
        }
1448
        if (!str_beginsWith($key, '#')) {
1449
          $precedingKey = $key;
1450
        }
1451
      }
1452
    }
1453
  }
1454
  return $res;
1455
}
1456

    
1457
function nameTypeToDTYPE($dtype){
1458
  static $nameTypeLabelMap = array(
1459
    "ICNB" => "BacterialName",
1460
    "ICNAFP" => "BotanicalName",
1461
    "ICNCP" => "CultivarPlantName",
1462
    "ICZN" => "ZoologicalName",
1463
    "ICVCN" => "ViralName",
1464
    "Any taxon name" => "TaxonName",
1465
    "NonViral" => "TaxonName",
1466
    "Fungus" => "BotanicalName",
1467
    "Plant" => "BotanicalName",
1468
    "Algae" => "BotanicalName",
1469
  );
1470
  return $nameTypeLabelMap[$dtype];
1471

    
1472
}
1473

    
1474

    
1475
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1476
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1477
}
1478

    
1479
/**
1480
 * Provides an array with the different registration types covered by the passed registration.
1481
 *
1482
 * The labels in the returned array are translatable.
1483
 *
1484
 * See also https://dev.e-taxonomy.eu/redmine/issues/8016
1485
 *
1486
 * @param $registration_dto
1487
 * @return array
1488
 *    An array of the labels describing the different registration types covered by the passed registration.
1489
 */
1490
function registration_types($registration_dto){
1491
  $reg_type_labels = array();
1492
  if(isset($registration_dto->nameRef)){
1493
    $reg_type_labels["name"] = t("new name");
1494
    $reg_type_labels["taxon"] = t("new taxon");
1495
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1496
    $is_new_combination = true;
1497
    foreach($name_relations as $name_rel){
1498
      if(isset($name_rel->type->uuid)){
1499
        $name_is_from_name = $registration_dto->nameRef->uuid == $name_rel->fromName->uuid;
1500
        switch($name_rel->type->uuid) {
1501
          case UUID_NAMERELATIONSHIPTYPE_BASIONYM:
1502
            if(!$name_is_from_name){
1503
              $reg_type_labels["basionym"] = t("new combination");
1504
              $is_new_combination = true;
1505
            }
1506
            break;
1507
          case UUID_NAMERELATIONSHIPTYPE_REPLACED_SYNONYM:
1508
            if(!$name_is_from_name) {
1509
              $is_new_combination = true;
1510
            }
1511
            break;
1512
          case UUID_NAMERELATIONSHIPTYPE_VALIDATED_BY_NAME:
1513
            if(!$name_is_from_name) {
1514
              $reg_type_labels["validation"] = t("validation");
1515
            }
1516
            break;
1517
          case UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT:
1518
            if(!$name_is_from_name) {
1519
              $reg_type_labels["orth_var"] = t("orthographical correction");
1520
            }break;
1521
          default:
1522
            // NOTHING
1523
        }
1524
      }
1525
    }
1526
    if($is_new_combination){
1527
      unset($reg_type_labels["taxon"]);
1528
    }
1529
  }
1530
  if(isset($registration_dto->orderdTypeDesignationWorkingSets)){
1531
    $reg_type_labels[] = t("new nomenclatural type");
1532
  }
1533
  return $reg_type_labels;
1534
}
1535

    
1536
/**
1537
 * Collects and deduplicates the type designations associated with the passes synonyms.
1538
 *
1539
 * @param $synonymy_group
1540
 *    An array containing a homotypic or heterotypic group of names.
1541
 * @param $accepted_taxon_name_uuid
1542
 *    The uuid of the accepted taxon name. Optional parameter. The type designations associated
1543
 *    with the accepted name will be added to the resulting list also.
1544
 * @return array
1545
 *    The type designations
1546
 */
1547
function type_designations_for_synonymy_group($synonymy_group, $accepted_taxon_name_uuid = null) {
1548
  $type_designations_map = array();
1549

    
1550
  // 1.
1551
  foreach ($synonymy_group as $synonym) {
1552
    $type_designations_by_name = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $synonym->name->uuid);
1553
    if ($type_designations_by_name) {
1554
      foreach ($type_designations_by_name as $td) {
1555
        if (!isset($type_designations_map[$td->uuid])) {
1556
          $type_designations_map[$td->uuid] = $td;
1557
        }
1558
      }
1559
    }
1560
  }
1561

    
1562
  if($accepted_taxon_name_uuid){
1563
    $accepted_name_type_designations = cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $accepted_taxon_name_uuid);
1564
    if($accepted_name_type_designations  && count($accepted_name_type_designations) > 0){
1565
      foreach ($accepted_name_type_designations as $td){
1566
        $type_designations_map[$td->uuid] = $td;
1567
      }
1568
    }
1569
  }
1570

    
1571
  if(count($type_designations_map) > 0){
1572
    return array_values($type_designations_map);
1573
  } else {
1574
    return array();
1575
  }
1576
}
(5-5/10)