Project

General

Profile

Download (52 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2

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

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

    
34
define('TAXON_TYPE_SYNONYM', 'Synonym');
35
define('TAXON_TYPE_MISAPPLIEDNAME', 'MisappliedName');
36

    
37
/**
38
 * Returns HTML for misapplied names and invalid designations.
39
 *
40
 * Both relation types are currently treated the same!
41
 *
42
 * @param object taxonRelationships
43
 *   A TaxonRelationshipsDTO, see taxon/{uuid}/taxonRelationshipsDTO
44
 *
45
 * @param object focusedTaxon
46
 *  The taxon being in the focus of the application
47
 *
48
 * @return string
49
 *    the rendered html
50
 */
51
function cdm_taxonRelationships($taxonRelationshipsDTO, $focusedTaxon){
52

    
53
  static $relationship_type_order_weights = [
54
    //
55
    UUID_PROPARTE_MISAPPLIEDNAME_FOR => 0,
56
    UUID_PARTIAL_MISAPPLIEDNAME_FOR => 0,
57
    //
58
    UUID_MISAPPLIED_NAME_FOR  => 1,
59
    //
60
    UUID_PROPARTE_SYNONYM_FOR  => 2,
61
    UUID_PARTIAL_SYNONYM_FOR  => 2
62
  ];
63

    
64
  if (!$taxonRelationshipsDTO || $taxonRelationshipsDTO->size < 1) {
65
    return null;
66
  }
67

    
68
  static $dedup_rel_type_uuids = array(
69
    UUID_MISAPPLIED_NAME_FOR,
70
    UUID_PARTIAL_MISAPPLIEDNAME_FOR,
71
    UUID_PROPARTE_MISAPPLIEDNAME_FOR
72
  );
73

    
74
  RenderHints::pushToRenderStack('taxon_relationships');
75
  $footnote_list_key = 'taxon_relationships';
76
  RenderHints::setFootnoteListKey($footnote_list_key);
77

    
78
  $misapplied = array();
79
  $joined_refs = array();
80

    
81
  $taxon_relationship_types = variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT));
82

    
83
  // Aggregate misapplied names having the same fullname:
84
  //  - deduplicate misapplied names, so that the same name is not shown multiple times in case
85
  //    the duplicates only have different sensu references with detail and appended phrase (see #5647)
86
  //  - show only the author team as short citation for the sec reference
87
  //  - show the according reference as footnote to this short citation
88
  //
89
  // Example:
90
  // "Xenoxylum foobar" sensu Grumbach¹; sensu Lem²
91
  //    1. Novel marsian species, Grumbach, 2022
92
  //    2. Flora solaris, Lem, 2019
93
  if (isset($taxonRelationshipsDTO->relations[0])) {
94
    foreach($taxonRelationshipsDTO->relations as $taxon_relation){
95

    
96
      if (in_array($taxon_relation->type->uuid, $taxon_relationship_types)) {
97

    
98
        if (in_array($taxon_relation->type->uuid, $dedup_rel_type_uuids)) {
99

    
100
          RenderHints::pushToRenderStack('misapplied_name_for'); // TODO the render path string should in future come from $taxonRelation->type->...
101

    
102
          // full name with relation symbol, rel sec as de-duplication key
103
          // the sensu part will be removed from the key below in case it is present
104
          $name_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedText, array('name')));
105
          $full_name_key = cdm_tagged_text_to_string($taxon_relation->taggedText, array('symbol', 'appendedPhrase'));
106
          $symbol_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedText, array('symbol')));
107
          $full_name_key = $name_text . ' ' . str_replace($name_text, '', $full_name_key) . ' ' . $symbol_text;
108

    
109
          cdm_taxonRelationships_process_relationship_dto($taxon_relation, $misapplied, $joined_refs, $relationship_type_order_weights , $full_name_key);
110

    
111
          RenderHints::popFromRenderStack();
112
        } else {
113
          RenderHints::pushToRenderStack('other_taxon_relationship');
114
          // All relationship types except misapplied_name_for and invalid_designation_for.
115

    
116
          $taxon_relationships_lines[] = cdm_tagged_text_to_markup($taxon_relation->taggedText);
117

    
118
          RenderHints::popFromRenderStack();
119
        }
120
      }
121
    } // END loop over $taxonRelationshipsDTO->relations
122

    
123
  }
124

    
125
  // Sort the $joined_refs and create footnotes and footnote keys.
126
  uasort($joined_refs, function($a, $b) {
127
    if ($a['order_by_key'] == $b['order_by_key']) {
128
      return 0;
129
    }
130
    return ($a['order_by_key'] < $b['order_by_key']) ? -1 : 1;
131
  });
132

    
133

    
134
  foreach ($joined_refs as $ref_key => $sensu_strings) {
135
    if(!empty($sensu_strings)) {
136
      $ref_key_tokens = explode('#', $ref_key);
137
      $sensu_uuid = $ref_key_tokens[0];
138
      $sensu_reference = cdm_ws_get(CDM_WS_REFERENCE, $sensu_uuid);
139
      if(!$sensu_reference){
140
        drupal_set_message("Problem fetching sensu reference with uuid " . $sensu_uuid, 'error');
141
      }
142
      if($sensu_strings['order_by_key'] != $sensu_reference->titleCache){
143
        $sensu_reference_markup = cdm_reference_markup($sensu_reference);
144
        $footnote_key = FootnoteManager::addNewFootnote($footnote_list_key, $sensu_reference_markup);
145
        $footnote_key = render_footnote_key($footnote_key);
146
        $joined_refs[$ref_key]['markup'] = '<span class="sensu">' . $sensu_strings['markup'] . $footnote_key . '</span>';
147
      }
148
    }
149
  }
150

    
151
  // ---- Generate output ---- //
152
  $out = '<div class="taxon-relationships">';
153
  if (count($misapplied) > 0) {
154
    ksort($misapplied); // order the misapplied by scientific name
155
    $out .= '<ul class="misapplied">';
156

    
157
    // create the list entries per misapplied name
158
    foreach ($misapplied as $misapplied_name) {
159
      $misapplied_name_markup = $misapplied_name['out'];
160
      // all sensu and auct. for this MAN
161
      if (isset($misapplied_name['sensu_uuids'])) {
162
        $sensu_refs_with_fkey = array();
163
        foreach ($misapplied_name['sensu_uuids'] as $sensu_data) {
164
          if($sensu_data['uuid']){
165
            $joined_ref_key = $sensu_data['uuid'] . ($sensu_data['citation_detail'] ? '#' .  $sensu_data['citation_detail'] : '');
166
            $sensu_refs_with_fkey[$sensu_data['prefix'] . $joined_refs[$joined_ref_key]['order_by_key']] = $sensu_data['prefix'] . $joined_refs[$joined_ref_key]['markup'];
167
          } else {
168
            $sensu_refs_with_fkey[$sensu_data['prefix']] = $sensu_data['prefix'];
169
          }
170
        }
171
        ksort($sensu_refs_with_fkey);
172
        $sensu_refs_with_fkey_markup = join('; ', $sensu_refs_with_fkey);
173
        if(strpos($misapplied_name_markup, '{PLACEHOLDER_secReference}') !== false){
174
          $misapplied_name_markup = str_replace('{PLACEHOLDER_secReference}', $sensu_refs_with_fkey_markup, $misapplied_name_markup);
175
          // just remove the appendedPhrase placeholder as was included in the sensu_refs_with_fkey_markup
176
          $misapplied_name_markup = str_replace('{PLACEHOLDER_appendedPhrase}', '', $misapplied_name_markup);
177
        } else {
178
          // no sec ref so there could only be the appended phrase
179
          $misapplied_name_markup = str_replace('{PLACEHOLDER_appendedPhrase}', $sensu_refs_with_fkey_markup, $misapplied_name_markup);
180
        }
181
      }
182

    
183
      // append the err. sec. if there is any for this MAN
184
      if (isset($misapplied_name['relsec_uuids'])) {
185
        $relsec_refs_with_fkey = array();
186
        foreach ($misapplied_name['relsec_uuids'] as $relsec_data) {
187
          if($relsec_data['uuid']) {
188
            $relsec_refs_with_fkey[$relsec_data['prefix'] . $joined_refs[$relsec_data['uuid']]['order_by_key']] = $relsec_data['prefix'] . $joined_refs[$relsec_data['uuid']]['markup'];
189
          }
190
        }
191
        ksort($relsec_refs_with_fkey);
192
        $relsec_refs_with_fkey_markup = join('; ', $relsec_refs_with_fkey);
193
        $misapplied_name_markup = str_replace('{PLACEHOLDER_relSecReference}', $relsec_refs_with_fkey_markup, $misapplied_name_markup);
194
      }
195
      // final line
196
      $out .= '<li class="synonym"><span class="misapplied">' . $misapplied_name_markup . ' </span></li>';
197
    }
198
    $out .= '</ul>';
199
  }
200

    
201
  if (isset($taxon_relationships_lines) && is_array($taxon_relationships_lines) && count($taxon_relationships_lines) > 0) {
202
    $out .= '<ul class="taxonRelationships">';
203
    foreach ($taxon_relationships_lines as $taxon_relationship_line) {
204
      $out .= '<li class="synonym">' . $taxon_relationship_line . '</li>';
205
    }
206
    $out .= '</ul>';
207
  }
208

    
209
  $footnotes = render_footnotes($footnote_list_key, 'li');
210

    
211
  $out .= '<ul class="footnotes">' . $footnotes . '</ul>';
212
  $out .= '</div>';
213

    
214
  RenderHints::popFromRenderStack();
215
  return $out;
216
}
217

    
218
/**
219
 * Returns HTML for misapplied names and invalid designations.
220
 *
221
 * Both relation types are currently treated the same!
222
 *
223
 * @param object taxonRelationships
224
 *   A TaxonRelationshipsDTO, see taxon/{uuid}/taxonRelationshipsDTO
225
 *
226
 * @param object focusedTaxon
227
 *  The taxon being in the focus of the application
228
 *
229
 * @return string
230
 *    the rendered html
231
 */
232
function cdm_new_taxonRelationships($taxonRelationshipsDTO, $focusedTaxon){
233

    
234
    static $relationship_type_order_weights = [
235
        //
236
        UUID_PROPARTE_MISAPPLIEDNAME_FOR => 0,
237
        UUID_PARTIAL_MISAPPLIEDNAME_FOR => 0,
238
        //
239
        UUID_MISAPPLIED_NAME_FOR  => 1,
240
        //
241
        UUID_PROPARTE_SYNONYM_FOR  => 2,
242
        UUID_PARTIAL_SYNONYM_FOR  => 2
243
    ];
244

    
245
    if (!$taxonRelationshipsDTO || $taxonRelationshipsDTO->count < 1) {
246
        return null;
247
    }
248

    
249
    static $dedup_rel_type_uuids = array(
250
        UUID_MISAPPLIED_NAME_FOR,
251
        UUID_PARTIAL_MISAPPLIEDNAME_FOR,
252
        UUID_PROPARTE_MISAPPLIEDNAME_FOR
253
    );
254

    
255
    RenderHints::pushToRenderStack('taxon_relationships');
256
    $footnote_list_key = 'taxon_relationships';
257
    RenderHints::setFootnoteListKey($footnote_list_key);
258

    
259
    $misapplied = array();
260
    $joined_refs = array();
261

    
262
    $taxon_relationship_types = variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT));
263

    
264
    // Aggregate misapplied names having the same fullname:
265
    //  - deduplicate misapplied names, so that the same name is not shown multiple times in case
266
    //    the duplicates only have different sensu references with detail and appended phrase (see #5647)
267
    //  - show only the author team as short citation for the sec reference
268
    //  - show the according reference as footnote to this short citation
269
    //
270
    // Example:
271
    // "Xenoxylum foobar" sensu Grumbach¹; sensu Lem²
272
    //    1. Novel marsian species, Grumbach, 2022
273
    //    2. Flora solaris, Lem, 2019
274
   // if (isset($taxonRelationshipsDTO->relations[0])) {
275
    foreach($taxonRelationshipsDTO->items as $taxon_relation){
276

    
277
        if (in_array($taxon_relation->relTypeUuid, $taxon_relationship_types)) {
278

    
279
            if (in_array($taxon_relation->relTypeUuid, $dedup_rel_type_uuids)) {
280

    
281
                RenderHints::pushToRenderStack('misapplied_name_for'); // TODO the render path string should in future come from $taxonRelation->type->...
282

    
283
                // full name with relation symbol, rel sec as de-duplication key
284
                // the sensu part will be removed from the key below in case it is present
285
                $name_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedLabel, array('name')));
286
                $full_name_key = cdm_tagged_text_to_string($taxon_relation->taggedLabel, array('symbol', 'appendedPhrase'));
287
                $symbol_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedLabel, array('symbol')));
288
                $full_name_key = $name_text . ' ' . str_replace($name_text, '', $full_name_key) . ' ' . $symbol_text;
289

    
290
                cdm_new_taxonRelationships_process_relationship_dto($taxon_relation, $misapplied, $joined_refs, $relationship_type_order_weights , $full_name_key);
291

    
292
                RenderHints::popFromRenderStack();
293
            } else {
294
                RenderHints::pushToRenderStack('other_taxon_relationship');
295
                // All relationship types except misapplied_name_for and invalid_designation_for.
296

    
297
                $taxon_relationships_lines[] = cdm_tagged_text_to_markup($taxon_relation->taggedLabel);
298

    
299
                RenderHints::popFromRenderStack();
300
            }
301
        }
302
    } // END loop over $taxonRelationshipsDTO->relations
303

    
304
    //}
305

    
306
    // Sort the $joined_refs and create footnotes and footnote keys.
307
    uasort($joined_refs, function($a, $b) {
308
        if ($a['order_by_key'] == $b['order_by_key']) {
309
            return 0;
310
        }
311
        return ($a['order_by_key'] < $b['order_by_key']) ? -1 : 1;
312
    });
313

    
314

    
315
    foreach ($joined_refs as $ref_key => $sensu_strings) {
316
        if(!empty($sensu_strings)) {
317
            $ref_key_tokens = explode('#', $ref_key);
318
            $sensu_uuid = $ref_key_tokens[0];
319
            //TODO!!!
320
            //$sensu_reference = cdm_ws_get(CDM_WS_REFERENCE, $sensu_uuid);
321
            $sensu_reference = $sensu_strings['markup'];
322
            if(!$sensu_reference){
323
                drupal_set_message("Problem fetching sensu reference with uuid " . $sensu_uuid, 'error');
324
            }
325
            //TODO: Check whether this still needs to be handled
326
           if($sensu_strings['order_by_key'] != $sensu_strings['longCitation']){
327
                $sensu_reference_markup = $sensu_strings['markup'];
328
                $footnote_key = FootnoteManager::addNewFootnote($footnote_list_key, $sensu_reference_markup);
329
                $footnote_key = render_footnote_key($footnote_key);
330
                $joined_refs[$ref_key]['markup'] = '<span class="sensu">' . $sensu_strings['shortCitation'] . $footnote_key . '</span>';
331
           }
332
        }
333
    }
334

    
335
    // ---- Generate output ---- //
336
    $out = '<div class="taxon-relationships">';
337
    if (count($misapplied) > 0) {
338
        ksort($misapplied); // order the misapplied by scientific name
339
        $out .= '<ul class="misapplied">';
340

    
341
        // create the list entries per misapplied name
342
        foreach ($misapplied as $misapplied_name) {
343
            $misapplied_name_markup = $misapplied_name['out'];
344
            // all sensu and auct. for this MAN
345
            if (isset($misapplied_name['sensu_uuids'])) {
346
                $sensu_refs_with_fkey = array();
347
                foreach ($misapplied_name['sensu_uuids'] as $sensu_data) {
348
                    if($sensu_data['uuid']){
349
                        $joined_ref_key = $sensu_data['uuid'] . ($sensu_data['citation_detail'] ? '#' .  $sensu_data['citation_detail'] : '');
350
                        $sensu_refs_with_fkey[$sensu_data['prefix'] . $joined_refs[$joined_ref_key]['shortCitation']] = $sensu_data['prefix'] . $joined_refs[$joined_ref_key]['markup'];
351
                    } else {
352
                        $sensu_refs_with_fkey[$sensu_data['prefix']] = $sensu_data['prefix'];
353
                    }
354
                }
355
                ksort($sensu_refs_with_fkey);
356
                $sensu_refs_with_fkey_markup = join('; ', $sensu_refs_with_fkey);
357
                if(strpos($misapplied_name_markup, '{PLACEHOLDER_secReference}') !== false){
358
                    $misapplied_name_markup = str_replace('{PLACEHOLDER_secReference}', $sensu_refs_with_fkey_markup, $misapplied_name_markup);
359
                    // just remove the appendedPhrase placeholder as was included in the sensu_refs_with_fkey_markup
360
                    $misapplied_name_markup = str_replace('{PLACEHOLDER_appendedPhrase}', '', $misapplied_name_markup);
361
                } else {
362
                    // no sec ref so there could only be the appended phrase
363
                    $misapplied_name_markup = str_replace('{PLACEHOLDER_appendedPhrase}', $sensu_refs_with_fkey_markup, $misapplied_name_markup);
364
                }
365
            }
366

    
367
            // append the err. sec. if there is any for this MAN
368
            if (isset($misapplied_name['relsec_uuids'])) {
369
                $relsec_refs_with_fkey = array();
370
                foreach ($misapplied_name['relsec_uuids'] as $relsec_data) {
371
                    if($relsec_data['uuid']) {
372
                        $relsec_refs_with_fkey[$relsec_data['prefix'] . $joined_refs[$relsec_data['uuid']]['order_by_key']] = $relsec_data['prefix'] . $joined_refs[$relsec_data['uuid']]['markup'];
373
                    }
374
                }
375
                ksort($relsec_refs_with_fkey);
376
                $relsec_refs_with_fkey_markup = join('; ', $relsec_refs_with_fkey);
377
                $misapplied_name_markup = str_replace('{PLACEHOLDER_relSecReference}', $relsec_refs_with_fkey_markup, $misapplied_name_markup);
378
            }
379
            // final line
380
            $out .= '<li class="synonym"><span class="misapplied">' . $misapplied_name_markup . ' </span></li>';
381
        }
382
        $out .= '</ul>';
383
    }
384

    
385
    if (isset($taxon_relationships_lines) && is_array($taxon_relationships_lines) && count($taxon_relationships_lines) > 0) {
386
        $out .= '<ul class="taxonRelationships">';
387
        foreach ($taxon_relationships_lines as $taxon_relationship_line) {
388
            $out .= '<li class="synonym">' . $taxon_relationship_line . '</li>';
389
        }
390
        $out .= '</ul>';
391
    }
392

    
393
    $footnotes = render_footnotes($footnote_list_key, 'li');
394

    
395
    $out .= '<ul class="footnotes">' . $footnotes . '</ul>';
396
    $out .= '</div>';
397

    
398
    RenderHints::popFromRenderStack();
399
    return $out;
400
}
401

    
402

    
403
/**
404
 * @param $taxon_relation
405
 * @param $misapplied
406
 * @param $joined_refs
407
 * @param $relationship_type_weights
408
 * @param $name_dedup_key
409
 */
410
function cdm_taxonRelationships_process_relationship_dto($taxon_relation, &$misapplied, &$joined_refs, $relationship_type_weights, $name_dedup_key) {
411

    
412
  $appended_phrase_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedText, array('appendedPhrase')));
413
  // remove/extract appendedPhrase, secReference, relSecReference and add placeholders if needed
414
  tagged_text_extract($taxon_relation->taggedText, 'appendedPhrase', true);
415
  $sensu_tagged_text = tagged_text_extract_reference_and_detail($taxon_relation->taggedText, "secReference", true);
416
  $relsec_tagged_text = tagged_text_extract_reference_and_detail($taxon_relation->taggedText, "relSecReference", true);
417

    
418
  // prepend the weight value for the relationship type to the $name_dedup_key so that the key can be used for ordering the
419
  // entries in the $misapplied array
420
  if(isset($relationship_type_weights[$taxon_relation->type->uuid])){
421
    $reltype_weight = $relationship_type_weights[$taxon_relation->type->uuid];
422
  } else {
423
    $reltype_weight = 99;
424
  }
425
  $name_dedup_key = str_pad( $reltype_weight, 2, '0', STR_PAD_LEFT) . '-' . $name_dedup_key;
426
  $skipTags = array();
427
  $skipTags[] = "secMicroReference";
428
  if (isset($sensu_tagged_text[1])) {
429
    // for de-duplication everything else needs to be equal except for appendedPhrase + MAN.sec + MAN.secDetail. see #7658#note-21
430
    $name_dedup_key = str_replace(cdm_tagged_text_to_string($sensu_tagged_text), ' ', $name_dedup_key);
431
    $appended_phrase_text = $appended_phrase_text . array_shift($sensu_tagged_text)->text; // remove first element which contains the "sensu", this will be added later in this code
432
    $sensu_citation_detail = trim(join(' ', cdm_tagged_text_values($sensu_tagged_text, array('secMicroReference'))));
433
    //TODO: add footnote placeholder in front of the secMicroReference
434
    $sensu_citation_short_markup = cdm_tagged_text_to_markup($sensu_tagged_text);
435
    //only one footnote for a reference undependent of detail
436
    $sensu_citation_short = cdm_tagged_text_to_string($sensu_tagged_text, array('secMicroReference'));
437
    $sensu_uuid = $sensu_tagged_text[0]->entityReference->uuid;
438
    $name_dedup_key = preg_replace('/\s+/', ' ', $name_dedup_key); // sanitize multiple whitespace characters
439
    $misapplied[$name_dedup_key]['sensu_uuids'][] = array('uuid' => $sensu_uuid, 'prefix' => $appended_phrase_text, 'citation_detail' => $sensu_citation_detail);
440
    $ref_key = $sensu_uuid . ($sensu_citation_detail ? '#' . $sensu_citation_detail : '');
441
    if (!isset($joined_refs[$ref_key])) {
442
      $joined_refs[$ref_key] = array(
443
        'order_by_key' => $sensu_citation_short,
444
        'markup' => $sensu_citation_short_markup // the footnote key will be appended later
445
      );
446
    }
447
  } else if ($appended_phrase_text) {
448
    // appended phrase without reference
449
    $name_dedup_key = preg_replace('/\s+/', ' ', $name_dedup_key); // sanitize multiple whitespace characters
450
    $misapplied[$name_dedup_key]['sensu_uuids'][] = array('uuid' => null, 'prefix' => $appended_phrase_text);
451
  }
452

    
453
  if (isset($relsec_tagged_text[1])) {
454
    $appended_phrase_text = array_shift($relsec_tagged_text)->text; // remove first element which contains the "err. sec", this will be added later in this code
455
    $relsec_citation_detail = trim(join(' ', cdm_tagged_text_values($relsec_tagged_text, array('secMicroReference'))));
456
    $relsec_citation_short_markup = cdm_tagged_text_to_markup($relsec_tagged_text);
457
    $relsec_citation_short = cdm_tagged_text_to_string($relsec_tagged_text, array('secMicroReference'));
458
    $relsec_uuid = $relsec_tagged_text[0]->entityReference->uuid;
459
    $misapplied[$name_dedup_key]['relsec_uuids'][] = array('uuid' => $relsec_uuid, 'prefix' => $appended_phrase_text, 'citation_detail' => $relsec_citation_detail);;
460
    $ref_key = $relsec_uuid . ($relsec_citation_detail ? '#' . $relsec_citation_detail : '');
461
    if (!isset($joined_refs[$ref_key])) {
462
      $joined_refs[$ref_key] = array(
463
        'order_by_key' => $relsec_citation_short,
464
        'markup' => $relsec_citation_short_markup // the footnote key will be appended later
465
      );
466
    }
467
  }
468

    
469
  if (!isset($misapplied[$name_dedup_key]['out'])) {
470
    // helpful for debugging: // cdm_tagged_text_add_options($taxon_relation->taggedText, array(array('filter-type' => 'symbol', 'attributes' => array('title' =>  array($taxon_relation->type->representations[0]->label)))));
471
    $misapplied[$name_dedup_key]['out'] = cdm_tagged_text_to_markup($taxon_relation->taggedText);
472
  } else {
473
    // We need to add the anchors for all of the other misapplied names not
474
    // being rendered explicitly.
475
    $misapplied[$name_dedup_key]['out'] = uuid_anchor($taxon_relation->taxonUuid, $misapplied[$name_dedup_key]['out']);
476
  }
477

    
478
}
479
/**
480
 * @param $taxon_relation
481
 * @param $misapplied
482
 * @param $joined_refs
483
 * @param $relationship_type_weights
484
 * @param $name_dedup_key
485
 */
486
function cdm_new_taxonRelationships_process_relationship_dto($taxon_relation, &$misapplied, &$joined_refs, $relationship_type_weights, $name_dedup_key) {
487

    
488
    $appended_phrase_text = join(' ', cdm_tagged_text_values($taxon_relation->taggedLabel, array('appendedPhrase')));
489
    // remove/extract appendedPhrase, secReference, relSecReference and add placeholders if needed
490
    tagged_text_extract($taxon_relation->taggedLabel, 'appendedPhrase', true);
491
    $sensu_tagged_text = tagged_text_extract_reference_and_detail($taxon_relation->taggedLabel, "secReference", true);
492
    $relsec_tagged_text = tagged_text_extract_reference_and_detail($taxon_relation->taggedLabel, "relSecReference", true);
493

    
494
    // prepend the weight value for the relationship type to the $name_dedup_key so that the key can be used for ordering the
495
    // entries in the $misapplied array
496
    if(isset($relationship_type_weights[$taxon_relation->relTypeUuid])){
497
        $reltype_weight = $relationship_type_weights[$taxon_relation->relTypeUuid];
498
    } else {
499
        $reltype_weight = 99;
500
    }
501
    $name_dedup_key = str_pad( $reltype_weight, 2, '0', STR_PAD_LEFT) . '-' . $name_dedup_key;
502

    
503
    if (isset($sensu_tagged_text[1])) {
504
        // for de-duplication everything else needs to be equal except for appendedPhrase + MAN.sec + MAN.secDetail. see #7658#note-21
505
        $name_dedup_key = str_replace(cdm_tagged_text_to_string($sensu_tagged_text), ' ', $name_dedup_key);
506
        $appended_phrase_text = $appended_phrase_text . array_shift($sensu_tagged_text)->text; // remove first element which contains the "sensu", this will be added later in this code
507
        $sensu_citation_detail = trim(join(' ', cdm_tagged_text_values($sensu_tagged_text, array('secMicroReference'))));
508
        if (isset_not_empty($taxon_relation->secSource) && isset_not_empty($taxon_relation->secSource->label[0])){
509
            $sensu_citation_long = $taxon_relation->secSource->label[0]->label;
510
        }
511
        $sensu_citation_long_markup = render_original_source($taxon_relation->secSource, FALSE);
512
        $sensu_citation_short = cdm_tagged_text_to_string($sensu_tagged_text);
513
        $sensu_citation_short_without_detail = cdm_tagged_text_to_string($sensu_tagged_text, array('secMicroReference'));
514
        $sensu_uuid = $sensu_tagged_text[0]->entityReference->uuid;
515
        $name_dedup_key = preg_replace('/\s+/', ' ', $name_dedup_key); // sanitize multiple whitespace characters
516
        $misapplied[$name_dedup_key]['sensu_uuids'][] = array('uuid' => $sensu_uuid, 'prefix' => $appended_phrase_text, 'citation_detail' => $sensu_citation_detail);
517
        $ref_key = $sensu_uuid . ($sensu_citation_detail ? '#' . $sensu_citation_detail : '');
518
        if (!isset($joined_refs[$ref_key])) {
519
            $joined_refs[$ref_key] = array(
520
                'order_by_key' => $sensu_citation_short_without_detail,
521
                'markup' => $sensu_citation_long_markup,
522
                'shortCitation' => $sensu_citation_short,
523
                'longCitation' => $sensu_citation_long// the footnote key will be appended later
524
            );
525
        }
526
    } else if ($appended_phrase_text) {
527
        // appended phrase without reference
528
        $name_dedup_key = preg_replace('/\s+/', ' ', $name_dedup_key); // sanitize multiple whitespace characters
529
        $misapplied[$name_dedup_key]['sensu_uuids'][] = array('uuid' => null, 'prefix' => $appended_phrase_text);
530
    }
531

    
532
    if (isset($relsec_tagged_text[1])) {
533
        $appended_phrase_text = array_shift($relsec_tagged_text)->text; // remove first element which contains the "err. sec", this will be added later in this code
534
        $relsec_citation_detail = trim(join(' ', cdm_tagged_text_values($relsec_tagged_text, array('secMicroReference'))));
535
        $relsec_citation_long_markup = render_original_source($taxon_relation->relSource, FALSE);
536
        if (isset_not_empty($taxon_relation->relSource) && isset_not_empty($taxon_relation->relSource->label[0])){
537
            $relsec_citation_long = $taxon_relation->relSource->label[0]->label;
538
        }
539
        $relsec_citation_short_without_detail = cdm_tagged_text_to_string($relsec_tagged_text, array('secMicroReference'));
540
        $relsec_citation_short = cdm_tagged_text_to_string($relsec_tagged_text);
541
        $relsec_uuid = $relsec_tagged_text[0]->entityReference->uuid;
542
        $misapplied[$name_dedup_key]['relsec_uuids'][] = array('uuid' => $relsec_uuid, 'prefix' => $appended_phrase_text, 'citation_detail' => $relsec_citation_detail);;
543
        $ref_key = $relsec_uuid . ($relsec_citation_detail ? '#' . $relsec_citation_detail : '');
544
        if (!isset($joined_refs[$ref_key])) {
545
            $joined_refs[$ref_key] = array(
546
                'order_by_key' => $relsec_citation_short_without_detail,
547
                'markup' => $relsec_citation_long_markup,
548
                'shortCitation' => $relsec_citation_short,
549
                'longCitation' => $relsec_citation_long// the footnote key will be appended later
550
            );
551
        }
552
    }
553

    
554
    if (!isset($misapplied[$name_dedup_key]['out'])) {
555
        // helpful for debugging: // cdm_tagged_text_add_options($taxon_relation->taggedText, array(array('filter-type' => 'symbol', 'attributes' => array('title' =>  array($taxon_relation->type->representations[0]->label)))));
556
        $misapplied[$name_dedup_key]['out'] = cdm_tagged_text_to_markup($taxon_relation->taggedLabel);
557
        $misapplied[$name_dedup_key]['out'] = uuid_anchor($taxon_relation->relTaxonUuid, $misapplied[$name_dedup_key]['out']);
558
    } else {
559
        // We need to add the anchors for all of the other misapplied names not
560
        // being rendered explicitly. TODO!!
561
       // $misapplied[$name_dedup_key]['out'] = uuid_anchor($taxon_relation->taxonUuid, $misapplied[$name_dedup_key]['out']);
562
    }
563

    
564
}
565

    
566

    
567
/**
568
 * Renders a representation of the given taxon relationship.
569
 *
570
 * According name relationships are also being rendered.
571
 *
572
 * @param $taxon
573
 *  The CDM TaxonBase entity
574
 * @param $reltype_uuid
575
 *  The UUID of the TaxonRelationshipType
576
 * @param $relsign
577
 *  Optional. Can be  used to override the internal decision strategy on finding a suitable icon for the relationship
578
 * @param $reltype_representation
579
 *   Optional: Defines the value for the title attribute of the html element enclosing the relsign
580
 * @param $doubtful
581
 *   TODO
582
 * @param $doLinkTaxon
583
 *   The taxon will be rendered as clickable link when true.
584
 *
585
 * @return string
586
 *   Markup for the taxon relationship.
587
 *
588
 * @throws Exception
589
 */
590
function cdm_related_taxon($taxon, $reltype_uuid = NULL) {
591
  static $relsign_homo = '≡';
592
  static $relsign_hetero = '=';
593
  static $relsign_invalid = '&ndash;';
594
  static $nom_status_invalid_type_uuids =  array(
595
    UUID_NOMENCLATURALSTATUS_TYPE_INVALID,
596
    UUID_NOMENCLATURALSTATUS_TYPE_NUDUM,
597
    UUID_NOMENCLATURALSTATUS_TYPE_COMBINATIONINVALID,
598
    UUID_NOMENCLATURALSTATUS_TYPE_PROVISIONAL
599
  );
600

    
601
  // 'taxonRelationships';
602
  $footnoteListKey = NULL;
603

    
604
  $skip_render_template_keys = array();
605

    
606
  $is_invalid = false;
607

    
608

    
609
  switch ($reltype_uuid) {
610
    case UUID_HETEROTYPIC_SYNONYM_OF:
611
    case UUID_SYNONYM_OF:
612
      $relsign = $relsign_hetero;
613
      break;
614

    
615
    case UUID_HOMOTYPIC_SYNONYM_OF:
616
      $relsign = $relsign_homo;
617
      break;
618

    
619
    case UUID_MISAPPLIED_NAME_FOR:
620
      $skip_render_template_keys[] = 'nameAuthorPart';
621
      $is_invalid = true;
622
      $relsign = $relsign_invalid;
623

    
624
      break;
625

    
626
    default:
627
      $relsign = $relsign_invalid;
628
  }
629

    
630

    
631
  /*
632
  Names with status invalid or nudum are to be displayed with the
633
  $relsign_invalid, these names appear at the end of all names in their
634
  homotypic group (ordered correctly by the java cdm_lib).
635
  */
636
  if (isset($taxon->name->status) && is_array($taxon->name->status)) {
637
    foreach ($taxon->name->status as $status) {
638
      if (in_array($status->type->uuid , $nom_status_invalid_type_uuids)) {
639
        $relsign = $relsign_invalid;
640
        break;
641
      }
642
    }
643
  }
644

    
645
  // Now rendering starts ..
646
  RenderHints::pushToRenderStack('related_taxon');
647

    
648
  if (isset($taxon->name->nomenclaturalSource->citation)) {
649
    $referenceUri = url(path_to_reference($taxon->name->nomenclaturalSource->citation->uuid));
650
  }
651
  $taxonUri = '';
652

    
653
  // Printing the taxonName and the handling the special case of annotations.
654
  if (!isset($referenceUri)) {
655
    $referenceUri = FALSE;
656
  }
657
  $out_taxon_part = render_taxon_or_name($taxon, $taxonUri, $referenceUri, TRUE, TRUE, FALSE, $skip_render_template_keys, $is_invalid);
658
  $name_relations = cdm_name_relationships_for_taxon($taxon);
659
  $name_relations_render_array = compose_name_relationships_inline($name_relations, $taxon->name->uuid, $taxon->uuid);
660

    
661
  $out = '<span class="relation_sign">' . $relsign . '</span>'
662
    . $out_taxon_part;
663
  if(isset($name_relations_render_array['list']['items'][0])){
664
    $out .= ' '  . drupal_render($name_relations_render_array);
665
  }
666

    
667
  $out = uuid_anchor($taxon->uuid, $out);
668

    
669
  RenderHints::popFromRenderStack();
670

    
671
  return $out;
672
}
673
/**
674
 * Renders a representation of the given taxon relationship.
675
 *
676
 * According name relationships are also being rendered.
677
 *
678
 * @param $taxon_dto
679
 *  The CDM TaxonBase dto
680
 * @param $reltype_uuid
681
 *  The UUID of the TaxonRelationshipType
682
 * @param $relsign
683
 *  Optional. Can be  used to override the internal decision strategy on finding a suitable icon for the relationship
684
 * @param $reltype_representation
685
 *   Optional: Defines the value for the title attribute of the html element enclosing the relsign
686
 * @param $doubtful
687
 *   TODO
688
 * @param $doLinkTaxon
689
 *   The taxon will be rendered as clickable link when true.
690
 *
691
 * @return string
692
 *   Markup for the taxon relationship.
693
 *
694
 * @throws Exception
695
 */
696
function cdm_new_related_taxon($taxon_dto, $reltype_uuid = NULL) {
697
    static $relsign_homo = '≡';
698
    static $relsign_hetero = '=';
699
    static $relsign_invalid = '&ndash;';
700
    static $nom_status_invalid_type_uuids =  array(
701
        UUID_NOMENCLATURALSTATUS_TYPE_INVALID,
702
        UUID_NOMENCLATURALSTATUS_TYPE_NUDUM,
703
        UUID_NOMENCLATURALSTATUS_TYPE_COMBINATIONINVALID,
704
        UUID_NOMENCLATURALSTATUS_TYPE_PROVISIONAL
705
    );
706

    
707
    // 'taxonRelationships';
708
    $footnoteListKey = NULL;
709

    
710
    $skip_render_template_keys = array();
711

    
712
    $is_invalid = false;
713

    
714

    
715
    switch ($reltype_uuid) {
716
        case UUID_HETEROTYPIC_SYNONYM_OF:
717
        case UUID_SYNONYM_OF:
718
            $relsign = $relsign_hetero;
719
            break;
720

    
721
        case UUID_HOMOTYPIC_SYNONYM_OF:
722
            $relsign = $relsign_homo;
723
            break;
724

    
725
        case UUID_MISAPPLIED_NAME_FOR:
726
            $skip_render_template_keys[] = 'nameAuthorPart';
727
            $is_invalid = true;
728
            $relsign = $relsign_invalid;
729

    
730
            break;
731

    
732
        default:
733
            $relsign = $relsign_invalid;
734
    }
735

    
736

    
737
    /*
738
    Names with status invalid or nudum are to be displayed with the
739
    $relsign_invalid, these names appear at the end of all names in their
740
    homotypic group (ordered correctly by the java cdm_lib).
741
    */
742
    //TODO: how it is implemented in new dto???
743
    if (isset($taxon_dto->taggedLabel) ) {
744
        //if ()
745
    }
746

    
747
    // Now rendering starts ..
748
    RenderHints::pushToRenderStack('related_taxon');
749
//TODO: actually the uuid of the nomenclatural source is not available in taxon dto
750
    /*if (isset($taxon_dto->name->nomenclaturalSource->citation)) {
751
        $referenceUri = url(path_to_reference($taxon->name->nomenclaturalSource->citation->uuid));
752
    }*/
753
    $taxonUri = '';
754

    
755
    // Printing the taxonName and the handling the special case of annotations.
756
    if (!isset($referenceUri)) {
757
        $referenceUri = FALSE;
758
    }
759
    $out_taxon_part = render_new_taxon_or_name($taxon_dto, true, $taxonUri, $referenceUri, TRUE, FALSE, $skip_render_template_keys, $is_invalid);
760
    $name_relations = cdm_name_relationships_for_taxon_new($taxon_dto);
761
    //TODO the name uuid is not available!!!
762
    $name_relations_render_array = compose_new_name_relationships_inline($name_relations, $taxon_dto->uuid, $taxon_dto->nameType);
763

    
764
    $out = '<span class="relation_sign">' . $relsign . '</span>'
765
        . $out_taxon_part;
766
    if(isset($name_relations_render_array['list']['items'][0])){
767
        $out .= ' '  . drupal_render($name_relations_render_array);
768
    }
769

    
770
    $out = uuid_anchor($taxon_dto->uuid, $out);
771

    
772
    RenderHints::popFromRenderStack();
773

    
774
    return $out;
775
}
776
/**
777
 * Creates markup for a taxon which is the accepted of another one
778
 *
779
 * @param $accepted_for_uuid
780
 *   The uuid of the accepted taxon
781
 */
782
function cdm_accepted_for($accepted_for_uuid) {
783

    
784
  if(!is_uuid($accepted_for_uuid)){
785
    return '';
786
  }
787

    
788
  RenderHints::pushToRenderStack('acceptedFor');
789
  $out = '';
790

    
791
  $synonym = cdm_ws_get(CDM_WS_PORTAL_TAXON, $accepted_for_uuid);
792
  if ($synonym) {
793
    $out .= '<span class="acceptedFor">';
794
    $out .= t('is accepted for ');
795
    $referenceUri = null;
796
    if (isset($synonym->name->nomenclaturalSource->citation)) {
797
      $referenceUri = url(path_to_reference($synonym->name->nomenclaturalSource->citation->uuid));
798
    }
799
    $out .= render_taxon_or_name($synonym->name, NULL, $referenceUri);
800
    RenderHints::setAnnotationsAndSourceConfig(synonymy_annotations_and_source_config());
801
    $annotations_and_sources = handle_annotations_and_sources($synonym);
802
    $out .= $annotations_and_sources->footNoteKeysMarkup();
803
    $out .= '</span>';
804
  }
805
  RenderHints::popFromRenderStack();
806
  return $out;
807
}
808

    
809
/**
810
 * Compose function for a list of taxa.
811
 *
812
 * This function is for used to:
813
 *
814
 * 1. Display search results
815
 * 2. List the taxa for a taxon name in the name page.
816
 *
817
 * @param $taxon_list array
818
 *   The list of CDM Taxon entities. e.g. The records array as contained in a pager object.
819
 * @param $freetext_search_results array
820
 * @param $show_classification boolean
821
 *
822
 * @ingroup compose
823
 */
824
function compose_list_of_taxa($taxon_list, $freetext_search_results = array(), $show_classification = false) {
825

    
826
    RenderHints::pushToRenderStack('list_of_taxa');
827

    
828
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SEARCH_GALLERY_NAME);
829

    
830
    $showMedia_taxa = $gallery_settings['cdm_dataportal_show_taxon_thumbnails'];
831
    $showMedia_synonyms = $gallery_settings['cdm_dataportal_show_synonym_thumbnails'];
832
    $searched_in_classification = cdm_dataportal_searched_in_classification();
833
    $searched_in_classification_uuid = null;
834
    if(isset($searched_in_classification->uuid)){
835
        $searched_in_classification_uuid = $searched_in_classification->uuid;
836
    }
837

    
838
    // .. Well, for sure not as performant as before, but better than nothing.
839
    $synonym_uuids = array();
840
    $misapplied_uuids = array();
841
    foreach ($taxon_list as $taxon) {
842
        if ($taxon->class == "Synonym") {
843
            if (!array_key_exists($taxon->uuid, $synonym_uuids)) {
844
                $synonym_uuids[$taxon->uuid] = $taxon->uuid;
845
            }
846
        }
847
        elseif (!_cdm_dataportal_acceptedByCurrentView($taxon)) {
848
            // Assuming that it is a misapplied name, will be further examined below.
849
            $misapplied_uuids[$taxon->uuid] = $taxon->uuid;
850
        }
851
    }
852

    
853
    // Batch service not jet implemented:
854
    // $table_of_accepted = cdm_ws_property(CDM_WS_PORTAL_TAXON_ACCEPTED,
855
    // join(',', $synonym_uuids));
856
    // thus ...
857
    $table_of_accepted = array();
858

    
859
    foreach ($synonym_uuids as $misapplication_uuid) {
860
        $classification_filter = '';
861
        if($searched_in_classification_uuid){
862
            $classification_filter = 'classificationFilter=' . $searched_in_classification_uuid;
863
        }
864
        $table_of_accepted[$misapplication_uuid] = cdm_ws_get(
865
            CDM_WS_PORTAL_TAXON_ACCEPTED,
866
            array($misapplication_uuid),
867
            $classification_filter
868
        );
869
    }
870

    
871
    foreach ($misapplied_uuids as $mispplication_uuid) {
872
        $taxonRelationsDTO = cdm_ws_get(CDM_WS_PORTAL_TAXON_RELATIONS_DTO, array(
873
            $mispplication_uuid,
874
        ));
875
        if(isset($taxonRelationsDTO->relations)){
876
            foreach ($taxonRelationsDTO->relations as $relation) {
877
                if ($relation->type->uuid == UUID_MISAPPLIED_NAME_FOR && _cdm_dataportal_matches_current_view($relation->classificationsUUIDs)) {
878
                    $table_of_accepted[$mispplication_uuid][] = cdm_ws_get(CDM_WS_TAXON, $relation->taxonUuid);
879
                }
880
            }
881
        }
882
    }
883

    
884
    $out = '<div class="cdm-item-list" style="background-image: none;">';
885
    $itemCnt = -1;
886
    foreach ($taxon_list as $taxon) {
887
        $itemCnt++;
888

    
889
        if (isset($table_of_accepted[$taxon->uuid])) {
890
            // Its a synonym or misapplied name.
891
            $is_synonym = isset($synonym_uuids[$taxon->uuid]); //TODO better use the $taxon->class attribute?
892
            $taxon_type = $is_synonym ? TAXON_TYPE_SYNONYM :TAXON_TYPE_MISAPPLIEDNAME;
893

    
894
            $acceptedTaxa = $table_of_accepted[$taxon->uuid];
895

    
896
            if (!is_array($acceptedTaxa)) {
897
                $acceptedTaxa = array($acceptedTaxa);
898
            }
899

    
900
            foreach ($acceptedTaxa as $acceptedTaxon) {
901
                if (is_object($acceptedTaxon)) {
902

    
903
                    $taxonUri = uri_to_synonym($taxon->uuid, $acceptedTaxon->uuid);
904
                    $referenceUri = '';
905
                    if (isset($acceptedTaxon->name->nomenclaturalSource->citation)) {
906
                        $referenceUri = url(path_to_reference($acceptedTaxon->name->nomenclaturalSource->citation->uuid));
907
                    }
908
                    $skip_render_template_parts = $is_synonym ? ['secReferencePart'] : [];
909
                    // $taxon_or_name this is a trick to suppress the sec reference for synonyms
910
                    // supplying the name will cause render_taxon_or_name() to not show the sec reference
911
                    $out .= "<div class=\"item " . $taxon_type . "\">" . render_taxon_or_name($taxon, $taxonUri, $referenceUri, true, false, $skip_render_template_parts);
912
                    if($taxon_type == TAXON_TYPE_MISAPPLIEDNAME && isset_not_empty($taxon->secSource) && isset_not_empty($taxon->secSource->citation)) {
913
                        if (isset($taxon->secSource->citation->authorship)) {
914
                            $authorship = $taxon->secSource->citation->authorship->titleCache;
915
                        }
916
                        else {
917
                            $authorship = $taxon->secSource->citation->titleCache;
918
                        }
919
                        $out .= ' sensu ' . $authorship;
920
                    }
921
                    if ($show_classification) {
922
                        $out .= render_classifications_for_taxon($taxon);
923
                    }
924
                    if ($showMedia_synonyms) {
925
                        $out .= theme('cdm_taxon_list_thumbnails', array('taxon' => $acceptedTaxon));
926
                    }
927
                }
928
            }
929
        }
930
        else {
931
            // Its a Taxon.
932
            $taxonUri = url(path_to_taxon($taxon->uuid));
933
            $referenceUri = '';
934
            if (isset($taxon->name->nomenclaturalSource->citation)) {
935
                $referenceUri = url(path_to_reference($taxon->name->nomenclaturalSource->citation->uuid));
936
            }
937
            $out .= '<div class="item Taxon">' . render_taxon_or_name($taxon, $taxonUri, $referenceUri, false);
938
            if ($show_classification) {
939
                $out .= render_classifications_for_taxon($taxon);
940
            }
941
            if ($showMedia_taxa) {
942
                $out .= theme('cdm_taxon_list_thumbnails', array('taxon' => $taxon));
943
            }
944
        }
945

    
946
        /*
947
         * the score field will be empty in case of MultiTermQueries like
948
         * WildcardQueries, since these are  constant score by default
949
         * since Lucene 2.9
950
         */
951
        if(isset($freetext_search_results[$itemCnt]) && $freetext_search_results[$itemCnt]->score && $freetext_search_results[$itemCnt]->maxScore){
952
            $percentage =  ( $freetext_search_results[$itemCnt]->score / $freetext_search_results[$itemCnt]->maxScore ) * 100;
953
            $out .= '<div class="score-bar"><div class="score-bar-indicator" style="width:' . $percentage .'% "></div></div>';
954
            $out .= '<div class="score-bar-value">' . number_format($percentage, 2) .'%</div>';
955
        }
956

    
957
        // Render highlighted fragments, these are made available by free text
958
        // searches.
959
        if (isset($freetext_search_results[$itemCnt]->fieldHighlightMap)) {
960
            $field_fragments = (array) $freetext_search_results[$itemCnt]->fieldHighlightMap;
961
            if (count($field_fragments) > 0) {
962
                $fragments_out = '';
963
                foreach ($field_fragments as $fieldName => $fragments) {
964
                    $fragments_out .= '... <span class="' . $fieldName. '">' . filter_xss(join(" ... ", $fragments), array('b') ) . '</span>';
965
                }
966
                $out .= '<div class="fragment_highlight">' . $fragments_out . ' ...</div>';
967
            }
968
        }
969

    
970
        $out .= '</div>';
971
    }
972

    
973
    $out .= '</div>';
974
    RenderHints::popFromRenderStack();
975

    
976
    return markup_to_render_array($out); // TODO create render array of all list items in function
977
}
978

    
979
/**
980
 * Compose function for a list of taxa.
981
 *
982
 * This function is for used to:
983
 *
984
 * 1. Display search results
985
 * 2. List the taxa for a taxon name in the name page.
986
 *
987
 * @param $taxon_list array
988
 *   The list of CDM Taxon entities. e.g. The records array as contained in a pager object.
989
 * @param $freetext_search_results array
990
 * @param $show_classification boolean
991
 *
992
 * @ingroup compose
993
 */
994
function compose_list_of_taxon_search_result($taxon_list, $freetext_search_results = array(), $show_classification = false) {
995

    
996
    RenderHints::pushToRenderStack('list_of_taxa');
997

    
998
    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SEARCH_GALLERY_NAME);
999

    
1000
    $showMedia_taxa = $gallery_settings['cdm_dataportal_show_taxon_thumbnails'];
1001
    $showMedia_synonyms = $gallery_settings['cdm_dataportal_show_synonym_thumbnails'];
1002
    $searched_in_classification = cdm_dataportal_searched_in_classification();
1003
    $searched_in_classification_uuid = null;
1004
    if(isset($searched_in_classification->uuid)){
1005
        $searched_in_classification_uuid = $searched_in_classification->uuid;
1006
    }
1007

    
1008
    // .. Well, for sure not as performant as before, but better than nothing.
1009
    $misapplied_uuids = array();
1010
    foreach ($taxon_list as $taxon) {
1011
        if ($taxon->entity->class == 'Taxon' && !_cdm_dataportal_acceptedByCurrentView($taxon)) {
1012
            // Assuming that it is a misapplied name, will be further examined below.
1013
            $misapplied_uuids[$taxon->entity->uuid] = $taxon->entity->uuid;
1014
        }
1015
    }
1016

    
1017
    // Batch service not jet implemented:
1018
    // $table_of_accepted = cdm_ws_property(CDM_WS_PORTAL_TAXON_ACCEPTED,
1019
    // join(',', $synonym_uuids));
1020
    // thus ...
1021
    $table_of_accepted = array();
1022
    foreach ($misapplied_uuids as $mispplication_uuid) {
1023
        $taxonRelationsDTO = cdm_ws_get(CDM_WS_PORTAL_TAXON_RELATIONS_DTO, array(
1024
            $mispplication_uuid,
1025
        ));
1026
        if(isset($taxonRelationsDTO->relations)){
1027
            $taxon_relationship_types = variable_get(CDM_TAXON_RELATIONSHIP_TYPES, unserialize(CDM_TAXON_RELATIONSHIP_TYPES_DEFAULT));
1028
            foreach ($taxonRelationsDTO->relations as $relation) {
1029
                if (in_array($relation->type->uuid, $taxon_relationship_types) && in_array($searched_in_classification->uuid,$relation->classificationsUUIDs)  )  {
1030
                //if (($relation->type->uuid == UUID_MISAPPLIED_NAME_FOR || $relation->typeUuid == UUID_MISAPPLIED_NAME_FOR || $relation->type->uuid == UUID_PROPARTE_SYNONYM_FOR || $relation->typeUuid == UUID_PROPARTE_SYNONYM_FOR) && _cdm_dataportal_matches_current_view($relation->classificationsUUIDs)) {
1031
                 //   $table_of_accepted[$mispplication_uuid][] = cdm_ws_get(CDM_WS_TAXON, $relation);
1032
                    $table_of_accepted[$mispplication_uuid][] = $relation;
1033
                }
1034
            }
1035
        }
1036
    }
1037

    
1038
    $out = '<div class="cdm-item-list" style="background-image: none;">';
1039
    $itemCnt = -1;
1040
    foreach ($taxon_list as $taxon) {
1041
        $itemCnt++;
1042
       if ($taxon->entity->class == "Synonym") {
1043
        $synonym = $taxon;
1044
        $taxonUri = uri_to_synonym($synonym->entity->uuid, $synonym->acceptedTaxonUuid);
1045
        $taxon_type = TAXON_TYPE_SYNONYM;
1046
        $out .=createOutput($taxon_type, $taxon, $taxonUri, "");
1047
       }else {
1048
         if (isset($table_of_accepted[$taxon->entity->uuid])) {
1049
           // Its a misapplied name.
1050
           $taxon_type = TAXON_TYPE_MISAPPLIEDNAME;
1051
           $relations = $table_of_accepted[$taxon->entity->uuid];
1052

    
1053
           if (!is_array($relations)) {
1054
               $relations = array($relations);
1055
           }
1056
           $taxa_count = count($relations)-1;
1057
           $index = 0;
1058
           foreach ($relations as $relation) {
1059
             if (is_object($relation)) {
1060
                 $taxonUri = uri_to_synonym($taxon->entity->uuid, $relation->taxonUuid);
1061
                 $referenceUri = '';
1062
                 //if (isset($acceptedTaxon->name->nomenclaturalSource->citation)) {
1063
                 //    $referenceUri = url(path_to_reference($acceptedTaxon->name->nomenclaturalSource->citation->uuid));
1064
                 //}
1065
                 $out .= createOutput($taxon_type, $taxon, $taxonUri, $referenceUri);
1066
                 $out .= " as ". cdm_tagged_text_to_markup($relation->taggedText, ['reference', 'secReference', 'relSecReference']);
1067
                 if ($index<$taxa_count) {
1068
                     $out .= "</div>";
1069
                 }
1070
                 $index++;
1071
             }
1072
           }
1073
         }else{
1074
           if (isset_not_empty($taxon->entity) && isset_not_empty($taxon->entity->uuid)){
1075
              $taxonUri = url(path_to_taxon($taxon->entity->uuid));
1076
              $taxon_type = "Taxon";                                                                                                                             
1077
              $referenceUri = '';                                                                                                                                
1078
              if (isset_not_empty($taxon->entity->name->nomenclaturalSource) && isset_not_empty($taxon->entity->name->nomenclaturalSource->citation)) {          
1079
                 $referenceUri = url(path_to_reference($taxon->entity->name->nomenclaturalSource->citation->uuid));                                              
1080
              }                                                                                                                                                  
1081
              $out .= createOutput($taxon_type, $taxon, $taxonUri, $referenceUri);                                                                               
1082
           }
1083
         }
1084

    
1085
        }
1086

    
1087
        //$out .= '<div class="item Taxon">' . render_taxon_or_name($taxon, $taxonUri, $referenceUri, false);
1088
       // $out = createOutput($taxon_type, $taxon, $taxonUri, $referenceUri, $out);
1089
        if ($show_classification) {
1090
            $out .= render_classifications_for_taxon($taxon-> entity);
1091
        }
1092
        if ($showMedia_taxa) {
1093
            $out .= theme('cdm_taxon_list_thumbnails', array('taxon' => $taxon));
1094
        }
1095

    
1096
        
1097

    
1098
        /*
1099
         * the score field will be empty in case of MultiTermQueries like
1100
         * WildcardQueries, since these are  constant score by default
1101
         * since Lucene 2.9
1102
         */
1103
        if(isset($freetext_search_results[$itemCnt]) && $freetext_search_results[$itemCnt]->score && $freetext_search_results[$itemCnt]->maxScore){
1104
            $percentage =  ( $freetext_search_results[$itemCnt]->score / $freetext_search_results[$itemCnt]->maxScore ) * 100;
1105
            $out .= '<div class="score-bar"><div class="score-bar-indicator" style="width:' . $percentage .'% "></div></div>';
1106
            $out .= '<div class="score-bar-value">' . number_format($percentage, 2) .'%</div>';
1107
        }
1108

    
1109
        // Render highlighted fragments, these are made available by free text
1110
        // searches.
1111
        if (isset($freetext_search_results[$itemCnt]->fieldHighlightMap)) {
1112
            $field_fragments = (array) $freetext_search_results[$itemCnt]->fieldHighlightMap;
1113
            if (count($field_fragments) > 0) {
1114
                $fragments_out = '';
1115
                foreach ($field_fragments as $fieldName => $fragments) {
1116
                    $fragments_out .= '... <span class="' . $fieldName. '">' . filter_xss(join(" ... ", $fragments), array('b') ) . '</span>';
1117
                }
1118
                $out .= '<div class="fragment_highlight">' . $fragments_out . ' ...</div>';
1119
            }
1120
        }
1121

    
1122
        $out .= '</div>';
1123
    }
1124

    
1125
    $out .= '</div>';
1126
    RenderHints::popFromRenderStack();
1127

    
1128
    return markup_to_render_array($out); // TODO create render array of all list items in function
1129
}
1130

    
1131
/**
1132
 * @param string $taxon_type
1133
 * @param mixed $taxon
1134
 * @param string $taxonUri
1135
 * @param string $referenceUri
1136
 * @param string $out
1137
 * @return string
1138
 */
1139
function createOutput($taxon_type, $taxon, $taxonUri, $referenceUri): string
1140
{
1141
    $out = "";
1142
    $skip_render_template_parts = $taxon_type == TAXON_TYPE_SYNONYM ? ['secReferencePart'] : [];
1143
    $skip_render_template_parts = $taxon_type == TAXON_TYPE_MISAPPLIEDNAME ? ['referencePart', 'secReferencePart'] : [];
1144
    $out .= "<div class=\"item " . $taxon_type . "\">" . render_new_taxon_or_name($taxon, true, $taxonUri, $referenceUri, false, false, false, $skip_render_template_parts);
1145
    return $out;
1146
}
1147

    
1148

    
1149
function render_classifications_for_taxon($taxon) {
1150
  $unclassified_snippet = '<span class="unclassified">' . t('unclassified') . '</span>';
1151

    
1152
  $classifications = get_classifications_for_taxon($taxon);
1153
  $classification_titles = array();
1154
  foreach ($classifications as $classification) {
1155
    if (isset($classification->titleCache)) {
1156
      $classification_titles[] = $classification->titleCache;
1157
    }
1158
  }
1159
  if (count($classification_titles) == 0) {
1160
    $classification_titles[] = $unclassified_snippet;
1161
  }
1162
  return '<span class="classifications"><span class="separator"> : </span>' . implode(', ', $classification_titles) . '</span>';
1163
}
1164

    
1165
/**
1166
 * Compose function for the taxonomic children
1167
 *
1168
 * @param $taxon_uuid
1169
 *    The uuuid of the taxon to compose the list of taxonomic children for
1170
 * @return
1171
 *   A drupal render array.
1172
 *
1173
 * @ingroup compose
1174
 */
1175
function compose_taxonomic_children($taxon_uuid){
1176

    
1177
  $render_array = array();
1178
  
1179
  if($taxon_uuid) {
1180
    $children = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1181
      get_current_classification_uuid(),
1182
      $taxon_uuid
1183
      ));
1184
    if($children){
1185
      $taxonomic_children = theme('cdm_taxontree', array('tree' => $children));
1186
      $render_array = markup_to_render_array($taxonomic_children);
1187
    }
1188
  }
1189
  return $render_array;
1190
}
1191

    
(15-15/16)