Project

General

Profile

Download (94.2 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Module to provide a CDM Dataportal.
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
 *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
18
 */
19

    
20
  module_load_include('php', 'cdm_dataportal', 'node_types');
21
  module_load_include('php', 'cdm_dataportal', 'settings');
22
  module_load_include('php', 'cdm_dataportal', 'help');
23
  module_load_include('php', 'cdm_dataportal', 'cdm_dataportal.search');
24

    
25
  module_load_include('inc', 'cdm_dataportal', 'includes/common');
26
  module_load_include('inc', 'cdm_dataportal', 'includes/name');
27
  module_load_include('inc', 'cdm_dataportal', 'includes/taxon');
28
  module_load_include('inc', 'cdm_dataportal', 'includes/references');
29
  module_load_include('inc', 'cdm_dataportal', 'includes/pages');
30
  module_load_include('inc', 'cdm_dataportal', 'includes/media');
31
  module_load_include('inc', 'cdm_dataportal', 'includes/maps');
32
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
33
  module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
34
  module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
35

    
36
  module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
37
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
38
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
39
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
40
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
41
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
42
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
43
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
44
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
45

    
46
  module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
47
  module_load_include('php', 'cdm_dataportal', 'classes/footnote');
48
  module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
49
  module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
50

    
51

    
52
  /* ============================ java script functions ============================= */
53

    
54

    
55
  /**
56
  * loads external java script files asynchronously.
57
  *
58
  * @param unknown_type $script_url
59
  */
60
  function drupal_add_js_async($script_url, $callback){
61

    
62
    drupal_add_js("
63
          jQuery(document).ready(function() {
64
            jQuery.ajax({
65
              url: '" . $script_url . "',
66
              dataType: 'script',
67
              cache: true, // otherwise will get fresh copy every page load
68
              success: function() {
69
                    " . $callback . "
70
              }
71
            });
72
          });"
73
    , 'inline');
74
  }
75

    
76
  /**
77
   */
78
  function drupal_add_js_rowToggle($tableId){
79

    
80
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/table_modification.js');
81
      drupal_add_js('jQuery(document).ready(function(){
82
          addRowToggle("' . $tableId . '");
83
      });
84
      ', array('type' => 'inline'));
85
  }
86

    
87
  /**
88
   * @param unknown_type $link_element_selector
89
   * @param unknown_type $progress_element_selector
90
   */
91
  function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
92

    
93
    $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
94

    
95
    drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
96

    
97
    //   drupal_add_js("
98
    //   	  if (Drupal.jsEnabled) {
99
    //         $(document).ready(function() {
100
    //       		$('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');
101
    //         });
102
    //       }", 'inline');
103
    }
104

    
105
  /**
106
   * @todo Please document this function.
107
   * @see http://drupal.org/node/1354
108
   */
109
  function _add_js_treeselector() {
110
    // drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
111
    drupal_add_js("
112
        jQuery(document).ready(function() {
113
           jQuery('#cdm-taxonomictree-selector-form #edit-val').change(function () {
114
                jQuery('#cdm-taxonomictree-selector-form').submit();
115
            });
116

    
117
        });
118
      ",
119
      array(
120
        'type' => 'inline',
121
        'scope' => 'footer'
122
      )
123
    );
124
  }
125

    
126
  function _add_js_resizable_element($selector, $y_axis_only) {
127

    
128
    _add_jquery_ui();
129
    $options = "";
130
    if($y_axis_only) {
131
      $options = "resize: function(event, ui) {
132
        ui.size.width = ui.originalSize.width;
133
        },
134
        handles: \"s\"";
135

    
136
    }
137
    drupal_add_js("
138
          jQuery(document).ready(function() {
139
             jQuery('" . $selector . "').resizable({". $options ."});
140
          });
141
        ",
142
      array(
143
        'type' => 'inline',
144
        'scope' => 'footer'
145
      )
146
    );
147
  }
148

    
149
  function _add_js_openlayers() {
150

    
151
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
152
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
153

    
154
    if(variable_get('cdm_js_devel_mode', FALSE)){
155
      // develooper mode libs
156
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
157
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
158
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
159
    }
160

    
161
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
162
      array(
163
        'type' => 'file',
164
        'group' => JS_LIBRARY,
165
        'weight' => 0,
166
        'cache' => TRUE,
167
        'preprocess' => FALSE
168
      )
169
    );
170

    
171
    // see https://github.com/proj4js/proj4js
172
    // http://openlayers.org/dev/examples/using-proj4js.html
173
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
174
      array(
175
        'type' => 'file',
176
        'group' => JS_LIBRARY,
177
        'weight' => -1, // before open layers
178
        'cache' => TRUE,
179
      )
180
    );
181

    
182
    // configure the theme
183
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
184
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
185
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
186
        'type' => 'inline',
187
        'group' => JS_LIBRARY,
188
        'weight' => 1, // after openlayers
189
        'cache' => TRUE,
190
        'preprocess' => FALSE
191
      ));
192

    
193
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
194
      array(
195
        'type' => 'file',
196
        'cache' => TRUE,
197
        'preprocess' => FALSE
198
      )
199
    );
200

    
201
  }
202

    
203
  /**
204
   * @todo Please document this function.
205
   * @see http://drupal.org/node/1354
206
   */
207
  function _add_js_thickbox() {
208
    // ---- jQuery thickbox:
209
    /*
210
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
211
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
212
    */
213
    // drupal_add_js(drupal_get_path('module',
214
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
215
    //
216
    // Add a setting for the path to cdm_dataportal module, used to find the path
217
    // for the loading animation image in thickbox.
218
    drupal_add_js(array(
219
    'cdm_dataportal' => array(
220
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
221
    )
222
    ),
223
    'setting'
224
        );
225
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
226
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
227
  }
228

    
229
  /**
230
   * @todo Please document this function.
231
   * @see http://drupal.org/node/1354
232
   */
233
  function _add_js_lightbox($galleryID) {
234
    /*
235
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
236
     * allow using the "alt" attribute for captions instead of the "title"
237
     * attribute
238
     */
239
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
240
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
241
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
242
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
243
    drupal_add_js('jQuery(document).ready(function() {
244
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
245
          fixedNavigation:  true,
246
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
247
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
248
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
249
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
250
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
251
          adjustToWindow: true
252
        });
253
      });
254
      ', array('type' => 'inline'));
255
  }
256

    
257
  /**
258
   * @todo Please document this function.
259
   * @see http://drupal.org/node/1354
260
   */
261
  function _add_js_footnotes() {
262
    _add_js_domEvent();
263
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
264
  }
265

    
266
  /**
267
   * @todo Please document this function.
268
   * @see http://drupal.org/node/1354
269
   */
270
  function _add_js_ahah() {
271

    
272
    _add_js_domEvent(); // requires domEvent.js
273
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
274
  }
275

    
276
/**
277
 * @todo Please document this function.
278
 * @see http://drupal.org/node/1354
279
 */
280
function _add_js_taxonomic_children($jquery_selector) {
281

    
282
  global $base_url;
283

    
284

    
285
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
286
  
287
  drupal_add_js('jQuery(document).ready(function() {
288
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
289
          // hoverClass: "fa-rotate-90",
290
          // activeClass: "fa-rotate-90",
291
          classificationUuid: "' . get_current_classification_uuid() . '",
292
          taxonUuid: "' . get_current_taxon_uuid() . '",
293
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
294
          proxyBaseUri: "' . $base_url . '",
295
          
296
        });
297
      });
298
      ', array('type' => 'inline'));
299
}
300

    
301
  /**
302
   * Adds the external javascript file for domEvent.js.
303
   *
304
   * @see drupal_add_js()
305
   */
306
  function _add_js_domEvent() {
307
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
308
  }
309

    
310
  function _add_jquery_ui()
311
  {
312
    drupal_add_css(drupal_get_path('module',
313
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
314
    drupal_add_js(drupal_get_path('module',
315
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
316
      array(
317
        'type' => 'file',
318
        'weight' => JS_LIBRARY,
319
        'cache' => TRUE,
320
        'preprocess' => FALSE
321
      )
322
    );
323
  }
324

    
325
  function _add_js_ui_accordion(){
326
    _add_jquery_ui();
327
    drupal_add_js('jQuery(document).ready(function() {
328
        jQuery( "#accordion" ).accordion();
329
      });',
330
      array('type' => 'inline')
331
    );
332
  }
333

    
334
  /**
335
   * Provides the markup for an font awesome icon.
336
   *
337
   * The icons is created in default size without any extra features.
338
   *
339
   * The available icons are listed here http://fontawesome.io/cheatsheet/
340
   * fontawesome icons have much more features than implemented here in this function,
341
   * for spinning icons, fixed width icons, rotation, etc please checkout the
342
   * examples at http://fontawesome.io/examples/
343
   *
344
   * @parameter $icon_name
345
   *  The name of the icon which starts with 'fa-'
346
   *
347
   * @return String
348
   *    the markup for the icon in an <i> tag
349
   *
350
   */
351
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
352
    _add_font_awesome_font();
353

    
354

    
355
    if($icon_name){
356
      if(!isset($attributes['class'])){
357
        $attributes['class'] = array();
358
      }
359
      $attributes['class'][] = 'fa';
360
      $attributes['class'][] = $icon_name;
361

    
362
      return '<i ' . drupal_attributes($attributes) . '></i>';
363
    }
364

    
365
    return '';
366
  }
367

    
368
/**
369
 * @param string $glyph_name
370
 *   The name of the gloyph (e.g. 'icon-interal-link-alt-solid') for the foll list please
371
 *   refer to modules/cdm_dataportal/fonts/custom-icon-font
372
 * @param array $attributes
373
 * @return string
374
 */
375
  function custom_icon_font_markup($glyph_name = NULL, $attributes = array()){
376
    _add_font_custom_icon_font();
377

    
378

    
379
    if($glyph_name){
380
      if(!isset($attributes['class'])){
381
        $attributes['class'] = array();
382
      }
383
      $attributes['class'][] = $glyph_name;
384

    
385
      return '<i ' . drupal_attributes($attributes) . '></i>';
386
    }
387

    
388
    return '';
389
  }
390

    
391
/**
392
 * Adds the css  containing the font awesome icons to the html header.
393
 */
394
function _add_font_awesome_font()
395
{
396
  $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/font-awesome-4.6.3/css/font-awesome.min.css';
397

    
398
  drupal_add_html_head_link(
399
    array(
400
      'href' => $font_awesome_css_uri,
401
      'rel' => 'stylesheet'
402
    )
403
  );
404
}
405

    
406
/**
407
 * Adds the css  containing the font awesome icons to the html header.
408
 */
409
function _add_font_custom_icon_font()
410
{
411

    
412
  $custom_icon_font_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/custom-icon-font/style.css';
413

    
414
  drupal_add_html_head_link(
415
    array(
416
      'href' => $custom_icon_font_css_uri,
417
      'rel' => 'stylesheet'
418
    )
419
  );
420
}
421

    
422
/* ====================== hook implementations ====================== */
423
  /**
424
   * Implements hook_permission().
425
   *
426
   * Valid permissions for this module.
427
   *
428
   * @return array
429
   *   An array of valid permissions for the cdm_dataportal module.
430
   */
431
  function cdm_dataportal_permission() {
432
    return array(
433
      'administer cdm_dataportal' => array(
434
        'title' => t('Administer CDM DataPortal settings'),
435
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
436
      ),
437
      'access cdm content' => array(
438
        'title' => t('Access CDM content'),
439
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
440
      ),
441
    );
442
  }
443

    
444
/**
445
 * Implements hook_menu().
446
 */
447
function cdm_dataportal_menu() {
448
  $items = array();
449

    
450
  // @see settings.php.
451
  cdm_dataportal_menu_admin($items);
452
  cdm_dataportal_menu_help($items);
453

    
454
  $items['cdm_dataportal/names'] = array(
455
    'page callback' => 'cdm_dataportal_view_names',
456
    'access arguments' => array('access cdm content'),
457
    'type' => MENU_CALLBACK,
458
  );
459

    
460
  // Optional callback arguments: page.
461
  $items['cdm_dataportal/taxon'] = array(
462
    'page callback' => 'cdm_dataportal_taxon_page_view',
463
    'access arguments' => array('access cdm content'),
464
    'type' => MENU_CALLBACK,
465
    // Expected callback arguments: uuid.
466
  );
467

    
468
  $items['cdm_dataportal/occurrence'] = array(
469
        'page callback' => 'cdm_dataportal_specimen_page_view',
470
        'access arguments' => array('access cdm content'),
471
        'type' => MENU_CALLBACK,
472
        // Expected callback arguments: uuid.
473
    );
474

    
475
   $items['cdm_dataportal/specimen/accession_number'] = array(
476
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
477
        'access arguments' => array('access cdm content'),
478
        'type' => MENU_CALLBACK,
479
        // Expected callback arguments: accession number.
480
    );
481
  $items['cdm_dataportal/named_area'] = array(
482
    'page callback' => 'cdm_dataportal_named_area_page_view',
483
    'access arguments' => array('access cdm content'),
484
    'type' => MENU_CALLBACK,
485
    // Expected callback arguments: uuid.
486
  );
487

    
488
  $items['cdm_dataportal/name'] = array(
489
    'page callback' => 'cdm_dataportal_name_page_view',
490
      /*
491
    'page arguments' => array(
492
       'taxon_name_uuid',
493
       'taxon_to_hide_uuid',
494
       'synonym_uuid' => NULL
495
      ),
496
      */
497
    'access arguments' => array('access cdm content'),
498
    'type' => MENU_CALLBACK,
499
    // Expected callback arguments: uuid.
500
  );
501

    
502
  $items['cdm_dataportal/reference'] = array(
503
    'page callback' => 'cdm_dataportal_view_reference',
504
    'access arguments' => array('access cdm content'),
505
    'type' => MENU_CALLBACK,
506
    // Expected callback arguments: uuid.
507
  );
508

    
509
  $items['cdm_dataportal/reference/list'] = array(
510
    'page callback' => 'cdm_dataportal_view_reference_list',
511
    'access arguments' => array('access cdm content'),
512
    'type' => MENU_CALLBACK,
513
    // Expected callback arguments: uuid.
514
  );
515

    
516
  $items['cdm_dataportal/media'] = array(
517
    'page callback' => 'cdm_dataportal_view_media',
518
    'access arguments' => array('access cdm content'),
519
    'type' => MENU_CALLBACK,
520
    // Expected callback arguments:
521
    // uuid, mediarepresentation_uuid, part_uuid or part#.
522
  );
523

    
524
  $items['cdm_dataportal/polytomousKey'] = array(
525
    'page callback' => 'cdm_dataportal_view_polytomousKey',
526
    'access arguments' => array('access cdm content'),
527
    'type' => MENU_CALLBACK,
528
    // Expected callback arguments: polytomousKey->uuid.
529
  );
530

    
531
  $items['cdm_dataportal/search'] = array(
532
    'page callback' => 'cdm_dataportal_view_search_advanced',
533
    'access arguments' => array('access cdm content'),
534
    'type' => MENU_CALLBACK,
535
  );
536

    
537
  $items['cdm_dataportal/search/advanced'] = array(
538
    'title' => 'Advanced', // will be passed through t()
539
    'page callback' => 'cdm_dataportal_view_search_advanced',
540
    'access arguments' => array('access cdm content'),
541
    'type' => MENU_DEFAULT_LOCAL_TASK,
542
  );
543
  $items['cdm_dataportal/search/blast'] = array(
544
    'title' => 'Blast', // will be passed through t()
545
    'page callback' => 'cdm_dataportal_view_search_blast',
546
    'access arguments' => array('access cdm content'),
547
    'type' => MENU_LOCAL_TASK,
548
  );
549

    
550
  $items['cdm_dataportal/search/taxon_by_description'] = array(
551
    'title' => 'By content category', // will be passed through t()
552
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
553
    'access arguments' => array('access cdm content'),
554
    'type' => MENU_LOCAL_TASK,
555
  );
556
  $items['cdm_dataportal/search/results/taxon'] = array(
557
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
558
    'access arguments' => array('access cdm content'),
559
    'type' => MENU_CALLBACK,
560
  );
561

    
562

    
563
  $items['cdm_dataportal/search/results/specimen'] = array(
564
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
565
      'access arguments' => array('access cdm content'),
566
      'type' => MENU_CALLBACK,
567
  );
568

    
569
  /*
570
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
571
   * tabs in the subordinate paths work, accessing this 'page' will cause the
572
   * MENU_DEFAULT_LOCAL_TASK being displayed
573
   */
574
  $items['cdm_dataportal/registration-search'] = array(
575
    'title' => 'Search', // will be passed through t()
576
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
577
    'page arguments' => array("filter"),
578
    'access arguments' => array('access cdm content'),
579
    'type' => MENU_CALLBACK,
580
  );
581
  /*
582
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
583
   * defined at a higher level of the path (cdm_dataportal/registration-search)
584
   */
585
  $items['cdm_dataportal/registration-search/filter'] = array(
586
    'title' => 'Search', // will be passed through t()
587
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
588
    'page arguments' => array("filter"),
589
    'access arguments' => array('access cdm content'),
590
    'type' => MENU_DEFAULT_LOCAL_TASK,
591
  );
592
  /*
593
   * the MENU_LOCAL_TASK creates another tab
594
   */
595
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
596
    'title' => 'Taxonomic search', // will be passed through t()
597
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
598
    'page arguments' => array("taxongraph"),
599
    'access arguments' => array('access cdm content'),
600
    'type' => MENU_LOCAL_TASK,
601
  );
602

    
603
  // Optional callback arguments: page.
604
  $items['cdm_dataportal/registration'] = array(
605
    'page callback' => 'cdm_dataportal_registration_page_view',
606
    'access arguments' => array('access cdm content'),
607
    'type' => MENU_CALLBACK,
608
    // Expected callback arguments: uuid.
609
  );
610

    
611
  /*
612
   $items['cdm/xml2json'] = array(
613
   'page callback' => 'cdm_view_xml2json',
614
   'access arguments' => array('access cdm content'),
615
   'type' => MENU_CALLBACK,
616
   );
617
   */
618

    
619
  // 'May not cache' in D5.
620
  $items['cdm_dataportal/name/%'] = array(
621
    // 'page callback' => 'cdm_dataportal_view_name',
622
    'page callback' => 'cdm_dataportal_name_page_view',
623
    'page arguments' => array(2, 3, 4, 5),
624
    'access arguments' => array('access cdm content'),
625
    'type' => MENU_CALLBACK,
626
  );
627

    
628
  // --- Local tasks for Taxon.
629
  // --- tabbed taxon page
630
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
631
    $items['cdm_dataportal/taxon/%'] = array(
632
      'title' => cdm_taxonpage_tab_label('General'),
633
      'page callback' => 'cdm_dataportal_taxon_page_view',
634
      'access arguments' => array('access cdm content'),
635
      'type' => MENU_CALLBACK,
636
      'weight' => 1,
637
      'page arguments' => array(2, "description")
638
      , // Expected callback arguments: taxon_uuid.
639
    );
640

    
641
    $items['cdm_dataportal/taxon/%/all'] = array(
642
      'title' => cdm_taxonpage_tab_label('General'),
643
      'page callback' => 'cdm_dataportal_taxon_page_view',
644
      'access arguments' => array('access cdm content'),
645
      'type' => MENU_CALLBACK,
646
      'weight' => 2,
647
      'page arguments' => array(2, "all")
648
      , // Expected callback arguments: taxon_uuid.
649
    );
650

    
651
    $items['cdm_dataportal/taxon/%/description'] = array(
652
      'title' => cdm_taxonpage_tab_label('General'),
653
      'page callback' => 'cdm_dataportal_taxon_page_view',
654
      'access arguments' => array('access cdm content'),
655
      'type' => MENU_DEFAULT_LOCAL_TASK,
656
      'weight' => 2,
657
      'page arguments' => array(2, "description")
658
      , // Expected callback arguments: taxon_uuid.
659
    );
660

    
661
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
662
      'title' => cdm_taxonpage_tab_label('Synonymy'),
663
      'page callback' => 'cdm_dataportal_taxon_page_view',
664
      'access arguments' => array('access cdm content'),
665
      'type' => MENU_LOCAL_TASK,
666
      'weight' => 4,
667
      'page arguments' => array(2, "synonymy", 4)
668
      , // Expected callback arguments: taxon_uuid and ...
669
    );
670
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
671
      'title' => cdm_taxonpage_tab_label('Images'),
672
      'page callback' => 'cdm_dataportal_taxon_page_view',
673
      'access arguments' => array('access cdm content'),
674
      'type' => MENU_LOCAL_TASK,
675
      'weight' => 5,
676
      'page arguments' => array(2, "images")
677
      , // Expected callback arguments: taxon_uuid.
678
    );
679

    
680
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
681
      'title' => cdm_taxonpage_tab_label('Specimens'),
682
      'page callback' => 'cdm_dataportal_taxon_page_view',
683
      'access arguments' => array('access cdm content'),
684
      'type' => MENU_LOCAL_TASK,
685
      'weight' => 6,
686
      'page arguments' => array(2, "specimens")
687
      , // Expected callback arguments: taxon_uuid.
688
    );
689

    
690
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
691
      'title' => cdm_taxonpage_tab_label('Keys'),
692
      'page callback' => 'cdm_dataportal_taxon_page_view',
693
      'access arguments' => array('access cdm content'),
694
      'type' => MENU_LOCAL_TASK,
695
      'weight' => 6,
696
      'page arguments' => array(2, "keys")
697
      , // Expected callback arguments: taxon_uuid.
698
    );
699

    
700
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
701
      'title' => cdm_taxonpage_tab_label('Experts'),
702
        'page callback' => 'cdm_dataportal_taxon_page_view',
703
        'access arguments' => array('access cdm content'),
704
        'type' => MENU_LOCAL_TASK,
705
        'weight' => 6,
706
        'page arguments' => array(2, "experts")
707
    , // Expected callback arguments: taxon_uuid.
708
    );
709

    
710
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
711
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
712
        'access arguments' => array('access cdm content'),
713
        'page arguments' => array(3,4,5),
714
        'type' => MENU_CALLBACK
715
    );
716
  }
717

    
718
  // --- refresh link for all cdmnode types
719
  foreach (cdm_get_nodetypes() as $type=>$name) {
720
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
721
        'title' => 'Refresh',
722
        'page callback' => 'cdm_dataportal_refresh_node',
723
        'access arguments' => array('administer cdm_dataportal'),
724
        'type' => MENU_LOCAL_TASK,
725
        'weight' => 100,
726
        'page arguments' => array($name, 2)
727
    );
728
  }
729

    
730
  return $items;
731
}
732

    
733
/**
734
 * Implements hook_init().
735
 *
736
 */
737
function cdm_dataportal_init() {
738
  if (!path_is_admin(current_path())) {
739
    //FIXME To add CSS or JS that should be present on all pages, modules
740
    //      should not implement this hook, but declare these files in their .info file.
741
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
742
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
743
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
744
  } else {
745
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
746
  }
747

    
748
  if(variable_get('cdm_debug_mode', FALSE)){
749
    $file = 'temporary://drupal_debug.txt';
750
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
751
  }
752

    
753
  $bibliography_settings = get_bibliography_settings();
754
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
755
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
756
}
757

    
758
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
759

    
760
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
761

    
762
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
763
    // force reloading of all and notify user about this special loading
764
    drupal_set_message(t('The level 2 cache has been cleared for all tabs of this taxon page at once, please click here to return to the tabbed page: ')
765
        . l('Back to tabbed taxon page', $base_path));
766
    $base_path .= '/all';
767
  } else {
768
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
769
  }
770

    
771
  $parameters['cacheL2_refresh'] ='1';
772

    
773

    
774
  drupal_goto($base_path, array('query' => $parameters));
775
}
776

    
777
/**
778
 * Implements hook_requirements($phase)
779
 */
780
function cdm_dataportal_requirements($phase) {
781
    $requirements = array();
782
    if($phase == 'runtime'){
783

    
784
    }
785
    return $requirements;
786
}
787

    
788
/**
789
 * Implements hook_block_info().
790
 */
791
function cdm_dataportal_block_info() {
792

    
793
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
794
    // $block[1]["info"] = t("CDM DataPortal Credits");
795
    $block["2"] = array(
796
        "info" => t("CDM - Search Taxa"),
797
        "cache" => DRUPAL_NO_CACHE
798
      );
799
    // $block[3]["info"] = t("CDM Filters");
800
    $block["4"]["info"] = t("CDM  - Dataportal Print");
801
    $block["keys"]["info"] = t("CDM - Identification keys");
802
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
803
    $block["classification_breadcrumbs"] =  array(
804
        'info' => t('CDM - Classification breadcrumbs'),
805
        'cache' => DRUPAL_CACHE_PER_PAGE
806
      );
807
    $block["taxonomic_children"] =  array(
808
      'info' => t('CDM - Taxonomic children'),
809
      'cache' => DRUPAL_CACHE_PER_PAGE
810
    );
811
    $block["back_to_search_results"] =  array(
812
      'title' => '<none>',
813
      'info' => t('CDM - Back to search Results'),
814
      'cache' => DRUPAL_CACHE_PER_PAGE,
815
      'visibility' => BLOCK_VISIBILITY_LISTED,
816
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
817
    );
818
  $block['registrations_search_filter'] =  array(
819
    'title' => 'Filter registrations',
820
    'info' => t('CDM - Registrations search filter'),
821
    'cache' => DRUPAL_CACHE_PER_PAGE,
822
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
823
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
824
  );
825
  $block['registrations_search_taxongraph'] =  array(
826
    'title' => 'Taxonomic registration search',
827
    'info' => t('CDM - Registrations search by taxon graph'),
828
    'cache' => DRUPAL_CACHE_PER_PAGE,
829
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
830
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
831
  );
832
  $block['registrations_search'] =  array(
833
    'title' => 'Search',
834
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
835
    'cache' => DRUPAL_CACHE_PER_PAGE,
836
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
837
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
838
  );
839
  return $block;
840
}
841

    
842
/**
843
 * Implements hook_block_view().
844
 */
845
function cdm_dataportal_block_view($delta) {
846
  // TODO Rename block deltas (e.g. '2') to readable strings.
847
  switch ($delta) {
848
    // case 'delta-1':
849
    // $block['subject'] = t('Credits');
850
    // $block['content'] = theme('cdm_credits');
851
    // return $block;
852
    case '2':
853
      $block['subject'] = t('Search taxa');
854
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
855
      $block['content'] = drupal_render($form);
856

    
857
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
858
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
859
      }
860
      if (variable_get(CDM_SEARCH_BLAST_ENABLED)){
861
          $block['content'] .= '<div>' . l(t('Blast Search'), 'cdm_dataportal/search/blast') . '</div>';
862
      }
863
      return $block;
864
    case '4':
865
      $block['subject'] = '';
866
      $block['content'] = theme('cdm_print_button');
867
      return $block;
868
    case "keys":
869
      $block['subject'] = t('Identification Keys');
870
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
871
      return $block;
872
    case "fundedByEDIT":
873
      // t('Funded by EDIT');
874
      $text = '<none>';
875
      $block['subject'] = $text;
876
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
877
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
878
        'attributes' => array("target" => "EDIT"),
879
        'absolute' => TRUE,
880
        'html' => TRUE,
881
      ));
882
      return $block;
883
    case 'classification_breadcrumbs':
884
      $taxon_uuid = get_current_taxon_uuid();
885
      $block['subject'] = '<none>';
886
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
887
      return $block;
888
    case 'taxonomic_children':
889
      $taxon_uuid = get_current_taxon_uuid();
890
      $block['subject'] = '<none>';
891
      $block['content'] = compose_taxonomic_children($taxon_uuid);
892
      return $block;
893
    case 'back_to_search_results':
894
      $block['subject'] = '<none>';
895
      if (isset($_SESSION['cdm']['search'])) {
896
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
897
      }
898
      return $block;
899
    case 'registrations_search_filter':
900
      $block['subject'] = '<none>';
901
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
902
      return $block;
903
    case 'registrations_search_taxongraph':
904
      $block['subject'] = '<none>';
905
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
906
      return $block;
907
    case 'registrations_search':
908
      _add_js_ui_accordion();
909
      _add_font_awesome_font();
910
      $block['subject'] = '<none>';
911
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
912
      $filter_form['#prefix'] = '<div>';
913
      $filter_form['#suffix'] = '</div>';
914
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
915
      $taxongraph_form['#prefix'] = '<div>';
916
      $taxongraph_form['#suffix'] = '</div>';
917
      $block['content'] = array(
918
        'accordion' => array(
919
          '#markup' => '',
920
          '#prefix' => '<div id="accordion">',
921
          '#suffix' => '</div>',
922
          'content' => array(
923
            array('#markup' => '<h3>Filter</h3>'),
924
            $filter_form,
925
            array('#markup' => '<h3>Taxon graph</h3>'),
926
            $taxongraph_form,
927
          )
928
        )
929
    );
930
       return $block;
931
    default:
932
      return null;
933
  }
934
}
935

    
936
/**
937
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
938
 *
939
 * @return string
940
 *   the taxon uuid or NULL
941
 */
942
function get_current_taxon_uuid()
943
{
944
  static $taxon_uuid;
945

    
946
  if(!isset($taxon_uuid)){
947
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
948
      $taxon_uuid = $_REQUEST['currentTaxon'];
949
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
950
      $taxon_uuid = arg(2);
951
    } else {
952
      $taxon_uuid = null;
953
    }
954
  }
955

    
956
  return $taxon_uuid;
957
}
958

    
959
/**
960
 * Returns the currently classification tree in use.
961
 *
962
 * @return string
963
 *   The uuid of the currently focused classification
964
 */
965
function get_current_classification_uuid() {
966
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
967
    return $_SESSION['cdm']['taxonomictree_uuid'];
968
  }
969
  else {
970
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
971
  }
972
}
973

    
974
/*
975
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
976
 $_SESSION['cdm'] = NULL;
977
 if(is_string($cdm_ws_uri_update)){
978
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
979
 }
980
 }
981

    
982
 function cdm_dataportal_session_validate(){
983
 if(!isset($_SESSION['cdm']['ws_uri'])){
984
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
985
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
986
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
987
 }
988
 }
989
 */
990

    
991
/**
992
 * creates a  selector form for taxonomic trees.
993
 *
994
 * @return array
995
 *  a drupal form array
996
 */
997
function cdm_taxonomictree_selector() {
998
  _add_js_treeselector();
999

    
1000
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1001
  return $form;
1002
}
1003

    
1004
/**
1005
 * @todo Please document this function.
1006
 * @see http://drupal.org/node/1354
1007
 *
1008
 * @deprecated use compose_classification_selector instead
1009
 */
1010
function cdm_taxonomictree_selector_form($form, &$form_state) {
1011

    
1012
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1013
  $form['#action'] = $url;
1014

    
1015
  $form['var'] = array(
1016
    '#weight' => -3,
1017
    '#type' => 'hidden',
1018
    '#value' => '[cdm][taxonomictree_uuid]',
1019
  );
1020

    
1021
  $destination_array = drupal_get_destination();
1022
  $destination = $destination_array['destination'];
1023

    
1024
  $form['destination'] = array(
1025
    '#weight' => -3,
1026
    '#type' => 'hidden',
1027
    '#value' =>  $destination,
1028
  );
1029

    
1030
  $options = cdm_get_taxontrees_as_options();
1031
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1032
  if($taxontree_includes){
1033
    $filtered_options = array();
1034
    foreach($options as $uuid=>$label){
1035
      if(!empty($taxontree_includes[$uuid])){
1036
        $filtered_options[$uuid] = $label;
1037
      }
1038
    }
1039
    $options = $filtered_options;
1040
  }
1041

    
1042
  $form['val'] = array(
1043
    '#type' => 'select',
1044
    '#title' => t('Available classifications'),
1045
    '#default_value' => get_current_classification_uuid(),
1046
    '#options' => $options,
1047
    '#attributes' => array('class' => array('highlite-first-child')),
1048
  );
1049

    
1050
  return $form;
1051

    
1052
}
1053

    
1054
/**
1055
 *
1056
 * @ingroup compose
1057
 */
1058
function compose_classification_selector() {
1059

    
1060
  $destination_array = drupal_get_destination();
1061
  $destination = $destination_array['destination'];
1062

    
1063
  $options = cdm_get_taxontrees_as_options();
1064
  $items = array();
1065
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1066

    
1067
  $current_classification_uuid = get_current_classification_uuid();
1068

    
1069

    
1070
  foreach($options as $uuid=>$label){
1071
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1072

    
1073
      $class_attributes = '';
1074
      if($current_classification_uuid == $uuid){
1075
        $class_attributes  = array('focused');
1076
      }
1077
      $items[] = array(
1078
        'data' => l($label,
1079
          'cdm_api/setvalue/session',
1080
          array(
1081
            'query' => array(
1082
              'destination' => $destination,
1083
              'val' => $uuid,
1084
              'var' => '[cdm][taxonomictree_uuid]'
1085
            ),
1086
          )
1087
        ),
1088
        'class' => $class_attributes
1089
      );
1090
    }
1091
  }
1092

    
1093
  $render_array = array(
1094
    '#theme' => 'item_list',
1095
    '#type' => 'ul',
1096
    '#items' => $items
1097
  );
1098

    
1099
  return $render_array;
1100
}
1101

    
1102

    
1103
/* UNREACHABLE since action of form directly links to view.
1104
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1105

    
1106
 $_SESSION['cdm']['search'] = $form_values;
1107
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1108
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1109
 //$paramstr = compose_url_prameterstr($form_values);
1110
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1111
 }
1112
 */
1113
/* ====================== menu callback functions ====================== */
1114
/**
1115
 * @todo Please document this function.
1116
 * @see http://drupal.org/node/1354
1117
 */
1118
/*
1119
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1120
  static $comment_node_disabled =  0;
1121
  static $comment_node_read_only =  1;
1122
  static $comment_node_read_write =  2;
1123

    
1124
  if ($form_id == 'node_type_form'
1125
   && isset($form['identity']['type'])
1126
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1127
  ) {
1128
    $form['workflow']['comment'] = array(
1129
      '#type' => 'radios',
1130
      '#title' => t('Default comment setting'),
1131
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1132
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1133
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1134
    );
1135
  }
1136
}
1137
*/
1138

    
1139
/**
1140
 * Displays a list of the known taxonomic names.
1141
 *
1142
 * When the list of taxonomic names is displayed, long lists are split up into
1143
 * multiple pages.
1144
 *
1145
 * TODO: Parameters are still preliminary.
1146
 *
1147
 * @param string $beginsWith
1148
 * @param string $page
1149
 *   Page number to diplay defaults to page 1.
1150
 * @param bool $onlyAccepted
1151
 */
1152
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1153

    
1154
  $out = t('<h3>Sorry, the name list feature is not yet available in this version of the DataPortal software<h3>');
1155

    
1156
  /*
1157
  // FIXME the filter for accepted names will be a form element, thus this
1158
  // widget should be generated via form api preferably as block.
1159
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1160
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1161
  $out .= theme('cdm_listof_taxa', $taxonPager);
1162
  return $out;
1163
  */
1164
}
1165

    
1166
/**
1167
 * @todo Please document this function.
1168
 * @see http://drupal.org/node/1354
1169
 * @throws Exception
1170
 */
1171
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1172

    
1173
  cdm_check_valid_portal_page();
1174

    
1175
  return compose_cdm_reference_page($uuid);
1176
}
1177

    
1178
/**
1179
 * Creates a view on a all references contained in the portal.
1180
 *
1181
 * This function is used at the path cdm_dataportal/reference/list
1182
 */
1183
function cdm_dataportal_view_reference_list($pageNumber) {
1184
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1185
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1186
}
1187

    
1188
/**
1189
 * @todo Please document this function.
1190
 * @see http://drupal.org/node/1354
1191
 */
1192
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1193

    
1194
  cdm_check_valid_portal_page();
1195

    
1196
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1197
  return theme('cdm_media_page', array(
1198
    'media' => $media,
1199
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1200
    'partId' => $part,
1201
    ));
1202
}
1203

    
1204
/**
1205
 * @todo Please document this function.
1206
 * @see http://drupal.org/node/1354
1207
 */
1208
function _load_taxonBase(&$taxonBase) {
1209
  if (isset($taxonBase->uuid)) {
1210
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1211
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1212
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1213
  }
1214
}
1215

    
1216
/**
1217
 * Loads the media associated to the given taxon from the cdm server.
1218
 * The aggregation settings regarding taxon relathionships and
1219
 * taxonnomic childen are taken into account.
1220
 *
1221
 * The media lists are cached in a static variable.
1222
 *
1223
 * @param Taxon $taxon
1224
 *   A CDM Taxon entitiy
1225
 *
1226
 * @return array
1227
 *   An array of CDM Media entities
1228
 *
1229
 */
1230
function _load_media_for_taxon($taxon) {
1231

    
1232
  static $media = NULL;
1233

    
1234
  if(!isset($media)) {
1235
    $media = array();
1236
  }
1237
  if (!isset($media[$taxon->uuid])) {
1238

    
1239
    // --- GET Images --- //
1240
    $mediaQueryParameters = array(
1241
        "type" => "ImageFile",
1242
    );
1243

    
1244
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1245
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1246
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1247

    
1248
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1249
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1250
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1251
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1252

    
1253
    $ws_endpoint = NULL;
1254
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1255
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1256
    } else {
1257
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1258
    }
1259

    
1260
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1261
        array(
1262
            $taxon->uuid,
1263
        ),
1264
        queryString($mediaQueryParameters)
1265
       );
1266
  }
1267

    
1268
  return $media[$taxon->uuid];
1269
}
1270

    
1271
/**
1272
 *
1273
 * @param Taxon $taxon
1274
 *   A CDM Taxon entitiy
1275
 *
1276
 * @return array
1277
 *   An array of CDM SpecimenOrObservation entities
1278
 *
1279
function _load_occurences_for_taxon($taxon){
1280

    
1281
  static $occurences = NULL;
1282

    
1283
  if(!isset($occurences)) {
1284
    $occurences = array();
1285
  }
1286

    
1287
  if (!isset($occurences[$taxon->uuid])){
1288

    
1289
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1290
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1291
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1292

    
1293
    $by_associatedtaxon_query = http_build_query(array(
1294
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1295
        'relationships' => implode(',', $relationship_choice['direct']),
1296
        'pageSize' => null // all hits in one page
1297
    )
1298
    );
1299

    
1300
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1301
        null,
1302
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1303
    );
1304

    
1305

    
1306
    if(isset($pager->records[0])){
1307
      $occurences[$taxon->uuid] =  $pager->records;
1308
    }
1309
  }
1310
  return $occurences[$taxon->uuid];
1311
}
1312
 */
1313

    
1314
/**
1315
 * Gets a Drupal variable, string or array and returns it.
1316
 *
1317
 * Similar to the variable_get() function of Drupal, except that this function
1318
 * is able to handle arrays correctly. This function is especially useful
1319
 * when dealing with collections of settings form elements (#tree = TRUE).
1320
 *
1321
 * @param string $variableKey
1322
 *   The Unique key of the Drupal variable in the Drupal variables table.
1323
 * @param string $defaultValueString
1324
 *   A string as for example derived from a CONSTANT.
1325
 *
1326
 * @return mixed
1327
 *   usually an array, depending on the nature of the variable.
1328
 *
1329
 * TODO compare with get_array_variable_merged() duplicate functions?
1330
 * @deprecated rather use get_array_variable_merged() since this function
1331
 * used an array as second parameter
1332
 */
1333
function mixed_variable_get($variableKey, $defaultValueString) {
1334
  $systemDefaults = unserialize($defaultValueString);
1335
  $storedSettings = variable_get($variableKey, array());
1336
  if (is_array($storedSettings)) {
1337
    // TODO better use drupal_array_merge_deep() ?
1338
    $settings = array_merge($systemDefaults, $storedSettings);
1339
  }
1340
  else {
1341
    $settings = $systemDefaults;
1342
  }
1343
  return $settings;
1344
}
1345

    
1346
/**
1347
 * Recursive function to convert an object into an array.
1348
 * also subordinate objects will be converted.
1349
 *
1350
 * @param object $object
1351
 *  the object to be converted
1352
 * @return array
1353
 *  The array
1354
 */
1355
function object_to_array($object) {
1356
  if(is_object($object) || is_array($object)) {
1357
    $array = (array)$object;
1358
    foreach ($array as $key=>$value){
1359
      $array[$key] = object_to_array($value);
1360
    }
1361
    return $array;
1362
  } else {
1363
    return $object;
1364
  }
1365
}
1366

    
1367
/**
1368
 * Searches the $collection for the cdm entitiy given as $element.
1369
 *
1370
 * The elements are compared by their UUID.
1371
 *
1372
 * @param $element
1373
 *  the CDM entitiy to search for
1374
 * @param $collection
1375
 *  the list of CDM entities to search in
1376
 *
1377
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1378
 *
1379
 */
1380
function contains_cdm_entitiy($element, $collection) {
1381
  $result = FALSE;
1382
  foreach ($collection as $a) {
1383
    if ($a->uuid == $element->uuid) {
1384
      $result = TRUE;
1385
    }
1386
  }
1387
  return $result;
1388
}
1389

    
1390
/**
1391
 * Filters the array $entity_list of CDM entities by the list
1392
 * of $excludes. Any element contained in the $excludes will be removed
1393
 * from included int the returned list.
1394
 *
1395
 * If the $entity_list is not an array the $excludes will be returned.
1396
 */
1397
function filter_cdm_entity_list($entity_list, $excludes) {
1398
  if (is_array($entity_list)) {
1399
    $result = $entity_list;
1400
    if ($excludes) {
1401
      foreach ($excludes as $exclude) {
1402
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1403
          $result[] = $exclude;
1404
        }
1405
      }
1406
    }
1407
  }
1408
  else {
1409
    $result = $excludes;
1410
  }
1411
  return $result;
1412
}
1413

    
1414
/**
1415
 * Wraps the given $html string into a render array suitable for drupal_render()
1416
 *
1417
 * @param $html
1418
 *   the html string, see
1419
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1420
 * @param $weight
1421
 *   A positive or negative number (integer or decimal).
1422
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1423
 * @param $prefix
1424
 *   Optional markup for the '#prefix' element of the render array
1425
 * @param $suffix
1426
 *   Optional markup for the '#suffix' element of the render array
1427
 *
1428
 * @return array
1429
 *   A render array
1430
 *
1431
 */
1432
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1433
  $render_array = array(
1434
    '#markup' => $html
1435
      );
1436
  if (is_numeric($weight)) {
1437
    $render_array['#weight'] = $weight;
1438
  }
1439
  if($prefix){
1440
    $render_array['#prefix'] = $prefix;
1441
  }
1442
  if($suffix) {
1443
    $render_array['#suffix'] = $suffix;
1444
  }
1445
  return $render_array;
1446
}
1447

    
1448
/**
1449
 * Loads the subgraph of a given PolytomousKeyNode.
1450
 *
1451
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1452
 * the CDM REST service.
1453
 *
1454
 * @param mixed $polytomousKeyNode
1455
 *   PolytomousKeyNode passed by reference.
1456
 *
1457
 * @return void
1458
 */
1459
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1460

    
1461
  if (!$polytomousKeyNode) {
1462
    return;
1463
  }
1464
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1465
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1466
    return;
1467
  }
1468
  if (!is_uuid($polytomousKeyNode->uuid)) {
1469
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1470
    return;
1471
  }
1472

    
1473
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1474

    
1475
  if (!$polytomousKeyNode) {
1476
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1477
    return;
1478
  }
1479

    
1480
  // Load children.
1481
  foreach ($polytomousKeyNode->children as &$childNode) {
1482
    _load_polytomousKeySubGraph($childNode);
1483
  }
1484

    
1485
  // Load subkey.
1486
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1487

    
1488
  // Load taxon.
1489
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1490
  _load_taxonBase($polytomousKeyNode->taxon);
1491
  return;
1492
}
1493

    
1494
/**
1495
 * @todo Please document this function.
1496
 * @see http://drupal.org/node/1354
1497
 */
1498
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1499

    
1500
  cdm_check_valid_portal_page();
1501

    
1502
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1503

    
1504
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1505
  if (is_array($sourcePager->records)) {
1506
    $polytomousKey->sources = $sourcePager->records;
1507
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1508
  }
1509

    
1510
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1511
  if (is_array($annotationPager->records)) {
1512
    $polytomousKey->annotations = $annotationPager->records;
1513
  }
1514

    
1515
  _load_polytomousKeySubGraph($polytomousKey->root);
1516
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1517
}
1518

    
1519
/**
1520
 * Creates a taxon page view or a chapter of it.
1521
 *
1522
 * The taxon page gives detailed information on a taxon, it shows:
1523
 *  - Taxon name.
1524
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1525
 *    heterotypic and finally followed by misapplied names.
1526
 *    The list is ordered historically.
1527
 *  - All description associated with the taxon.
1528
 *
1529
 * @param string $uuid
1530
 * @param string $chapter
1531
 *   Name of the part to display, valid values are:
1532
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1533
 *
1534
 * @return string
1535
 */
1536
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1537

    
1538
  cdm_check_valid_taxon_page($chapter);
1539
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1540

    
1541

    
1542
  // Display the page for the taxon defined by $uuid.
1543
  // set_last_taxon_page_tab(arg(3));
1544
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1545
  if (!empty($taxonpage)) {
1546
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1547
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1548
  }
1549
  else {
1550
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1551
    return '';
1552
  }
1553
}
1554

    
1555
/**
1556
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1557
 * which has two fields, one for the page title and one for the content. Later on in the
1558
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1559
 * function as the function parameters $title and $content.
1560
 *
1561
 * @param string $uuid
1562
 *   the uuid of the taxon to show
1563
 * @param string $chapter
1564
 *   Name of the part to display, valid values are:
1565
 *   'description', 'images', 'synonymy', 'all'.
1566
 *
1567
 * @return object with the following fields:
1568
 *   - title : the title of the page
1569
 *   - content: the content of the page
1570
 *
1571
 * @throws Exception
1572
 *
1573
 */
1574
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1575
  // Taxon object.
1576
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1577
  if (empty($taxon)) {
1578
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1579
    return null;
1580
  }
1581
  $taxonpage = new stdClass();
1582

    
1583
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1584
    'taxon' => $taxon
1585
  ));
1586

    
1587
  // Check if the taxon id contained in the currently selected tree.
1588
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1589

    
1590
  if (!$taxon_in_current_classification) {
1591
    $classifications = get_classifications_for_taxon($taxon);
1592
    RenderHints::pushToRenderStack('not_in_current_classification');
1593
    $taxon_name_markup = render_taxon_or_name($taxon);
1594

    
1595
    if (count($classifications) == 0) {
1596
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1597
        array(
1598
        '!taxonname' => $taxon_name_markup,
1599
        )
1600
      ), 'warning');
1601
    }
1602
    else {
1603
      $trees = '';
1604
      foreach ($classifications as $classification) {
1605
        if (isset($classification->titleCache)) {
1606
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1607
        }
1608
      }
1609

    
1610
      drupal_set_message(format_plural(count($trees),
1611
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1612
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1613
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1614
        ) ,
1615
        'warning');
1616
    }
1617
    RenderHints::popFromRenderStack();
1618
  }
1619

    
1620
  // Render the taxon page.
1621
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1622
  $taxonpage->content = drupal_render($render_array);
1623

    
1624
  return $taxonpage;
1625
}
1626
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1627
{
1628
    if (isset($accession_number)) {
1629
        $specimen_or_observation = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1630

    
1631
        if (isset($specimen_or_observation) && $specimen_or_observation){
1632

    
1633
            $nodes = cdm_dataportal_specimen_page_view($specimen_or_observation->uuid, $specimen_or_observation);
1634
            return $nodes;
1635
        }else{
1636
            return '';
1637
        }
1638

    
1639
    }
1640
}
1641
/**
1642
 * Creates a specimen page view.
1643
 * @param string $uuid the UUID of the specimen
1644
 * @return array|string
1645
 */
1646
function cdm_dataportal_specimen_page_view($uuid, $specimenDTO = null) {
1647

    
1648
    cdm_check_valid_portal_page();
1649

    
1650
    // Display the page for the specimen defined by $uuid.
1651
    if (isset($specimenDTO)){
1652
        //$specimenpage = compose_specimen_array($specimenDTO);
1653
        $dto_array = array($specimenDTO);
1654
        $specimen_array = compose_specimen_array($dto_array);
1655
        $specimen_table = array(
1656
            '#theme' => 'table',
1657
            '#weight' => 2,
1658
            // prefix attributes and rows with '#' to let it pass toF the theme function,
1659
            // otherwise it is handled as child render array
1660

    
1661
            '#attributes' => array('class' => 'specimens'),
1662
            '#rows' => array(),
1663
            '#prefix' => '<div id="specimens">',
1664
            '#suffix' => '</div>',
1665

    
1666

    
1667
        );
1668
        foreach($specimen_array as $value){
1669
            $renderArray = array(
1670
                '#theme' => 'item_list',
1671
                '#items' => array($value),
1672
                '#type' => 'ul');
1673
            $output = drupal_render($renderArray);
1674
//            $specimen_table['#rows'][] = array(
1675
//                // An array of table rows. collabsible row
1676
//                'data' => "",
1677
//                'class' => array('expand_column')
1678
//            );
1679
            $specimen_table['#rows'][] = array(
1680
                // An array of table rows. Every row is an array of cells, or an associative array
1681
                'data' => array($output),
1682
                'class' =>  array(
1683
                    'descriptionElement',
1684
                    'descriptionElement_IndividualsAssociation'
1685
                ),
1686
            );
1687

    
1688

    
1689
        }
1690
        $specimenpage = new stdClass();
1691

    
1692
        $specimenpage->title = theme('theme_cdm_specimen_dto_page_title', array(
1693
            'specimen' => $specimenDTO
1694
        ));
1695

    
1696
        $render_array['markup'] = $specimen_table;
1697

    
1698
//        $render_array['specimens'] = array(
1699
//            '#prefix' => '<div id="specimens" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Specimens')) . '</h2>' : ''),
1700
//            'content' => $specimen_table, // returns render array
1701
//            '#suffix' => '</div>',
1702
//        );
1703
        $specimenpage->content = drupal_render($render_array);
1704
    }else{
1705
        $specimenpage = cdm_dataportal_specimen_view($uuid);
1706
    }
1707

    
1708
    if (!empty($specimenpage)) {
1709
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1710
    }
1711
    else {
1712
        return '';
1713
    }
1714
}
1715

    
1716
/**
1717
 *
1718
 * Creates a specimen view.
1719
 * @param string $uuid the UUID of the specimen
1720
 * @return array|string
1721
 */
1722
function cdm_dataportal_specimen_view($uuid) {
1723
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1724
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1725
    if (empty($specimen)) {
1726
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1727
        return FALSE;
1728
    }
1729
    $specimenpage = new stdClass();
1730

    
1731
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1732
        'specimen' => $specimen
1733
    ));
1734

    
1735
    // Render the specimen page.
1736
    $render_array = compose_cdm_specimen_page($specimen);
1737
    $specimenpage->content = drupal_render($render_array);
1738

    
1739
    return $specimenpage;
1740
}
1741

    
1742
/**
1743
 *
1744
 * Creates a named area view.
1745
 * @param string $uuid the UUID of the specimen
1746
 *  * @return object
1747
 *   An object with two fields:
1748
 *     - title: the page title
1749
 *     - content: the page content
1750
 */
1751

    
1752
function cdm_dataportal_named_area_view($uuid) {
1753
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1754
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1755
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1756
    return FALSE;
1757
  }
1758
  $named_area_page = new stdClass();
1759

    
1760
  $named_area_page->title = $named_area->representation_L10n;
1761

    
1762
  // Render the specimen page.
1763
  $render_array = compose_cdm_named_area_page($uuid);
1764
  $named_area_page->content = drupal_render($render_array);
1765

    
1766
  return $named_area_page;
1767
}
1768

    
1769
function cdm_dataportal_named_area_page_view($uuid) {
1770

    
1771
  cdm_check_valid_portal_page();
1772

    
1773
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1774
  if (!empty($named_area_page)) {
1775
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1776
  }
1777
  else {
1778
    return '';
1779
  }
1780

    
1781

    
1782
}
1783

    
1784
/**
1785
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1786
 *
1787
 * The node page shows the taxon name title and the list of taxon related
1788
 * with such taxon. Name on the tree already in use.
1789
 *
1790
 * @param string $taxon_name_uuid
1791
 *   The uuid of the CDM TaxonName to show a name page for
1792
 * @param string $taxon_to_hide_uuid
1793
 *   A taxon which should not be displayed in the taxon list
1794
 * @param $redirect_to_taxon
1795
 *   Automatically redirect to the related taxon if there is only one
1796
 *   accepted taxon for this name.
1797
 * @param string $highlite_synonym_uuid
1798
 *   Optinal parameter wich takes another taxon uuid, if given the
1799
 *   target taxon pages will show the syonymy tab where the taxon
1800
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1801
 *   in case it is found on this page.
1802
 *
1803
 * @return mixed
1804
 *   The formatted name page as node.
1805
 */
1806
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = false) {
1807

    
1808
  cdm_check_valid_portal_page();
1809

    
1810
  $taxonname_page = cdm_dataportal_name_view(
1811
    is_uuid($taxon_name_uuid) ? $taxon_name_uuid : null,
1812
    is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : null,
1813
    $redirect_to_taxon == 'redirect_to_taxon',
1814
    is_uuid($synonym_uuid) ? $synonym_uuid : null);
1815
  if (!empty($taxonname_page)) {
1816
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1817
  }
1818
  else {
1819
    return '';
1820
  }
1821
}
1822

    
1823
/**
1824
 * View function for a TaxonName page.
1825
 *
1826
 * The name page lists all taxa for which the name specified by the
1827
 * $taxon_name_uuid is being used. I case there is only one name the
1828
 * page automatically redirects ti the according taxon page. Otherwise
1829
 * the list of names is displayed.
1830
 *
1831
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1832
 * list of taxa. This is useful for example when referencing from a taxon
1833
 * to the name page and the referring taxon should not be repeaded in the
1834
 * name page.
1835
 *
1836
 *
1837
 * @param string $taxon_name_uuid
1838
 *   The uuid of the CDM TaxonName to show a name page for
1839
 * @param string $taxon_to_hide_uuid
1840
 *   A taxon which should not be displayed in the taxon list
1841
 * @param $redirect_to_taxon
1842
 *   Automatically redirect to the related taxon if there is only one
1843
 *   accepted taxon for this name.
1844
 * @param string $highlite_synonym_uuid
1845
 *   Optional parameter which takes another taxon uuid, if given the
1846
 *   target taxon pages will show the synonymy tab where the taxon
1847
 *   referenced by the $highlite_synonym_uuid will be highlighted
1848
 *   in case it is found on this page.
1849
 *
1850
 * @return object|boolean
1851
 *   An object with two fields:
1852
 *     - title: the page title
1853
 *     - content: the page content
1854
 *   or FALSE
1855
 *
1856
 */
1857
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $redirect_to_taxon, $highlite_synonym_uuid = NULL) {
1858
  // Getting the full taxonname object from the server.
1859
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1860
  if (!$taxon_name) {
1861
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1862
    return FALSE;
1863
  }
1864
  cdm_load_tagged_full_title($taxon_name);
1865
  // Searching for all the taxa connected with the taxon name on the tree
1866
  // in use.
1867
  $name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1868
  $restrictions = array(new Restriction("name.titleCache","EXACT", array($name->titleCache), 'AND'));
1869
  $init_strategy = array(
1870
    "name.titleCache",
1871
    "name.nomenclaturalReference.authorship",
1872
    "name.nomenclaturalReference.inReference.authorship",
1873
    "name.nomenclaturalReference.inReference.inReference.authorship",
1874
    "name.nomenclaturalReference.inReference.inReference.inReference.authorship"
1875
  );
1876
  $taxa = cdm_ws_fetch_all_by_restriction("Taxon", $restrictions, $init_strategy);
1877

    
1878
  // Removing the name where we came from.
1879
  foreach ($taxa as $k => &$taxon) {
1880
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1881
      unset($taxa[$k]);
1882
    }
1883
  }
1884
  // Show the taxa list or go to the singular taxon.
1885
  if (sizeof($taxa) == 1 && $redirect_to_taxon) {
1886
    // redirect to the taxon if there is only one.
1887
    $singleTaxon = array_pop($taxa);
1888
    if ($singleTaxon->class != "Taxon") {
1889
      // It is a Synonym -> look for the accepted.
1890
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1891
      if (!empty($highlite_synonym_uuid)) {
1892
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1893
      }
1894
      else {
1895
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1896
      }
1897
    }
1898
    else {
1899
      // It is an accepted taxon.
1900
      if (!empty($highlite_synonym_uuid)) {
1901
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1902
      }
1903
      else {
1904
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1905
      }
1906
    }
1907
  }
1908
  else {
1909
    // display the name page content
1910
    $taxon_name_page = new stdClass();
1911
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1912
    $content = array();
1913

    
1914
    RenderHints::pushToRenderStack('name_page');
1915
    RenderHints::setFootnoteListKey('name_page');
1916
    $content['taxon_name'] = markup_to_render_array(render_taxon_or_name($taxon_name));
1917

    
1918

    
1919
    // name relationships
1920
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $taxon_name->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1921
    if(count($name_relations) > 0){
1922
      $content['name_relationships'] = compose_name_relationships_list($name_relations, $taxon_name->uuid, null);
1923
    }
1924

    
1925
    $type_designations =  cdm_ws_get(CDM_WS_PORTAL_NAME_TYPEDESIGNATIONS, $taxon_name->uuid);
1926
    if ($type_designations) {
1927
      $content['type_designations'] = markup_to_render_array(
1928
        theme('cdm_typedesignations', array('typeDesignations' => $type_designations, 'enclosing_tag' => 'p', 'element_tag' => 'div'))
1929
      );
1930

    
1931
      $points = array();
1932
      foreach ($type_designations as $td){
1933
        if($td->class == "SpecimenTypeDesignation"){
1934
          $derived_unit_facade = cdm_ws_get(CDM_WS_PORTAL_DERIVEDUNIT_FACADE, array($td->typeSpecimen->uuid));
1935
          if(isset($derived_unit_facade->exactLocation)){
1936
            $points[] = $derived_unit_facade->exactLocation->latitude . ',' . $derived_unit_facade->exactLocation->longitude;
1937
          }
1938
        }
1939
      }
1940

    
1941
      // os=1:c/ff0000/10/noLabel&od=1:52.52079,13.57781|-43.46333333333333,172.60355&legend=0
1942
      $occurrence_query = 'os=1:c/ff0000/10/noLabel&od=1:' . join('|', $points) . '&legend=0';
1943
      // $occurrence_query = 'os=1:c/ff0000/10/noLabel&od=1:52.52079,13.57781|-43.46333333333333,172.60355&legend=0';
1944
      $legend_format_query = null;
1945
      $distribution_query = NULL;
1946
      $content['map'] = compose_map('specimens', $occurrence_query, $distribution_query, $legend_format_query, array());
1947
    }
1948

    
1949
    // registrations
1950
    $registrationDTOs= cdm_ws_fetch_all(CDM_WS_REGISTRATION_DTO,  array('nameUuid' => $taxon_name_uuid));
1951
    if(isset($registrationDTOs) && count($registrationDTOs ) > 0 ){
1952
      $content['registrations'][] = markup_to_render_array('<h2>' . t("Registrations") . '</h2>') ;
1953
      foreach ($registrationDTOs as $regDTO){
1954
        $content['registrations'][] = compose_registration_dto_compact($regDTO);
1955
      }
1956
    }
1957

    
1958

    
1959
    // related taxa
1960
    if ($taxa) {
1961
      $content['related_taxa_header'] = markup_to_render_array("<h2>Taxa for this name</h2>");
1962
      $content['related_taxa'] = compose_list_of_taxa($taxa);
1963
    }
1964
    else {
1965
      $content['related_taxa'] = markup_to_render_array('This name is not assigned to a taxon.', null, '<div class="no-taxon-message">', '</div>');
1966
    }
1967

    
1968
    $taxon_name_page->content = $content;
1969
    RenderHints::popFromRenderStack();
1970
    RenderHints::clearFootnoteListKey();
1971
    return $taxon_name_page;
1972
  }
1973
}
1974

    
1975
/**
1976
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1977
 *
1978
 * @param string  $registration_identifier_encoded
1979
 *   The persistent identifier of the registration urlencoded.
1980
 * @return mixed
1981
 *   The formatted registration page as node.
1982
 */
1983
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
1984

    
1985
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
1986
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
1987
  return cdm_node_show_simulate($registration_page);
1988
}
1989

    
1990
function cdm_dataportal_registration_view($registration_identifier_encoded) {
1991

    
1992
  $registration_identifier = urldecode($registration_identifier_encoded);
1993

    
1994
  RenderHints::pushToRenderStack('registration_page');
1995
  RenderHints::setFootnoteListKey('registration_page');
1996

    
1997
  $render_array = array();
1998
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
1999
  if($registration_dto){
2000

    
2001
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
2002
    $render_array = compose_registration_dto_full($registration_dto, true);
2003

    
2004
  } else {
2005
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
2006
    if(isset($status_text->String)) {
2007
      $status_text = strtolower($status_text->String);
2008
      if($status_text == 'preparation' || $status_text == 'curation'){
2009
        $status_text = 'in ' . $status_text;
2010
      }
2011
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
2012
      //$status_message;
2013
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
2014
    } else {
2015
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
2016
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
2017
    }
2018
  }
2019

    
2020
  $render_array = array(
2021
    '#prefix' => '<div id="registration">',
2022
    'registration' => $render_array,
2023
    '#suffix' => '</div>',
2024
  );
2025

    
2026
  RenderHints::popFromRenderStack();
2027
  RenderHints::clearFootnoteListKey();
2028

    
2029
  return $render_array ;
2030
}
2031

    
2032

    
2033
/**
2034
 * Creates a page with the advance search form.
2035
 *
2036
 * NOTE: The advance search form allows searching for taxa.
2037
 */
2038
function cdm_dataportal_view_search_advanced() {
2039
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2040
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2041
}
2042

    
2043
/**
2044
 * Creates a page with the blast search form.
2045
 *
2046
 * NOTE: The advance search form allows searching for specimen in blast DB.
2047
 */
2048
function cdm_dataportal_view_search_blast() {
2049
    drupal_set_title(t('Blast search'), PASS_THROUGH);
2050
    return drupal_get_form('cdm_dataportal_search_blast_form');
2051
}
2052

    
2053
/**
2054
 * Creates a page with the search form for searching by taxon descriptions.
2055
 */
2056
function cdm_dataportal_view_search_taxon_by_description() {
2057
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2058
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2059
}
2060

    
2061
/**
2062
 * Executes the search and generates the result list of taxa.
2063
 */
2064
function cdm_dataportal_view_search_results_taxon() {
2065

    
2066
  $taxonPager = cdm_dataportal_search_taxon_execute();
2067

    
2068
  $showThumbnails = do_showThumbnails();
2069

    
2070
  $setSessionUri = url('cdm_api/setvalue/session', array(
2071
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2072
  ));
2073

    
2074
  drupal_add_js('jQuery(document).ready(function() {
2075

    
2076
      // init
2077
      if(' . $showThumbnails . ' == 1){
2078
          jQuery(\'.media_gallery\').show(20);
2079
      } else {
2080
          jQuery(\'.media_gallery\').hide(20);
2081
      }
2082

    
2083
      // add change handler
2084
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2085
      function(event){
2086
        var state = 0;
2087
        if(jQuery(this).is(\':checked\')){
2088
          jQuery(\'.media_gallery\').show(20);
2089
          state = 1;
2090
        } else {
2091
          jQuery(\'.media_gallery\').hide(20);
2092
        }
2093
        // store state in session variable
2094
        var uri = \'' . $setSessionUri . '\' + state;
2095
        jQuery.get(uri);
2096
      });
2097
  });',
2098
  array('type' => "inline", 'scope' => JS_DEFAULT));
2099

    
2100
  drupal_set_title(t('Search results'), PASS_THROUGH);
2101

    
2102
  return theme('cdm_search_taxa_results', array(
2103
    'pager' => $taxonPager,
2104
    'path' => 'cdm_dataportal/search/results/taxon',
2105
    ));
2106
}
2107

    
2108
/**
2109
 * Executes the blast search and generates the result list of specimen.
2110
 */
2111
function cdm_dataportal_view_search_results_specimen() {
2112

    
2113
    $specimenPager = cdm_dataportal_search_blast_execute();
2114

    
2115
    return theme('cdm_search_specimen_results', array(
2116
        'pager' => $specimenPager,
2117
        'path' => 'cdm_dataportal/search/results/specimen',
2118
    ));
2119
}
2120

    
2121

    
2122
/**
2123
 * Executes the search for registrations and generates the result list..
2124
 */
2125
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2126

    
2127
  switch($mode ){
2128
    case 'taxongraph':
2129
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2130
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2131
      break;
2132
    case 'filter':
2133
    default:
2134
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2135
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2136
  }
2137
  $block->title = null;
2138

    
2139
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2140

    
2141
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2142
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2143
  $render_array = array_merge($render_array, $registrations_pager_array);
2144

    
2145
  return $render_array;
2146
}
2147

    
2148

    
2149
/**
2150
 * Provides the standard image which indicated a loading process
2151
 *
2152
 * @return string
2153
 *  The img html tag
2154
 */
2155
function loading_image_html() {
2156
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2157
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2158
}
2159

    
2160
/**
2161
 * Returns the state of the the showThumbnails flag set in the
2162
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2163
 *
2164
 * @return boolean
2165
 *    returns 1 if the flag is set
2166
 */
2167
function do_showThumbnails() {
2168
  static $showThumbnails = null;
2169

    
2170
  if($showThumbnails == null) {
2171
    $showThumbnails = 0;
2172
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2173
      $showThumbnails = 0;
2174
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2175
      $showThumbnails = is_array($search_gallery_settings)
2176
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2177
        && (
2178
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2179
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2180
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2181
            )
2182
         ? 1 : 0;
2183

    
2184
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2185
    }
2186
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2187
    if (!is_numeric($showThumbnails)) {
2188
      $showThumbnails = 1;
2189
    }
2190
  }
2191

    
2192
  return $showThumbnails;
2193
}
2194

    
2195

    
2196

    
2197
/* ====================== other functions ====================== */
2198
/**
2199
 * Creates a URL to the taxon page specified by the $uuid parameter.
2200
 *
2201
 * The URL will be prepended with a path element to a specific taxon page tab.
2202
 *
2203
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2204
 * be set globally in the administrative settings or individually in the user
2205
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2206
 * the last portal will stay on this last tab.
2207
 *
2208
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2209
 * internal mechanism by a specific value.
2210
 *
2211
 * @param string $uuid
2212
 *   The UUID of the taxon.
2213
 * @param string $page_tab
2214
 *   Overwriting the preset mechanism by defining specific value for the
2215
 *   taxon page tab.
2216
 *
2217
 * @return string
2218
 *   The created URL.
2219
 */
2220
function path_to_taxon($uuid, $page_tab = FALSE) {
2221

    
2222
  $tab = get_default_taxon_tab();
2223
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2224

    
2225
  if (!$uuid) {
2226
    return FALSE;
2227
  }
2228

    
2229
  if ($page_tab) {
2230
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2231
  }
2232
  elseif (!$tab || strtolower($tab) == 'general') {
2233
    return 'cdm_dataportal/taxon/' . $uuid;
2234
  }
2235
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2236
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2237
  }
2238
  else {
2239
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2240
  }
2241
}
2242

    
2243
function path_to_specimen($uuid) {
2244

    
2245
    if (!$uuid) {
2246
        return FALSE;
2247
    }
2248
    else {
2249
        return 'cdm_dataportal/occurrence/' . $uuid;
2250
    }
2251
}
2252

    
2253
function path_to_specimen_by_accession_number($accession_number) {
2254

    
2255
    if (!$accession_number) {
2256
        return FALSE;
2257
    }
2258
    else {
2259
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2260
    }
2261
}
2262

    
2263
function path_to_named_area($uuid) {
2264

    
2265
  if (!$uuid) {
2266
    return FALSE;
2267
  }
2268
  else {
2269
    return 'cdm_dataportal/named_area/' . $uuid;
2270
  }
2271
}
2272

    
2273
/**
2274
 * Creates a URL to show a synonmy in the according taxon page.
2275
 *
2276
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2277
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2278
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2279
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2280
 * in the page
2281
 *
2282
 * @param string $synonymUuid
2283
 *    The uuid of the synonym
2284
 * @param string $acceptedUuid
2285
 *    The uuid of the according accepted taxon
2286
 * @return string
2287
 *    The URL to show a synonmy in the according taxon page
2288
 */
2289
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2290
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2291
  return url($acceptedPath, array(
2292
      'query' => array(
2293
        // highlite the synony in the synonymy
2294
        'highlite' => $synonymUuid,
2295
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2296
        // see theme_taxon_page_title()
2297
        'acceptedFor' => $synonymUuid
2298
      ),
2299
      'fragment' => $synonymUuid
2300
  ));
2301

    
2302
}
2303

    
2304
/**
2305
 * Composes the drupal path to the key identified by the uuid.
2306
 *
2307
 * @param string $keyType
2308
 *    the key typer corresponds to the specific class of the CDM
2309
 *    IdentificationKey. Possible values are
2310
 *      -PolytomousKey
2311
 *      -MultimediaKey
2312
 *      - ...
2313
 * @param string $keyUuid
2314
 *   The UUID of the key
2315
 */
2316
function path_to_key($keyType, $keyUuid) {
2317
  if (!$keyUuid || !$keyType) {
2318
    return FALSE;
2319
  }
2320
  $keyType{0} = strtolower($keyType{0});
2321
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2322
}
2323

    
2324
/**
2325
 * Composes the drupal path to the reference identified by the uuid.
2326
 *
2327
 * @param $uuid string String representation of the registration entity uuid.
2328
 *
2329
 * @return string
2330
 *  The drupal path
2331
 *
2332
 */
2333
function path_to_reference($uuid) {
2334
  if (!$uuid) {
2335
    return FALSE;
2336
  }
2337
  return 'cdm_dataportal/reference/' . $uuid;
2338
}
2339

    
2340
/**
2341
 * Composes the drupal path to the reference identified by the uuid.
2342
 *
2343
 * @param string $identifier
2344
 *  The persistent identifier of the registration entity (Registration.identifier).
2345
 * @return string
2346
 *  The drupal path
2347
 */
2348
function path_to_registration($identifier) {
2349

    
2350
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2351
    return $identifier;
2352
  } else {
2353
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2354
  }
2355
}
2356

    
2357
/**
2358
 * Creates the path to a cdm_dataportal taxon name page.
2359
 *
2360
 * @param string $taxon_name_uuid
2361
 *   The uuid as string of the CDM TaxonName to show a name page for
2362
 * @param string $taxon_to_hide_uuid
2363
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2364
 * @param string $highlited_synonym_uuid
2365
 *   Optional parameter which takes another taxon uuid, if given the
2366
 *   target taxon pages will show the synonymy tab where the taxon
2367
 *   referenced by the $highlite_synonym_uuid will be highlighted
2368
 *   in case it is found on this page.
2369
 * @param $redirect_to_taxon
2370
 *   If true, the name page will redirect to the related taxon if there is a single one
2371
 *   for this name only.
2372
 *
2373
 * @return string
2374
 *  URI path element as string
2375
 */
2376
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2377
  $res = FALSE;
2378
  if ($name_uuid) {
2379
    $res = 'cdm_dataportal/name/' . $name_uuid .
2380
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2381
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2382
    '/' . ($redirect_to_taxon || variable_get(CDM_NAME_PAGE_AUTOREDIRECT, 0) ? "redirect_to_taxon" : "");
2383
  }
2384

    
2385
  return $res;
2386
}
2387

    
2388
/**
2389
 * Composes the drupal path to the media entity identified by the uuid.
2390
 *
2391
 * @param string $uuid
2392
 *  The persistent identifier of the entity entity
2393
 * @return string
2394
 *  The drupal path
2395
 */
2396
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2397
  if (!$uuid) {
2398
    return FALSE;
2399
  }
2400
  $out = 'cdm_dataportal/media/' . $uuid;
2401
  if ($representaion_uuid) {
2402
    $out .= '/' . $representaion_uuid;
2403
    if (is_numeric($partId)) {
2404
      $out .= '/' . $partId;
2405
    }
2406
  }
2407
  return $out;
2408
}
2409

    
2410
/**
2411
 * Compares thisRank with thatRank.
2412
 *
2413
 * Returns a negative integer, zero, or a positive integer
2414
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2415
 * e.g:
2416
 * <ul>
2417
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2418
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2419
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2420
 * </ul>
2421
 * <p>
2422
 * This compare logic of the underlying webservice is the
2423
 * <b>inverse logic</b> of the the one implemented in
2424
 * java.lang.Comparable#compareTo(java.lang.Object)
2425
 *
2426
 * @param $thisRankUuid
2427
 * @param $thatRankUuid
2428
 *
2429
 * @return int
2430
 *   A negative integer, zero, or a positive integer
2431
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2432
 */
2433
function rank_compare($thisRankUuid, $thatRankUuid) {
2434
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2435
  return $result->Integer;
2436
}
2437

    
2438
/**
2439
 * Composes an HTML element class attribute value composed of
2440
 * the short-name of the cdm class and the uuid of the entity.
2441
 * This class attribute should be used wherever an cdm-entity is rendered.
2442
 *
2443
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2444
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2445
 * Taxon uuid is added also as taxon_uuid:<uuid>
2446
 *
2447
 * These according class selectors in css must be escaped, eg:
2448
 *    .cdm\:TextData
2449
 *
2450
 * @param $cdm_entity
2451
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2452
 */
2453
function html_class_attribute_ref($cdm_entity) {
2454

    
2455
  $attributes = '';
2456
  if (is_cdm_entity($cdm_entity)) {
2457
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2458
  } else if($cdm_entity->class == 'TypedEntityReference') {
2459
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2460
  }
2461
  if($cdm_entity->class == 'TaxonNodeDto'){
2462
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2463
  }
2464
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2465
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2466
  }
2467
  return $attributes;
2468
}
2469

    
2470

    
2471
/**
2472
 * Creates a short version of a taxonname.
2473
 *
2474
 * The short name is created by using the taggedTitle field of
2475
 * TaxonNodeDTO instances.
2476
 * If the taggedTitle if empty the fullname will be returned.
2477
 *
2478
 * @param object $taxonNodeDTO
2479
 *   A TaxonNodeDTO object
2480
 *
2481
 * @return string
2482
 */
2483
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2484

    
2485
  $nameStr = '';
2486

    
2487
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2488

    
2489
  // Get all tagged text tokens of the scientific name.
2490
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2491
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2492
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2493
    }
2494
  }
2495
  $nameStr = trim($nameStr);
2496

    
2497
  if ($nameStr) {
2498

    
2499
    // Do not return short names for these.
2500
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2501
      return $nameStr;
2502
    }
2503

    
2504
    /*
2505
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2506
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2507
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2508
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2509
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2510
    */
2511
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2512
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2513
      return $matches[1][0] . "." . $matches[3][0];
2514
    }
2515
    else {
2516
      return $nameStr;
2517
    }
2518
  }
2519
  else {
2520
    return $taxonNodeDTO->titleCache;
2521
  }
2522
}
2523

    
2524
/**
2525
 * Check if a taxon is accepted by the current taxonomic tree.
2526
 *
2527
 * @param mixed $taxon
2528
 *   The Taxon obkect to check.
2529
 *
2530
 * @return bool
2531
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2532
 */
2533
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2534

    
2535
  $defaultTreeUuid = get_current_classification_uuid();
2536

    
2537
  if (isset($taxon->taxonNodes)) {
2538
    $taxonNodes = $taxon->taxonNodes;
2539
  }
2540
  else {
2541
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2542
  }
2543

    
2544
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2545
    foreach ($taxonNodes as $node) {
2546
      if (isset($node->classification)){
2547
        if(is_object($node->classification)) {
2548
          if ($node->classification->uuid == $defaultTreeUuid) {
2549
            return TRUE;
2550
          }
2551
        }
2552
        else {
2553
          if ($node->classification == $defaultTreeUuid) {
2554
            return TRUE;
2555
          }
2556
        }
2557
      }
2558
    }
2559
  }
2560

    
2561
  return FALSE;
2562
}
2563

    
2564
/**
2565
 * Checks is the source has one of the given types.
2566
 *
2567
 * @param object $source
2568
 *   The original source entity
2569
 * @param array $types
2570
 *   An array of elementd of the OriginalSourceType enumeration
2571
 *   If not set the default will be used which is:
2572
 *    - Lineage
2573
 *    - PrimaryMediaSource
2574
 *    - PrimaryTaxonomicSource
2575
 *    - Unknown
2576
 *    - Other
2577
 * @return boolean
2578
 */
2579
  function _is_original_source_type($source, $types = null) {
2580
    // this is the default
2581
    // maybe this should also be put into the settings
2582
    static $default = array(
2583
      OriginalSourceType::Lineage,
2584
      OriginalSourceType::PrimaryMediaSource,
2585
      OriginalSourceType::PrimaryTaxonomicSource,
2586
      OriginalSourceType::Unknown,
2587
      OriginalSourceType::Other,
2588
    );
2589

    
2590
    if(!$types){
2591
      $types = $default;
2592
    }
2593
    return isset($source->type) && in_array($source->type, $types);
2594
  }
2595

    
2596
/**
2597
 * Collects all the media from a list of description elements.
2598
 *
2599
 * @param array $descriptionElements
2600
 *   The description elements from which to collect the media.
2601
 *
2602
 * @return array
2603
 *   The output with all the collected media.
2604
 */
2605
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2606

    
2607
  $outArrayOfMedia = array();
2608

    
2609
  // Avoiding a warning box in Drupal for Flora Malesiana.
2610
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2611
    foreach ($descriptionElements as $descriptionElement) {
2612
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2613
        foreach ($descriptionElement->media as $media) {
2614
          if (is_object($media)) {
2615
            $outArrayOfMedia[] = $media;
2616
          }
2617
        }
2618
      }
2619
    }
2620
  }
2621
  return $outArrayOfMedia;
2622
}
2623

    
2624
/**
2625
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2626
 *
2627
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2628
 *
2629
 * @see cdm_fetch_visible_annotations()
2630
 *
2631
 * @param array $cdm_entities
2632
 *   An array of CdmBase instances or a single instance.
2633
 * @param string $footnote_list_key_suggestion
2634
 *
2635
 * @return array of footnote keys
2636
 */
2637
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2638

    
2639
  $footNoteKeys = array();
2640

    
2641
  // Is argument cdmBase an array?
2642
  if (!is_array($cdm_entities)) {
2643
    $cdmBase_array = array();
2644
    $cdmBase_array[] = $cdm_entities;
2645
  }
2646
  else {
2647
    $cdmBase_array = $cdm_entities;
2648
  }
2649

    
2650
  // Getting the key for the footnotemanager.
2651
  if (isset($footnote_list_key_suggestion)) {
2652
    $footnote_list_key = $footnote_list_key_suggestion;
2653
  }
2654
  else {
2655
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2656
  }
2657

    
2658
  // Adding the footnotes keys.
2659
  foreach ($cdmBase_array as $cdmBase_element) {
2660
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2661
    if (is_array($annotations)) {
2662
      foreach ($annotations as $annotation) {
2663
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2664
      }
2665
    }
2666
  }
2667

    
2668
  return $footNoteKeys;
2669
}
2670

    
2671

    
2672
/**
2673
 * Creates a CDM Dynabox.
2674
 *
2675
 * @param string $dynabox_id
2676
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2677
 * @param string $label
2678
 *   The clickable text to show.
2679
 * @param string $content_url
2680
 *   The cdm REST service request url wich will deliver the content to be shown
2681
 *   once the dynabox toggles open.
2682
 * @param string $theme
2683
 *   The theme to be used for rendering the cdm REST service response with is
2684
 *   returned from the $content_url.
2685
 * @param string $link_alt_text
2686
 *   The value for the alt attribute of the dynabox link.
2687
 * @param array $enclosingtags
2688
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2689
 *   element itself, $enclosingtags[1] is the tag to be used for the
2690
 *   dynabox_content (optional)
2691
 * @param array $attributes
2692
 * @param $content_element_selector
2693
 *   Optional jQuery selector which can be used to reference a dom element which should
2694
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2695
 *  element will be placed in this container.
2696
 *
2697
 * @param string $open_callback
2698
 *   optional javascript call back function to be triggered after toggling the box to
2699
 *   the open state.
2700
 * @param string $close_callback
2701
 *   optional javascript call back function to be triggered after toggling the box to
2702
 *   the closed state.
2703
 * @return string Returns HTML for a dynabox.
2704
 * Returns HTML for a dynabox.
2705
 */
2706
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2707
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2708
                     $content_element_selector = null,
2709
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2710
  $out = '';
2711

    
2712
  // check for plain class attribute string
2713
  $dynabox_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $dynabox_id);
2714

    
2715
  if(!array_key_exists('class', $attributes)) {
2716
    $attributes['class'] = array();
2717
  }
2718
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2719
  $dynabox_attributes = drupal_attributes($attributes);
2720

    
2721

    
2722
  _add_js_domEvent(); // requires domEvent.js
2723
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2724
  drupal_add_js("
2725
  jQuery(document).ready(
2726
      function() {
2727
        dynabox('". $dynabox_id ."',
2728
          {
2729
            open_callback: " . $open_callback .",
2730
            close_callback: " . $close_callback .
2731
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2732
          }
2733
        );
2734
      }
2735
   );",
2736
   array(
2737
    'type'=>'inline',
2738
    'scope'=>'footer'
2739
    )
2740
  );
2741

    
2742

    
2743
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2744
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2745
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t('@link-alt-text', array('@link-alt-text' => $link_alt_text)) . '">' . $label . '</a>';
2746
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2747
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2748
  $out .= '    </' . $enclosingtags[1] . '>';
2749
  $out .= '  </' . $enclosingtags[0] . '>';
2750
  $out .= '<!-- dynabox end -->';
2751
  return $out;
2752
}
2753

    
2754
/**
2755
 * Checks whether a feature has any description elements.
2756
 *
2757
 * @param mixed $featureNode
2758
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2759
 *
2760
 * @see _mergeFeatureTreeDescriptions()
2761
 *
2762
 * @return bool
2763
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2764
 *   contains at least one non empty TextData or at least one DescriptionElement
2765
 *   of an other type. A TextData element holding a multilanguageText or a
2766
 *   source reference is considered to be not empty.
2767
 *
2768
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2769
 *       see $block_content_is_not_empty in make_feature_block_list() and
2770
 *       $feature_block_has_content in compose_feature_block_items_generic
2771
 */
2772
function has_feature_node_description_elements($featureNode) {
2773

    
2774
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2775
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2776
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2777
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2778
          && $descriptionElement->multilanguageText_L10n->text != ''
2779
          || isset($descriptionElement->sources[0])
2780
          || isset($descriptionElement->media[0]) ) {
2781
          return TRUE;
2782
        }
2783
      }
2784
    }
2785
  }
2786
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2787
    foreach ($featureNode->childNodes as $child) {
2788
      if (has_feature_node_description_elements($child)) {
2789
        return TRUE;
2790
      }
2791
    }
2792
  }
2793
  return FALSE;
2794
}
2795

    
2796
/**
2797
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2798
 *
2799
 * @param $chapter
2800
 *   The taxon page chapter or part
2801
 */
2802
function cdm_check_valid_taxon_page($chapter){
2803
  static $taxon_tabs = null;
2804

    
2805
  cdm_check_valid_portal_page();
2806

    
2807
  if($taxon_tabs == null){
2808
    $taxon_tabs = array('all', 'description');
2809
    foreach(get_taxon_tabs_list() as $tab){
2810
      $taxon_tabs[] = strtolower($tab);
2811
    }
2812
  }
2813

    
2814
  if(!in_array($chapter, $taxon_tabs)){
2815
    // oops this is not a valid chapter name
2816
    http_response_code(404); // 404 = Not Found
2817
  }
2818

    
2819
}
2820

    
2821
function check_js_devel_mode_disabled() {
2822
  if(variable_get('cdm_js_devel_mode', FALSE)) {
2823
    drupal_set_message(t('The !url1 is enabled.
2824
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
2825
      '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
2826
    )),
2827
      'warning'
2828
    );
2829
  }
2830
}
2831

    
2832
/**
2833
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2834
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2835
 *
2836
 * @param $preg_pattern
2837
 *   Optional regular expression pattern to be used in preg_match().
2838
 */
2839
function cdm_check_valid_portal_page($preg_pattern = null){
2840
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2841
  if($preg_pattern === null){
2842
    $preg_pattern = $ends_with_file_suffix_pattern;
2843
  }
2844
  if(preg_match($preg_pattern, $_GET['q'])){
2845
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2846
    http_response_code(404); // 404 = Not Found
2847
    exit('HTTP 404');
2848
  }
2849
  check_js_devel_mode_disabled();
2850
}
2851

    
2852
/**
2853
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2854
 *
2855
 * @param $text_a
2856
 * @param $text_b
2857
 * @return string
2858
 */
2859
function diff_viewer($text_a, $text_b) {
2860

    
2861
  static $diff_viewer_count = 0;
2862

    
2863
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2864

    
2865
  // http://code.stephenmorley.org/php/diff-implementation/
2866
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2867
  drupal_add_css(drupal_get_path('module',
2868
      'cdm_dataportal') . '/css/diff.css');
2869
  _add_jquery_ui();
2870
  drupal_add_js(
2871
    'jQuery(document).ready( function(){
2872
        jQuery(\'#' . $element_id . '\').accordion({
2873
        collapsible: true,
2874
        active: false,
2875
        fillSpace: true,
2876
        }).children(\'div\').css({ \'height\': \'auto\' });
2877
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2878
     });'
2879
    , array(
2880
    'type' => 'inline',
2881
    'scope' => 'footer'
2882
  ));
2883

    
2884
  $diff = Diff::compare($text_a,
2885
    $text_b);
2886
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2887
    . Diff::toTable($diff, '', '')
2888
    . '</div></div>';
2889
  return $diff_viewer_markup;
2890
}
2891

    
2892

    
(10-10/18)