Project

General

Profile

Download (57 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Page functions.
5
 *
6
 * @copyright
7
 *   (C) 2007-2012 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
/**
21
 * Creates a render array representing the ocurrences associetad with the $taxon.
22
 *
23
 * The resulting render array contains two elements:
24
 *  - 'map': A map showing all point locations of the occurences is availabale
25
 *  - 'specimen_list': the list of occurences prepated as table for theme_table()
26
 *
27
 * @param object $taxon
28
 *   A cdm Taxon object
29
 * @return
30
 *   A render array suitable for drupal_render()
31
 *
32
 */
33
function cdm_dataportal_taxon_page_specimens($taxon) {
34

    
35
    $render_array = array();
36
    RenderHints::pushToRenderStack('taxon_page_specimens');
37

    
38
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
39
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
40
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
41

    
42
    $by_associatedtaxon_query_parameters = array(
43
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
44
        'relationships' => implode(',', $relationship_choice['direct']),
45
    );
46

    
47
    if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
48
        $by_associatedtaxon_query_parameters = array_merge($by_associatedtaxon_query_parameters, $_REQUEST['pager']);
49
    }
50

    
51
    $by_associatedtaxon_query = http_build_query($by_associatedtaxon_query_parameters);
52

    
53
    $ws_string = 'specimensOrObservation';
54
    if (variable_get('cdm_dataportal_specimen_derivate_tree')){
55
        $ws_string .= "DTOs";
56
    }else{
57
        $ws_string .= "s";
58
    }
59

    
60
    $specimensOrObservations = cdm_ws_get(CDM_WS_TAXON, array( $taxon->uuid, $ws_string));
61
    if(!variable_get('cdm_dataportal_specimen_derivate_tree')) {
62
        $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
63
            null,
64
            $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
65
        );
66
        $specimensOrObservations = array();
67
        if (isset($pager->records[0])) {
68
            $specimensOrObservations = $pager->records;
69
        }
70
    }
71
     // cdm_ws_get(CDM_WS_OCCURRENCE_FIELDUNIT_DTO_BY_ASSOCIATEDTAXON,
72
     // null,
73
     // $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
74
    // );
75

    
76
   // $specimensOrObservations = array();
77
   // if(isset($pager->records[0])){
78
    //    $specimensOrObservations =  $pager->records;
79
   // }
80

    
81
    // order occurrences by date but types should be on top of the list
82
    $type_specimens = array();
83
    $other_occurrences = array();
84
    foreach ($specimensOrObservations as $occurrence) {
85
       $typeDesignationsPager = cdm_ws_get(CDM_WS_OCCURRENCE . '/$0/specimenTypeDesignations', $occurrence->uuid);
86
        if (isset($typeDesignationsPager->count) && $typeDesignationsPager->count > 0) {
87
            $type_specimens[] = $occurrence;
88
       } else {
89
           $other_occurrences[] = $occurrence;
90
        }
91
    }
92
    $specimensOrObservations = array_merge($type_specimens, $other_occurrences);
93

    
94
    // Collect media (fieldObjectMedia, derivedUnitMedia) and add as a custom field
95
    if (!variable_get('cdm_dataportal_specimen_derivate_tree')) {
96
        foreach ($specimensOrObservations as &$occurrence) {
97
            $occurrence->_fieldObjectMedia = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, array(
98
                $occurrence->uuid,
99
                'fieldObjectMediaDTO',
100
            ));
101
            $occurrence->_derivedUnitMedia = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, array(
102
                $occurrence->uuid,
103
                'derivedUnitMedia',
104
            ));
105
        }
106
    }
107

    
108
    // --- get map service HTTP query parameters
109

    
110
    if (count($specimensOrObservations) > 0) {
111

    
112
        $occurrence_queryDto = cdm_ws_get(CDM_WS_GEOSERVICE_OCCURRENCEMAP, $taxon->uuid, $by_associatedtaxon_query);
113

    
114
        $map_visibility = variable_get(SPECIMEN_MAP_VISIBILITY, SPECIMEN_MAP_VISIBILITY_DEFAULT);
115
        if ($map_visibility == 'always' ||
116
            variable_get(SPECIMEN_MAP_VISIBILITY, SPECIMEN_MAP_VISIBILITY_DEFAULT) == 'automatic' &&
117
            (isset($occurrence_queryDto->fieldUnitPoints[0]) || isset($occurrence_queryDto->derivedUnitPoints[0]))) {
118
            $occurrence_query = $occurrence_queryDto->occurrenceQuery;
119
            $legend_format_query = null;
120
            $distribution_query = NULL;
121
            $render_array['map'] = compose_map('specimens', $occurrence_query, $distribution_query, $legend_format_query, array());
122
        }
123
    }
124

    
125
    // -------------------------------------------------------
126

    
127

    
128

    
129
    if(variable_get('cdm_dataportal_compressed_specimen_derivate_table')){
130

    
131
        //COMPRESSED SPECIMEN DERIVATE TABLE
132
        $associatedFieldUnitsQuery_parameters = array();
133
        if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
134
            $associatedFieldUnitsQuery_parameters = array_merge($associatedFieldUnitsQuery_parameters, $_REQUEST['pager']);
135
        }
136

    
137
        $by_associatedtaxon_query = http_build_query($associatedFieldUnitsQuery_parameters);
138
        $pager_field_units = cdm_ws_get(CDM_WS_PORTAL_TAXON,
139
            array($taxon->uuid, 'associatedFieldUnits'),
140
            $by_associatedtaxon_query . '&pageSize=' . variable_get('cdm_dataportal_compressed_specimen_derivate_table_page_size')
141
        );
142

    
143
        if (isset($pager_field_units->records[0])) {
144
          $field_unit_uuids = array();
145
          foreach ($pager_field_units->records as $field_unit) {
146
            $field_unit_uuids[] = $field_unit->uuid;
147
          }
148

    
149
          $render_array['derivate_hierarchy_table'] = compose_specimen_table($field_unit_uuids);
150
        }
151

    
152
        $render_array['pager'] = markup_to_render_array(
153
            theme('cdm_pager', array(
154
                'pager' => $pager_field_units,
155
                'path' => $_REQUEST['q'],
156
                'parameters' => $_REQUEST
157
            )),
158
            10 // weight
159
        );
160
    }
161
    else if(variable_get('cdm_dataportal_specimen_derivate_tree')){
162
        $specimen_table = array(
163
            '#theme' => 'table',
164
            '#weight' => 2,
165
            // prefix attributes and rows with '#' to let it pass toF the theme function,
166
            // otherwise it is handled as child render array
167
            '#attributes' => array('class' => 'specimens'),
168
            '#rows' => array(),
169
        );
170
        $specimen_array = compose_specimen_array($specimensOrObservations);
171

    
172
        foreach($specimen_array as $value){
173
            $renderArray = array(
174
                '#theme' => 'item_list',
175
                '#items' => array($value),
176
                '#type' => 'ul');
177
            $output = drupal_render($renderArray);
178
//            $specimen_table['#rows'][] = array(
179
//                // An array of table rows. collabsible row
180
//                'data' => "",
181
//                'class' => array('expand_column')
182
//            );
183
            $specimen_table['#rows'][] = array(
184
                // An array of table rows. Every row is an array of cells, or an associative array
185
                'data' => array($output),
186
                'class' =>  array(
187
                    'descriptionElement',
188
                    'descriptionElement_IndividualsAssociation'
189
                ),
190
            );
191

    
192

    
193
        }
194

    
195
        $render_array['specimen_list'] = $specimen_table;
196

    
197

    
198
    }
199
    else{
200
        //BOTTOM-UP-SPECIMEN-TABLE
201
        // --- generate the specimen list as table
202
        $specimen_table = array(
203
            '#theme' => 'table',
204
            '#weight' => 2,
205
            // prefix attributes and rows with '#' to let it pass toF the theme function,
206
            // otherwise it is handled as child render array
207
            '#attributes' => array('class' => 'specimens'),
208
            '#rows' => array(),
209
        );
210

    
211
        if ($specimensOrObservations) {
212

    
213
            foreach ($specimensOrObservations as $specimenOrObservation) {
214

    
215
                $mediaList = array();
216
                if (is_array($specimenOrObservation->_fieldObjectMedia)) {
217
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_fieldObjectMedia);
218
                }
219
                if (is_array($specimenOrObservation->_derivedUnitMedia)) {
220
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_derivedUnitMedia);
221
                }
222

    
223

    
224
                // typelabel will contain the typeStatus
225
                $type_label = '';
226
                $typeDesignationPager = cdm_ws_get(CDM_WS_OCCURRENCE . '/$0/specimenTypeDesignations', $specimenOrObservation->uuid);
227
                if (isset($typeDesignationPager) and isset($typeDesignationPager->records)) {
228
                    $type_status = array();
229
                    foreach ($typeDesignationPager->records as $typeDesignation) {
230
                        if (isset($typeDesignation->typeStatus->representation_L10n)){
231
                            $type_status[] = $typeDesignation->typeStatus->representation_L10n;
232
                        }
233
                    }
234
                    $type_label = implode(', ', $type_status);
235
                    if($type_label){
236
                        $type_label .= ': ' ;
237
                    }
238
                }
239

    
240
                // --- Specimen entry as dynamic label:
241
                //     -> Dynabox for the specimenOrObservation
242
                $gallery_name = $specimenOrObservation->uuid;
243

    
244
                $derived_unit_ws_request = cdm_compose_url(CDM_WS_OCCURRENCE, array( $specimenOrObservation->uuid));
245
                // --- Render associated media.
246
                $gallery_html = '';
247
                if (count($mediaList) > 0) {
248
                    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
249
                    $captionElements = array(
250
                        '#uri' => t('open media'),
251
                    );
252

    
253
                    $gallery_html = compose_cdm_media_gallerie(array(
254
                        'mediaList' => $mediaList,
255
                        'galleryName' => $gallery_name,
256
                        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
257
                        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
258
                        'maxRows' => isset($gallery_settings['cdm_dataportal_media_maxRows']) ? isset($gallery_settings['cdm_dataportal_media_maxRows']) : null,
259
                        'captionElements' => $captionElements,
260
                        'mediaLinkType' => 'LIGHTBOX',
261
                        'alternativeMediaUri' => NULL,
262
                        'galleryLinkUri' => NULL,
263
                    ));
264
                }
265
                //here we should use the data we already have
266
                $label_html = cdm_dynabox(
267
                  $specimenOrObservation->uuid,
268
                  $type_label . $specimenOrObservation->titleCache,
269
                  $derived_unit_ws_request,
270
                  'cdm_specimen_or_observation',
271
                  'Click for details',
272
                  array('div', 'div'),
273
                  array(),
274
                  null, // $content_element_selector
275
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').hide(); }', // open_callback
276
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').show(); }' // close_callback
277
                );
278

    
279
                // --- Render associated media.
280
                $gallery_html = '';
281
                if (count($mediaList) > 0) {
282
                    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
283
                    $captionElements = array(
284
                        '#uri' => t('open media'),
285
                    );
286

    
287
                    $gallery_html = compose_cdm_media_gallerie(array(
288
                        'mediaList' => $mediaList,
289
                        'galleryName' => $gallery_name,
290
                        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
291
                        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
292
                        'maxRows' => isset($gallery_settings['cdm_dataportal_media_maxRows']) ? isset($gallery_settings['cdm_dataportal_media_maxRows']) : null,
293
                        'captionElements' => $captionElements,
294
                        'mediaLinkType' => 'LIGHTBOX',
295
                        'alternativeMediaUri' => NULL,
296
                        'galleryLinkUri' => NULL,
297
                    ));
298
                }
299

    
300
                $specimen_table['#rows'][] = array(
301
                    // An array of table rows. Every row is an array of cells, or an associative array
302
                    'data' => array(
303
                        // Each cell can be either a string or an associative array
304
                        $label_html . $gallery_html
305
                    ),
306
                    'class' =>  array(
307
                        'descriptionElement',
308
                        'descriptionElement_IndividualsAssociation'
309
                    ),
310
                );
311
            }
312
        }
313

    
314
        $render_array['specimen_list'] = $specimen_table;
315
        $render_array['pager'] = markup_to_render_array(
316
            theme('cdm_pager', array(
317
                'pager' => $pager,
318
                'path' => $_REQUEST['q'],
319
                'parameters' => $_REQUEST,
320
            )),
321
            10 // weight
322
        );
323
    }
324

    
325
    RenderHints::popFromRenderStack();
326
    return $render_array;
327
}
328

    
329
/**
330
 * Creates the drupal render array for the table showing all derivated which are
331
 * derive from a common gathering event.
332
 *
333
 * @param $field_unit_uuids array
334
 *  An array of uuids for cdm FieldUnit entities.
335
 *
336
 * @return array
337
 *  A drupal render array for a table
338
 *
339
 * @ingroup compose
340
 */
341
function compose_specimen_table($field_unit_uuids)
342
{
343
// get icon images
344
  $expand_icon = font_awesome_icon_markup(
345
    'fa-plus-square-o',
346
    array(
347
      'alt' => 'Show details',
348
      'class' => array('expand_icon')
349
    )
350
  );
351
  $collapse_icon = font_awesome_icon_markup(
352
    'fa-minus-square-o',
353
    array(
354
      'alt' => 'Show details',
355
      'class' => array('collapse_icon')
356
    )
357
  );
358
  $detail_image_icon = '<img title="Detail Image" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/detail_image_derivate-16x16-32.png' . '"/>';
359
  $checked_box_icon = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/step_done.gif' . '"/>';
360
  $sequence_icon = '<img title="Molecular Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/sequence_derivate-16x16-32.png' . '"/>';
361
  $character_data_icon = '<img title="Character Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/character_data_derivate-16x16-32.png' . '"/>';
362

    
363
  $rowcount = 0;
364
  $rows = array();
365

    
366
  foreach ($field_unit_uuids as $field_unit_uuid) {
367

    
368
    //get derivate hierarchy for the FieldUnit
369
    $derivateHierarchy = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($field_unit_uuid, 'derivateHierarchy'));
370
    if ($derivateHierarchy) {
371
      //summary row
372
      $rows[] = array(
373
        'data' => array(
374
          array(
375
            'data' => $expand_icon . $collapse_icon,
376
            'class' => array('summary_row_cell', 'summary_row_icon', 'expand_column')
377
          ),
378
          array(
379
            'data' => $derivateHierarchy->country,
380
            'class' => array('summary_row_cell')
381
          ),
382
          array(
383
            'data' => $derivateHierarchy->date,
384
            'class' => array('summary_row_cell')
385
          ),
386
          array(
387
            'data' => $derivateHierarchy->collectingString,
388
            'class' => array('summary_row_cell')
389
          ),
390
          @array(
391
            'data' => $derivateHierarchy->collection,
392
            'class' => array('summary_row_cell')
393
          ),
394
          array(
395
            'data' => $derivateHierarchy->hasType ? $checked_box_icon : "",
396
            'class' => array('summary_row_cell', 'summary_row_icon')
397
          ),
398
          array(
399
            'data' => $derivateHierarchy->hasSpecimenScan ? $checked_box_icon : "",
400
            'class' => array('summary_row_cell', 'summary_row_icon')
401
          ),
402
          array(
403
            'data' => ($derivateHierarchy->hasDna ? $sequence_icon : "") . " "
404
              . ($derivateHierarchy->hasDetailImage ? $detail_image_icon : "") . " "
405
              . ($derivateHierarchy->hasCharacterData ? $character_data_icon : ""),
406
            'class' => array('summary_row_cell', 'summary_row_icon')
407
          )
408
        ),
409
        'id' => 'derivate_summary' . $rowcount, // summary row id
410
        'class' => array('summary_row'),
411
      );
412

    
413
      //assemble field unit details
414
      $detail_html = "";
415
      // - citation
416
      if ($derivateHierarchy->citation) {
417
        $detail_html .= create_label("Citation") . $derivateHierarchy->citation . "<br>";
418
      }
419
      //assemble specimen details
420
      if ($derivateHierarchy->derivates) {
421
        foreach ($derivateHierarchy->derivates as $preservedSpecimenDTO) {
422
          $detail_html .= "<br>";
423
          $detail_html .= render_cdm_specimenDTO_page($preservedSpecimenDTO);
424
      }
425
      }
426
      $detail_html .= "<br>";
427
      //detail row resp. one BIG detail cell
428
      $rows[] = array(
429
        'data' => array(
430
          array(
431
            'data' => "", //empty first column
432
            'class' => array('expand_column')
433
          ),
434
          array(
435
            'data' => $detail_html,
436
            'colspan' => 7,
437
          ),
438
        ),
439
        'id' => 'derivate_details' . $rowcount,//details row ID
440
        'class' => array('detail_row'),
441
      );
442
      $rowcount++;
443
    }
444
  }
445

    
446
  $tableId = "derivate_hierarchy_table";
447
  $derivateHierarchyTable = array(
448
    "#theme" => "table",
449
    "#weight" => 2,
450
    "#header" => array(
451
      array(
452
        'data' => "",
453
        'class' => array('expand_column')
454
      ),
455
      "Country", "Date", "Collector + collecting number", "Herbaria", "Type", "Scan", "Derivatives"),
456
    "#rows" => $rows,
457
    "#attributes" => array(
458
      "id" => $tableId,
459
      "border" => 2
460
    )
461
  );
462

    
463
  //add toggle functionality to derivate hierarchy table
464
  drupal_add_js_rowToggle("#" . $tableId);
465

    
466
  return $derivateHierarchyTable;
467
}
468

    
469
function create_html_link($link, $openInExternalWindow=false){
470
    $html = "";
471
    if($link->uri && $link->uri!=""){
472
        $html .= '<a  href="' . $link->uri . '"';
473
        if($openInExternalWindow){
474
            $html .= ' target="_blank"';
475
        }
476
        $html .= '>' . $link->linkText . '</a>';
477
    }
478
    else{
479
        $html .= $link->linkText;
480
    }
481
    return $html;
482
}
483

    
484
/**
485
 * Creates HTML links from the given link list concatenated by default by a comma.
486
 * @param $linkList the list with Link objects having "uri" and "linkText" as members
487
 * @return string the assembled HTML string containing the links
488
 */
489
function create_html_links($linkList, $openInExternalWindow=false, $separator=", ")
490
{
491
    $html = "";
492
    if ($linkList) {
493
        foreach ($linkList as $link) {
494
            $html .= create_html_link($link, $openInExternalWindow).$separator;
495
        }
496
        $html = rtrim($html, $separator);
497
    }
498
    return $html;
499
}
500

    
501
/**
502
 * Composes a taxon page which can consist of multiple parts like
503
 * 'General', 'Synonymy', 'Images', 'Keys'. These parts can be displayed
504
 * as tabs or as sections of a single page.
505
 *
506
 * It is headed by the name of the accepted taxon without author and reference.
507
 *
508
 * @param $taxon
509
 *   The CDM Taxon Instance to compose the page for.
510
 * @param $page_part
511
 *   Name of the part to display, valid values are:
512
 *    - 'description' -  for the general part
513
 *    - 'images'
514
 *    - 'synonymy'
515
 *    - 'keys'
516
 *    - 'all'
517
 *
518
 * @return array
519
 *   A drupal render array
520
 *
521
 * @ingroup compose
522
 */
523
function compose_cdm_taxon_page($taxon, $page_part = 'description') {
524

    
525
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
526
  $http_request_params = drupal_get_query_parameters();
527

    
528
  // add all mandatory js sources
529
  _add_js_footnotes();
530

    
531

    
532
  $render_array = array();
533
  $weight = 0; // the weight for the render array elements
534

    
535
  $tabsToDisplay = variable_get('cdm_taxonpage_tabs_visibility', unserialize(TAXONPAGE_VISIBILITY_OPTIONS_DEFAULT));
536

    
537
  $page_part = variable_get('cdm_dataportal_taxonpage_tabs', 1) ? $page_part : 'all';
538

    
539
  $synonymy_as_tab = variable_get(CDM_SYNONYMY_AS_TAB, CDM_SYNONYMY_AS_TAB_DEFAULT) === 1;
540
  if(!$synonymy_as_tab){
541
    unset($tabsToDisplay["Synonymy"]);
542
    // the synonymy is located in the general part in this case
543
    if($page_part == 'synonymy'){
544
      $page_part = 'description';
545
    }
546
  }
547

    
548
  $media = _load_media_for_taxon($taxon);
549

    
550

    
551
  if (!isset($media[0]) || ($tabsToDisplay["Images"] == '0')) {
552
    taxon_page_tabs_hidden_add('images');
553
  }
554

    
555
  // --- GET specimensOrObservations --- //
556
  $specimensOrObservations = cdm_ws_get(CDM_WS_TAXON, array( $taxon->uuid, 'specimensOrObservationsCount'));
557

    
558
  $specimensOrObservationsCount = $specimensOrObservations != null ? $specimensOrObservations->result : 0;
559
  if ($specimensOrObservationsCount == 0 || ($tabsToDisplay["Specimens"] == '0')) {
560
    taxon_page_tabs_hidden_add('specimens');
561
  }
562

    
563
  // --- GET polytomousKeys --- //
564
  $polytomousKeysPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, NULL, "findByTaxonomicScope=$taxon->uuid");
565
  $identificationKeyCount = 0;
566
  if ($polytomousKeysPager) {
567
    $identificationKeyCount += $polytomousKeysPager->count;
568
  }
569
  if ($identificationKeyCount == 0 || ($tabsToDisplay["Keys"] == '0')) {
570
    taxon_page_tabs_hidden_add('keys');
571
  }
572

    
573
  // --- GET TaxonNodeAgentRelations --- //
574
  $current_classification_uuid = get_current_classification_uuid();
575
  $taxon_node_agent_relations_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
576
      array(
577
          $taxon->uuid,
578
          $current_classification_uuid,
579
      ),
580
      "pageSize=1&pageIndex=0"// we are only interested into the count so we are fetching only one item, o is not possible!
581
  );
582
  if (!$taxon_node_agent_relations_pager || $taxon_node_agent_relations_pager->count == 0){
583
      taxon_page_tabs_hidden_add('experts');
584
  }
585

    
586
  if (!isset($tabsToDisplay["Synonymy"]) || $tabsToDisplay["Synonymy"] == '0') {
587
    taxon_page_tabs_hidden_add('synonymy');
588
  }
589

    
590
  // -------------------------------------------- //
591

    
592
  if (variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR) && isset($_REQUEST['acceptedFor'])) {
593
    $render_array['accepted_for'] = markup_to_render_array(cdm_accepted_for($_REQUEST['acceptedFor']), $weight++);
594
  }
595

    
596
  // --- PAGE PART: DESCRIPTION --- //
597
  if (!taxon_page_tabs_hidden_check('description') && ($page_part == 'description' || $page_part == 'all')) {
598

    
599
    $merged_tree = merged_taxon_feature_tree($taxon);
600

    
601

    
602
    $render_array['general'] = compose_cdm_taxon_page_profile($taxon, $merged_tree, $media, !$synonymy_as_tab);
603
    $render_array['general']['#weight'] = $weight++;
604
    $render_array['general']['#prefix'] = '<div id="general" class="page-part">';
605
    $render_array['general']['#suffix'] = '</div>';
606
  }
607

    
608
  // --- PAGE PART: IMAGES --- //
609
  if (!taxon_page_tabs_hidden_check('images') && ($page_part == 'images' || $page_part == 'all')) {
610
    $images_html = '<div id="images" class="page-part">';
611
    if ($page_part == 'all') {
612
      $images_html .= '<h2>' . t(cdm_taxonpage_tab_label('Images')) . '</h2>';
613
    }
614
    // Get the image gallery as configured by the admin.
615
    $default_image_gallery = 'default';
616
    $configured_image_gallery_viewer = variable_get('image_gallery_viewer', 'default');
617
    $taxon_image_gallery = '<div class="error">No image gallery viewer configured</div>';
618
    if($configured_image_gallery_viewer == $default_image_gallery || $configured_image_gallery_viewer == 'fsi'){
619
      // the fsi_gallery requires a flash plugin, in case the client browser is not supporting
620
      // flash we also need to provide an the default gallery as alternative
621
      $taxon_image_gallery = '<div id="default-gallery-viewer">' .
622
        call_user_func_array('taxon_image_gallery_' . $default_image_gallery, array(
623
          $taxon,
624
          $media,
625
        ))
626
        . '</div>';
627
    }
628
    if($configured_image_gallery_viewer == 'fsi'){
629
      $taxon_image_gallery .= '<div id="'. $configured_image_gallery_viewer .'-gallery-viewer">' .
630
        call_user_func_array('taxon_image_gallery_' . $configured_image_gallery_viewer, array(
631
          $taxon,
632
          $media,
633
        ))
634
       . '</div>';
635
    }
636
    $images_html .= $taxon_image_gallery;
637
    $images_html .= '</div>';
638
    $render_array['images'] = markup_to_render_array($images_html, $weight++);
639
  }
640

    
641
  // --- PAGE PART: SYNONYMY --- //
642
  if (!taxon_page_tabs_hidden_check('synonymy') && (($page_part == 'synonymy' || $page_part == 'all') && $synonymy_as_tab)) {
643
    $synonymy_html = '<div id="synonymy" class="page-part">';
644
    if ($page_part == 'all') {
645
      $synonymy_html .= '<h2>' . t(cdm_taxonpage_tab_label('Synonymy')) . '</h2>';
646
    }
647
    $addAcceptedTaxon = variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE);
648

    
649
    $synonym_a = compose_cdm_taxon_page_synonymy($taxon, $addAcceptedTaxon);
650
    $synonymy_html .= drupal_render($synonym_a);
651

    
652
    $synonymy_html .= '</div>';
653
    $render_array['synonymy'] = markup_to_render_array($synonymy_html, $weight++);
654

    
655
  }
656

    
657
  // --- PAGE PART: SPECIMENS --- //
658
  if (!taxon_page_tabs_hidden_check('specimens') && ($specimensOrObservationsCount > 0 && ($page_part == 'specimens' || $page_part == 'all'))) {
659
    $render_array['specimens'] = array(
660
        '#prefix' => '<div id="specimens" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Specimens')) . '</h2>' : ''),
661
        'content' => cdm_dataportal_taxon_page_specimens($taxon), // returns render array
662
        '#suffix' => '</div>',
663
    );
664
  }
665

    
666
  // --- PAGE PART: KEYS --- //
667
  if(!taxon_page_tabs_hidden_check('keys')){
668
    if ($identificationKeyCount == 1 && $page_part == 'keys'){
669
      drupal_goto(path_to_key($polytomousKeysPager->records[0]->class, $polytomousKeysPager->records[0]->uuid));
670
    }
671
    else if ($identificationKeyCount > 0 && ($page_part == 'keys' || $page_part == 'all')) {
672
      $keys_html = '<div id="keys" class="page-part">';
673
      if ($page_part == 'all') {
674
        $keys_html .= '<h2>' . t(cdm_taxonpage_tab_label('Keys')) . '</h2>';
675
      }
676
      $keys_html .= theme('cdm_block_IdentificationKeys', array('taxonUuid' => $taxon->uuid));
677
      $keys_html .= '</div>';
678
      $render_array['keys'] = markup_to_render_array($keys_html, $weight++);
679
    }
680
  }
681

    
682
  // --- PAGE PART: EXPERTS --- //
683

    
684
  if (!taxon_page_tabs_hidden_check('experts') && ($page_part == 'experts' || $page_part == 'all')) {
685
    $render_array['experts'] = array(
686
        '#prefix' => '<div id="experts" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Experts')) . '</h2>' : ''),
687
        'content' => compose_cdm_taxon_page_experts($taxon), // returns render array
688
        '#suffix' => '</div>',
689
    );
690
  }
691

    
692
  // ------------------ END OF PARTS -------------- //
693

    
694
  // adjust weights of page and toc elements according to the settings
695
  $taxontabs_weights = get_array_variable_merged(CDM_TAXONPAGE_TAB_WEIGHT, CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
696
  foreach($taxontabs_weights as $tab_key => $weight){
697
    if(isset($render_array[$tab_key])){
698
      $render_array[$tab_key]['#weight'] = $weight;
699
    }
700
  }
701

    
702

    
703
  // set up the TOC for the pages which contain all pageparts
704
  if($page_part == 'all') {
705

    
706
    asort($taxontabs_weights);
707
    foreach(array_keys($taxontabs_weights) as $tab_key){
708
      if(isset($render_array[$tab_key])){
709
        if($tab_key != 'general'){
710
          // add entry for page part
711
          $toc_elements[] = array(
712
              'data' => l(t(cdm_taxonpage_tab_label(ucfirst($tab_key))), $_GET['q'], array('fragment' => $tab_key, 'query' => $http_request_params)),
713
              'class' => array('page-part-toc-item-' . $tab_key)
714
          );
715
        } else {
716
          // add content of profile part instead
717
          if(isset($render_array['general'])) {
718
            // in case all tabs are shown at once the feature tocs
719
            // should be integrated into the tabs toc as sub list
720
            // and the profile image should be on top of the page
721
            if(isset($render_array['general']['taxon_description_feature_toc'])){;
722
            foreach ($render_array['general']['taxon_description_feature_toc']['#items'] as $profile_toc_item){
723
              $toc_elements[] = $profile_toc_item;
724
            }
725
            unset($render_array['general']['taxon_description_feature_toc']);
726
            }
727
          }
728
        }
729
      }
730
    }
731

    
732
    // move profile image in page structure
733
    if(isset($render_array['general']['taxon_profile_image'])){
734
      $render_array['profile_image'] = $render_array['general']['taxon_profile_image'];
735
      $render_array['profile_image']['#weight'] = -100;
736
      unset($render_array['general']['taxon_profile_image']);
737
    }
738

    
739
    // finally add the table of contents to the render array
740
    $render_array['toc'] = array(
741
        '#theme' => 'item_list',
742
        '#items' => $toc_elements,
743
        '#title' => t('Content'),
744
        '#weight' => -101,
745
        '#suffix' => '</div>',
746
        '#prefix'=> '<div id="page-toc">'
747
    );
748
  }
749

    
750

    
751
  return $render_array;
752
}
753

    
754
/**
755
 * TODO should this function really be a compose function?
756
 *     For a compose function must there always be a theme function with the same name? (ak 8.8.2013)
757
 *
758
 * composes and returns an render array containing the components of the taxon profile tab:
759
 *  - 'taxon_profile_image'
760
 *  - 'taxon_description_feature_toc'
761
 *  - 'taxon_description_features'
762
 *
763
 *
764
 * @param object taxon
765
 * @param object $merged_tree
766
 * @param object media
767
 * @param bool $add_synonymy
768
 *
769
 * @return array
770
 *   A Drupal render array with the following elements:
771
 *     - 'taxon_profile_image'
772
 *     - 'taxon_description_feature_toc'
773
 *     - 'taxon_description_features'
774
 *
775
 * @throws Exception
776
 *
777
 * @ingroup compose
778
 */
779
function compose_cdm_taxon_page_profile($taxon, $merged_tree, $media, $add_synonymy) {
780

    
781
  $render_array = array();
782

    
783
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
784

    
785
  $hide_taxon_profile_image = FALSE;
786
  if (variable_get('image_hide_rank', '0') != '0' && isset($taxon->name->rank->uuid)) {
787
    $rankCompare = rank_compare($taxon->name->rank->uuid, variable_get('image_hide_rank', '-99'));
788
    $hide_taxon_profile_image = ($rankCompare > -1);
789
  }
790

    
791
  if ($taxon_profile_image_settings['show'] && !$hide_taxon_profile_image) {
792

    
793
    $representationPart = new stdClass();
794
    $attributes = array();
795
    if (isset($media[0])) {
796
      // due to a bug the portal/taxon/{uuid}/media service only delivers a filtered media object
797
      // which only contains the thumbnail representation even if the height and width filters are not set.
798
      // -->
799
      $preferred_media = cdm_ws_get(CDM_WS_MEDIA, $media[0]->uuid);
800
      $preferred_representations = cdm_preferred_media_representations($preferred_media, array(
801
        'image/jpg',
802
        'image/jpeg',
803
        'image/png',
804
        'image/gif',
805
      ),
806
        $taxon_profile_image_settings['maxextend'],
807
        $taxon_profile_image_settings['maxextend']
808
      );
809
      if(count($preferred_representations) > 0){
810

    
811
        $representation = array_shift($preferred_representations);
812
        $representationPart = $representation->parts[0];
813
        $attributes['alt'] = $representationPart->uri;
814

    
815
        if (!empty($taxon_profile_image_settings['media_uri_query'])) {
816
          $representationPart->uri = $representationPart->uri
817
            . (strpos($representationPart->uri, '?') !== FALSE ? '&' : '?')
818
            . $taxon_profile_image_settings['media_uri_query'];
819
        }
820
      }
821
    }
822
    else {
823
      if ($taxon_profile_image_settings['custom_placeholder_enabled']) {
824
        // show placeholder image instead
825
        if (!empty($taxon_profile_image_settings['custom_placeholder_image_on']) && !empty($taxon_profile_image_settings['custom_placeholder_image_fid'])) {
826
          // use the user provided image
827
          $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
828
          $url = file_create_url($profile_image_file->uri);
829
          $image_info = image_get_info($profile_image_file->uri);
830
          $representationPart->width = $image_info['width'];
831
          $representationPart->height = $image_info['height'];
832
          $representationPart->uri = $url;
833
        }
834
        else {
835
          // use the hard coded default
836
          $representationPart->width = 184;
837
          $representationPart->height = 144;
838
          $representationPart->uri = base_path() . drupal_get_path('module',
839
              'cdm_dataportal') . '/images/no_picture.png';
840
        }
841
        $attributes['alt'] = "no image available";
842
      }
843
    }
844

    
845
    if (isset($representationPart->uri)) {
846
      $profile_image = cdm_media_gallerie_image($representationPart, $taxon_profile_image_settings['maxextend'], FALSE, $attributes);
847
      // NOTE: style="width:${maxextend}px' is needed for IE8 !!!
848
      $render_array['taxon_profile_image'] = markup_to_render_array('<div id="taxonProfileImage" style="width:' . $taxon_profile_image_settings['maxextend'] . 'px">' . $profile_image . '</div>',
849
        -101);
850
    }
851
  }
852

    
853
  if($add_synonymy){
854
    $synonymy_a = compose_cdm_taxon_page_synonymy($taxon, true);
855
    $synonymy_a['#weight'] = -102;
856
    $render_array['synonymy'] = $synonymy_a;
857
  }
858

    
859
  $pseudo_feature_blocks = array();
860
  $pseudo_feature_block_toc_items = array();
861

    
862

    
863
  // Render the sections for each real feature
864
  $feature_block_list = make_feature_block_list($merged_tree->root->childNodes, $taxon);
865

    
866
  // Bibliography
867
  $bibliography_settings = get_bibliography_settings();
868
  if($bibliography_settings['enabled'] == 1){
869
    $bibliography_markup = FootnoteManager::renderFootnoteList('BIBLIOGRAPHY', '');
870
    if($bibliography_markup) {
871
      $feature_bibliography = make_pseudo_feature('Bibliography', 'BIBLIOGRAPHY');
872
      $bibliography_block = feature_block(t('Bibliography'), $feature_bibliography);
873
      $bibliography_item = markup_to_render_array($bibliography_markup);
874
      $bibliography_block->content[] = compose_feature_block_wrap_elements(array($bibliography_item), $feature_bibliography);
875

    
876
      $pseudo_feature_block_toc_items['Bibliography']= 'bibliography';
877
      $pseudo_feature_blocks[] = $bibliography_block;
878
    }
879
  }
880

    
881
  $render_array['taxon_description_features'] = _block_get_renderable_array(
882
    array_merge($feature_block_list, $pseudo_feature_blocks)
883
  );
884

    
885
  if($pseudo_feature_block_toc_items){
886
    foreach ($pseudo_feature_block_toc_items as $label=>$fragment){
887
      cdm_toc_list_add_item($label, $fragment);
888
    }
889
  }
890

    
891
  // create the table of content
892
  $toc = array(
893
      '#theme' => 'item_list',
894
    '#items' => cdm_toc_list(),
895
      '#title' => t('Content'),
896
    '#weight' => -100,                  // move to the top
897
      '#suffix' => '</div>',
898
      '#prefix'=> '<div id="page-toc">'
899
  );
900
  $render_array['taxon_description_feature_toc'] = $toc;
901

    
902
  return $render_array;
903
}
904

    
905

    
906
/**
907
 * Returns HTML containing the synonymy for the accepted taxon.
908
 *
909
 * Shows the whole synonymy for the accepted taxon.
910
 * The synonymy list is headed by the complete scientific name
911
 * of the accepted taxon with nomenclatural reference.
912
 *
913
 * @param object $taxon
914
 * @param boolean $add_accepted_taxon
915
 *
916
 * @return array
917
 *  Drupal render array for the synonymy
918
 *
919
 * @throws Exception
920
 *
921
 * @ingroup compose
922
 */
923
function compose_cdm_taxon_page_synonymy($taxon, $add_accepted_taxon) {
924

    
925
  RenderHints::pushToRenderStack('taxon_page_synonymy');
926

    
927
  // footnote key for the homotypic group and accepted taxon,
928
  // both should have the same footnote key
929
  RenderHints::setFootnoteListKey(RenderHints::getRenderPath());
930

    
931
  $synomymie = cdm_ws_get(CDM_WS_PORTAL_TAXON_SYNONYMY, array($taxon->uuid));
932

    
933
  $out = '';
934

    
935
  // Render accepted taxon.
936
  //
937
  // foonotes of the accepted taxon will be rendered in the homotypic group section
938
  // even if there are not synonyms in the homotypic group
939
  // homotypic group and accepted taxon should have the same footnote key
940
  $referenceUri = '';
941
  if ($add_accepted_taxon) {
942
    // remember the last part of the render path
943
    $synonymy_render_path = RenderHints::getRenderPath();
944
    // set new render path for the accepted taxon so
945
    // it can be styled differently via the name render part definitions
946
    RenderHints::pushToRenderStack('accepted_taxon');
947
    $accepted_name = '';
948
    if (variable_get(CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE, 0)) {
949
      $label = variable_get(CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE_LABEL, CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE_LABEL_DEFAULT);
950
      $accepted_name .= '<div class="secReference"><span class="label">' . t($label) . ':</span> ' . $taxon->sec->titleCache . '</div>';
951
    }
952
    if (isset($taxon->name->nomenclaturalReference)) {
953
      $referenceUri = url(path_to_reference($taxon->name->nomenclaturalReference->uuid));
954
    }
955

    
956
    $accepted_name .= '<div class="accepted-name">';
957
    $accepted_name .= render_taxon_or_name($taxon, NULL, $referenceUri);
958

    
959
    $name_relations = cdm_name_relationships_for_taxon($taxon);
960
    $name_relationships = compose_name_relationships_inline($name_relations, $taxon->name->uuid, $taxon->uuid);
961
    // Render relationships of accepted name.
962
    if(isset($name_relationships['list']['items'][0])){
963
      $accepted_name .= ' ' . drupal_render($name_relationships);
964
    }
965

    
966
    // handle annotations of the name and taxon
967
    $special_annotations_array = array();
968
    $special_annotations_array[] = $taxon->name;
969
    $special_annotations_array[] = $taxon;
970
    $accepted_name .= theme('cdm_annotations_as_footnotekeys', array(
971
        'cdmBase_list' => $special_annotations_array,
972
        'footnote_list_key' => $synonymy_render_path . '-annotations')
973
    );
974
    $accepted_name .= '</div>';
975
    RenderHints::popFromRenderStack();
976
  }
977

    
978
  // --- Render homotypic synonymy group
979
  if (!empty($accepted_name)) {
980
    $out .= $accepted_name;
981
  }
982

    
983
  // Render the homotypicSynonymyGroup including the type information.
984
  $out .= theme(
985
    'cdm_homotypicSynonymyGroup',
986
    array(
987
      'synonymList' => $synomymie->homotypicSynonymsByHomotypicGroup,
988
      'accepted_taxon_name_uuid' => $taxon->name->uuid
989
    )
990
  );
991

    
992

    
993
  // Render accepted taxon heterotypic synonymy groups.
994
  if ($synomymie->heterotypicSynonymyGroups) {
995
    foreach ($synomymie->heterotypicSynonymyGroups as $homotypicalGroup) {
996
      $out .= theme('cdm_heterotypicSynonymyGroup', array('homotypicalGroup' => $homotypicalGroup));
997
    }
998
  }
999
  // Render taxon relationships.
1000
  if (variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT)) {
1001
    $taxonRelationshipsDTO = cdm_ws_get(CDM_WS_PORTAL_TAXON_RELATIONS_DTO, $taxon->uuid);
1002
    $out .= cdm_taxonRelationships($taxonRelationshipsDTO, $taxon);
1003
  }
1004

    
1005
  RenderHints::popFromRenderStack();
1006

    
1007
  return markup_to_render_array($out);
1008
}
1009

    
1010

    
1011
/**
1012
 * composes and returns an render array for the experts associated with the given taxon
1013
 *
1014
 * @param object taxon
1015
 *
1016
 * @return array
1017
 *   A Drupal render array for a table with the experts
1018
 *
1019
 * @ingroup compose
1020
 */
1021
function compose_cdm_taxon_page_experts($taxon){
1022

    
1023
  $render_array = array();
1024
  if(!isset($taxon->uuid)){
1025
    return $render_array;
1026
  }
1027

    
1028
  $current_classification_uuid = get_current_classification_uuid();
1029
  // TODO use cdm_ws_fetchall below but this failes! needs fix!
1030
  $taxon_node_agent_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
1031
    array(
1032
      $taxon->uuid,
1033
      $current_classification_uuid
1034
    )
1035
  );
1036

    
1037
  $header = array(
1038
    array('data' => t('Expert')),
1039
    array('data' => t('Role'))
1040
  );
1041
  $rows = array();
1042

    
1043

    
1044
  foreach($taxon_node_agent_relations->records as $taxon_node_agent_relation){
1045

    
1046

    
1047
    $expert_role_id = $taxon_node_agent_relation->agent->uuid . '-' . $taxon_node_agent_relation->type->uuid;
1048
    $expert_details_container_id = 'expert_details_' . $expert_role_id;
1049

    
1050
    $agent_label_markup = cdm_dynabox(
1051
      'expert_' . $expert_role_id,
1052
      $taxon_node_agent_relation->agent->titleCache,
1053
      // specifying both ends of the relationship will return only one record in the pager
1054
      cdm_compose_url(CDM_WS_PORTAL_AGENT,
1055
         array($taxon_node_agent_relation->agent->uuid, 'taxonNodeAgentRelations'),
1056
        'taxon_uuid=' . $taxon->uuid . '&relType_uuid=' . $taxon_node_agent_relation->type->uuid),
1057
      'cdm_taxon_expert',
1058
      'Click for details',
1059
      array('div', 'div'),
1060
      array(), // attributes
1061
      '#' . $expert_details_container_id // $content_element_selector
1062
    );
1063

    
1064
    // Expert and Role
1065
    $rows[] = array(
1066
      'data' => array(
1067
        array(
1068
          'data' => $agent_label_markup,
1069
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->agent))
1070
        ),
1071
        array(
1072
          'data' => $taxon_node_agent_relation->type->representation_L10n,
1073
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->type))
1074
        )
1075
      )
1076
    );
1077
    // Agent details
1078
    $rows[] = array(
1079
      'data' => array(
1080
        array(
1081
          'data' => '<!-- expert_details_container -->',
1082
          'id' => $expert_details_container_id,
1083
          'colspan' => 2
1084
        )
1085
      )
1086
    );
1087

    
1088
  }
1089

    
1090

    
1091
  $render_array['experts_table'] = array(
1092
    '#theme' => 'table',
1093
    '#header' => $header,
1094
    '#rows' => $rows,
1095
  );
1096

    
1097

    
1098
  return $render_array;
1099
}
1100

    
1101

    
1102
/**
1103
 * Manages the tabs to be hidden in the taxon page.
1104
 *
1105
 * The tabs are identified by their last menu link path element:
1106
 *  - description
1107
 *  - synonymy
1108
 *  - images
1109
 *  - specimens
1110
 *  - key
1111
 *
1112
 * Internally the tabs are stored in a static variable which is
1113
 * managed by drupal_static().
1114
 *
1115
 * @param string $add_tab
1116
 *   Optional parameter. The given string will be added to the array of tabs
1117
 *
1118
 * @return
1119
 *   The array of tabs
1120
 */
1121
function taxon_page_tabs_hidden_add($add_tab = NULL) {
1122
  $tabs = &drupal_static('taxon_page_tabs_hidden');
1123

    
1124
  if(!isset($tabs)){
1125
    $tabs = array();
1126
  }
1127

    
1128
  if (isset($add_tab) && !array_key_exists($add_tab, $tabs)) {
1129
    $tabs[] = $add_tab;
1130
  }
1131

    
1132
  return $tabs;
1133
}
1134

    
1135
/**
1136
 * Manages the tabs to be hidden in the taxon page.
1137
 *
1138
 * The tabs names are identified by their last menu link path element:
1139
 *  - description
1140
 *  - synonymy
1141
 *  - images
1142
 *  - specimens
1143
 *  - key
1144
 *
1145
 * Internally the tabs are stored in a static variable which is
1146
 * managed by drupal_static().
1147
 *
1148
 * @param string $tabname
1149
 *   The name of the tab to check
1150
 *
1151
 * @return boolean
1152
 *   True if the tab or section is to be hidden
1153
 */
1154
function taxon_page_tabs_hidden_check($tabname) {
1155

    
1156
  $tabs = &drupal_static('taxon_page_tabs_hidden');
1157

    
1158
  if(!isset($tabs)){
1159
    $tabs = array();
1160
  }
1161

    
1162
  return array_search($tabname, $tabs) !== FALSE;
1163
}
1164

    
1165
/**
1166
 * Implements the hook_preprocess_HOOK() for theme_menu_local_tasks()
1167
 *
1168
 *  - Removes the tabs to be hidden, @see taxon_page_tabs_hidden_add()
1169
 *  - Renames tabs according to the settings // TODO (this will replace the theme_cdm_taxonpage_tab() function !!!)
1170
 *
1171
 * @param array $variables
1172
 *   The variables array
1173
 */
1174
function cdm_dataportal_preprocess_menu_local_tasks(&$variables) {
1175

    
1176
  $hidden_tabs = taxon_page_tabs_hidden_add();
1177

    
1178
  if (!variable_get(CDM_SEARCH_BLAST_ENABLED)) {
1179
      if (is_array($variables['primary'])) {
1180
          foreach ($variables['primary'] as $key => &$element) {
1181
              if ($element['#link']['path'] == 'cdm_dataportal/search/blast') {
1182
                  // remove the tab
1183
                  unset($variables['primary'][$key]);
1184
              }
1185

    
1186
          }
1187
      }
1188
  }
1189
  if (is_array($variables['primary'])) {
1190
    foreach ($variables['primary'] as $key => &$element) {
1191

    
1192
      // 1. Remove the tabs to be hidden
1193
      foreach ($hidden_tabs as $tab) {
1194
        if ($element['#link']['path'] == 'cdm_dataportal/taxon/%/' . $tab) {
1195
          // remove the tab
1196
          unset($variables['primary'][$key]);
1197
        }
1198
      }
1199
    }
1200
  }
1201
}
1202

    
1203

    
1204

    
1205
/**
1206
 * Implements the hook_preprocess_HOOK() for theme_menu_local_task()
1207
 *
1208
 *
1209
 * @param array $variables
1210
 *   An associative array containing:
1211
 *     - element: A render element containing:
1212
 *          #link: A menu link array with 'title', 'href', and 'localized_options' keys.
1213
 *          #active: A boolean indicating whether the local task is active.
1214
 *
1215
 */
1216
function cdm_dataportal_preprocess_menu_local_task(&$variables) {
1217

    
1218
  $link = $variables['element']['#link'];
1219
  if (preg_match('/cdm_dataportal\/.*\/refresh$/', $link['href'])) {
1220
    $link['title'] = '<img class="refresh" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/view-refresh.png' . '" alt="' . check_plain($link['title']) . '" title="' . check_plain($link['title']) . '"/>';
1221
    $link['localized_options']['html'] = TRUE;
1222

    
1223
    $variables['element']['#link'] = $link;
1224
  }
1225
}
1226

    
1227
/* =================== block composition ===================== */
1228

    
1229
/**
1230
 * Composes and returns an render array for the classification breadcrumbs of the given taxon.
1231
 *
1232
 * @param taxon
1233
 *
1234
 * @return array
1235
 *   A Drupal render array for a table with the experts
1236
 *
1237
 * @ingroup compose
1238
 */
1239
function compose_classification_breadcrumbs($taxon_uuid) {
1240

    
1241
  _add_js_taxonomic_children('#classification-breadcrumbs .taxonomic-children-button');
1242

    
1243
  $render_array = array();
1244

    
1245
  $render_array['#theme'] = 'item_list';
1246
  $render_array['#type'] = 'ul';
1247
  $render_array['#attributes'] = array(
1248
    'id' => 'classification-breadcrumbs',
1249
    'class' => 'breadcrumbs inline',
1250
  );
1251

    
1252
  $items = array();
1253

    
1254
  $parent_taxon_nodes = null;
1255
  if($taxon_uuid){
1256
    $parent_taxon_nodes = cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1257
  }
1258

    
1259
  $classifications = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
1260
  // find current classification in list
1261
  $classification = null;
1262
  $current_classification_uuid = get_current_classification_uuid();
1263
  foreach ($classifications as $classification){
1264
    if($classification->uuid == $current_classification_uuid){
1265
      break;
1266
    }
1267
  }
1268

    
1269
  $node_name = '';
1270
  if(count($classifications) > 1 ){
1271
    // need to add the current classification as first label
1272

    
1273
    $label = $classification->titleCache;
1274
    if(strlen($label) > 20){
1275
      $label = substr($label, 0, strpos($label, ' ', 15)) . '...';
1276
    }
1277
    $node_name = font_awesome_icon_markup('fa-th-list')  . ' ' . l($label, '#', array(
1278
      'attributes' => array(
1279
        'class' => 'taxonomic-children-button classification-chooser',
1280
        'data-destination-uri' => drupal_get_destination(),
1281
        'data-cdm-align-with' => array('prev')
1282
      ),
1283
      'html' => true
1284
    ));
1285
  }
1286

    
1287
  $rank_limit_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1288

    
1289
  $rank_separator = '<span> '
1290
    . font_awesome_icon_markup('fa-chevron-right')
1291
    . ' </span>';
1292
  $more_children_icon = font_awesome_icon_markup('fa-sitemap fa-rotate-270');
1293
  $more_children_label = '...';
1294

    
1295
  $items[] = $node_name;
1296

    
1297
  $more_children_for = null;
1298
  if($parent_taxon_nodes){
1299
    foreach ($parent_taxon_nodes as $node) {
1300

    
1301
      $is_first_item = count($items) == 0;
1302
      $is_last_item = count($items) == count($parent_taxon_nodes);
1303
      $node_name = cdm_dataportal_shortname_of($node);
1304
      $path = path_to_taxon($node->taxonUuid);
1305

    
1306
      if($node->taxonomicChildrenCount > 0) {
1307
        $more_children_for = $node->taxonUuid;
1308
      } else {
1309
        $more_children_for = null;
1310
      }
1311

    
1312
      // 'fa-sitemap'
1313

    
1314
      $items[] =
1315
        ($is_first_item ? '' : ' ')
1316
        . $rank_separator
1317
        . l(
1318
          '<span class="' . html_class_attribute_ref($node) . '">' . $node_name . '</span>',
1319
          $path,
1320
          array(
1321
            'attributes' => array(
1322
              'class' => array('taxonomic-children-button'),
1323
              'data-cdm-taxon-uuid' => array($node->taxonUuid),
1324
              'data-cdm-classification-mode' => array('siblings'),
1325
              'data-cdm-align-with' => array('prev')
1326
            ),
1327
            'html' => true
1328
          )
1329
        );
1330
      }
1331
    }
1332

    
1333
  // add more button to the end
1334
  if(!$parent_taxon_nodes) {
1335
    // not taxon focused yet, adding button to make  the root nodes available
1336
    $items[] = '<span>'
1337
      . $more_children_icon . '&nbsp;' .
1338
      '<span class="taxonomic-children-button" data-classification-uuid="' . $current_classification_uuid
1339
      . '" data-rank-limit-uuid="' . $rank_limit_uuid . '" data-cdm-align-with="prev"> ' . $more_children_label . '<span>'
1340
      . '</span>';
1341
  } else if($more_children_for){
1342
    // last parent item has child taxon nodes
1343
    $items[] = ' <span>'
1344
      . $more_children_icon . '&nbsp;' .
1345
      '<span class="taxonomic-children-button" data-cdm-taxon-uuid="' .$more_children_for
1346
      . '" data-cdm-classification-mode="children" data-cdm-align-with="prev"> ' . $more_children_label . '</span>'
1347
      . '</span>';
1348

    
1349
  }
1350

    
1351
  $render_array['#items'] = $items;
1352

    
1353
  return $render_array;
1354
}
1355

    
1356

    
1357
/**
1358
 * @param $specimen_uuid
1359
 * @return array
1360
 *    The drupal render array for the page
1361
 *
1362
 * @ingroup compose
1363
 */
1364
function compose_cdm_specimen_page($specimen_uuid)
1365
{
1366
  drupal_set_title("Specimen Details");
1367
  $render_array = array();
1368
  RenderHints::pushToRenderStack('specimen_page');
1369

    
1370
  $specimen_table = array(
1371
      '#theme' => 'table',
1372
      '#weight' => 2,
1373
      // prefix attributes and rows with '#' to let it pass toF the theme function,
1374
      // otherwise it is handled as child render array
1375

    
1376
    '#attributes' => array('class' => 'specimens'),
1377
      '#rows' => array(),
1378
      '#prefix' => '<div id="specimens">',
1379
      '#suffix' => '</div>',
1380

    
1381

    
1382
  );
1383
  $specimen = compose_cdm_specimen_or_observation($specimen_uuid, true);
1384
  $renderArray = array(
1385
          '#theme' => 'item_list',
1386
          '#items' => array($specimen),
1387
          '#type' => 'ul');
1388
  $output = drupal_render($renderArray);
1389

    
1390
  $specimen_table['#rows'][] = array(
1391
          // An array of table rows. Every row is an array of cells, or an associative array
1392
          'data' => array($output),
1393
          'class' =>  array(
1394
              'descriptionElement',
1395
              'descriptionElement_IndividualsAssociation'
1396
          ),
1397

    
1398
  );
1399

    
1400

    
1401
 // $detail_html = compose_cdm_specimen_or_observation($specimen_uuid, true);
1402
//    $render_array['markup'] = array(
1403
//        '#prefix' => '<div id="specimens" class="page">',
1404
//        'content' => $specimen_table,
1405
//        '#suffix' => '</div>',
1406
//    );
1407
    $render_array['markup'] =  $specimen_table;
1408

    
1409
  RenderHints::popFromRenderStack();
1410
  return $render_array;
1411
}
1412

    
1413
/**
1414
 * @param $named_area_uuid
1415
 * @return array
1416
 *    The drupal render array for the page
1417
 *
1418
 * @ingroup compose
1419
 */
1420
function compose_cdm_named_area_page($named_area_uuid)
1421
{
1422

    
1423
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, array($named_area_uuid));
1424

    
1425
  $render_array = array();
1426
  RenderHints::pushToRenderStack('named_area_page');
1427

    
1428
  $groups = array();
1429
  @_description_list_group_add($groups, t('Name') . ':', $named_area->representation_L10n);
1430
  @_description_list_group_add($groups, t('IdInVocabulary') . ':', $named_area->idInVocabulary);
1431
  if(isset($named_area->level)) {
1432
    @_description_list_group_add($groups, t('Level') . ':', $named_area->level->representation_L10n);
1433
  }
1434

    
1435
  $name_area_details_elements = array(
1436
   // '#title' => $title,
1437
    '#theme' => 'description_list',
1438
    '#groups' => $groups,
1439
    '#attributes' => array('class' => html_class_attribute_ref($named_area)),
1440
  );
1441

    
1442
  $render_array[] = $name_area_details_elements;
1443

    
1444
  RenderHints::popFromRenderStack();
1445
  return $render_array;
1446
}
1447

    
1448

    
1449
/**
1450
 * Returns a drupal render array for a single reference page.
1451
 *
1452
 * Composes a page with all data on a single reference.
1453
 *
1454
 * @param string $uuid
1455
 *   An uuid for a cdm reference.
1456
 *
1457
 * @return array
1458
 *  A drupal render array
1459
 *
1460
 * @throws Exception
1461
 *
1462
 * @ingroup compose
1463
 */
1464
function compose_cdm_reference_page($uuid) {
1465

    
1466
  $pathelement = "reference_page";
1467
  RenderHints::pushToRenderStack($pathelement);
1468
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1469
  if (isset($reference->titleCache)) {
1470
    drupal_set_title($reference->titleCache, PASS_THROUGH);
1471
  }
1472

    
1473
  $field_order = array(
1474
    "title",
1475
    "abbrevTitle",
1476
    // "titleCache" abbrevTitleCache
1477
    // "citation",
1478
    "authorship",
1479
    "editor",
1480
    "publisher",
1481
    "placePublished",
1482
    "datePublished",
1483
    "year",
1484
    "edition",// Class Book.
1485
    "volume",// Class Article.
1486
    "seriesPart",
1487
    "inReference",
1488
    "nomRefBase", // Class BookSection, Book, Article.
1489
    "pages",// Class Article.
1490
    "series",// Class Article, PrintSeries.
1491
    "school",// Class Thesis.
1492
    "institution",// Class Report.
1493
    "organization",// Class Proceedings.
1494
    "nextVersion",
1495
    "previousVersion",
1496
    "isbn",// Class Book.
1497
    "issn",// Class Journal.
1498
    "doi",
1499
    "uri"
1500
  );
1501

    
1502
  $table_rows = array();
1503

    
1504
  if (!isset($reference->authorship)) {
1505
    $authorship = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $reference->uuid);
1506
    $reference->authorship = isset($authorship->titleCache) ? $authorship->titleCache : '';
1507
  }
1508

    
1509
  if (!isset($reference->inReference)) {
1510
    $reference->inReference = cdm_ws_get(CDM_WS_REFERENCE, array(
1511
      $reference->uuid,
1512
      "inReference",
1513
    ));
1514
  }
1515

    
1516
  foreach ($field_order as $fieldname) {
1517

    
1518
    if (isset($reference->$fieldname)) {
1519

    
1520
      if ($fieldname == "datePublished") {
1521
        $period = $reference->$fieldname;
1522
        $datePublished = timePeriodToString($period);
1523
        if (isset($datePublished) && $datePublished != '') {
1524
          $table_rows[] = array(
1525
            t("Date published"),
1526
            $datePublished,
1527
          );
1528
        }
1529
      }
1530
      elseif ($fieldname == "doi" && is_object($reference->doi)) {
1531
        $table_rows[] = array(
1532
          t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1533
          cdm_doi($reference->doi, false)
1534
        );
1535
      }
1536
      elseif ($fieldname == "uri" && isset($reference->uri) && $reference->uri) {
1537
        $table_rows[] = array(
1538
          t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1539
          cdm_external_uri($reference->uri, false)
1540
        );
1541
      }
1542
      elseif (is_object($reference->$fieldname)) {
1543
        if ($fieldname == "authorship") {
1544
          $dump = $reference->$fieldname;
1545
          $teammembers = "teamMembers";
1546
          $team = $dump->$teammembers;
1547
          $nameArray = array();
1548

    
1549
          foreach ($team as $member) {
1550
            if (strlen($member->lastname) > 0) {
1551
              $nname = $member->lastname;
1552
              $name = $nname;
1553
              if (strlen($member->firstname) > 0) {
1554
                $vname = $member->firstname;
1555
                $name = $vname . " " . $nname;
1556
              }
1557
              $nameArray[] = $name;
1558
            }
1559
            else {
1560
              if (strlen($member->titleCache) > 0) {
1561
                $nameArray[] = $member->titleCache;
1562
              }
1563
            }
1564
          }
1565
          $value = join($nameArray, ", ");
1566
        }
1567
        elseif ($fieldname == "inReference") {
1568
          $type = $reference->$fieldname->type;
1569
          $value = l($reference->$fieldname->titleCache, path_to_reference($reference->$fieldname->uuid));
1570
          switch ($type) {
1571
            case "Book":
1572
              $fieldname = "in book";
1573
              break;
1574
            case "Journal":
1575
              $fieldname = "in journal";
1576
              break;
1577
            case "Proceedings":
1578
              $fieldname = "in proceedings";
1579
              break;
1580
          }
1581
        }
1582
        else {
1583
          $value = $reference->$fieldname->titleCache;
1584
        }
1585

    
1586

    
1587
        if (isset($value) && $value != '') {
1588
          $table_rows[] = array(
1589
            t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1590
            $value,
1591
          );
1592
        }
1593

    
1594
      }
1595
      else {
1596
        if (isset($reference->$fieldname) && $reference->$fieldname != '') {
1597
          $table_rows[] = array(
1598
            t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1599
            $reference->$fieldname,
1600
          );
1601
        }
1602
      }
1603
    }
1604
  }
1605

    
1606
  $out = theme_table(array(
1607
    'header' => array(),
1608
    'rows' => $table_rows,
1609
    'attributes' => array(
1610
      'class' => html_class_attribute_ref($reference)
1611
    ),
1612
    'caption' => NULL,
1613
    'colgroups' => NULL,
1614
    'sticky' => NULL,
1615
    'empty' => NULL,
1616
  ));
1617

    
1618
  if(isset($reference->referenceAbstract)){
1619
    $out .= '<h2 class="block-title">Abstract</h2><div class="abstract">' . $reference->referenceAbstract . '</div>';
1620
  }
1621

    
1622

    
1623
  // Annotations below the table
1624
  $annotations = cdm_fetch_visible_annotations($reference);
1625
  $out .= theme("cdm_annotations", array('annotations' => $annotations));
1626

    
1627
  $registration_working_set = cdm_ws_get("registrationWorkingSetDTO", array($uuid));
1628
  if($registration_working_set && count($registration_working_set->registrationDTOs) > 0){
1629
    $out .= "<h3>Nomenclatural acts:</h3><div class=\"cdm-item-list registration-item-list\">";
1630
    foreach($registration_working_set->registrationDTOs as $registration_dto){
1631
      if($registration_dto->status == "PUBLISHED"){
1632
        $registration_render_a = compose_registration_dto_compact($registration_dto, 'citation');
1633
        $registration_render_a["#prefix"] = "<div class=\"item item-registration\">";
1634
        $registration_render_a["#suffix"] = "</div>";
1635
        $out .= drupal_render($registration_render_a);
1636
      }
1637
    }
1638
    $out .= "</div>";
1639
  }
1640

    
1641
  RenderHints::popFromRenderStack();
1642

    
1643
  return markup_to_render_array($out);
1644
}
1645

    
1646
/**
1647
 * Provides the the label string for taxon page tabs.
1648
 *
1649
 * The $tabname as passed to the method will be returned if no override
1650
 * label is configured in the settings.
1651
 */
1652
function cdm_taxonpage_tab_label($tabname) {
1653
  static $taxon_tabs_labels = null;
1654
  if($taxon_tabs_labels == null){
1655
    $taxon_tabs_labels = get_array_variable_merged(CDM_TAXONPAGE_TAB_LABELS, CDM_TAXONPAGE_TAB_LABELS_DEFAULT);
1656
  }
1657
  $tabname_key = strtolower($tabname);
1658
  if(isset($taxon_tabs_labels[$tabname_key]) && $taxon_tabs_labels[$tabname_key]){
1659
    return $taxon_tabs_labels[$tabname_key];
1660
  }
1661
  return $tabname;
1662
}
(7-7/10)