Project

General

Profile

Download (51.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.taggedTitle so we have the secRef
285
    $taggedTitle = $taxon_name_or_taxon_base->taggedTitle;
286
  } else {
287
    // assuming this is a TaxonName
288
    $taxonName = $taxon_name_or_taxon_base;
289
    $taggedTitle = $taxon_name_or_taxon_base->taggedName;
290
  }
291

    
292

    
293
  $renderTemplate = get_nameRenderTemplate(RenderHints::getRenderPath(), $nameLink, $refenceLink);
294
  $partDefinition = get_partDefinition($taxonName->nameType);
295

    
296
  // Apply definitions to template.
297
  foreach ($renderTemplate as $part => $uri) {
298

    
299
    if (isset($partDefinition[$part])) {
300
      $renderTemplate[$part] = $partDefinition[$part];
301
    }
302
    if (is_array($uri) && isset($uri['#uri'])) {
303
      $renderTemplate[$part]['#uri'] = $uri['#uri'];
304
    }
305
  }
306

    
307
  $secref_tagged_text = tagged_text_extract_secref($taggedTitle);
308
  $nom_status_tagged_text = tagged_text_extract_nomstatus($taggedTitle);
309
  $appended_phrase_tagged_text = array(); // this is filled later
310

    
311
  normalize_tagged_text($taggedTitle);
312

    
313
  $firstEntryIsValidNamePart =
314
    isset($taggedTitle)
315
    && is_array($taggedTitle)
316
    && isset($taggedTitle[0]->text)
317
    && is_string($taggedTitle[0]->text)
318
    && $taggedTitle[0]->text != ''
319
    && isset($taggedTitle[0]->type)
320
    && $taggedTitle[0]->type == 'name';
321
  $lastAuthorElementString = FALSE;
322

    
323
  $name_encasement = $is_invalid ? '"' : '';
324
  $doubtful_marker = $is_doubtful ? '?&#8239;' : ''; // 	&#8239; =  NARROW NO-BREAK SPACE
325
  $doubtful_marker_markup = '';
326

    
327
  if($doubtful_marker){
328
    $doubtful_marker_markup = '<span class="doubtful">' . $doubtful_marker . '</span>';
329
  }
330

    
331
  // split off all appendedPhrase item  from the end of the array (usually there only should  be one)
332
  while($taggedTitle[count($taggedTitle)-1]->type == "appendedPhrase"){
333
    $appended_phrase_tagged_text[] = array_pop($taggedTitle);
334
  }
335

    
336
  // Got to use second entry as first one, see ToDo comment below ...
337
  if ($firstEntryIsValidNamePart) {
338

    
339
    $taggedName = $taggedTitle;
340
    $hasNamePart_with_Authors = isset($renderTemplate['namePart']) && isset($renderTemplate['namePart']['authors']);
341
    $hasNameAuthorPart_with_Authors = isset($renderTemplate['nameAuthorPart']) && isset($renderTemplate['nameAuthorPart']['authors']);
342

    
343

    
344
    if (!(($hasNamePart_with_Authors) || ($hasNameAuthorPart_with_Authors))) {
345
      // Find author and split off from name.
346
      // TODO expecting to find the author as the last element.
347
      /*
348
      if($taggedName[count($taggedName)- 1]->type == 'authors'){
349
        $authorTeam = $taggedName[count($taggedName)- 1]->text;
350
        unset($taggedName[count($taggedName)- 1]);
351
      }
352
      */
353

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

    
373

    
374
  if(isset($appended_phrase_tagged_text[0])){
375
    $name .= ' <span class="appended-phrase">'. cdm_tagged_text_to_markup($appended_phrase_tagged_text) . '</span>';
376
  }
377

    
378
  // Fill name into $renderTemplate.
379
  array_setr('name', $name , $renderTemplate);
380

    
381
  // Fill with authorTeam.
382
  /*
383
  if($authorTeam){
384
    $authorTeamHtml = ' <span class="authorTeam">'.$authorTeam.'</span>';
385
    array_setr('authorTeam', $authorTeamHtml, $renderTemplate);
386
  }
387
  */
388

    
389
  // Fill with reference.
390
  if (isset($renderTemplate['referencePart']) && !$is_type_designation) {
391

    
392
    $registrations = cdm_ws_get(CDM_WS_NAME, array($taxonName->uuid, "registrations"));
393
    $registration_markup = render_registrations($registrations);
394

    
395
    // default separator
396
    $separator = '';
397

    
398
    // [Eckhard]:"Komma nach dem Taxonnamen ist grunsätzlich falsch,
399
    // Komma nach dem Autornamen ist überall dort falsch, wo ein "in" folgt."
400
    if (isset($renderTemplate['referencePart']['reference']) && isset($taxonName->nomenclaturalReference)) {
401
      $microreference = NULL;
402
      if (isset($renderTemplate['referencePart']['microreference'])&& isset($taxonName->nomenclaturalMicroReference)) {
403
        $microreference = $taxonName->nomenclaturalMicroReference;
404
      }
405
      $citation = cdm_ws_getNomenclaturalReference($taxonName->nomenclaturalReference->uuid, $microreference);
406

    
407
      // Find preceding element of the reference.
408
      $precedingKey = get_preceding_contentElementKey('reference', $renderTemplate);
409
      if (str_beginsWith($citation, ", in")) {
410
        $citation = substr($citation, 2);
411
        $separator = ' ';
412
      }
413
      elseif (!str_beginsWith($citation, "in") && $precedingKey == 'authors') {
414
        $separator = ', ';
415
      } else {
416
        $separator = ' ';
417
      }
418

    
419

    
420
      $referenceArray['#separator'] = $separator;
421
      $referenceArray['#html'] = '<span class="reference">' . $citation . '</span>' . $registration_markup;
422
      array_setr('reference', $referenceArray, $renderTemplate);
423
    }
424

    
425
    // If authors have been removed from the name part the last named authorteam
426
    // should be added to the reference citation, otherwise, keep the separator
427
    // out of the reference.
428
    if (isset($renderTemplate['referencePart']['authors']) && $lastAuthorElementString) {
429
      // If the nomenclaturalReference citation is not included in the
430
      // reference part but display of the microreference
431
      // is wanted, append the microreference to the authorTeam.
432
      $citation = '';
433
      if (!isset($renderTemplate['referencePart']['reference']) && isset($renderTemplate['referencePart']['microreference'])) {
434
        $separator = ": ";
435
        $citation = $taxonName->nomenclaturalMicroReference;
436
      }
437
      $referenceArray['#html'] = ' <span class="reference">' . $lastAuthorElementString . $separator . $citation . '</span>';
438
      array_setr('authors', $referenceArray, $renderTemplate);
439
    }
440
  }
441

    
442
  $is_reference_year = false;
443
  if (isset($renderTemplate['referenceYearPart']['reference.year'])) {
444
    if(isset($taxonName->nomenclaturalReference->datePublished)){
445
      $referenceArray['#html'] = ' <span class="reference">' . timePeriodToString($taxonName->nomenclaturalReference->datePublished) . '</span>';
446
      array_setr('reference.year', $referenceArray, $renderTemplate);
447
      $is_reference_year = true;
448
    }
449
  }
450

    
451
  // Fill with status.
452
  if(isset($renderTemplate['statusPart']['status'])){
453
    if (isset($nom_status_tagged_text[0])) {
454
        array_setr('status', '<span class="nomenclatural_status">' . cdm_tagged_text_to_markup($nom_status_tagged_text, array('postSeparator')) . '</span>', $renderTemplate);
455
    }
456
  }
457

    
458
  if (isset($renderTemplate['secReferencePart'])){
459
    if(isset($secref_tagged_text[1])){
460
      $post_separator_markup = $is_reference_year ? '.': '';
461
      if(isset($nom_status_tagged_text[count($nom_status_tagged_text) - 1]) && ($nom_status_tagged_text[count($nom_status_tagged_text) - 1]->type ==  'postSeparator')){
462
        $post_separator_markup = cdm_tagged_text_to_markup(array($nom_status_tagged_text[count($nom_status_tagged_text) - 1 ]));
463
      };
464
      array_setr('secReference',
465
        $post_separator_markup
466
          . ' <span class="sec_reference">'
467
          . join('', cdm_tagged_text_values($secref_tagged_text))
468
          . '</span>', $renderTemplate);
469
    }
470
  }
471

    
472
  // Fill with protologues etc...
473
  $descriptionHtml = '';
474
  if (array_setr('description', TRUE, $renderTemplate)) {
475
    $descriptions = cdm_ws_get(CDM_WS_PORTAL_NAME_DESCRIPTIONS, $taxonName->uuid);
476
    foreach ($descriptions as $description) {
477
      if (!empty($description)) {
478
        foreach ($description->elements as $description_element) {
479
          $second_citation = '';
480
          if (isset($description_element->multilanguageText_L10n) && $description_element->multilanguageText_L10n->text) {
481
            $second_citation = '[& ' . $description_element->multilanguageText_L10n->text . '].';
482
          }
483
          $descriptionHtml .= $second_citation;
484
          $descriptionHtml .= cdm_description_element_media(
485
              $description_element,
486
              array(
487
                'application/pdf',
488
                'image/png',
489
                'image/jpeg',
490
                'image/gif',
491
                'text/html',
492
              )
493
          );
494

    
495
        }
496
      }
497
    }
498
    array_setr('description', $descriptionHtml, $renderTemplate);
499
  }
500

    
501
  // Render.
502
  $out = '';
503
  if(isset($_REQUEST['RENDER_PATH'])){
504
    // developer option to show the render path with each taxon name
505
    $out .= '<span class="render-path">' . RenderHints::getRenderPath() . '</span>';
506
  }
507
  $out .= '<span class="' . html_class_attribute_ref($taxon_name_or_taxon_base)
508
    . '" data-cdm-ref="/name/' . $taxonName->uuid . '" data-cdm-render-path="' . RenderHints::getRenderPath() .'">';
509

    
510
  foreach ($renderTemplate as $partName => $part) {
511
    $separator = '';
512
    $partHtml = '';
513
    $uri = FALSE;
514
    if (!is_array($part)) {
515
      continue;
516
    }
517
    if (isset($part['#uri']) && is_string($part['#uri'])) {
518
      $uri = $part['#uri'];
519
      unset($part['#uri']);
520
    }
521
    foreach ($part as $key => $content) {
522
      $html = '';
523
      if (is_array($content)) {
524
        $html = $content['#html'];
525
        if(isset($content['#separator'])) {
526
          $separator = $content['#separator'];
527
        }
528
      }
529
      elseif (is_string($content)) {
530
        $html = $content;
531
      }
532
      $partHtml .= '<span class="' . $key . '">' . $html . '</span>';
533
    }
534
    if ($uri) {
535
      // cannot use l() here since the #uri aleady should have been processed through uri() at this point
536
      $out .= $separator . '<a href="' . $uri . '" class="' . $partName . '">' . $partHtml . '</a>';
537

    
538
    }
539
    else {
540
      $out .= $separator . $partHtml;
541
    }
542
  }
543
  $out .= '</span>';
544
  if ($show_annotations) {
545
    // $out .= theme('cdm_annotations_as_footnotekeys', $taxonName);
546
  }
547
  return $out;
548
}
549

    
550

    
551

    
552
/**
553
 * Composes information for a registration from a dto object.
554
 *
555
 * Registrations which are not yet published are suppressed.
556
 *
557
 * @param $registration_dto
558
 * @param $with_citation
559
 *   Whether to show the citation.
560
 *
561
 * @return array
562
 *    A drupal render array with the elements:
563
 *    - 'name'
564
 *    - 'name-relations'
565
 *    - 'specimen_type_designations'
566
 *    - 'name_type_designations'
567
 *    - 'citation'
568
 *    - 'registration_date_and_institute'
569
 * @ingroup compose
570
 */
571
function compose_registration_dto_full($registration_dto, $with_citation = true)
572
{
573
  $render_array = array(
574
    '#prefix' => '<div class="registration">',
575
    '#suffix' => '</div>'
576
  );
577

    
578
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
579
    return $render_array;
580
  }
581

    
582
  // name and typedesignation in detail
583
  if($registration_dto->nameRef){
584
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->nameRef->uuid);
585
    $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);
586
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
587
    $render_array['name_relations'] = compose_name_relationships_list($name_relations, $registration_dto->nameRef->uuid, null);
588
    $render_array['name_relations']['#weight'] = 10;
589
  } else {
590
    // in this case the registration must have a
591
    $name = cdm_ws_get(CDM_WS_PORTAL_NAME, $registration_dto->typifiedNameRef->uuid);
592
    $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);
593
  }
594
  if(is_object($registration_dto->orderdTypeDesignationWorkingSets)) {
595
    $field_unit_uuids = array();
596
    $specimen_type_designation_refs = array();
597
    $name_type_designation_refs = array();
598
    foreach ((array)$registration_dto->orderdTypeDesignationWorkingSets as $workingset_ref => $obj) {
599
      $tokens = explode("#", $workingset_ref);
600
      $types_in_fieldunit = get_object_vars($obj); // convert into associative array
601

    
602
      if ($tokens[0] == 'NameTypeDesignation') {
603
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
604
          if(!isset($name_type_designation_refs[$type_status])){
605
            $name_type_designation_refs[$type_status]  = $entity_reference_list;
606
          } else {
607
            array_push($name_type_designation_refs[$type_status] ,$entity_reference_list);
608
          }
609
        }
610
      } else if ($tokens[0] == 'FieldUnit'){
611
        $field_unit_uuids[] = $tokens[1];
612
        foreach ($types_in_fieldunit as $type_status => $entity_reference_list) {
613
          if(!isset($specimen_type_designation_refs[$type_status])){
614
            $specimen_type_designation_refs[$type_status] =  $entity_reference_list;
615
          } else {
616
            array_push($specimen_type_designation_refs[$type_status], $entity_reference_list);
617
          }
618
        }
619
      } else {
620
        drupal_set_message("Unimplemented type: " . $tokens[0], 'error');
621
      }
622
    }
623
    if (count($name_type_designation_refs) > 0) {
624
      $render_array['name_type_designations'] = compose_name_type_designations($name_type_designation_refs);
625
      $render_array['name_type_designations']['#prefix'] = '<p class="name_type_designations">';
626
      $render_array['name_type_designations']['#suffix'] = '</p>';
627
      $render_array['name_type_designations']['#weight'] = 20;
628
    }
629
    if (count($field_unit_uuids) > 0) {
630
      $render_array['specimen_type_designations'] = compose_specimen_type_designations($specimen_type_designation_refs);
631
    }
632
  }
633

    
634
  // citation
635
  if ($with_citation) {
636
    $render_array['citation'] = markup_to_render_array(
637
      "<p class=\"citation " . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
638
      . l($registration_dto->bibliographicInRefCitationString, path_to_reference($registration_dto->citationUuid))
639
      . "</p>",
640
      50);
641
  }
642

    
643
  // registration date and office
644
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto);
645
  if($registration_date_insitute_markup){
646
    $render_array['registration_date_and_institute'] = markup_to_render_array(
647
      $registration_date_insitute_markup . '</p>',
648
      100);
649
  }
650

    
651
  return $render_array;
652
}
653

    
654

    
655
/**
656
 * Composes a compact representation for a registrationDTO object
657
 *
658
 * Registrations which are not yet published are suppressed.
659
 *
660
 * @param $registration_dto
661
 * @param $style string
662
 *   The style of how to compose the 'identifier' and 'registration_date_and_institute' part with the summary
663
 *   - 'citation': Similar to the arrearance of nomenclatural acts in print media
664
 *   - 'list-item' : style suitable for result lists etc
665
 *
666
 * @return array
667
 *    A drupal render array with the elements:
668
 *    - 'registration-metadata' when $style == 'list-item'
669
 *    - 'summary'
670
 * @ingroup compose
671
 */
672
function compose_registration_dto_compact($registration_dto, $style = 'citation', $tag_enclosing_summary = 'p')
673
{
674
  $render_array = array();
675
  $media_link_map = array();
676

    
677
  if(!(isset($registration_dto->identifier) && $registration_dto->status == 'PUBLISHED')){
678
    return $render_array;
679
  }
680

    
681
  $registration_date_insitute_markup = render_registration_date_and_institute($registration_dto, 'span');
682
  $itentifier_markup = l($registration_dto->identifier, path_to_registration($registration_dto->identifier), array('attributes' => array('class' => array('identifier'))));
683

    
684
  $tagged_text_options = array();
685
  if(isset($registration_dto->nameRef)){
686
    $tagged_text_options[] = array(
687
      'filter-type' => 'name',
688
      'prefix' => '<span class="registered_name">',
689
      'suffix' => '</span>',
690
    );
691
  } else {
692
    $tagged_text_options[] = array(
693
      'filter-type' => 'name',
694
      'prefix' => '<span class="referenced_typified_name">',
695
      'suffix' => '</span>',
696
    );
697
  }
698
  cdm_tagged_text_add_options($registration_dto->summaryTaggedText, $tagged_text_options);
699
  $taggged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
700
  foreach ($taggged_text_expanded  as $tagged_text){
701
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
702
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
703
      if(isset($mediaDTOs[0]->uri)){
704
        $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
705
        $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
706
        $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
707
      }
708
    }
709
  }
710
  $registation_markup = cdm_tagged_text_to_markup($taggged_text_expanded);
711
  foreach($media_link_map as $media_url_key => $link){
712
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
713
  }
714
  if($style == 'citation') {
715
    $registation_markup = $registation_markup . ' ' . $itentifier_markup . ' ' . $registration_date_insitute_markup;
716
  } else {
717
    $render_array['registration-metadata'] = markup_to_render_array('<div class="registration-metadata">' . $itentifier_markup . ' ' . $registration_date_insitute_markup. "</div>", -10);
718
  }
719
  $render_array['summary'] = markup_to_render_array('<' . $tag_enclosing_summary . ' class="registration-summary">' . $registation_markup . '</' . $tag_enclosing_summary . '>', 0);
720

    
721
  return $render_array;
722
}
723

    
724

    
725
/**
726
 * Renders the registrationDate and institutionTitleCache of the $registration_dto as markup.
727
 *
728
 * @param $registration_dto
729
 * @return string
730
 *    The markup or an empty string
731
 */
732
function render_registration_date_and_institute($registration_dto, $enclosing_tag = 'p') {
733
  $registration_date_institute_markup = '';
734
  if ($registration_dto->registrationDate) {
735
    $date_string = format_datetime($registration_dto->registrationDate);
736
    if (isset($registration_dto->institutionTitleCache) && $registration_dto->institutionTitleCache) {
737
      $registration_date_institute_markup =
738
        t("Registration on @date in @institution", array(
739
          '@date' => $date_string,
740
          '@institution' => $registration_dto->institutionTitleCache,
741
        ));
742
    } else {
743
      $registration_date_institute_markup =
744
        t("Registration on @date", array(
745
          '@date' => $date_string
746
        ));
747
    }
748
    $registration_date_institute_markup = '<' .$enclosing_tag . ' class="registration-date-and-institute">'. $registration_date_institute_markup . '</' .$enclosing_tag . '>';
749
  }
750
  return $registration_date_institute_markup;
751
}
752

    
753

    
754
/**
755
 * @param $registrations
756
 * @return string
757
 */
758
function render_registrations($registrations)
759
{
760
  $registration_markup = '';
761
  $registration_markup_array = array();
762
  if ($registrations) {
763
    foreach ($registrations as $reg) {
764
      $registration_markup_array[] = render_registration($reg);
765
    }
766
    $registration_markup = " Registration" . (count($registration_markup_array) > 1 ? 's: ' : ': ')
767
      . join(', ', $registration_markup_array);
768
  }
769
  return $registration_markup;
770
}
771

    
772

    
773
/**
774
 * Renders a registration
775
 *
776
 * TODO replace by compose_registration_dto_compact
777
 * @param $registration
778
 */
779
function render_registration($registration){
780
  $markup = '';
781

    
782
  if(isset($registration->identifier) && $registration->status == 'PUBLISHED'){
783
    $office_class_attribute = '';
784
    if(isset($registration->institution->titleCache)){
785
      $office_class_attribute = registration_intitute_class_attribute($registration);
786
    }
787
    $markup = "<span class=\"registration $office_class_attribute\">" . l($registration->identifier, path_to_registration($registration->identifier)) . ', '
788
      .  preg_replace('/^([^T]*)(.*)$/', '${1}', $registration->registrationDate)
789
      . '</span>';
790
  }
791
  return $markup;
792
}
793

    
794
/**
795
 * @param $registration
796
 * @return string
797
 */
798
function registration_intitute_class_attribute($registration_dto)
799
{
800
  if(isset($registration_dto->institutionTitleCache)){
801
    $institutionTitleCache = $registration_dto->institutionTitleCache;
802
  } else {
803
    // fall back option to also support cdm entities
804
    $institutionTitleCache = @$registration_dto->institution->titleCache;
805
  }
806
  return $institutionTitleCache ? 'registration-' . strtolower(preg_replace('/[^a-zA-Z0-9]/', '-', $institutionTitleCache)) : '';
807
}
808

    
809

    
810
/**
811
 * Composes the TypedEntityReference to name type designations passed as associatve array.
812
 *
813
 * @param $$type_entity_refs array
814
 *   an associative array of name type type => TypedEntityReference for name type designations as
815
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
816
 *
817
 * @ingroup compose
818
 */
819
function compose_name_type_designations($type_entity_refs){
820
  $render_array = array();
821
  $preferredStableUri = '';
822
  foreach($type_entity_refs as $type_status => $name_types){
823
    foreach ($name_types as $name_type){
824
      $type_designation = cdm_ws_get(CDM_TYPEDESIGNATION, array($name_type->uuid, 'preferredUri'));
825
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
826
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
827
      }
828
      $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>: "
829
        . $name_type->label
830
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
831
        . '</div>');
832
      }
833
  }
834
  return $render_array;
835
}
836

    
837
/**
838
 * Composes the TypedEntityReference to specimen type designations passed as associatve array.
839
 *
840
 * @param $type_entity_refs array
841
 *   an associative array of specimen type type => TypedEntityReference for specimen type designations as
842
 *   produced by the eu.etaxonomy.cdm.api.service.name.TypeDesignationSetManager
843
 *
844
 * @ingroup compose
845
 */
846
function compose_specimen_type_designations($type_entity_refs){
847

    
848
  $render_array = array();
849

    
850
  foreach($type_entity_refs as $type_status => $specimen_types){
851
    foreach($specimen_types as $specimen_type){
852

    
853
      $type_designation = cdm_ws_get(CDM_TYPEDESIGNATION, array($specimen_type->uuid));
854

    
855
      $preferredStableUri = '';
856
      $citation_markup = '';
857
      $media = '';
858

    
859
      // preferredStableUri
860
      if(isset($type_designation->typeSpecimen->preferredStableUri) && $type_designation->typeSpecimen->preferredStableUri){
861
        $preferredStableUri = $type_designation->typeSpecimen->preferredStableUri;
862
      }
863

    
864
      $mediaSpecimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($type_designation->typeSpecimen->uuid, 'mediaSpecimen'));
865
      if($mediaSpecimen){
866
        // compose output
867
        // mediaURI
868
        if(isset($mediaSpecimen->representations[0])) {
869
          $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
870
          $captionElements = array(
871
            '#uri' => t('open media'),
872
            'elements' => array('-none-'),
873
            'sources_as_content' => true
874
          );
875
          $media = compose_cdm_media_gallerie(array(
876
            'mediaList' => array($mediaSpecimen),
877
            'galleryName' => CDM_DATAPORTAL_TYPE_SPECIMEN_GALLERY_NAME . '_' . $specimen_type->uuid,
878
            'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
879
            'cols' => $gallery_settings['cdm_dataportal_media_cols'],
880
            'captionElements' => $captionElements,
881
          ));
882
        }
883
        // citation and detail
884
        $annotations_and_sources = handle_annotations_and_sources(
885
            $mediaSpecimen,
886
            array(
887
                'sources_as_content' => true,
888
                'link_to_name_used_in_source' => false,
889
                'link_to_reference' => true,
890
                'add_footnote_keys' => false,
891
                'bibliography_aware' => false),
892
            '',
893
            null
894
        );
895
        if(is_array( $annotations_and_sources['source_references'])){
896
          $citation_markup = join(', ', $annotations_and_sources['source_references']);
897
        }
898
      }
899

    
900
      $render_array[] = markup_to_render_array('<div class="specimen_type_designation ' . html_class_attribute_ref($specimen_type)  . '">
901
          <span class="type_status">' . ucfirst($type_status) . "</span>: "
902
        . $specimen_type->label
903
        . ($citation_markup ? ' '. $citation_markup : '')
904
        . ($preferredStableUri ? " ". l($preferredStableUri,  $preferredStableUri) : '')
905
        . $media
906
        . '</div>');
907
    }
908
  }
909
  return $render_array;
910
}
911

    
912
/**
913
 * @param $name_rel
914
 * @param $current_name_uuid
915
 * @param $current_taxon_uuid
916
 * @param $suppress_if_current_name_is_source // FIXME UNUSED !!!!
917
 * @param $show_name_cache_only
918
 *    The nameCache will be shown instead of the titleCache if this parameter is true.
919
 * @return null|string
920
 */
921
function name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, $show_name_cache_only = false){
922

    
923
  $relationship_markup = null;
924

    
925
  $current_name_is_toName = $current_name_uuid == $name_rel->toName->uuid;
926

    
927
  if($current_name_is_toName){
928
    $name = $name_rel->fromName;
929
  } else {
930
    $name = $name_rel->toName;
931
  }
932

    
933
  $highlited_synonym_uuid = isset ($name->taxonBases[0]->uuid) ? $name->taxonBases[0]->uuid : '';
934
  if(!$show_name_cache_only){
935
    $relationship_markup = render_taxon_or_name($name,
936
      url(path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false))
937
    );
938
  } else {
939
    $relationship_markup = l(
940
      '<span class="' . html_class_attribute_ref($name) . '"">' . $name->nameCache . '</span>',
941
      path_to_name($name->uuid, $current_taxon_uuid, $highlited_synonym_uuid, false),
942
      array('html' => true)
943
    );
944
  }
945

    
946
  return $relationship_markup;
947
}
948

    
949

    
950
/**
951
 * Composes an inline representation of selected name relationships
952
 *
953
 * The output of this function will be usually appended to taxon name representations.
954
 * Only the following types are displayed: LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR, ORTHOGRAPHIC_VARIANT
955
 *
956
 * LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR are displayed as
957
 * non {titleCache} nec {titleCache} nec {titleCache} whereas the related names
958
 * are ordered alphabetically.
959
 *
960
 * ORTHOGRAPHIC_VARIANT is displayed as 'ort. var. {nameCache}'
961
 *
962
 * Related issues:
963
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
964
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
965
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
966
 *   - https://dev.e-taxonomy.eu/redmine/issues/2001 "[Cichorieae Portal] Name Relationship -> blocking name are not shown"
967
 *
968
 * @param $name_relations
969
 *    The list of CDM NameRelationsips
970
 * @param $current_name_uuid
971
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
972
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
973
 * @param $suppress_if_current_name_is_source
974
 *    The display of the relation will be
975
 *    suppressed is the current name is on the source of the relation edge.
976
 *    That is if it is on the from side of the relation. Except for 'blocking name for' which is
977
 *    an inverse relation. For this relation type the toName is taken in to account.
978
 * @param $current_taxon_uuid
979
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
980
 * @return array
981
 *    A drupal render array
982
 *
983
 * @ingroup Compose
984
 */
985
function compose_name_relationships_inline($name_relations, $current_name_uuid, $current_taxon_uuid, $suppress_if_current_name_is_source = true) {
986

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

    
990
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_INLINE_TYPES, unserialize(CDM_NAME_RELATIONSHIP_INLINE_TYPES_DEFAULT));
991
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
992
  foreach ($selected_name_rel_uuids as $uuid){
993
    $name_rel_type_filter['direct'][$uuid] = $uuid;
994
    if($uuid != UUID_NAMERELATIONSHIPTYPE_MISSPELLING){
995
      $name_rel_type_filter['inverse'][$uuid] = $uuid;
996
    }
997
  }
998

    
999
  $list_prefix = '<span class="name_relationships">[';
1000
  $list_suffix = ']</span>';
1001
  $item_prefix = '<span class="item">';
1002
  $item_suffix = '</span> ';
1003
  $show_relationship_symbol = true;
1004
  $render_array = compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid, $show_relationship_symbol, $list_prefix, $list_suffix, $item_prefix, $item_suffix);
1005

    
1006
  // remove the glue space from the last item element which has been added by the $item_suffix = '</span> '
1007
  $items_ctn = count($render_array['list']['items']);
1008
  if($items_ctn){
1009
    $render_array['list']['items'][$items_ctn - 1]['#suffix'] = '</span>';
1010
  }
1011

    
1012
  RenderHints::popFromRenderStack();
1013
  return $render_array;
1014
}
1015

    
1016
/**
1017
 * Composes an list representation of the name relationships.
1018
 *
1019
 * The output of this function will be usually appended to taxon name representations.
1020
 *
1021
 * Related issues:
1022
 *   - https://dev.e-taxonomy.eu/redmine/issues/5697 "Show name conserved against as [non xxx]"
1023
 *   - https://dev.e-taxonomy.eu/redmine/issues/6678 "How to correctly show name relationship "orth. var." in dataportal"
1024
 *   - https://dev.e-taxonomy.eu/redmine/issues/5857
1025
 *
1026
 * @param $name_relations
1027
 *    The list of CDM NameRelationsips
1028
 * @param $current_name_uuid
1029
 *    The Uuid of the name for which the relations are to be rendered, the current name will be hidden when
1030
 *    rendering the relation an only the other name is shown. Parameter is REQUIRED.
1031
 * @param $current_taxon_uuid
1032
 *    The taxon to be omitted from related taxa. This is only used to create links, see path_to_name()
1033
 * @return array
1034
 *    A drupal render array
1035
 *
1036
 * @ingroup Compose
1037
 */
1038
function compose_name_relationships_list($name_relations, $current_name_uuid, $current_taxon_uuid) {
1039

    
1040
  // $ordered_name_relation_type_uuids = array_keys(cdm_terms_by_type_as_option('NameRelationshipType', CDM_ORDER_BY_ORDER_INDEX_ASC));
1041

    
1042
  RenderHints::pushToRenderStack('name_relationships');
1043
  RenderHints::setFootnoteListKey('name_relationships');
1044
  // the render stack element homonyms is being used in the default render templates !!!, see CDM_NAME_RENDER_TEMPLATES_DEFAULT
1045

    
1046
  $selected_name_rel_uuids = variable_get(CDM_NAME_RELATIONSHIP_LIST_TYPES, unserialize(CDM_NAME_RELATIONSHIP_LIST_TYPES_DEFAULT));
1047
  $name_rel_type_filter = array('direct' => array(), 'inverse' => array());
1048
  foreach ($selected_name_rel_uuids as $uuid){
1049
    $name_rel_type_filter['direct'][$uuid] = $uuid;
1050
    $name_rel_type_filter['inverse'][$uuid] = $uuid;
1051
  }
1052

    
1053
  $list_prefix = '<div class="relationships_list name_relationships">';
1054
  $list_suffix = '</div>';
1055
  $item_prefix = '<div class="item">';
1056
  $item_suffix = '</div>';
1057
  $show_relationship_symbol = true;
1058

    
1059
  $render_array = compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid, $show_relationship_symbol, $list_prefix, $list_suffix, $item_prefix, $item_suffix);
1060

    
1061
  RenderHints::popFromRenderStack();
1062
  $render_array['footnotes'] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => RenderHints::getFootnoteListKey())));
1063
  RenderHints::clearFootnoteListKey();
1064

    
1065
  return $render_array;
1066
}
1067

    
1068
/**
1069
 * @param $name_relations
1070
 * @param $name_rel_type_filter
1071
 *   Associative array with two keys:
1072
 *   - 'direct': the relationship type uuids for the direct direction of the relation edge to be included
1073
 *   - 'inverse': the relationship type uuids for the direct direction of the relation edge to be included
1074
 * @param $current_name_uuid
1075
 * @param $current_taxon_uuid
1076
 * @param $show_relationship_symbol
1077
 * @param $list_prefix
1078
 * @param $list_suffix
1079
 * @param $item_prefix
1080
 * @param $item_suffix
1081
 * @return array
1082
 *
1083
 * @ingroup Compose
1084
 */
1085
function compose_name_relationships($name_relations, $name_rel_type_filter, $current_name_uuid, $current_taxon_uuid,
1086
                                    $show_relationship_symbol, $list_prefix, $list_suffix, $item_prefix, $item_suffix)
1087
{
1088
  $non_nec_name_reltype_uuids = array(UUID_NAMERELATIONSHIPTYPE_LATER_HOMONYM,
1089
    UUID_NAMERELATIONSHIPTYPE_TREATED_AS_LATER_HOMONYM,
1090
    UUID_NAMERELATIONSHIPTYPE_CONSERVED_AGAINST,
1091
    UUID_NAMERELATIONSHIPTYPE_MISSPELLING,
1092
    UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR);
1093

    
1094
  $render_array = array(
1095
    'list' => array(
1096
      '#prefix' => $list_prefix,
1097
      '#suffix' => $list_suffix,
1098
      'items' => array()
1099
    ),
1100
    'footnotes' => array()
1101
  );
1102

    
1103
  if ($name_relations) {
1104

    
1105
    // remove all relations which are not selected in the settings and
1106
    // separate all LATER_HOMONYM, TREATED_AS_LATER_HOMONYM, BLOCKING_NAME_FOR relations and ORTHOGRAPHIC_VARIANTs
1107
    // for special handling
1108
    $filtered_name_rels = array();
1109
    $non_nec_name_rels = array();
1110
    $orthographic_variants = array();
1111
    foreach ($name_relations as $name_rel) {
1112
      $rel_type_uuid = $name_rel->type->uuid;
1113
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1114
      if ((!$is_inverse_relation && isset($name_rel_type_filter['direct'][$rel_type_uuid]) && $name_rel_type_filter['direct'][$rel_type_uuid])
1115
        ||($is_inverse_relation && isset($name_rel_type_filter['inverse'][$rel_type_uuid]) && $name_rel_type_filter['inverse'][$rel_type_uuid])) {
1116

    
1117
        if (array_search($rel_type_uuid, $non_nec_name_reltype_uuids) !== false && (
1118
            $current_name_uuid == $name_rel->fromName->uuid && $rel_type_uuid != UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1119
            || $current_name_uuid == $name_rel->toName->uuid && $rel_type_uuid == UUID_NAMERELATIONSHIPTYPE_BLOCKING_NAME_FOR
1120
          )
1121
        ){
1122
          $non_nec_name_rels[] = $name_rel;
1123
        } else if (UUID_NAMERELATIONSHIPTYPE_ORTHOGRAPHIC_VARIANT == $rel_type_uuid) {
1124
          $orthographic_variants[] = $name_rel;
1125
        } else {
1126

    
1127
          $filtered_name_rels[] = $name_rel;
1128
        }
1129
      }
1130
    }
1131
    $name_relations = $filtered_name_rels;
1132

    
1133
    usort($name_relations, 'compare_name_relations_by_term_order_index');
1134

    
1135
    // compose
1136
    foreach ($name_relations as $name_rel) {
1137

    
1138
      $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1139

    
1140
      $footnote_key_markup = name_relationship_footnote_markup($name_rel);
1141
      $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1142

    
1143
      $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1144
      $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1145
      $symbol_markup = $show_relationship_symbol ? '<span class="symbol" title="' . $label . '">' . $symbol . '</span> ' : '';
1146
      $relationship_markup = $symbol_markup . $relationship_markup . $footnote_key_markup;
1147
      if ($relationship_markup) {
1148
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1149
          null,
1150
          $item_prefix,
1151
          $item_suffix);
1152
      }
1153
    }
1154

    
1155
    // name relationships to be displayed as non nec
1156
    if (count($non_nec_name_rels) > 0) {
1157
      $non_nec_markup = '';
1158
      foreach ($non_nec_name_rels as $name_rel) {
1159
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1160
        $footnote_key_markup = name_relationship_footnote_markup($name_rel);
1161
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid);
1162
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1163
        $symbol = $non_nec_markup ? ' nec ' : 'non';
1164
        $symbol_markup = $show_relationship_symbol ? '<span class="symbol" title="' . $label . '">' . $symbol . '</span> ' : '';
1165
        $non_nec_markup .= $symbol_markup . $relationship_markup . $footnote_key_markup;
1166
      }
1167
      if ($non_nec_markup) {
1168
        $render_array['list']['items'][] = markup_to_render_array($non_nec_markup,
1169
          null,
1170
          $item_prefix,
1171
          $item_suffix);
1172
      }
1173
    }
1174

    
1175
    // orthographic variants
1176
    if (count($orthographic_variants) > 0) {
1177
      foreach ($orthographic_variants as $name_rel) {
1178

    
1179
        $is_inverse_relation = $current_name_uuid == $name_rel->toName->uuid;
1180
        $footnote_key_markup = name_relationship_footnote_markup($name_rel);
1181
        $footnote_key_markup .= ($footnote_key_markup ? ', ' : '') . nomenclatural_reference_footnote_markup($name_rel->toName);
1182
        $relationship_markup = name_relationship_markup($name_rel, $current_name_uuid, $current_taxon_uuid, TRUE);
1183
        $label = cdm_relationship_type_term_abbreviated_label($name_rel->type, $is_inverse_relation);
1184
        $symbol = cdm_relationship_type_term_symbol($name_rel->type, $is_inverse_relation);
1185
        $symbol_markup = $show_relationship_symbol ? '<span class="symbol" title="' . $label . '">' . $symbol . '</span> ' : '';
1186
        $relationship_markup = $symbol_markup . $relationship_markup . $footnote_key_markup;
1187
      }
1188
      if ($relationship_markup) {
1189
        $render_array['list']['items'][] = markup_to_render_array($relationship_markup,
1190
          null,
1191
          $item_prefix,
1192
          $item_suffix);
1193
      }
1194
    }
1195
  }
1196
  return $render_array;
1197
}
1198

    
1199
/**
1200
 * @param $name_rel
1201
 * @return string
1202
 */
1203
function name_relationship_footnote_markup($name_rel)
1204
{
1205
  $footnote_markup = '';
1206
  $footnote_key_markup = '';
1207
  if (isset($name_rel->ruleConsidered) && $name_rel) {
1208
    $footnote_markup = '<span class="rule_considered">' . $name_rel->ruleConsidered . '</span> ';
1209
  }
1210
  if (isset($name_rel->citation)) {
1211
    $footnote_markup .= '<span class="reference">' . $name_rel->citation->abbrevTitleCache . '</span>';
1212
  }
1213
  if (isset($name_rel->citationMicroReference)) {
1214
    $footnote_markup .= (isset($name_rel->citation) ? ':' : '') . '<span class="reference_detail">' . $name_rel->citationMicroReference . '</span>';
1215
  }
1216
  if ($footnote_markup) {
1217
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1218
    $footnote_key_markup = theme('cdm_footnote_key', array(
1219
      'footnoteKey' => $fnkey,
1220
      'separator' => ',',
1221
      'highlightable' => TRUE,
1222
      'separator_off' => TRUE,
1223
    ));
1224
  }
1225
  return $footnote_key_markup;
1226
}
1227

    
1228
/**
1229
 * @param $name
1230
 * @return string
1231
 */
1232
function nomenclatural_reference_footnote_markup($name)
1233
{
1234
  $footnote_markup = '';
1235
  $footnote_key_markup = '';
1236
  if (isset($name->nomenclaturalReference) && $name->nomenclaturalReference) {
1237
    $footnote_markup .= '<span class="reference">' . $name->nomenclaturalReference->titleCache . '</span>';
1238
  }
1239
  if (isset($name->nomenclaturalMicroReference)) {
1240
    $footnote_markup .= ($footnote_key_markup ? ':' : '') . '<span class="reference_detail">' . $name->nomenclaturalMicroReference . '</span>';
1241
  }
1242
  if ($footnote_markup) {
1243
    $fnkey = FootnoteManager::addNewFootnote(RenderHints::getFootnoteListKey(), $footnote_markup);
1244
    $footnote_key_markup = theme('cdm_footnote_key', array(
1245
      'footnoteKey' => $fnkey,
1246
      'separator' => ',',
1247
      'highlightable' => TRUE,
1248
      'separator_off' => TRUE,
1249
    ));
1250
  }
1251
  return $footnote_key_markup;
1252
}
1253

    
1254
/**
1255
 * @param $taxon
1256
 * @return array
1257
 */
1258
function cdm_name_relationships_for_taxon($taxon)
1259
{
1260
  $from_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_FROM_NAMERELATIONS, $taxon->uuid);
1261
  $to_name_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TO_NAMERELATIONS, $taxon->uuid);
1262
  $name_relations = array_merge($from_name_relations, $to_name_relations);
1263
  return $name_relations;
1264
}
1265

    
1266

    
1267
/**
1268
 * Recursively searches the array for the $key and sets the given value.
1269
 *
1270
 * @param mixed $key
1271
 *   Key to search for.
1272
 * @param mixed $value
1273
 *   Value to set.'
1274
 * @param array $array
1275
 *   Array to search in.
1276
 *
1277
 * @return bool
1278
 *   True if the key has been found.
1279
 */
1280
function &array_setr($key, $value, array &$array) {
1281
  $res = NULL;
1282
  foreach ($array as $k => &$v) {
1283
    if ($key == $k) {
1284
      $v = $value;
1285
      return $array;
1286
    }
1287
    elseif (is_array($v)) {
1288
      $innerArray = array_setr($key, $value, $v);
1289
      if ($innerArray) {
1290
        return $array;
1291
      }
1292
    }
1293
  }
1294
  return $res;
1295
}
1296

    
1297
/**
1298
 * @todo Please document this function.
1299
 * @see http://drupal.org/node/1354
1300
 */
1301
function &get_preceding_contentElement($contentElementKey, array &$renderTemplate) {
1302
  $res = NULL;
1303
  $precedingElement = NULL;
1304
  foreach ($renderTemplate as &$part) {
1305
    foreach ($part as $key => &$element) {
1306
      if ($key == $contentElementKey) {
1307
        return $precedingElement;
1308
      }
1309
      $precedingElement = $element;
1310
    }
1311
  }
1312
  return $res;
1313
}
1314

    
1315
/**
1316
 * @todo Please document this function.
1317
 * @see http://drupal.org/node/1354
1318
 */
1319
function &get_preceding_contentElementKey($contentElementKey, array &$renderTemplate) {
1320
  $res = NULL;
1321
  $precedingKey = NULL;
1322
  foreach ($renderTemplate as &$part) {
1323
    if (is_array($part)) {
1324
      foreach ($part as $key => &$element) {
1325
        if ($key == $contentElementKey) {
1326
          return $precedingKey;
1327
        }
1328
        if (!str_beginsWith($key, '#')) {
1329
          $precedingKey = $key;
1330
        }
1331
      }
1332
    }
1333
  }
1334
  return $res;
1335
}
1336

    
1337
function nameTypeToDTYPE($dtype){
1338
  static $nameTypeLabelMap = array(
1339
    "ICNB" => "BacterialName",
1340
    "ICNAFP" => "BotanicalName",
1341
    "ICNCP" => "CultivarPlantName",
1342
    "ICZN" => "ZoologicalName",
1343
    "ICVCN" => "ViralName",
1344
    "Any taxon name" => "TaxonName",
1345
    "NonViral" => "TaxonName",
1346
    "Fungus" => "BotanicalName",
1347
    "Plant" => "BotanicalName",
1348
    "Algae" => "BotanicalName",
1349
  );
1350
  return $nameTypeLabelMap[$dtype];
1351

    
1352
}
1353

    
1354

    
1355
function compare_name_relations_by_term_order_index($name_rel1, $name_rel2){
1356
  return compare_terms_by_order_index($name_rel1->type, $name_rel2->type);
1357
}
(5-5/10)