Project

General

Profile

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

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

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

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

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

    
240
        //add toggle functionality to derivate hierarchy table
241
        drupal_add_js_rowToggle("#".$tableId);
242

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

    
265
        if ($specimensOrObservations) {
266

    
267
            foreach ($specimensOrObservations as $specimenOrObservation) {
268

    
269
                $mediaList = array();
270
                if (is_array($specimenOrObservation->_fieldObjectMedia)) {
271
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_fieldObjectMedia);
272
                }
273
                if (is_array($specimenOrObservation->_derivedUnitMedia)) {
274
                    $mediaList = array_merge($mediaList, $specimenOrObservation->_derivedUnitMedia);
275
                }
276

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

    
293
                // --- Specimen entry as dynamic label:
294
                //     -> Dynabox for the specimenOrObservation
295
                $gallery_name = $specimenOrObservation->uuid;
296

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

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

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

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

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

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

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

    
416
  // we better cache here since drupal_get_query_parameters has no internal static cache variable
417
  $http_request_params = drupal_get_query_parameters();
418

    
419
  // add all mandatory js sources
420
  _add_js_footnotes();
421

    
422

    
423
  $render_array = array();
424
  $weight = 0; // the weight for the render array elements
425

    
426
  $tabsToDisplay = variable_get('cdm_taxonpage_tabs_visibility', unserialize(TAXONPAGE_VISIBILITY_OPTIONS_DEFAULT));
427

    
428
  $page_part = variable_get('cdm_dataportal_taxonpage_tabs', 1) ? $page_part : 'all';
429

    
430
  $media = _load_media_for_taxon($taxon);
431

    
432

    
433
  if (!isset($media[0]) || ($tabsToDisplay["Images"] == '0')) {
434
    taxon_page_tabs_hidden('images');
435
  }
436

    
437
  // --- GET specimensOrObservations --- //
438
  $specimensOrObservations = cdm_ws_get(CDM_WS_TAXON, array( $taxon->uuid, 'specimensOrObservations'));
439

    
440
  $specimensOrObservationsCount = is_array($specimensOrObservations) ? count($specimensOrObservations) : 0;
441
  if ($specimensOrObservationsCount == 0 || ($tabsToDisplay["Specimens"] == '0')) {
442
    taxon_page_tabs_hidden('specimens');
443
  }
444

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

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

    
468
    if ($tabsToDisplay["Synonymy"] == '0') {
469
    taxon_page_tabs_hidden('synonymy');
470
  }
471

    
472
  // -------------------------------------------- //
473

    
474
  if (variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR) && isset($_REQUEST['acceptedFor'])) {
475
    $render_array['accepted_for'] = markup_to_render_array(cdm_accepted_for($_REQUEST['acceptedFor']), $weight++);
476
  }
477

    
478
  // --- PAGE PART: DESCRIPTION --- //
479
  if ($page_part == 'description' || $page_part == 'all') {
480

    
481
    $merged_tree = merged_taxon_feature_tree($taxon);
482

    
483

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

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

    
522
  // --- PAGE PART: SYNONYMY --- //
523
  if (($page_part == 'synonymy' || $page_part == 'all')) {
524
    $synonymy_html = '<div id="synonymy" class="page-part">';
525
    if ($page_part == 'all') {
526
      $synonymy_html .= '<h2>' . t('Synonymy') . '</h2>';
527
    }
528
    $addAcceptedTaxon = variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE);
529

    
530
    $synonymy_html .= theme('cdm_taxon_page_synonymy', array('taxon' => $taxon, 'addAcceptedTaxon' => $addAcceptedTaxon));
531

    
532
    $synonymy_html .= '</div>';
533
    $render_array['synonymy'] = markup_to_render_array($synonymy_html, $weight++);
534

    
535
  }
536

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

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

    
560
  // --- PAGE PART: EXPERTS --- //
561

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

    
570
  // ------------------ END OF PARTS -------------- //
571

    
572
  // adjust weights of page and toc elements according to the settings
573
  $taxontabs_weights = get_array_variable_merged('cdm_taxonpage_tabs_weight', CDM_TAXONPAGE_TAB_WEIGHT_DEFAULT);
574
  foreach($taxontabs_weights as $tab_key => $weight){
575
    if(isset($render_array[$tab_key])){
576
      $render_array[$tab_key]['#weight'] = $weight;
577
    }
578
  }
579

    
580

    
581
  // set up the TOC for the pages which contain all pageparts
582
  if($page_part == 'all') {
583

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

    
610
    // move profile image in page structure
611
    if(isset($render_array['general']['taxon_profile_image'])){
612
      $render_array['profile_image'] = $render_array['general']['taxon_profile_image'];
613
      $render_array['profile_image']['#weight'] = -100;
614
      unset($render_array['general']['taxon_profile_image']);
615
    }
616

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

    
628

    
629
  return $render_array;
630
}
631

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

    
656
  $render_array = array();
657

    
658
  $taxon_profile_image_settings = variable_get(CDM_TAXON_PROFILE_IMAGE, unserialize(CDM_TAXON_PROFILE_IMAGE_DEFAULT));
659

    
660
  $hide_taxon_profile_image = FALSE;
661
  if (variable_get('image_hide_rank', '0') != '0' && isset($taxon->name->rank->uuid)) {
662
    $rankCompare = rank_compare($taxon->name->rank->uuid, variable_get('image_hide_rank', '-99'));
663
    $hide_taxon_profile_image = ($rankCompare > -1);
664
  }
665

    
666
  if ($taxon_profile_image_settings['show'] && !$hide_taxon_profile_image) {
667

    
668
    $representationPart = new stdClass();
669
    $attributes = array();
670
    if (isset($media[0]->representations[0]->parts[0])) {
671
      $representationPart = $media[0]->representations[0]->parts[0];
672
      $attributes['alt'] = $representationPart->uri;
673

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

    
703
    if (isset($representationPart->uri)) {
704
      $profile_image = theme('cdm_media_gallerie_image', array(
705
        'mediaRepresentationPart' => $representationPart,
706
        'maxExtend' => $taxon_profile_image_settings['maxextend'],
707
        'addPassePartout' => FALSE,
708
        'attributes' => $attributes,
709
      ));
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

    
998
  $items[] = $node_name;
999

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

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

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

    
1015
      // 'fa-sitemap'
1016

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

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

    
1049
  }
1050

    
1051

    
1052

    
1053
  $render_array['#items'] = $items;
1054

    
1055
  return $render_array;
1056

    
1057
}
(7-7/10)