Project

General

Profile

Download (41.8 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
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
54
        null,
55
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
56
    );
57

    
58
    $specimensOrObservations = array();
59
    if(isset($pager->records[0])){
60
        $specimensOrObservations =  $pager->records;
61
    }
62

    
63
    // order occurrences by date but types should be on top of the list
64
    $type_specimens = array();
65
    $other_occurrences = array();
66
    foreach ($specimensOrObservations as &$occurrence) {
67
        $typeDesignationsPager = cdm_ws_get(CDM_WS_OCCURRENCE . '/$0/specimenTypeDesignations', $occurrence->uuid);
68
        if (isset($typeDesignationsPager->count) && $typeDesignationsPager->count > 0) {
69
            $type_specimens[] = $occurrence;
70
        } else {
71
            $other_occurrences[] = $occurrence;
72
        }
73
    }
74
    $specimensOrObservations = array_merge($type_specimens, $other_occurrences);
75

    
76
    // Collect media (fieldObjectMedia, derivedUnitMedia) and add as a custom field
77
    // $occurrence->_fieldObjectMedia
78
    foreach ($specimensOrObservations as &$occurrence) {
79
        $occurrence->_fieldObjectMedia = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, array(
80
            $occurrence->uuid,
81
            'fieldObjectMedia',
82
        ));
83
        $occurrence->_derivedUnitMedia = cdm_ws_get(CDM_WS_DERIVEDUNIT_FACADE, array(
84
            $occurrence->uuid,
85
            'derivedUnitMedia',
86
        ));
87
    }
88

    
89
    // --- get map service HTTP query parameters
90
    if (count($specimensOrObservations) > 0) {
91
        $occurrence_queryDto = cdm_ws_get(CDM_WS_GEOSERVICE_OCCURRENCEMAP, $taxon->uuid,  $by_associatedtaxon_query);
92

    
93
      $map_visibility = variable_get(SPECIMEN_MAP_VISIBILITY, SPECIMEN_MAP_VISIBILITY_DEFAULT);
94
      if($map_visibility == 'always' ||
95
        variable_get(SPECIMEN_MAP_VISIBILITY, SPECIMEN_MAP_VISIBILITY_DEFAULT) == 'automatic' &&
96
          (isset($occurrence_queryDto->fieldUnitPoints[0]) || isset($occurrence_queryDto->derivedUnitPoints[0]))
97
        )
98
      {
99
        $occurrence_query = $occurrence_queryDto->occurrenceQuery;
100
        $legend_format_query = null;
101
        $distribution_query = NULL;
102
        $render_array['map'] = compose_map('specimens', $occurrence_query, $distribution_query, $legend_format_query, array());
103
      }
104
    }
105
    if(variable_get('cdm_dataportal_compressed_specimen_derivate_table')){
106

    
107
        //COMPRESSED SPECIMEN DERIVATE TABLE
108
        $associatedFieldUnitsQuery_parameters = array();
109
        if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
110
            $associatedFieldUnitsQuery_parameters = array_merge($associatedFieldUnitsQuery_parameters, $_REQUEST['pager']);
111
        }
112

    
113
        $by_associatedtaxon_query = http_build_query($associatedFieldUnitsQuery_parameters);
114
        $pagerFieldUnits = cdm_ws_get(CDM_WS_PORTAL_TAXON,
115
            array($taxon->uuid, 'associatedFieldUnits'),
116
            $by_associatedtaxon_query . '&pageSize=' . variable_get('cdm_dataportal_compressed_specimen_derivate_table_page_size')
117
        );
118
        // get icon images
119
        $expand_icon = font_awesome_icon_markup(
120
            'fa-plus-square-o',
121
            array(
122
                'alt'=>'Show details',
123
                'class' => array('expand_icon')
124
            )
125
        );
126
        $collapse_icon = font_awesome_icon_markup(
127
            'fa-minus-square-o',
128
            array(
129
                'alt'=>'Show details',
130
                'class' => array('collapse_icon')
131
            )
132
        );
133
        $detail_image_icon = '<img title="Detail Image" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/detail_image_derivate-16x16-32.png' . '"/>';
134
        $checked_box_icon = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/step_done.gif' . '"/>';
135
        $sequence_icon = '<img title="Molecular Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/sequence_derivate-16x16-32.png' . '"/>';
136
        $character_data_icon = '<img title="Character Data" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/character_data_derivate-16x16-32.png' . '"/>';
137
        if (isset($pagerFieldUnits->records[0])) {
138
            $rowcount = 0;
139
            foreach ($pagerFieldUnits->records as $fieldUnit) {
140
                //get derivate hierarchy for the FieldUnit
141
                $derivateHierarchy = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($fieldUnit->uuid, 'derivateHierarchy'), 'taxonUuid=' . $taxon->uuid);
142
                if($derivateHierarchy){
143
                    //summary row
144
                    $rows[] = array(
145
                        'data' => array(
146
                            array(
147
                                'data' => $expand_icon . $collapse_icon,
148
                                'class' => array('summary_row_cell', 'summary_row_icon', 'expand_column')
149
                            ),
150
                            array(
151
                                'data' => $derivateHierarchy->country,
152
                                'class' => array('summary_row_cell')
153
                            ),
154
                            array(
155
                                'data' => $derivateHierarchy->date,
156
                                'class' => array('summary_row_cell')
157
                            ),
158
                            array(
159
                                'data' => $derivateHierarchy->collection,
160
                                'class' => array('summary_row_cell')
161
                            ),
162
                            array(
163
                                'data' => $derivateHierarchy->herbarium,
164
                                'class' => array('summary_row_cell')
165
                            ),
166
                            array(
167
                                'data' => $derivateHierarchy->hasType? $checked_box_icon:"",
168
                                'class' => array('summary_row_cell', 'summary_row_icon')
169
                            ),
170
                            array(
171
                                'data' => $derivateHierarchy->hasSpecimenScan? $checked_box_icon:"",
172
                                'class' => array('summary_row_cell', 'summary_row_icon')
173
                            ),
174
                            array(
175
                                'data' => ($derivateHierarchy->hasDna? $sequence_icon :"")." "
176
                                    .($derivateHierarchy->hasDetailImage?$detail_image_icon:"")." "
177
                                    .($derivateHierarchy->hasCharacterData?$character_data_icon:""),
178
                                'class' => array('summary_row_cell', 'summary_row_icon')
179
                            )
180
                        ),
181
                        'id' => ('derivate_summary' . $rowcount), // summary row id
182
                        'class' => array('summary_row'),
183
                    );
184

    
185
                    //assemble field unit details
186
                    $detail_html = "";
187
                    // - taxon name
188
                    if (variable_get('cdm_dataportal_compressed_specimen_derivate_table_show_determined_as') && $derivateHierarchy->taxonName) {
189
                        $detail_html .= create_label("Associated with") . $derivateHierarchy->taxonName . "<br>";
190
                    }
191
                    // - protologue
192
                    if ($derivateHierarchy->protologue) {
193
                        //$detail_html .= "<strong>Protologue:</strong> " . $derivateHierarchy->protologue . "<br>"
194
                    }
195
                    // - citation
196
                    if ($derivateHierarchy->citation) {
197
                        $detail_html .= create_label("Citation") . $derivateHierarchy->citation . "<br>";
198
                    }
199
                    //assemble specimen details
200
                    if($derivateHierarchy->preservedSpecimenDTOs){
201
                        foreach($derivateHierarchy->preservedSpecimenDTOs as $preservedSpecimenDTO) {
202
                            $detail_html .= "<br>";
203
                            $detail_html .= render_cdm_specimen_page($preservedSpecimenDTO);
204
                        }
205
                    }
206
                    $detail_html .= "<br>";
207
                    //detail row resp. one BIG detail cell
208
                    $rows[] = array(
209
                        'data' => array(
210
                            array(
211
                                'data' => "", //empty first column
212
                                'class' => array('expand_column')
213
                            ),
214
                            array(
215
                                'data' => $detail_html,
216
                                'colspan' => 7,
217
                            ),
218
                        ),
219
                        'id' => ('derivate_details' . $rowcount),//details row ID
220
                        'class' => array('detail_row'),
221
                    );
222
                    $rowcount++;
223
                }
224
            }
225
        }
226

    
227
        $tableId = "derivate_hierarchy_table";
228
        $derivateHierarchyTable = array(
229
            "#theme" => "table",
230
            "#weight" => 2,
231
            "#header" => array(
232
                array(
233
                    'data' => "",
234
                    'class' => array('expand_column')
235
                ),
236
                "Country", "Date", "Collector + collecting number", "Herbaria", "Type", "Scan", "Derivatives"),
237
            "#rows" => $rows,
238
            "#attributes" => array(
239
                "id" => $tableId,
240
                "border" => 2
241
            )
242
        );
243

    
244
        //add toggle functionality to derivate hierarchy table
245
        drupal_add_js_rowToggle("#".$tableId);
246

    
247
        $render_array['derivate_hierarchy_table'] = $derivateHierarchyTable;
248
        $render_array['pager'] = markup_to_render_array(
249
            theme('cdm_pager', array(
250
                'pager' => $pagerFieldUnits,
251
                'path' => $_REQUEST['q'],
252
                'parameters' => $_REQUEST
253
            )),
254
            10 // weight
255
        );
256
    }
257
    else{
258
        //BOTTOM-UP-SPECIMEN-TABLE
259
        // --- generate the specimen list as table
260
        $specimen_table = array(
261
            '#theme' => 'table',
262
            '#weight' => 2,
263
            // prefix attributes and rows with '#' to let it pass to the theme function,
264
            // otherwise it is handled as child render array
265
            '#attributes' => array('class' => 'specimens'),
266
            '#rows' => array(),
267
        );
268

    
269
        if ($specimensOrObservations) {
270

    
271
            foreach ($specimensOrObservations as $specimenOrObservation) {
272

    
273
                $mediaList = array();
274
                if (is_array($specimenOrObservation->_fieldObjectMedia)) {
275
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_fieldObjectMedia);
276
                }
277
                if (is_array($specimenOrObservation->_derivedUnitMedia)) {
278
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_derivedUnitMedia);
279
                }
280

    
281
                // typelabel will contain the typeStatus
282
                $type_label = '';
283
                $typeDesignationPager = cdm_ws_get(CDM_WS_OCCURRENCE . '/$0/specimenTypeDesignations', $specimenOrObservation->uuid);
284
                if (isset($typeDesignationPager) and isset($typeDesignationPager->records)) {
285
                    $type_status = array();
286
                    foreach ($typeDesignationPager->records as $typeDesignation) {
287
                        if (isset($typeDesignation->typeStatus->representation_L10n)){
288
                            $type_status[] = $typeDesignation->typeStatus->representation_L10n;
289
                        }
290
                    }
291
                    $type_label = implode(', ', $type_status);
292
                    if($type_label){
293
                        $type_label .= ': ' ;
294
                    }
295
                }
296

    
297
                // --- Specimen entry as dynamic label:
298
                //     -> Dynabox for the specimenOrObservation
299
                $gallery_name = $specimenOrObservation->uuid;
300

    
301
                $derived_unit_ws_request = cdm_compose_url(CDM_WS_OCCURRENCE, array( $specimenOrObservation->uuid));
302
                $label_html = cdm_dynabox(
303
                  $specimenOrObservation->uuid,
304
                  $type_label . $specimenOrObservation->titleCache,
305
                  $derived_unit_ws_request,
306
                  'cdm_specimenOrObservation',
307
                  'Click for details',
308
                  array('div', 'div'),
309
                  array(),
310
                  null, // $content_element_selector
311
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').hide(); }', // open_callback
312
                  'function(){ jQuery(\'#media_gallery_' . $gallery_name . '\').show(); }' // close_callback
313
                );
314

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

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

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

    
350
        $render_array['specimen_list'] = $specimen_table;
351
        $render_array['pager'] = markup_to_render_array(
352
            theme('cdm_pager', array(
353
                'pager' => $pager,
354
                'path' => $_REQUEST['q'],
355
                'parameters' => $_REQUEST,
356
            )),
357
            10 // weight
358
        );
359
    }
360
    RenderHints::popFromRenderStack();
361
    return $render_array;
362
}
363
 
364
function create_html_link($link, $openInExternalWindow=false){
365
    $html = "";
366
    if($link->uri && $link->uri!=""){
367
        $html .= '<a  href="' . $link->uri . '"';
368
        if($openInExternalWindow){
369
            $html .= ' target="_blank"';
370
        }
371
        $html .= '>' . $link->linkText . '</a>';
372
    }
373
    else{
374
        $html .= $link->linkText;
375
    }
376
    return $html;
377
}
378

    
379
/**
380
 * Creates HTML links from the given link list concatenated by default by a comma.
381
 * @param $linkList the list with Link objects having "uri" and "linkText" as members
382
 * @return string the assembled HTML string containing the links
383
 */
384
function create_html_links($linkList, $openInExternalWindow=false, $separator=", ")
385
{
386
    $html = "";
387
    if ($linkList) {
388
        foreach ($linkList as $link) {
389
            $html .= create_html_link($link, $openInExternalWindow).$separator;
390
        }
391
        $html = rtrim($html, $separator);
392
    }
393
    return $html;
394
}
395

    
396
/**
397
 * Composes a taxon page which can consist of multiple parts like
398
 * 'General', 'Synonymy', 'Images', 'Keys'. These parts can be displayed
399
 * as tabs or as sections of a single page.
400
 *
401
 * It is headed by the name of the accepted taxon without author and reference.
402
 *
403
 * @param $taxon
404
 *   The CDM Taxon Instance to compose the page for.
405
 * @param $page_part
406
 *   Name of the part to display, valid values are:
407
 *    - 'description' -  for the general part
408
 *    - 'images'
409
 *    - 'synonymy'
410
 *    - 'keys'
411
 *    - 'all'
412
 *
413
 * @return array
414
 *   A drupal render array
415
 *
416
 * @ingroup compose
417
 */
418
function compose_cdm_taxon_page($taxon, $page_part = 'description') {
419

    
420
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
421
  $http_request_params = drupal_get_query_parameters();
422

    
423
  // add all mandatory js sources
424
  _add_js_footnotes();
425

    
426

    
427
  $render_array = array();
428
  $weight = 0; // the weight for the render array elements
429

    
430
  $tabsToDisplay = variable_get('cdm_taxonpage_tabs_visibility', unserialize(TAXONPAGE_VISIBILITY_OPTIONS_DEFAULT));
431

    
432
  $page_part = variable_get('cdm_dataportal_taxonpage_tabs', 1) ? $page_part : 'all';
433

    
434
  $media = _load_media_for_taxon($taxon);
435

    
436

    
437
  if (!isset($media[0]) || ($tabsToDisplay["Images"] == '0')) {
438
    taxon_page_tabs_hidden('images');
439
  }
440

    
441
  // --- GET specimensOrObservations --- //
442
  $specimensOrObservations = cdm_ws_get(CDM_WS_TAXON, array( $taxon->uuid, 'specimensOrObservations'));
443

    
444
  $specimensOrObservationsCount = is_array($specimensOrObservations) ? count($specimensOrObservations) : 0;
445
  if ($specimensOrObservationsCount == 0 || ($tabsToDisplay["Specimens"] == '0')) {
446
    taxon_page_tabs_hidden('specimens');
447
  }
448

    
449
  // --- GET polytomousKeys --- //
450
  $polytomousKeysPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, NULL, "findByTaxonomicScope=$taxon->uuid");
451
  $identificationKeyCount = 0;
452
  if ($polytomousKeysPager) {
453
    $identificationKeyCount += $polytomousKeysPager->count;
454
  }
455
  if ($identificationKeyCount == 0 || ($tabsToDisplay["Keys"] == '0')) {
456
    taxon_page_tabs_hidden('keys');
457
  }
458

    
459
    // --- GET TaxonNodeAgentRelations --- //
460
    $current_classification_uuid = get_current_classification_uuid();
461
    $taxon_node_agent_relations_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
462
        array(
463
            $taxon->uuid,
464
            $current_classification_uuid,
465
        ),
466
        "pageSize=1&pageIndex=0"// we are only interested into the count so we are fetching only one item, o is not possible!
467
    );
468
    if (!$taxon_node_agent_relations_pager || $taxon_node_agent_relations_pager->count == 0){
469
        taxon_page_tabs_hidden('experts');
470
    }
471

    
472
    if ($tabsToDisplay["Synonymy"] == '0') {
473
    taxon_page_tabs_hidden('synonymy');
474
  }
475

    
476
  // -------------------------------------------- //
477

    
478
  if (variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR) && isset($_REQUEST['acceptedFor'])) {
479
    $render_array['accepted_for'] = markup_to_render_array(cdm_accepted_for($_REQUEST['acceptedFor']), $weight++);
480
  }
481

    
482
  // --- PAGE PART: DESCRIPTION --- //
483
  if ($page_part == 'description' || $page_part == 'all') {
484

    
485
    $merged_tree = merged_taxon_feature_tree($taxon);
486

    
487

    
488
    $render_array['general'] = compose_cdm_taxon_page_profile($taxon, $merged_tree, $media);
489
    $render_array['general']['#weight'] = $weight++;
490
    $render_array['general']['#prefix'] = '<div id="general" class="page-part">';
491
    $render_array['general']['#suffix'] = '</div>';
492
  }
493

    
494
  // --- PAGE PART: IMAGES --- //
495
  if (array_search('images', taxon_page_tabs_hidden()) === FALSE && ($page_part == 'images' || $page_part == 'all')) {
496
    $images_html = '<div id="images" class="page-part">';
497
    if ($page_part == 'all') {
498
      $images_html .= '<h2>' . t(cdm_taxonpage_tab_label('Images')) . '</h2>';
499
    }
500
    // Get the image gallery as configured by the admin.
501
    $default_image_gallery = 'default';
502
    $configured_image_gallery_viewer = variable_get('image_gallery_viewer', 'default');
503
    $taxon_image_gallery = '<div class="error">No image gallery viewer configured</div>';
504
    if($configured_image_gallery_viewer == $default_image_gallery || $configured_image_gallery_viewer == 'fsi'){
505
      // the fsi_gallery requires a flash plugin, in case the client browser is not supporting
506
      // flash we also need to provide an the default gallery as alternative
507
      $taxon_image_gallery = '<div id="default-gallery-viewer">' .
508
        call_user_func_array('taxon_image_gallery_' . $default_image_gallery, array(
509
          $taxon,
510
          $media,
511
        ))
512
        . '</div>';
513
    }
514
    if($configured_image_gallery_viewer == 'fsi'){
515
      $taxon_image_gallery .= '<div id="'. $configured_image_gallery_viewer .'-gallery-viewer">' .
516
        call_user_func_array('taxon_image_gallery_' . $configured_image_gallery_viewer, array(
517
          $taxon,
518
          $media,
519
        ))
520
       . '</div>';
521
    }
522
    $images_html .= $taxon_image_gallery;
523
    $images_html .= '</div>';
524
    $render_array['images'] = markup_to_render_array($images_html, $weight++);
525
  }
526

    
527
  // --- PAGE PART: SYNONYMY --- //
528
  if (($page_part == 'synonymy' || $page_part == 'all')) {
529
    $synonymy_html = '<div id="synonymy" class="page-part">';
530
    if ($page_part == 'all') {
531
      $synonymy_html .= '<h2>' . t(cdm_taxonpage_tab_label('Synonymy')) . '</h2>';
532
    }
533
    $addAcceptedTaxon = variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE);
534

    
535
    $synonymy_html .= theme('cdm_taxon_page_synonymy', array('taxon' => $taxon, 'addAcceptedTaxon' => $addAcceptedTaxon));
536

    
537
    $synonymy_html .= '</div>';
538
    $render_array['synonymy'] = markup_to_render_array($synonymy_html, $weight++);
539

    
540
  }
541

    
542
  // --- PAGE PART: SPECIMENS --- //
543
  if ($specimensOrObservationsCount > 0 && ($page_part == 'specimens' || $page_part == 'all')) {
544
    $render_array['specimens'] = array(
545
        '#prefix' => '<div id="specimens" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Specimens')) . '</h2>' : ''),
546
        'content' => cdm_dataportal_taxon_page_specimens($taxon), // returns render array
547
        '#suffix' => '</div>',
548
    );
549
  }
550

    
551
  // --- PAGE PART: KEYS --- //
552
  if ($identificationKeyCount == 1 && $page_part == 'keys'){
553
    drupal_goto(path_to_key($polytomousKeysPager->records[0]->class, $polytomousKeysPager->records[0]->uuid));
554
  }
555
  else if ($identificationKeyCount > 0 && ($page_part == 'keys' || $page_part == 'all')) {
556
    $keys_html = '<div id="keys" class="page-part">';
557
    if ($page_part == 'all') {
558
      $keys_html .= '<h2>' . t(cdm_taxonpage_tab_label('Keys')) . '</h2>';
559
    }
560
    $keys_html .= theme('cdm_block_IdentificationKeys', array('taxonUuid' => $taxon->uuid));
561
    $keys_html .= '</div>';
562
    $render_array['keys'] = markup_to_render_array($keys_html, $weight++);
563
  }
564

    
565
  // --- PAGE PART: EXPERTS --- //
566

    
567
  if (array_search('experts', taxon_page_tabs_hidden()) === FALSE && ($page_part == 'experts' || $page_part == 'all')) {
568
    $render_array['experts'] = array(
569
        '#prefix' => '<div id="experts" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Experts')) . '</h2>' : ''),
570
        'content' => compose_cdm_taxon_page_experts($taxon), // returns render array
571
        '#suffix' => '</div>',
572
    );
573
  }
574

    
575
  // ------------------ END OF PARTS -------------- //
576

    
577
  // adjust weights of page and toc elements according to the settings
578
  $taxontabs_weights = get_array_variable_merged(CDM_TAXONPAGE_TAB_WEIGHT, CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
579
  foreach($taxontabs_weights as $tab_key => $weight){
580
    if(isset($render_array[$tab_key])){
581
      $render_array[$tab_key]['#weight'] = $weight;
582
    }
583
  }
584

    
585

    
586
  // set up the TOC for the pages which contain all pageparts
587
  if($page_part == 'all') {
588

    
589
    asort($taxontabs_weights);
590
    foreach(array_keys($taxontabs_weights) as $tab_key){
591
      if(isset($render_array[$tab_key])){
592
        if($tab_key != 'general'){
593
          // add entry for page part
594
          $toc_elements[] = array(
595
              'data' => l(t(cdm_taxonpage_tab_label(ucfirst($tab_key))), $_GET['q'], array('fragment' => $tab_key, 'query' => $http_request_params)),
596
              'class' => array('page-part-toc-item-' . $tab_key)
597
          );
598
        } else {
599
          // add content of profile part instead
600
          if(isset($render_array['general'])) {
601
            // in case all tabs are shown at once the feature tocs
602
            // should be integrated into the tabs toc as sub list
603
            // and the profile image should be on top of the page
604
            if(isset($render_array['general']['taxon_description_feature_toc'])){;
605
            foreach ($render_array['general']['taxon_description_feature_toc']['#items'] as $profile_toc_item){
606
              $toc_elements[] = $profile_toc_item;
607
            }
608
            unset($render_array['general']['taxon_description_feature_toc']);
609
            }
610
          }
611
        }
612
      }
613
    }
614

    
615
    // move profile image in page structure
616
    if(isset($render_array['general']['taxon_profile_image'])){
617
      $render_array['profile_image'] = $render_array['general']['taxon_profile_image'];
618
      $render_array['profile_image']['#weight'] = -100;
619
      unset($render_array['general']['taxon_profile_image']);
620
    }
621

    
622
    // finally add the table of contents to the render array
623
    $render_array['toc'] = array(
624
        '#theme' => 'item_list',
625
        '#items' => $toc_elements,
626
        '#title' => t('Content'),
627
        '#weight' => -101,
628
        '#suffix' => '</div>',
629
        '#prefix'=> '<div id="page-toc">'
630
    );
631
  }
632

    
633

    
634
  return $render_array;
635
}
636

    
637
/**
638
 * TODO should this function really be a compose function?
639
 *     For a compose function must there always be a theme function with the same name? (ak 8.8.2013)
640
 *
641
 * composes and returns an render array containing the components of the taxon profile tab:
642
 *  - 'taxon_profile_image'
643
 *  - 'taxon_description_feature_toc'
644
 *  - 'taxon_description_features'
645
 *
646
 *
647
 * @param taxon
648
 * @param mergedTrees
649
 * @param media
650
 *
651
 * @return array
652
 *   A Drupal render array with the following elements:
653
 *     - 'taxon_profile_image'
654
 *     - 'taxon_description_feature_toc'
655
 *     - 'taxon_description_features'
656
 *
657
 * @ingroup compose
658
 */
659
function compose_cdm_taxon_page_profile($taxon, $merged_tree, $media) {
660

    
661
  $render_array = array();
662

    
663
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
664

    
665
  $hide_taxon_profile_image = FALSE;
666
  if (variable_get('image_hide_rank', '0') != '0' && isset($taxon->name->rank->uuid)) {
667
    $rankCompare = rank_compare($taxon->name->rank->uuid, variable_get('image_hide_rank', '-99'));
668
    $hide_taxon_profile_image = ($rankCompare > -1);
669
  }
670

    
671
  if ($taxon_profile_image_settings['show'] && !$hide_taxon_profile_image) {
672

    
673
    $representationPart = new stdClass();
674
    $attributes = array();
675
    if (isset($media[0]->representations[0]->parts[0])) {
676
      $representationPart = $media[0]->representations[0]->parts[0];
677
      $attributes['alt'] = $representationPart->uri;
678

    
679
      if (!empty($taxon_profile_image_settings['media_uri_query'])) {
680
        $representationPart->uri = $representationPart->uri
681
          . (strpos($representationPart->uri, '?') !== FALSE ? '&' : '?')
682
          . $taxon_profile_image_settings['media_uri_query'];
683
      }
684
    }
685
    else {
686
      if ($taxon_profile_image_settings['custom_placeholder_enabled']) {
687
        // show placeholder image instead
688
        if (!empty($taxon_profile_image_settings['custom_placeholder_image_on']) && !empty($taxon_profile_image_settings['custom_placeholder_image_fid'])) {
689
          // use the user provided image
690
          $profile_image_file = file_load($taxon_profile_image_settings['custom_placeholder_image_fid']);
691
          $url = file_create_url($profile_image_file->uri);
692
          $image_info = image_get_info($profile_image_file->uri);
693
          $representationPart->width = $image_info['width'];
694
          $representationPart->height = $image_info['height'];
695
          $representationPart->uri = $url;
696
        }
697
        else {
698
          // use the hard coded default
699
          $representationPart->width = 184;
700
          $representationPart->height = 144;
701
          $representationPart->uri = base_path() . drupal_get_path('module',
702
              'cdm_dataportal') . '/images/no_picture.png';
703
        }
704
        $attributes['alt'] = "no image available";
705
      }
706
    }
707

    
708
    if (isset($representationPart->uri)) {
709
      $profile_image = cdm_media_gallerie_image($representationPart, $taxon_profile_image_settings['maxextend'], FALSE, $attributes);
710
      // NOTE: style="width:${maxextend}px' is needed for IE8 !!!
711
      $render_array['taxon_profile_image'] = markup_to_render_array('<div id="taxonProfileImage" style="width:' . $taxon_profile_image_settings['maxextend'] . 'px">' . $profile_image . '</div>',
712
        -101);
713
    }
714
  }
715

    
716

    
717
  // Render the sections for each feature
718
  $render_array['taxon_description_features'] = compose_feature_blocks($merged_tree->root->childNodes, $taxon);
719

    
720
  $bibliography_settings = get_bibliography_settings();
721
  if($bibliography_settings['enabled'] == 1){
722
    $bibliography_block = feature_block(t('Bibliography'));
723
    $bibliography_block->content = FootnoteManager::renderFootnoteList('BIBLIOGRAPHY', '');
724

    
725
    if(!empty($bibliography_block->content)){
726
      $render_array['taxon_description_bibliography'] =  markup_to_render_array(
727
        theme('block',
728
          array(
729
            'elements' => array(
730
              '#block' => $bibliography_block,
731
              '#children' => $bibliography_block->content,
732
            )
733
          )
734
        ),
735
        100 // weight
736
      );
737
      cdm_toc_list_add_item('Bibliography', 'bibliography');
738
    }
739

    
740
  }
741

    
742
  // create the table of content
743
  $toc = array(
744
      '#theme' => 'item_list',
745
    '#items' => cdm_toc_list(),
746
      '#title' => t('Content'),
747
    '#weight' => -100,                  // move to the top
748
      '#suffix' => '</div>',
749
      '#prefix'=> '<div id="page-toc">'
750
  );
751
  $render_array['taxon_description_feature_toc'] = $toc;
752

    
753
  return $render_array;
754
}
755

    
756
/**
757
 * composes and returns an render array for the experts associated with the given taxon
758
 *
759
 * @param taxon
760
 *
761
 * @return array
762
 *   A Drupal render array for a table with the experts
763
 *
764
 * @ingroup compose
765
 */
766
function compose_cdm_taxon_page_experts($taxon){
767

    
768
  $render_array = array();
769
  if(!isset($taxon->uuid)){
770
    return $render_array;
771
  }
772

    
773
  $current_classification_uuid = get_current_classification_uuid();
774
  // TODO use cdm_ws_fetchall below but this failes! needs fix!
775
  $taxon_node_agent_relations = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODEAGENTRELATIONS,
776
    array(
777
      $taxon->uuid,
778
      $current_classification_uuid
779
    )
780
  );
781

    
782
  $header = array(
783
    array('data' => t('Expert')),
784
    array('data' => t('Role'))
785
  );
786
  $rows = array();
787

    
788

    
789
  foreach($taxon_node_agent_relations->records as $taxon_node_agent_relation){
790

    
791

    
792
    $expert_role_id = $taxon_node_agent_relation->agent->uuid . '-' . $taxon_node_agent_relation->type->uuid;
793
    $expert_details_container_id = 'expert_details_' . $expert_role_id;
794

    
795
    $agent_label_markup = cdm_dynabox(
796
      'expert_' . $expert_role_id,
797
      $taxon_node_agent_relation->agent->titleCache,
798
      // specifying both ends of the relationship will return only one record in the pager
799
      cdm_compose_url(CDM_WS_PORTAL_AGENT,
800
         array($taxon_node_agent_relation->agent->uuid, 'taxonNodeAgentRelations'),
801
        'taxon_uuid=' . $taxon->uuid . '&relType_uuid=' . $taxon_node_agent_relation->type->uuid),
802
      'cdm_taxon_expert',
803
      'Click for details',
804
      array('div', 'div'),
805
      array(), // attributes
806
      '#' . $expert_details_container_id // $content_element_selector
807
    );
808

    
809
    // Expert and Role
810
    $rows[] = array(
811
      'data' => array(
812
        array(
813
          'data' => $agent_label_markup,
814
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->agent))
815
        ),
816
        array(
817
          'data' => $taxon_node_agent_relation->type->representation_L10n,
818
          'class' => array(html_class_attribute_ref($taxon_node_agent_relation->type))
819
        )
820
      )
821
    );
822
    // Agent details
823
    $rows[] = array(
824
      'data' => array(
825
        array(
826
          'data' => '<!-- expert_details_container -->',
827
          'id' => $expert_details_container_id,
828
          'colspan' => 2
829
        )
830
      )
831
    );
832

    
833
  }
834

    
835

    
836
  $render_array['experts_table'] = array(
837
    '#theme' => 'table',
838
    '#header' => $header,
839
    '#rows' => $rows,
840
  );
841

    
842

    
843
  return $render_array;
844
}
845

    
846

    
847
/**
848
 * Manages the tabs to be hidden in the taxon page.
849
 *
850
 * The tabs are identified by their last menu link path element:
851
 *  - description
852
 *  - synonymy
853
 *  - images
854
 *  - specimens
855
 *  - key
856
 *
857
 * Internally the tabs are stored in a static variable which is
858
 * managed by drupal_static().
859
 *
860
 * @param string $add_tab
861
 *   Optional parameter. The given string will be added to the array of tabs
862
 *
863
 * @return
864
 *   The array of tabs
865
 */
866
function taxon_page_tabs_hidden($add_tab = NULL) {
867
  $tabs = &drupal_static(__FUNCTION__);
868

    
869
  if(!isset($tabs)){
870
    $tabs = array();
871
  }
872

    
873
  if (isset($add_tab) && !array_key_exists($add_tab, $tabs)) {
874
    $tabs[] = $add_tab;
875
  }
876

    
877
  return $tabs;
878
}
879

    
880
/**
881
 * Implements the hook_preprocess_HOOK() for theme_menu_local_tasks()
882
 *
883
 *  - Removes the tabs to be hidden, @see taxon_page_tabs_hidden()
884
 *  - Renames tabs according to the settings // TODO (this will replace the theme_cdm_taxonpage_tab() function !!!)
885
 *
886
 * @param array $variables
887
 *   The variables array
888
 */
889
function cdm_dataportal_preprocess_menu_local_tasks(&$variables) {
890

    
891
  $hidden_tabs = taxon_page_tabs_hidden();
892

    
893
  if (is_array($variables['primary'])) {
894
    foreach ($variables['primary'] as $key => &$element) {
895

    
896
      // 1. Remove the tabs to be hidden
897
      foreach ($hidden_tabs as $tab) {
898
        if ($element['#link']['path'] == 'cdm_dataportal/taxon/%/' . $tab) {
899
          // remove the tab
900
          unset($variables['primary'][$key]);
901
        }
902
      }
903
    }
904
  }
905
}
906

    
907

    
908

    
909
/**
910
 * Implements the hook_preprocess_HOOK() for theme_menu_local_task()
911
 *
912
 *
913
 * @param array $variables
914
 *   An associative array containing:
915
 *     - element: A render element containing:
916
 *          #link: A menu link array with 'title', 'href', and 'localized_options' keys.
917
 *          #active: A boolean indicating whether the local task is active.
918
 *
919
 */
920
function cdm_dataportal_preprocess_menu_local_task(&$variables) {
921

    
922
  $link = $variables['element']['#link'];
923
  if (preg_match('/cdm_dataportal\/.*\/refresh$/', $link['href'])) {
924
    $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']) . '"/>';
925
    $link['localized_options']['html'] = TRUE;
926

    
927
    $variables['element']['#link'] = $link;
928
  }
929
}
930

    
931
/* =================== block composition ===================== */
932

    
933
/**
934
 * Composes and returns an render array for the classification breadcrumbs of the given taxon.
935
 *
936
 * @param taxon
937
 *
938
 * @return array
939
 *   A Drupal render array for a table with the experts
940
 *
941
 * @ingroup compose
942
 */
943
function compose_classification_breadcrumbs($taxon_uuid) {
944

    
945
  _add_js_taxonomic_children('#classification-breadcrumbs .taxonomic-children-button');
946

    
947
  $render_array = array();
948

    
949
  $render_array['#theme'] = 'item_list';
950
  $render_array['#type'] = 'ul';
951
  $render_array['#attributes'] = array(
952
    'id' => 'classification-breadcrumbs',
953
    'class' => 'breadcrumbs inline',
954
  );
955

    
956
  $items = array();
957

    
958
  $parent_taxon_nodes = null;
959
  if($taxon_uuid){
960
    $parent_taxon_nodes = cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
961
  }
962

    
963
  $classifications = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
964
  // find current classification in list
965
  $classification = null;
966
  $current_classification_uuid = get_current_classification_uuid();
967
  foreach ($classifications as $classification){
968
    if($classification->uuid == $current_classification_uuid){
969
      break;
970
    }
971
  }
972

    
973
  $node_name = '';
974
  if(count($classifications) > 1 ){
975
    // need to add the current classification as first label
976

    
977
    $label = $classification->titleCache;
978
    if(strlen($label) > 20){
979
      $label = substr($label, 0, strpos($label, ' ', 15)) . '...';
980
    }
981
    $node_name = font_awesome_icon_markup('fa-th-list')  . ' ' . l($label, '#', array(
982
      'attributes' => array(
983
        'class' => 'taxonomic-children-button classification-chooser',
984
        'data-destination-uri' => drupal_get_destination(),
985
        'data-cdm-align-with' => array('prev')
986
      ),
987
      'html' => true
988
    ));
989
  }
990

    
991
  $rank_limit_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
992

    
993
  $rank_separator = '<span> '
994
    . font_awesome_icon_markup('fa-chevron-right')
995
    . ' </span>';
996
  $more_children_icon = font_awesome_icon_markup('fa-sitemap fa-rotate-270');
997
  $more_children_label = '...';
998

    
999
  $items[] = $node_name;
1000

    
1001
  $more_children_for = null;
1002
  if($parent_taxon_nodes){
1003
    foreach ($parent_taxon_nodes as $node) {
1004

    
1005
      $is_first_item = count($items) == 0;
1006
      $is_last_item = count($items) == count($parent_taxon_nodes);
1007
      $node_name = cdm_dataportal_shortname_of($node);
1008
      $path = path_to_taxon($node->taxonUuid);
1009

    
1010
      if($node->taxonomicChildrenCount > 0) {
1011
        $more_children_for = $node->taxonUuid;
1012
      } else {
1013
        $more_children_for = null;
1014
      }
1015

    
1016
      // 'fa-sitemap'
1017

    
1018
      $items[] =
1019
        ($is_first_item ? '' : ' ')
1020
        . $rank_separator
1021
        . l(
1022
          '<span class="' . html_class_attribute_ref($node) . '">' . $node_name . '</span>',
1023
          $path,
1024
          array(
1025
            'attributes' => array(
1026
              'class' => array('taxonomic-children-button'),
1027
              'data-cdm-taxon-uuid' => array($node->taxonUuid),
1028
              'data-cdm-classification-mode' => array('siblings'),
1029
              'data-cdm-align-with' => array('prev')
1030
            ),
1031
            'html' => true
1032
          )
1033
        );
1034
      }
1035
    }
1036

    
1037
  // add more button to the end
1038
  if(!$parent_taxon_nodes) {
1039
    // not taxon focused yet, adding button to make  the root nodes available
1040
    $items[] = '<span>'
1041
      . $more_children_icon . '&nbsp;' .
1042
      '<span class="taxonomic-children-button" data-classification-uuid="' . $current_classification_uuid
1043
      . '" data-rank-limit-uuid="' . $rank_limit_uuid . '" data-cdm-align-with="prev"> ' . $more_children_label . '<span>'
1044
      . '</span>';
1045
  } else if($more_children_for){
1046
    // last parent item has child taxon nodes
1047
    $items[] = ' <span>'
1048
      . $more_children_icon . '&nbsp;' .
1049
      '<span class="taxonomic-children-button" data-cdm-taxon-uuid="' .$more_children_for
1050
      . '" data-cdm-classification-mode="children" data-cdm-align-with="prev"> ' . $more_children_label . '</span>'
1051
      . '</span>';
1052

    
1053
  }
1054

    
1055
  $render_array['#items'] = $items;
1056

    
1057
  return $render_array;
1058
}
1059

    
1060

    
1061
/**
1062
 * @param $specimen_uuid
1063
 * @return array
1064
 *    The drupal render array for the page
1065
 *
1066
 * @ingroup compose
1067
 */
1068
function compose_cdm_specimen_page($specimen_uuid)
1069
{
1070
  drupal_set_title("Specimen Details");
1071
  $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, array($specimen_uuid, 'specimenDerivates'));
1072

    
1073
  $render_array = array();
1074
  RenderHints::pushToRenderStack('specimen_page');
1075

    
1076
  $detail_html = render_cdm_specimen_page($specimen, true);
1077
  $render_array['specimen_html'] = array(
1078
    '#markup' => $detail_html
1079
  );
1080

    
1081
  RenderHints::popFromRenderStack();
1082
  return $render_array;
1083
}
1084

    
1085
/**
1086
 * @param $named_area_uuid
1087
 * @return array
1088
 *    The drupal render array for the page
1089
 *
1090
 * @ingroup compose
1091
 */
1092
function compose_cdm_named_area_page($named_area_uuid)
1093
{
1094

    
1095
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, array($named_area_uuid));
1096

    
1097
  $render_array = array();
1098
  RenderHints::pushToRenderStack('named_area_page');
1099

    
1100
  $groups = array();
1101
  @_description_list_group_add($groups, t('Name') . ':', $named_area->representation_L10n);
1102
  @_description_list_group_add($groups, t('IdInVocabulary') . ':', $named_area->idInVocabulary);
1103
  if(isset($named_area->level)) {
1104
    @_description_list_group_add($groups, t('Level') . ':', $named_area->level->representation_L10n);
1105
  }
1106

    
1107
  $name_area_details_elements = array(
1108
   // '#title' => $title,
1109
    '#theme' => 'description_list',
1110
    '#groups' => $groups,
1111
    '#attributes' => array('class' => html_class_attribute_ref($named_area)),
1112
  );
1113

    
1114
  $render_array[] = $name_area_details_elements;
1115

    
1116
  RenderHints::popFromRenderStack();
1117
  return $render_array;
1118
}
1119

    
1120
/**
1121
 * Provides the the label string for taxon page tabs.
1122
 *
1123
 * The $tabname as passed to the method will be returned if no override
1124
 * label is configured in the settings.
1125
 */
1126
function cdm_taxonpage_tab_label($tabname) {
1127
  static $taxon_tabs_labels = null;
1128
  if($taxon_tabs_labels == null){
1129
    $taxon_tabs_labels = get_array_variable_merged(CDM_TAXONPAGE_TAB_LABELS, CDM_TAXONPAGE_TAB_LABELS_DEFAULT);
1130
  }
1131
  $tabname_key = strtolower($tabname);
1132
  if(isset($taxon_tabs_labels[$tabname_key]) && $taxon_tabs_labels[$tabname_key]){
1133
    return $taxon_tabs_labels[$tabname_key];
1134
  }
1135
  return $tabname;
1136
}
(7-7/10)