Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / includes / pages.inc @ 72d57201

History | View | Annotate | Download (58.1 KB)

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

    
163
        $expand_icon = font_awesome_icon_markup(
164
            'fa-plus-square-o',
165
            array(
166
                'alt' => 'Show details',
167
                'class' => array('expand_icon')
168
            )
169
        );
170
        $collapse_icon = font_awesome_icon_markup(
171
            'fa-minus-square-o',
172
            array(
173
                'alt' => 'Show details',
174
                'class' => array('collapse_icon')
175
            )
176
        );
177
        $tableId = "specimen_tree_table";
178
        $specimen_table = array(
179
            '#theme' => 'table',
180
            '#weight' => 2,
181
            // prefix attributes and rows with '#' to let it pass toF the theme function,
182
            // otherwise it is handled as child render array
183
            '#attributes' => array('class' => 'specimens',
184
                                    'id' => $tableId),
185
            '#rows' => array(),
186
        );
187
        $specimen_array = compose_specimen_array($specimensOrObservations);
188
        $rowcount = 0;
189
        foreach($specimen_array as $value){
190
            $renderArray = array(
191
                '#theme' => 'item_list',
192
                '#items' => $value['children'],
193
                '#type' => 'ul');
194
            $output = drupal_render($renderArray);
195

    
196
            $specimen_table['#rows'][] = array(
197
                'data' =>array(
198
                    array(
199
                        'data' => $expand_icon . $collapse_icon,
200
                        'class' => array('summary_row_cell', 'summary_row_icon', 'expand_column')
201
                    ),
202
                    $value['data']),
203

    
204
                'id' => 'label' . $rowcount, // summary row id
205
                'class' => array('summary_row'),
206
            );
207
            $specimen_table['#rows'][] = array(
208
                'data' =>  array(
209
                        array(
210
                            'data' => "", //empty first column
211
                            'class' => array('expand_column')
212
                        ),
213
                        array(
214
                        'data' => $output
215

    
216
                        )
217
                    ),
218
                    'class' =>  array('detail_row')
219
//                'class' =>  array(
220
//                    'descriptionElement',
221
//                    'descriptionElement_IndividualsAssociation'
222
 //               ),
223
            );
224
            $rowcount++;
225

    
226
        }
227
        drupal_add_js_rowToggle("#".$tableId);
228

    
229
        $render_array['specimen_list'] = $specimen_table;
230

    
231

    
232
    }
233
    else{
234
        //BOTTOM-UP-SPECIMEN-TABLE
235
        // --- generate the specimen list as table
236
        $specimen_table = array(
237
            '#theme' => 'table',
238
            '#weight' => 2,
239
            // prefix attributes and rows with '#' to let it pass toF the theme function,
240
            // otherwise it is handled as child render array
241
            '#attributes' => array('class' => 'specimens'),
242
            '#rows' => array(),
243
        );
244

    
245
        if ($specimensOrObservations) {
246

    
247
            foreach ($specimensOrObservations as $specimenOrObservation) {
248

    
249
                $mediaList = array();
250
                if (is_array($specimenOrObservation->_fieldObjectMedia)) {
251
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_fieldObjectMedia);
252
                }
253
                if (is_array($specimenOrObservation->_derivedUnitMedia)) {
254
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_derivedUnitMedia);
255
                }
256

    
257

    
258
                // typelabel will contain the typeStatus
259
                $type_label = '';
260
                $typeDesignationPager = cdm_ws_get(CDM_WS_OCCURRENCE . '/$0/specimenTypeDesignations', $specimenOrObservation->uuid);
261
                if (isset($typeDesignationPager) and isset($typeDesignationPager->records)) {
262
                    $type_status = array();
263
                    foreach ($typeDesignationPager->records as $typeDesignation) {
264
                        if (isset($typeDesignation->typeStatus->representation_L10n)){
265
                            $type_status[] = $typeDesignation->typeStatus->representation_L10n;
266
                        }
267
                    }
268
                    $type_label = implode(', ', $type_status);
269
                    if($type_label){
270
                        $type_label .= ': ' ;
271
                    }
272
                }
273

    
274
                // --- Specimen entry as dynamic label:
275
                //     -> Dynabox for the specimenOrObservation
276
                $gallery_name = $specimenOrObservation->uuid;
277

    
278
                $derived_unit_ws_request = cdm_compose_url(CDM_WS_OCCURRENCE, array( $specimenOrObservation->uuid));
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
                //here we should use the data we already have
300
                $label_html = cdm_dynabox(
301
                  $specimenOrObservation->uuid,
302
                  $type_label . $specimenOrObservation->titleCache,
303
                  $derived_unit_ws_request,
304
                  'cdm_specimen_or_observation',
305
                  'Click for details',
306
                  array('div', 'div'),
307
                  array(),
308
                  null, // $content_element_selector
309
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').hide(); }', // open_callback
310
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').show(); }' // close_callback
311
                );
312

    
313
                // --- Render associated media.
314
                $gallery_html = '';
315
                if (count($mediaList) > 0) {
316
                    $gallery_settings = getGallerySettings(CDM_DATAPORTAL_SPECIMEN_GALLERY_NAME);
317
                    $captionElements = array(
318
                        '#uri' => t('open media'),
319
                    );
320

    
321
                    $gallery_html = compose_cdm_media_gallerie(array(
322
                        'mediaList' => $mediaList,
323
                        'galleryName' => $gallery_name,
324
                        'maxExtend' => $gallery_settings['cdm_dataportal_media_maxextend'],
325
                        'cols' => $gallery_settings['cdm_dataportal_media_cols'],
326
                        'maxRows' => isset($gallery_settings['cdm_dataportal_media_maxRows']) ? isset($gallery_settings['cdm_dataportal_media_maxRows']) : null,
327
                        'captionElements' => $captionElements,
328
                        'mediaLinkType' => 'LIGHTBOX',
329
                        'alternativeMediaUri' => NULL,
330
                        'galleryLinkUri' => NULL,
331
                    ));
332
                }
333

    
334
                $specimen_table['#rows'][] = array(
335
                    // An array of table rows. Every row is an array of cells, or an associative array
336
                    'data' => array(
337
                        // Each cell can be either a string or an associative array
338
                        $label_html . $gallery_html
339
                    ),
340
                    'class' =>  array(
341
                        'descriptionElement',
342
                        'descriptionElement_IndividualsAssociation'
343
                    ),
344
                );
345
            }
346
        }
347

    
348
        $render_array['specimen_list'] = $specimen_table;
349
        $render_array['pager'] = markup_to_render_array(
350
            theme('cdm_pager', array(
351
                'pager' => $pager,
352
                'path' => $_REQUEST['q'],
353
                'parameters' => $_REQUEST,
354
            )),
355
            10 // weight
356
        );
357
    }
358

    
359
    RenderHints::popFromRenderStack();
360
    return $render_array;
361
}
362

    
363
/**
364
 * Creates the drupal render array for the table showing all derivated which are
365
 * derive from a common gathering event.
366
 *
367
 * @param $field_unit_uuids array
368
 *  An array of uuids for cdm FieldUnit entities.
369
 *
370
 * @return array
371
 *  A drupal render array for a table
372
 *
373
 * @ingroup compose
374
 */
375
function compose_specimen_table($field_unit_uuids)
376
{
377
// get icon images
378
  $expand_icon = font_awesome_icon_markup(
379
    'fa-plus-square-o',
380
    array(
381
      'alt' => 'Show details',
382
      'class' => array('expand_icon')
383
    )
384
  );
385
  $collapse_icon = font_awesome_icon_markup(
386
    'fa-minus-square-o',
387
    array(
388
      'alt' => 'Show details',
389
      'class' => array('collapse_icon')
390
    )
391
  );
392
  $detail_image_icon = '<img title="Detail Image" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/detail_image_derivate-16x16-32.png' . '"/>';
393
  $checked_box_icon = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/step_done.gif' . '"/>';
394
  $sequence_icon = '<img title="Molecular Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/sequence_derivate-16x16-32.png' . '"/>';
395
  $character_data_icon = '<img title="Character Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/character_data_derivate-16x16-32.png' . '"/>';
396

    
397
  $rowcount = 0;
398
  $rows = array();
399

    
400
  foreach ($field_unit_uuids as $field_unit_uuid) {
401

    
402
    //get derivate hierarchy for the FieldUnit
403
    $derivateHierarchy = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($field_unit_uuid, 'derivateHierarchy'));
404
    if ($derivateHierarchy) {
405
      //summary row
406
      $rows[] = array(
407
        'data' => array(
408
          array(
409
            'data' => $expand_icon . $collapse_icon,
410
            'class' => array('summary_row_cell', 'summary_row_icon', 'expand_column')
411
          ),
412
          array(
413
            'data' => $derivateHierarchy->country,
414
            'class' => array('summary_row_cell')
415
          ),
416
          array(
417
            'data' => $derivateHierarchy->date,
418
            'class' => array('summary_row_cell')
419
          ),
420
          array(
421
            'data' => $derivateHierarchy->collectingString,
422
            'class' => array('summary_row_cell')
423
          ),
424
          @array(
425
            'data' => $derivateHierarchy->collection,
426
            'class' => array('summary_row_cell')
427
          ),
428
          array(
429
            'data' => $derivateHierarchy->hasType ? $checked_box_icon : "",
430
            'class' => array('summary_row_cell', 'summary_row_icon')
431
          ),
432
          array(
433
            'data' => $derivateHierarchy->hasSpecimenScan ? $checked_box_icon : "",
434
            'class' => array('summary_row_cell', 'summary_row_icon')
435
          ),
436
          array(
437
            'data' => ($derivateHierarchy->hasDna ? $sequence_icon : "") . " "
438
              . ($derivateHierarchy->hasDetailImage ? $detail_image_icon : "") . " "
439
              . ($derivateHierarchy->hasCharacterData ? $character_data_icon : ""),
440
            'class' => array('summary_row_cell', 'summary_row_icon')
441
          )
442
        ),
443
        'id' => 'derivate_summary' . $rowcount, // summary row id
444
        'class' => array('summary_row'),
445
      );
446

    
447
      //assemble field unit details
448
      $detail_html = "";
449
      // - citation
450
      if ($derivateHierarchy->citation) {
451
        $detail_html .= create_label("Citation") . $derivateHierarchy->citation . "<br>";
452
      }
453
      //assemble specimen details
454
      if ($derivateHierarchy->derivates) {
455
        foreach ($derivateHierarchy->derivates as $preservedSpecimenDTO) {
456
          $detail_html .= "<br>";
457
          $detail_html .= render_cdm_specimenDTO_page($preservedSpecimenDTO);
458
      }
459
      }
460
      $detail_html .= "<br>";
461
      //detail row resp. one BIG detail cell
462
      $rows[] = array(
463
        'data' => array(
464
          array(
465
            'data' => "", //empty first column
466
            'class' => array('expand_column')
467
          ),
468
          array(
469
            'data' => $detail_html,
470
            'colspan' => 7,
471
          ),
472
        ),
473
        'id' => 'derivate_details' . $rowcount,//details row ID
474
        'class' => array('detail_row'),
475
      );
476
      $rowcount++;
477
    }
478
  }
479

    
480
  $tableId = "derivate_hierarchy_table";
481
  $derivateHierarchyTable = array(
482
    "#theme" => "table",
483
    "#weight" => 2,
484
    "#header" => array(
485
      array(
486
        'data' => "",
487
        'class' => array('expand_column')
488
      ),
489
      "Country", "Date", "Collector + collecting number", "Herbaria", "Type", "Scan", "Derivatives"),
490
    "#rows" => $rows,
491
    "#attributes" => array(
492
      "id" => $tableId,
493
      "border" => 2
494
    )
495
  );
496

    
497
  //add toggle functionality to derivate hierarchy table
498
  drupal_add_js_rowToggle("#" . $tableId);
499

    
500
  return $derivateHierarchyTable;
501
}
502

    
503
function create_html_link($link, $openInExternalWindow=false){
504
    $html = "";
505
    if($link->uri && $link->uri!=""){
506
        $html .= '<a  href="' . $link->uri . '"';
507
        if($openInExternalWindow){
508
            $html .= ' target="_blank"';
509
        }
510
        $html .= '>' . $link->linkText . '</a>';
511
    }
512
    else{
513
        $html .= $link->linkText;
514
    }
515
    return $html;
516
}
517

    
518
/**
519
 * Creates HTML links from the given link list concatenated by default by a comma.
520
 * @param $linkList the list with Link objects having "uri" and "linkText" as members
521
 * @return string the assembled HTML string containing the links
522
 */
523
function create_html_links($linkList, $openInExternalWindow=false, $separator=", ")
524
{
525
    $html = "";
526
    if ($linkList) {
527
        foreach ($linkList as $link) {
528
            $html .= create_html_link($link, $openInExternalWindow).$separator;
529
        }
530
        $html = rtrim($html, $separator);
531
    }
532
    return $html;
533
}
534

    
535
/**
536
 * Composes a taxon page which can consist of multiple parts like
537
 * 'General', 'Synonymy', 'Images', 'Keys'. These parts can be displayed
538
 * as tabs or as sections of a single page.
539
 *
540
 * It is headed by the name of the accepted taxon without author and reference.
541
 *
542
 * @param $taxon
543
 *   The CDM Taxon Instance to compose the page for.
544
 * @param $page_part
545
 *   Name of the part to display, valid values are:
546
 *    - 'description' -  for the general part
547
 *    - 'images'
548
 *    - 'synonymy'
549
 *    - 'keys'
550
 *    - 'all'
551
 *
552
 * @return array
553
 *   A drupal render array
554
 *
555
 * @ingroup compose
556
 */
557
function compose_cdm_taxon_page($taxon, $page_part = 'description') {
558

    
559
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
560
  $http_request_params = drupal_get_query_parameters();
561

    
562
  // add all mandatory js sources
563
  _add_js_footnotes();
564

    
565

    
566
  $render_array = array();
567
  $weight = 0; // the weight for the render array elements
568

    
569
  $tabsToDisplay = variable_get('cdm_taxonpage_tabs_visibility', unserialize(TAXONPAGE_VISIBILITY_OPTIONS_DEFAULT));
570

    
571
  $page_part = variable_get('cdm_dataportal_taxonpage_tabs', 1) ? $page_part : 'all';
572

    
573
  $synonymy_as_tab = variable_get(CDM_SYNONYMY_AS_TAB, CDM_SYNONYMY_AS_TAB_DEFAULT) === 1;
574
  if(!$synonymy_as_tab){
575
    unset($tabsToDisplay["Synonymy"]);
576
    // the synonymy is located in the general part in this case
577
    if($page_part == 'synonymy'){
578
      $page_part = 'description';
579
    }
580
  }
581

    
582
  $media = _load_media_for_taxon($taxon);
583

    
584

    
585
  if (!isset($media[0]) || ($tabsToDisplay["Images"] == '0')) {
586
    taxon_page_tabs_hidden_add('images');
587
  }
588

    
589
  // --- GET specimensOrObservations --- //
590
  $specimensOrObservations = cdm_ws_get(CDM_WS_TAXON, array( $taxon->uuid, 'specimensOrObservationsCount'));
591

    
592
  $specimensOrObservationsCount = $specimensOrObservations != null ? $specimensOrObservations->result : 0;
593
  if ($specimensOrObservationsCount == 0 || ($tabsToDisplay["Specimens"] == '0')) {
594
    taxon_page_tabs_hidden_add('specimens');
595
  }
596

    
597
  // --- GET polytomousKeys --- //
598
  $polytomousKeysPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, NULL, "findByTaxonomicScope=$taxon->uuid");
599
  $identificationKeyCount = 0;
600
  if ($polytomousKeysPager) {
601
    $identificationKeyCount += $polytomousKeysPager->count;
602
  }
603
  if ($identificationKeyCount == 0 || ($tabsToDisplay["Keys"] == '0')) {
604
    taxon_page_tabs_hidden_add('keys');
605
  }
606

    
607
  // --- GET TaxonNodeAgentRelations --- //
608
  $current_classification_uuid = get_current_classification_uuid();
609
  $taxon_node_agent_relations_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
610
      array(
611
          $taxon->uuid,
612
          $current_classification_uuid,
613
      ),
614
      "pageSize=1&pageIndex=0"// we are only interested into the count so we are fetching only one item, o is not possible!
615
  );
616
  if (!$taxon_node_agent_relations_pager || $taxon_node_agent_relations_pager->count == 0){
617
      taxon_page_tabs_hidden_add('experts');
618
  }
619

    
620
  if (!isset($tabsToDisplay["Synonymy"]) || $tabsToDisplay["Synonymy"] == '0') {
621
    taxon_page_tabs_hidden_add('synonymy');
622
  }
623

    
624
  // -------------------------------------------- //
625

    
626
  if (variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR) && isset($_REQUEST['acceptedFor'])) {
627
    $render_array['accepted_for'] = markup_to_render_array(cdm_accepted_for($_REQUEST['acceptedFor']), $weight++);
628
  }
629

    
630
  // --- PAGE PART: DESCRIPTION --- //
631
  if (!taxon_page_tabs_hidden_check('description') && ($page_part == 'description' || $page_part == 'all')) {
632

    
633
    $merged_tree = merged_taxon_feature_tree($taxon);
634

    
635

    
636
    $render_array['general'] = compose_cdm_taxon_page_profile($taxon, $merged_tree, $media, !$synonymy_as_tab);
637
    $render_array['general']['#weight'] = $weight++;
638
    $render_array['general']['#prefix'] = '<div id="general" class="page-part">';
639
    $render_array['general']['#suffix'] = '</div>';
640
  }
641

    
642
  // --- PAGE PART: IMAGES --- //
643
  if (!taxon_page_tabs_hidden_check('images') && ($page_part == 'images' || $page_part == 'all')) {
644
    $images_html = '<div id="images" class="page-part">';
645
    if ($page_part == 'all') {
646
      $images_html .= '<h2>' . t(cdm_taxonpage_tab_label('Images')) . '</h2>';
647
    }
648
    // Get the image gallery as configured by the admin.
649
    $default_image_gallery = 'default';
650
    $configured_image_gallery_viewer = variable_get('image_gallery_viewer', 'default');
651
    $taxon_image_gallery = '<div class="error">No image gallery viewer configured</div>';
652
    if($configured_image_gallery_viewer == $default_image_gallery || $configured_image_gallery_viewer == 'fsi'){
653
      // the fsi_gallery requires a flash plugin, in case the client browser is not supporting
654
      // flash we also need to provide an the default gallery as alternative
655
      $taxon_image_gallery = '<div id="default-gallery-viewer">' .
656
        call_user_func_array('taxon_image_gallery_' . $default_image_gallery, array(
657
          $taxon,
658
          $media,
659
        ))
660
        . '</div>';
661
    }
662
    if($configured_image_gallery_viewer == 'fsi'){
663
      $taxon_image_gallery .= '<div id="'. $configured_image_gallery_viewer .'-gallery-viewer">' .
664
        call_user_func_array('taxon_image_gallery_' . $configured_image_gallery_viewer, array(
665
          $taxon,
666
          $media,
667
        ))
668
       . '</div>';
669
    }
670
    $images_html .= $taxon_image_gallery;
671
    $images_html .= '</div>';
672
    $render_array['images'] = markup_to_render_array($images_html, $weight++);
673
  }
674

    
675
  // --- PAGE PART: SYNONYMY --- //
676
  if (!taxon_page_tabs_hidden_check('synonymy') && (($page_part == 'synonymy' || $page_part == 'all') && $synonymy_as_tab)) {
677
    $synonymy_html = '<div id="synonymy" class="page-part">';
678
    if ($page_part == 'all') {
679
      $synonymy_html .= '<h2>' . t(cdm_taxonpage_tab_label('Synonymy')) . '</h2>';
680
    }
681
    $addAcceptedTaxon = variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE);
682

    
683
    $synonym_a = compose_cdm_taxon_page_synonymy($taxon, $addAcceptedTaxon);
684
    $synonymy_html .= drupal_render($synonym_a);
685

    
686
    $synonymy_html .= '</div>';
687
    $render_array['synonymy'] = markup_to_render_array($synonymy_html, $weight++);
688

    
689
  }
690

    
691
  // --- PAGE PART: SPECIMENS --- //
692
  if (!taxon_page_tabs_hidden_check('specimens') && ($specimensOrObservationsCount > 0 && ($page_part == 'specimens' || $page_part == 'all'))) {
693
    $render_array['specimens'] = array(
694
        '#prefix' => '<div id="specimens" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Specimens')) . '</h2>' : ''),
695
        'content' => cdm_dataportal_taxon_page_specimens($taxon), // returns render array
696
        '#suffix' => '</div>',
697
    );
698
  }
699

    
700
  // --- PAGE PART: KEYS --- //
701
  if(!taxon_page_tabs_hidden_check('keys')){
702
    if ($identificationKeyCount == 1 && $page_part == 'keys'){
703
      drupal_goto(path_to_key($polytomousKeysPager->records[0]->class, $polytomousKeysPager->records[0]->uuid));
704
    }
705
    else if ($identificationKeyCount > 0 && ($page_part == 'keys' || $page_part == 'all')) {
706
      $keys_html = '<div id="keys" class="page-part">';
707
      if ($page_part == 'all') {
708
        $keys_html .= '<h2>' . t(cdm_taxonpage_tab_label('Keys')) . '</h2>';
709
      }
710
      $keys_html .= theme('cdm_block_IdentificationKeys', array('taxonUuid' => $taxon->uuid));
711
      $keys_html .= '</div>';
712
      $render_array['keys'] = markup_to_render_array($keys_html, $weight++);
713
    }
714
  }
715

    
716
  // --- PAGE PART: EXPERTS --- //
717

    
718
  if (!taxon_page_tabs_hidden_check('experts') && ($page_part == 'experts' || $page_part == 'all')) {
719
    $render_array['experts'] = array(
720
        '#prefix' => '<div id="experts" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Experts')) . '</h2>' : ''),
721
        'content' => compose_cdm_taxon_page_experts($taxon), // returns render array
722
        '#suffix' => '</div>',
723
    );
724
  }
725

    
726
  // ------------------ END OF PARTS -------------- //
727

    
728
  // adjust weights of page and toc elements according to the settings
729
  $taxontabs_weights = get_array_variable_merged(CDM_TAXONPAGE_TAB_WEIGHT, CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
730
  foreach($taxontabs_weights as $tab_key => $weight){
731
    if(isset($render_array[$tab_key])){
732
      $render_array[$tab_key]['#weight'] = $weight;
733
    }
734
  }
735

    
736

    
737
  // set up the TOC for the pages which contain all pageparts
738
  if($page_part == 'all') {
739

    
740
    asort($taxontabs_weights);
741
    foreach(array_keys($taxontabs_weights) as $tab_key){
742
      if(isset($render_array[$tab_key])){
743
        if($tab_key != 'general'){
744
          // add entry for page part
745
          $toc_elements[] = array(
746
              'data' => l(t(cdm_taxonpage_tab_label(ucfirst($tab_key))), $_GET['q'], array('fragment' => $tab_key, 'query' => $http_request_params)),
747
              'class' => array('page-part-toc-item-' . $tab_key)
748
          );
749
        } else {
750
          // add content of profile part instead
751
          if(isset($render_array['general'])) {
752
            // in case all tabs are shown at once the feature tocs
753
            // should be integrated into the tabs toc as sub list
754
            // and the profile image should be on top of the page
755
            if(isset($render_array['general']['taxon_description_feature_toc'])){;
756
            foreach ($render_array['general']['taxon_description_feature_toc']['#items'] as $profile_toc_item){
757
              $toc_elements[] = $profile_toc_item;
758
            }
759
            unset($render_array['general']['taxon_description_feature_toc']);
760
            }
761
          }
762
        }
763
      }
764
    }
765

    
766
    // move profile image in page structure
767
    if(isset($render_array['general']['taxon_profile_image'])){
768
      $render_array['profile_image'] = $render_array['general']['taxon_profile_image'];
769
      $render_array['profile_image']['#weight'] = -100;
770
      unset($render_array['general']['taxon_profile_image']);
771
    }
772

    
773
    // finally add the table of contents to the render array
774
    $render_array['toc'] = array(
775
        '#theme' => 'item_list',
776
        '#items' => $toc_elements,
777
        '#title' => t('Content'),
778
        '#weight' => -101,
779
        '#suffix' => '</div>',
780
        '#prefix'=> '<div id="page-toc">'
781
    );
782
  }
783

    
784

    
785
  return $render_array;
786
}
787

    
788
/**
789
 * TODO should this function really be a compose function?
790
 *     For a compose function must there always be a theme function with the same name? (ak 8.8.2013)
791
 *
792
 * composes and returns an render array containing the components of the taxon profile tab:
793
 *  - 'taxon_profile_image'
794
 *  - 'taxon_description_feature_toc'
795
 *  - 'taxon_description_features'
796
 *
797
 *
798
 * @param object taxon
799
 * @param object $merged_tree
800
 * @param object media
801
 * @param bool $add_synonymy
802
 *
803
 * @return array
804
 *   A Drupal render array with the following elements:
805
 *     - 'taxon_profile_image'
806
 *     - 'taxon_description_feature_toc'
807
 *     - 'taxon_description_features'
808
 *
809
 * @throws Exception
810
 *
811
 * @ingroup compose
812
 */
813
function compose_cdm_taxon_page_profile($taxon, $merged_tree, $media, $add_synonymy) {
814

    
815
  $render_array = array();
816

    
817
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
818

    
819
  $hide_taxon_profile_image = FALSE;
820
  if (variable_get('image_hide_rank', '0') != '0' && isset($taxon->name->rank->uuid)) {
821
    $rankCompare = rank_compare($taxon->name->rank->uuid, variable_get('image_hide_rank', '-99'));
822
    $hide_taxon_profile_image = ($rankCompare > -1);
823
  }
824

    
825
  if ($taxon_profile_image_settings['show'] && !$hide_taxon_profile_image) {
826

    
827
    $representationPart = new stdClass();
828
    $attributes = array();
829
    if (isset($media[0])) {
830
      // due to a bug the portal/taxon/{uuid}/media service only delivers a filtered media object
831
      // which only contains the thumbnail representation even if the height and width filters are not set.
832
      // -->
833
      $preferred_media = cdm_ws_get(CDM_WS_MEDIA, $media[0]->uuid);
834
      $preferred_representations = cdm_preferred_media_representations($preferred_media, array(
835
        'image/jpg',
836
        'image/jpeg',
837
        'image/png',
838
        'image/gif',
839
      ),
840
        $taxon_profile_image_settings['maxextend'],
841
        $taxon_profile_image_settings['maxextend']
842
      );
843
      if(count($preferred_representations) > 0){
844

    
845
        $representation = array_shift($preferred_representations);
846
        $representationPart = $representation->parts[0];
847
        $attributes['alt'] = $representationPart->uri;
848

    
849
        if (!empty($taxon_profile_image_settings['media_uri_query'])) {
850
          $representationPart->uri = $representationPart->uri
851
            . (strpos($representationPart->uri, '?') !== FALSE ? '&' : '?')
852
            . $taxon_profile_image_settings['media_uri_query'];
853
        }
854
      }
855
    }
856
    else {
857
      if ($taxon_profile_image_settings['custom_placeholder_enabled']) {
858
        // show placeholder image instead
859
        if (!empty($taxon_profile_image_settings['custom_placeholder_image_on']) && !empty($taxon_profile_image_settings['custom_placeholder_image_fid'])) {
860
          // use the user provided image
861
          $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
862
          $url = file_create_url($profile_image_file->uri);
863
          $image_info = image_get_info($profile_image_file->uri);
864
          $representationPart->width = $image_info['width'];
865
          $representationPart->height = $image_info['height'];
866
          $representationPart->uri = $url;
867
        }
868
        else {
869
          // use the hard coded default
870
          $representationPart->width = 184;
871
          $representationPart->height = 144;
872
          $representationPart->uri = base_path() . drupal_get_path('module',
873
              'cdm_dataportal') . '/images/no_picture.png';
874
        }
875
        $attributes['alt'] = "no image available";
876
      }
877
    }
878

    
879
    if (isset($representationPart->uri)) {
880
      $profile_image = cdm_media_gallerie_image($representationPart, $taxon_profile_image_settings['maxextend'], FALSE, $attributes);
881
      // NOTE: style="width:${maxextend}px' is needed for IE8 !!!
882
      $render_array['taxon_profile_image'] = markup_to_render_array('<div id="taxonProfileImage" style="width:' . $taxon_profile_image_settings['maxextend'] . 'px">' . $profile_image . '</div>',
883
        -101);
884
    }
885
  }
886

    
887
  if($add_synonymy){
888
    $synonymy_a = compose_cdm_taxon_page_synonymy($taxon, true);
889
    $synonymy_a['#weight'] = -102;
890
    $render_array['synonymy'] = $synonymy_a;
891
  }
892

    
893
  $pseudo_feature_blocks = array();
894
  $pseudo_feature_block_toc_items = array();
895

    
896

    
897
  // Render the sections for each real feature
898
  $feature_block_list = make_feature_block_list($merged_tree->root->childNodes, $taxon);
899

    
900
  // Bibliography
901
  $bibliography_settings = get_bibliography_settings();
902
  if($bibliography_settings['enabled'] == 1){
903
    $bibliography_markup = FootnoteManager::renderFootnoteList('BIBLIOGRAPHY', '');
904
    if($bibliography_markup) {
905
      $feature_bibliography = make_pseudo_feature('Bibliography', 'BIBLIOGRAPHY');
906
      $bibliography_block = feature_block(t('Bibliography'), $feature_bibliography);
907
      $bibliography_item = markup_to_render_array($bibliography_markup);
908
      $bibliography_block->content[] = compose_feature_block_wrap_elements(array($bibliography_item), $feature_bibliography);
909

    
910
      $pseudo_feature_block_toc_items['Bibliography']= 'bibliography';
911
      $pseudo_feature_blocks[] = $bibliography_block;
912
    }
913
  }
914

    
915
  $render_array['taxon_description_features'] = _block_get_renderable_array(
916
    array_merge($feature_block_list, $pseudo_feature_blocks)
917
  );
918

    
919
  if($pseudo_feature_block_toc_items){
920
    foreach ($pseudo_feature_block_toc_items as $label=>$fragment){
921
      cdm_toc_list_add_item($label, $fragment);
922
    }
923
  }
924

    
925
  // create the table of content
926
  $toc = array(
927
      '#theme' => 'item_list',
928
    '#items' => cdm_toc_list(),
929
      '#title' => t('Content'),
930
    '#weight' => -100,                  // move to the top
931
      '#suffix' => '</div>',
932
      '#prefix'=> '<div id="page-toc">'
933
  );
934
  $render_array['taxon_description_feature_toc'] = $toc;
935

    
936
  return $render_array;
937
}
938

    
939

    
940
/**
941
 * Returns HTML containing the synonymy for the accepted taxon.
942
 *
943
 * Shows the whole synonymy for the accepted taxon.
944
 * The synonymy list is headed by the complete scientific name
945
 * of the accepted taxon with nomenclatural reference.
946
 *
947
 * @param object $taxon
948
 * @param boolean $add_accepted_taxon
949
 *
950
 * @return array
951
 *  Drupal render array for the synonymy
952
 *
953
 * @throws Exception
954
 *
955
 * @ingroup compose
956
 */
957
function compose_cdm_taxon_page_synonymy($taxon, $add_accepted_taxon) {
958

    
959
  RenderHints::pushToRenderStack('taxon_page_synonymy');
960

    
961
  // footnote key for the homotypic group and accepted taxon,
962
  // both should have the same footnote key
963
  RenderHints::setFootnoteListKey(RenderHints::getRenderPath());
964

    
965
  $synomymie = cdm_ws_get(CDM_WS_PORTAL_TAXON_SYNONYMY, array($taxon->uuid));
966

    
967
  $out = '';
968

    
969
  // Render accepted taxon.
970
  //
971
  // foonotes of the accepted taxon will be rendered in the homotypic group section
972
  // even if there are not synonyms in the homotypic group
973
  // homotypic group and accepted taxon should have the same footnote key
974
  $referenceUri = '';
975
  if ($add_accepted_taxon) {
976
    // remember the last part of the render path
977
    $synonymy_render_path = RenderHints::getRenderPath();
978
    // set new render path for the accepted taxon so
979
    // it can be styled differently via the name render part definitions
980
    RenderHints::pushToRenderStack('accepted_taxon');
981
    $accepted_name = '';
982
    if (variable_get(CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE, 0)) {
983
      $label = variable_get(CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE_LABEL, CDM_SYNONYMY_ACCEPTED_TAXON_SEC_SEPARATE_LABEL_DEFAULT);
984
      $accepted_name .= '<div class="secReference"><span class="label">' . t($label) . ':</span> ' . $taxon->sec->titleCache . '</div>';
985
    }
986
    if (isset($taxon->name->nomenclaturalReference)) {
987
      $referenceUri = url(path_to_reference($taxon->name->nomenclaturalReference->uuid));
988
    }
989

    
990
    $accepted_name .= '<div class="accepted-name">';
991
    $accepted_name .= render_taxon_or_name($taxon, NULL, $referenceUri);
992

    
993
    $name_relations = cdm_name_relationships_for_taxon($taxon);
994
    $name_relationships = compose_name_relationships_inline($name_relations, $taxon->name->uuid, $taxon->uuid);
995
    // Render relationships of accepted name.
996
    if(isset($name_relationships['list']['items'][0])){
997
      $accepted_name .= ' ' . drupal_render($name_relationships);
998
    }
999

    
1000
    // handle annotations of the name and taxon
1001
    $special_annotations_array = array();
1002
    $special_annotations_array[] = $taxon->name;
1003
    $special_annotations_array[] = $taxon;
1004
    $accepted_name .= theme('cdm_annotations_as_footnotekeys', array(
1005
        'cdmBase_list' => $special_annotations_array,
1006
        'footnote_list_key' => $synonymy_render_path . '-annotations')
1007
    );
1008
    $accepted_name .= '</div>';
1009
    RenderHints::popFromRenderStack();
1010
  }
1011

    
1012
  // --- Render homotypic synonymy group
1013
  if (!empty($accepted_name)) {
1014
    $out .= $accepted_name;
1015
  }
1016

    
1017
  // Render the homotypicSynonymyGroup including the type information.
1018
  $out .= theme(
1019
    'cdm_homotypicSynonymyGroup',
1020
    array(
1021
      'synonymList' => $synomymie->homotypicSynonymsByHomotypicGroup,
1022
      'accepted_taxon_name_uuid' => $taxon->name->uuid
1023
    )
1024
  );
1025

    
1026

    
1027
  // Render accepted taxon heterotypic synonymy groups.
1028
  if ($synomymie->heterotypicSynonymyGroups) {
1029
    foreach ($synomymie->heterotypicSynonymyGroups as $homotypicalGroup) {
1030
      $out .= theme('cdm_heterotypicSynonymyGroup', array('homotypicalGroup' => $homotypicalGroup));
1031
    }
1032
  }
1033
  // Render taxon relationships.
1034
  if (variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT)) {
1035
    $taxonRelationshipsDTO = cdm_ws_get(CDM_WS_PORTAL_TAXON_RELATIONS_DTO, $taxon->uuid);
1036
    $out .= cdm_taxonRelationships($taxonRelationshipsDTO, $taxon);
1037
  }
1038

    
1039
  RenderHints::popFromRenderStack();
1040

    
1041
  return markup_to_render_array($out);
1042
}
1043

    
1044

    
1045
/**
1046
 * composes and returns an render array for the experts associated with the given taxon
1047
 *
1048
 * @param object taxon
1049
 *
1050
 * @return array
1051
 *   A Drupal render array for a table with the experts
1052
 *
1053
 * @ingroup compose
1054
 */
1055
function compose_cdm_taxon_page_experts($taxon){
1056

    
1057
  $render_array = array();
1058
  if(!isset($taxon->uuid)){
1059
    return $render_array;
1060
  }
1061

    
1062
  $current_classification_uuid = get_current_classification_uuid();
1063
  // TODO use cdm_ws_fetchall below but this failes! needs fix!
1064
  $taxon_node_agent_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
1065
    array(
1066
      $taxon->uuid,
1067
      $current_classification_uuid
1068
    )
1069
  );
1070

    
1071
  $header = array(
1072
    array('data' => t('Expert')),
1073
    array('data' => t('Role'))
1074
  );
1075
  $rows = array();
1076

    
1077

    
1078
  foreach($taxon_node_agent_relations->records as $taxon_node_agent_relation){
1079

    
1080

    
1081
    $expert_role_id = $taxon_node_agent_relation->agent->uuid . '-' . $taxon_node_agent_relation->type->uuid;
1082
    $expert_details_container_id = 'expert_details_' . $expert_role_id;
1083

    
1084
    $agent_label_markup = cdm_dynabox(
1085
      'expert_' . $expert_role_id,
1086
      $taxon_node_agent_relation->agent->titleCache,
1087
      // specifying both ends of the relationship will return only one record in the pager
1088
      cdm_compose_url(CDM_WS_PORTAL_AGENT,
1089
         array($taxon_node_agent_relation->agent->uuid, 'taxonNodeAgentRelations'),
1090
        'taxon_uuid=' . $taxon->uuid . '&relType_uuid=' . $taxon_node_agent_relation->type->uuid),
1091
      'cdm_taxon_expert',
1092
      'Click for details',
1093
      array('div', 'div'),
1094
      array(), // attributes
1095
      '#' . $expert_details_container_id // $content_element_selector
1096
    );
1097

    
1098
    // Expert and Role
1099
    $rows[] = array(
1100
      'data' => array(
1101
        array(
1102
          'data' => $agent_label_markup,
1103
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->agent))
1104
        ),
1105
        array(
1106
          'data' => $taxon_node_agent_relation->type->representation_L10n,
1107
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->type))
1108
        )
1109
      )
1110
    );
1111
    // Agent details
1112
    $rows[] = array(
1113
      'data' => array(
1114
        array(
1115
          'data' => '<!-- expert_details_container -->',
1116
          'id' => $expert_details_container_id,
1117
          'colspan' => 2
1118
        )
1119
      )
1120
    );
1121

    
1122
  }
1123

    
1124

    
1125
  $render_array['experts_table'] = array(
1126
    '#theme' => 'table',
1127
    '#header' => $header,
1128
    '#rows' => $rows,
1129
  );
1130

    
1131

    
1132
  return $render_array;
1133
}
1134

    
1135

    
1136
/**
1137
 * Manages the tabs to be hidden in the taxon page.
1138
 *
1139
 * The tabs are identified by their last menu link path element:
1140
 *  - description
1141
 *  - synonymy
1142
 *  - images
1143
 *  - specimens
1144
 *  - key
1145
 *
1146
 * Internally the tabs are stored in a static variable which is
1147
 * managed by drupal_static().
1148
 *
1149
 * @param string $add_tab
1150
 *   Optional parameter. The given string will be added to the array of tabs
1151
 *
1152
 * @return
1153
 *   The array of tabs
1154
 */
1155
function taxon_page_tabs_hidden_add($add_tab = NULL) {
1156
  $tabs = &drupal_static('taxon_page_tabs_hidden');
1157

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

    
1162
  if (isset($add_tab) && !array_key_exists($add_tab, $tabs)) {
1163
    $tabs[] = $add_tab;
1164
  }
1165

    
1166
  return $tabs;
1167
}
1168

    
1169
/**
1170
 * Manages the tabs to be hidden in the taxon page.
1171
 *
1172
 * The tabs names are identified by their last menu link path element:
1173
 *  - description
1174
 *  - synonymy
1175
 *  - images
1176
 *  - specimens
1177
 *  - key
1178
 *
1179
 * Internally the tabs are stored in a static variable which is
1180
 * managed by drupal_static().
1181
 *
1182
 * @param string $tabname
1183
 *   The name of the tab to check
1184
 *
1185
 * @return boolean
1186
 *   True if the tab or section is to be hidden
1187
 */
1188
function taxon_page_tabs_hidden_check($tabname) {
1189

    
1190
  $tabs = &drupal_static('taxon_page_tabs_hidden');
1191

    
1192
  if(!isset($tabs)){
1193
    $tabs = array();
1194
  }
1195

    
1196
  return array_search($tabname, $tabs) !== FALSE;
1197
}
1198

    
1199
/**
1200
 * Implements the hook_preprocess_HOOK() for theme_menu_local_tasks()
1201
 *
1202
 *  - Removes the tabs to be hidden, @see taxon_page_tabs_hidden_add()
1203
 *  - Renames tabs according to the settings // TODO (this will replace the theme_cdm_taxonpage_tab() function !!!)
1204
 *
1205
 * @param array $variables
1206
 *   The variables array
1207
 */
1208
function cdm_dataportal_preprocess_menu_local_tasks(&$variables) {
1209

    
1210
  $hidden_tabs = taxon_page_tabs_hidden_add();
1211

    
1212
  if (!variable_get(CDM_SEARCH_BLAST_ENABLED)) {
1213
      if (is_array($variables['primary'])) {
1214
          foreach ($variables['primary'] as $key => &$element) {
1215
              if ($element['#link']['path'] == 'cdm_dataportal/search/blast') {
1216
                  // remove the tab
1217
                  unset($variables['primary'][$key]);
1218
              }
1219

    
1220
          }
1221
      }
1222
  }
1223
  if (is_array($variables['primary'])) {
1224
    foreach ($variables['primary'] as $key => &$element) {
1225

    
1226
      // 1. Remove the tabs to be hidden
1227
      foreach ($hidden_tabs as $tab) {
1228
        if ($element['#link']['path'] == 'cdm_dataportal/taxon/%/' . $tab) {
1229
          // remove the tab
1230
          unset($variables['primary'][$key]);
1231
        }
1232
      }
1233
    }
1234
  }
1235
}
1236

    
1237

    
1238

    
1239
/**
1240
 * Implements the hook_preprocess_HOOK() for theme_menu_local_task()
1241
 *
1242
 *
1243
 * @param array $variables
1244
 *   An associative array containing:
1245
 *     - element: A render element containing:
1246
 *          #link: A menu link array with 'title', 'href', and 'localized_options' keys.
1247
 *          #active: A boolean indicating whether the local task is active.
1248
 *
1249
 */
1250
function cdm_dataportal_preprocess_menu_local_task(&$variables) {
1251

    
1252
  $link = $variables['element']['#link'];
1253
  if (preg_match('/cdm_dataportal\/.*\/refresh$/', $link['href'])) {
1254
    $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']) . '"/>';
1255
    $link['localized_options']['html'] = TRUE;
1256

    
1257
    $variables['element']['#link'] = $link;
1258
  }
1259
}
1260

    
1261
/* =================== block composition ===================== */
1262

    
1263
/**
1264
 * Composes and returns an render array for the classification breadcrumbs of the given taxon.
1265
 *
1266
 * @param taxon
1267
 *
1268
 * @return array
1269
 *   A Drupal render array for a table with the experts
1270
 *
1271
 * @ingroup compose
1272
 */
1273
function compose_classification_breadcrumbs($taxon_uuid) {
1274

    
1275
  _add_js_taxonomic_children('#classification-breadcrumbs .taxonomic-children-button');
1276

    
1277
  $render_array = array();
1278

    
1279
  $render_array['#theme'] = 'item_list';
1280
  $render_array['#type'] = 'ul';
1281
  $render_array['#attributes'] = array(
1282
    'id' => 'classification-breadcrumbs',
1283
    'class' => 'breadcrumbs inline',
1284
  );
1285

    
1286
  $items = array();
1287

    
1288
  $parent_taxon_nodes = null;
1289
  if($taxon_uuid){
1290
    $parent_taxon_nodes = cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1291
  }
1292

    
1293
  $classifications = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
1294
  // find current classification in list
1295
  $classification = null;
1296
  $current_classification_uuid = get_current_classification_uuid();
1297
  foreach ($classifications as $classification){
1298
    if($classification->uuid == $current_classification_uuid){
1299
      break;
1300
    }
1301
  }
1302

    
1303
  $node_name = '';
1304
  if(count($classifications) > 1 ){
1305
    // need to add the current classification as first label
1306

    
1307
    $label = $classification->titleCache;
1308
    if(strlen($label) > 20){
1309
      $label = substr($label, 0, strpos($label, ' ', 15)) . '...';
1310
    }
1311
    $node_name = font_awesome_icon_markup('fa-th-list')  . ' ' . l($label, '#', array(
1312
      'attributes' => array(
1313
        'class' => 'taxonomic-children-button classification-chooser',
1314
        'data-destination-uri' => drupal_get_destination(),
1315
        'data-cdm-align-with' => array('prev')
1316
      ),
1317
      'html' => true
1318
    ));
1319
  }
1320

    
1321
  $rank_limit_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1322

    
1323
  $rank_separator = '<span> '
1324
    . font_awesome_icon_markup('fa-chevron-right')
1325
    . ' </span>';
1326
  $more_children_icon = font_awesome_icon_markup('fa-sitemap fa-rotate-270');
1327
  $more_children_label = '...';
1328

    
1329
  $items[] = $node_name;
1330

    
1331
  $more_children_for = null;
1332
  if($parent_taxon_nodes){
1333
    foreach ($parent_taxon_nodes as $node) {
1334

    
1335
      $is_first_item = count($items) == 0;
1336
      $is_last_item = count($items) == count($parent_taxon_nodes);
1337
      $node_name = cdm_dataportal_shortname_of($node);
1338
      $path = path_to_taxon($node->taxonUuid);
1339

    
1340
      if($node->taxonomicChildrenCount > 0) {
1341
        $more_children_for = $node->taxonUuid;
1342
      } else {
1343
        $more_children_for = null;
1344
      }
1345

    
1346
      // 'fa-sitemap'
1347

    
1348
      $items[] =
1349
        ($is_first_item ? '' : ' ')
1350
        . $rank_separator
1351
        . l(
1352
          '<span class="' . html_class_attribute_ref($node) . '">' . $node_name . '</span>',
1353
          $path,
1354
          array(
1355
            'attributes' => array(
1356
              'class' => array('taxonomic-children-button'),
1357
              'data-cdm-taxon-uuid' => array($node->taxonUuid),
1358
              'data-cdm-classification-mode' => array('siblings'),
1359
              'data-cdm-align-with' => array('prev')
1360
            ),
1361
            'html' => true
1362
          )
1363
        );
1364
      }
1365
    }
1366

    
1367
  // add more button to the end
1368
  if(!$parent_taxon_nodes) {
1369
    // not taxon focused yet, adding button to make  the root nodes available
1370
    $items[] = '<span>'
1371
      . $more_children_icon . '&nbsp;' .
1372
      '<span class="taxonomic-children-button" data-classification-uuid="' . $current_classification_uuid
1373
      . '" data-rank-limit-uuid="' . $rank_limit_uuid . '" data-cdm-align-with="prev"> ' . $more_children_label . '<span>'
1374
      . '</span>';
1375
  } else if($more_children_for){
1376
    // last parent item has child taxon nodes
1377
    $items[] = ' <span>'
1378
      . $more_children_icon . '&nbsp;' .
1379
      '<span class="taxonomic-children-button" data-cdm-taxon-uuid="' .$more_children_for
1380
      . '" data-cdm-classification-mode="children" data-cdm-align-with="prev"> ' . $more_children_label . '</span>'
1381
      . '</span>';
1382

    
1383
  }
1384

    
1385
  $render_array['#items'] = $items;
1386

    
1387
  return $render_array;
1388
}
1389

    
1390

    
1391
/**
1392
 * @param $specimen_uuid
1393
 * @return array
1394
 *    The drupal render array for the page
1395
 *
1396
 * @ingroup compose
1397
 */
1398
function compose_cdm_specimen_page($specimen_uuid)
1399
{
1400
  drupal_set_title("Specimen Details");
1401
  $render_array = array();
1402
  RenderHints::pushToRenderStack('specimen_page');
1403

    
1404
  $specimen_table = array(
1405
      '#theme' => 'table',
1406
      '#weight' => 2,
1407
      // prefix attributes and rows with '#' to let it pass toF the theme function,
1408
      // otherwise it is handled as child render array
1409

    
1410
    '#attributes' => array('class' => 'specimens'),
1411
      '#rows' => array(),
1412
      '#prefix' => '<div id="specimens">',
1413
      '#suffix' => '</div>',
1414

    
1415

    
1416
  );
1417
  $specimen = compose_cdm_specimen_or_observation($specimen_uuid, true);
1418
  $renderArray = array(
1419
          '#theme' => 'item_list',
1420
          '#items' => array($specimen),
1421
          '#type' => 'ul');
1422
  $output = drupal_render($renderArray);
1423

    
1424
  $specimen_table['#rows'][] = array(
1425
          // An array of table rows. Every row is an array of cells, or an associative array
1426
          'data' => array($output),
1427
          'class' =>  array(
1428
              'descriptionElement',
1429
              'descriptionElement_IndividualsAssociation'
1430
          ),
1431

    
1432
  );
1433

    
1434

    
1435
 // $detail_html = compose_cdm_specimen_or_observation($specimen_uuid, true);
1436
//    $render_array['markup'] = array(
1437
//        '#prefix' => '<div id="specimens" class="page">',
1438
//        'content' => $specimen_table,
1439
//        '#suffix' => '</div>',
1440
//    );
1441
    $render_array['markup'] =  $specimen_table;
1442

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

    
1447
/**
1448
 * @param $named_area_uuid
1449
 * @return array
1450
 *    The drupal render array for the page
1451
 *
1452
 * @ingroup compose
1453
 */
1454
function compose_cdm_named_area_page($named_area_uuid)
1455
{
1456

    
1457
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, array($named_area_uuid));
1458

    
1459
  $render_array = array();
1460
  RenderHints::pushToRenderStack('named_area_page');
1461

    
1462
  $groups = array();
1463
  @_description_list_group_add($groups, t('Name') . ':', $named_area->representation_L10n);
1464
  @_description_list_group_add($groups, t('IdInVocabulary') . ':', $named_area->idInVocabulary);
1465
  if(isset($named_area->level)) {
1466
    @_description_list_group_add($groups, t('Level') . ':', $named_area->level->representation_L10n);
1467
  }
1468

    
1469
  $name_area_details_elements = array(
1470
   // '#title' => $title,
1471
    '#theme' => 'description_list',
1472
    '#groups' => $groups,
1473
    '#attributes' => array('class' => html_class_attribute_ref($named_area)),
1474
  );
1475

    
1476
  $render_array[] = $name_area_details_elements;
1477

    
1478
  RenderHints::popFromRenderStack();
1479
  return $render_array;
1480
}
1481

    
1482

    
1483
/**
1484
 * Returns a drupal render array for a single reference page.
1485
 *
1486
 * Composes a page with all data on a single reference.
1487
 *
1488
 * @param string $uuid
1489
 *   An uuid for a cdm reference.
1490
 *
1491
 * @return array
1492
 *  A drupal render array
1493
 *
1494
 * @throws Exception
1495
 *
1496
 * @ingroup compose
1497
 */
1498
function compose_cdm_reference_page($uuid) {
1499

    
1500
  $pathelement = "reference_page";
1501
  RenderHints::pushToRenderStack($pathelement);
1502
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1503
  if (isset($reference->titleCache)) {
1504
    drupal_set_title($reference->titleCache, PASS_THROUGH);
1505
  }
1506

    
1507
  $field_order = array(
1508
    "title",
1509
    "abbrevTitle",
1510
    // "titleCache" abbrevTitleCache
1511
    // "citation",
1512
    "authorship",
1513
    "editor",
1514
    "publisher",
1515
    "placePublished",
1516
    "datePublished",
1517
    "year",
1518
    "edition",// Class Book.
1519
    "volume",// Class Article.
1520
    "seriesPart",
1521
    "inReference",
1522
    "nomRefBase", // Class BookSection, Book, Article.
1523
    "pages",// Class Article.
1524
    "series",// Class Article, PrintSeries.
1525
    "school",// Class Thesis.
1526
    "institution",// Class Report.
1527
    "organization",// Class Proceedings.
1528
    "nextVersion",
1529
    "previousVersion",
1530
    "isbn",// Class Book.
1531
    "issn",// Class Journal.
1532
    "doi",
1533
    "uri"
1534
  );
1535

    
1536
  $table_rows = array();
1537

    
1538
  if (!isset($reference->authorship)) {
1539
    $authorship = cdm_ws_get(CDM_WS_REFERENCE_AUTHORTEAM, $reference->uuid);
1540
    $reference->authorship = isset($authorship->titleCache) ? $authorship->titleCache : '';
1541
  }
1542

    
1543
  if (!isset($reference->inReference)) {
1544
    $reference->inReference = cdm_ws_get(CDM_WS_REFERENCE, array(
1545
      $reference->uuid,
1546
      "inReference",
1547
    ));
1548
  }
1549

    
1550
  foreach ($field_order as $fieldname) {
1551

    
1552
    if (isset($reference->$fieldname)) {
1553

    
1554
      if ($fieldname == "datePublished") {
1555
        $period = $reference->$fieldname;
1556
        $datePublished = timePeriodToString($period);
1557
        if (isset($datePublished) && $datePublished != '') {
1558
          $table_rows[] = array(
1559
            t("Date published"),
1560
            $datePublished,
1561
          );
1562
        }
1563
      }
1564
      elseif ($fieldname == "doi" && is_object($reference->doi)) {
1565
        $table_rows[] = array(
1566
          t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1567
          cdm_doi($reference->doi, false)
1568
        );
1569
      }
1570
      elseif ($fieldname == "uri" && isset($reference->uri) && $reference->uri) {
1571
        $table_rows[] = array(
1572
          t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1573
          cdm_external_uri($reference->uri, false)
1574
        );
1575
      }
1576
      elseif (is_object($reference->$fieldname)) {
1577
        if ($fieldname == "authorship") {
1578
          $dump = $reference->$fieldname;
1579
          $teammembers = "teamMembers";
1580
          $team = $dump->$teammembers;
1581
          $nameArray = array();
1582

    
1583
          foreach ($team as $member) {
1584
            if (strlen($member->lastname) > 0) {
1585
              $nname = $member->lastname;
1586
              $name = $nname;
1587
              if (strlen($member->firstname) > 0) {
1588
                $vname = $member->firstname;
1589
                $name = $vname . " " . $nname;
1590
              }
1591
              $nameArray[] = $name;
1592
            }
1593
            else {
1594
              if (strlen($member->titleCache) > 0) {
1595
                $nameArray[] = $member->titleCache;
1596
              }
1597
            }
1598
          }
1599
          $value = join($nameArray, ", ");
1600
        }
1601
        elseif ($fieldname == "inReference") {
1602
          $type = $reference->$fieldname->type;
1603
          $value = l($reference->$fieldname->titleCache, path_to_reference($reference->$fieldname->uuid));
1604
          switch ($type) {
1605
            case "Book":
1606
              $fieldname = "in book";
1607
              break;
1608
            case "Journal":
1609
              $fieldname = "in journal";
1610
              break;
1611
            case "Proceedings":
1612
              $fieldname = "in proceedings";
1613
              break;
1614
          }
1615
        }
1616
        else {
1617
          $value = $reference->$fieldname->titleCache;
1618
        }
1619

    
1620

    
1621
        if (isset($value) && $value != '') {
1622
          $table_rows[] = array(
1623
            t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1624
            $value,
1625
          );
1626
        }
1627

    
1628
      }
1629
      else {
1630
        if (isset($reference->$fieldname) && $reference->$fieldname != '') {
1631
          $table_rows[] = array(
1632
            t('@fieldname', array('@fieldname' => ucfirst(strtolower($fieldname)))),
1633
            $reference->$fieldname,
1634
          );
1635
        }
1636
      }
1637
    }
1638
  }
1639

    
1640
  $out = theme_table(array(
1641
    'header' => array(),
1642
    'rows' => $table_rows,
1643
    'attributes' => array(
1644
      'class' => html_class_attribute_ref($reference)
1645
    ),
1646
    'caption' => NULL,
1647
    'colgroups' => NULL,
1648
    'sticky' => NULL,
1649
    'empty' => NULL,
1650
  ));
1651

    
1652
  if(isset($reference->referenceAbstract)){
1653
    $out .= '<h2 class="block-title">Abstract</h2><div class="abstract">' . $reference->referenceAbstract . '</div>';
1654
  }
1655

    
1656

    
1657
  // Annotations below the table
1658
  $annotations = cdm_fetch_visible_annotations($reference);
1659
  $out .= theme("cdm_annotations", array('annotations' => $annotations));
1660

    
1661
  $registration_working_set = cdm_ws_get("registrationWorkingSetDTO", array($uuid));
1662
  if($registration_working_set && count($registration_working_set->registrationDTOs) > 0){
1663
    $out .= "<h3>Nomenclatural acts:</h3><div class=\"cdm-item-list registration-item-list\">";
1664
    foreach($registration_working_set->registrationDTOs as $registration_dto){
1665
      if($registration_dto->status == "PUBLISHED"){
1666
        $registration_render_a = compose_registration_dto_compact($registration_dto, 'citation');
1667
        $registration_render_a["#prefix"] = "<div class=\"item item-registration\">";
1668
        $registration_render_a["#suffix"] = "</div>";
1669
        $out .= drupal_render($registration_render_a);
1670
      }
1671
    }
1672
    $out .= "</div>";
1673
  }
1674

    
1675
  RenderHints::popFromRenderStack();
1676

    
1677
  return markup_to_render_array($out);
1678
}
1679

    
1680
/**
1681
 * Provides the the label string for taxon page tabs.
1682
 *
1683
 * The $tabname as passed to the method will be returned if no override
1684
 * label is configured in the settings.
1685
 */
1686
function cdm_taxonpage_tab_label($tabname) {
1687
  static $taxon_tabs_labels = null;
1688
  if($taxon_tabs_labels == null){
1689
    $taxon_tabs_labels = get_array_variable_merged(CDM_TAXONPAGE_TAB_LABELS, CDM_TAXONPAGE_TAB_LABELS_DEFAULT);
1690
  }
1691
  $tabname_key = strtolower($tabname);
1692
  if(isset($taxon_tabs_labels[$tabname_key]) && $taxon_tabs_labels[$tabname_key]){
1693
    return $taxon_tabs_labels[$tabname_key];
1694
  }
1695
  return $tabname;
1696
}
Add picture from clipboard (Maximum size: 40 MB)