Project

General

Profile

Download (95.6 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
function _add_js_utis_client($jquery_selector){
336

    
337
  drupal_add_js(drupal_get_path('module',
338
      'cdm_dataportal') . '/js/utis-client/utis-client.js',
339
    array(
340
      'type' => 'file',
341
      'weight' => JS_LIBRARY,
342
      'cache' => TRUE,
343
      'preprocess' => FALSE
344
    )
345
  );
346

    
347
  drupal_add_js('jQuery(document).ready(function() {
348
        jQuery( "' . $jquery_selector . '" ).utis_client(
349
        {
350
          spinnerIcon: \'' . font_awesome_icon_markup('fa-sync', array('class' => array('fa-3x',  'fa-spin'), 'style' => array('opacity: 0.3;'))) . '\',
351
          externalLinkIcon: \'' . font_awesome_icon_markup('fa-external-link-alt') . '\'
352
        });
353
      });',
354
    array('type' => 'inline')
355
  );
356
}
357

    
358
  /**
359
   * Provides the markup for an font awesome icon.
360
   *
361
   * The icons is created in default size without any extra features.
362
   *
363
   * The available icons are listed here http://fontawesome.io/cheatsheet/
364
   * fontawesome icons have much more features than implemented here in this function,
365
   * for spinning icons, fixed width icons, rotation, etc please checkout the
366
   * examples at http://fontawesome.io/examples/
367
   *
368
   * @parameter $icon_name
369
   *  The name of the icon which starts with 'fa-'
370
   *
371
   * @return String
372
   *    the markup for the icon in an <i> tag
373
   *
374
   */
375
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
376
    _add_font_awesome_font();
377

    
378

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

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

    
389
    return '';
390
  }
391

    
392
/**
393
 * @param string $glyph_name
394
 *   The name of the gloyph (e.g. 'icon-interal-link-alt-solid') for the foll list please
395
 *   refer to modules/cdm_dataportal/fonts/custom-icon-font
396
 * @param array $attributes
397
 * @return string
398
 */
399
  function custom_icon_font_markup($glyph_name = NULL, $attributes = array()){
400
    _add_font_custom_icon_font();
401

    
402

    
403
    if($glyph_name){
404
      if(!isset($attributes['class'])){
405
        $attributes['class'] = array();
406
      }
407
      $attributes['class'][] = $glyph_name;
408

    
409
      return '<i ' . drupal_attributes($attributes) . '></i>';
410
    }
411

    
412
    return '';
413
  }
414

    
415
/**
416
 * Adds the css  containing the font awesome icons to the html header.
417
 */
418
function _add_font_awesome_font()
419
{
420
  // $fa_font_version = 'font-awesome-4.6.3/css/font-awesome.min.css';
421
  $fa_font_version = 'fontawesome-free-5.9.0-web/css/all.css';
422
  $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/' . $fa_font_version;
423

    
424
  drupal_add_html_head_link(
425
    array(
426
      'href' => $font_awesome_css_uri,
427
      'rel' => 'stylesheet'
428
    )
429
  );
430
}
431

    
432
/**
433
 * Adds the css  containing the font awesome icons to the html header.
434
 */
435
function _add_font_custom_icon_font()
436
{
437

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

    
440
  drupal_add_html_head_link(
441
    array(
442
      'href' => $custom_icon_font_css_uri,
443
      'rel' => 'stylesheet'
444
    )
445
  );
446
}
447

    
448
/* ====================== hook implementations ====================== */
449
  /**
450
   * Implements hook_permission().
451
   *
452
   * Valid permissions for this module.
453
   *
454
   * @return array
455
   *   An array of valid permissions for the cdm_dataportal module.
456
   */
457
  function cdm_dataportal_permission() {
458
    return array(
459
      'administer cdm_dataportal' => array(
460
        'title' => t('Administer CDM DataPortal settings'),
461
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
462
      ),
463
      'access cdm content' => array(
464
        'title' => t('Access CDM content'),
465
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
466
      ),
467
    );
468
  }
469

    
470
/**
471
 * Implements hook_menu().
472
 */
473
function cdm_dataportal_menu() {
474
  $items = array();
475

    
476
  // @see settings.php.
477
  cdm_dataportal_menu_admin($items);
478
  cdm_dataportal_menu_help($items);
479

    
480
  $items['cdm_dataportal/names'] = array(
481
    'page callback' => 'cdm_dataportal_view_names',
482
    'access arguments' => array('access cdm content'),
483
    'type' => MENU_CALLBACK,
484
  );
485

    
486
  // Optional callback arguments: page.
487
  $items['cdm_dataportal/taxon'] = array(
488
    'page callback' => 'cdm_dataportal_taxon_page_view',
489
    'access arguments' => array('access cdm content'),
490
    'type' => MENU_CALLBACK,
491
    // Expected callback arguments: uuid.
492
  );
493

    
494
  $items['cdm_dataportal/occurrence'] = array(
495
        'page callback' => 'cdm_dataportal_specimen_page_view',
496
        'access arguments' => array('access cdm content'),
497
        'type' => MENU_CALLBACK,
498
        // Expected callback arguments: uuid.
499
    );
500

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

    
508
   $items['cdm_dataportal/specimen/accession_number'] = array(
509
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
510
        'access arguments' => array('access cdm content'),
511
        'type' => MENU_CALLBACK,
512
        // Expected callback arguments: accession number.
513
    );
514
  $items['cdm_dataportal/named_area'] = array(
515
    'page callback' => 'cdm_dataportal_named_area_page_view',
516
    'access arguments' => array('access cdm content'),
517
    'type' => MENU_CALLBACK,
518
    // Expected callback arguments: uuid.
519
  );
520

    
521
  $items['cdm_dataportal/name'] = array(
522
    'page callback' => 'cdm_dataportal_name_page_view',
523
      /*
524
    'page arguments' => array(
525
       'taxon_name_uuid',
526
       'taxon_to_hide_uuid',
527
       'synonym_uuid' => NULL
528
      ),
529
      */
530
    'access arguments' => array('access cdm content'),
531
    'type' => MENU_CALLBACK,
532
    // Expected callback arguments: uuid.
533
  );
534

    
535
  $items['cdm_dataportal/reference'] = array(
536
    'page callback' => 'cdm_dataportal_view_reference',
537
    'access arguments' => array('access cdm content'),
538
    'type' => MENU_CALLBACK,
539
    // Expected callback arguments: uuid.
540
  );
541

    
542
  $items['cdm_dataportal/reference/list'] = array(
543
    'page callback' => 'cdm_dataportal_view_reference_list',
544
    'access arguments' => array('access cdm content'),
545
    'type' => MENU_CALLBACK,
546
    // Expected callback arguments: uuid.
547
  );
548

    
549
  $items['cdm_dataportal/media'] = array(
550
    'page callback' => 'cdm_dataportal_view_media',
551
    'access arguments' => array('access cdm content'),
552
    'type' => MENU_CALLBACK,
553
    // Expected callback arguments:
554
    // uuid, mediarepresentation_uuid, part_uuid or part#.
555
  );
556

    
557
  $items['cdm_dataportal/polytomousKey'] = array(
558
    'page callback' => 'cdm_dataportal_view_polytomousKey',
559
    'access arguments' => array('access cdm content'),
560
    'type' => MENU_CALLBACK,
561
    // Expected callback arguments: polytomousKey->uuid.
562
  );
563

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

    
570
  $items['cdm_dataportal/search/advanced'] = array(
571
    'title' => 'Advanced', // will be passed through t()
572
    'page callback' => 'cdm_dataportal_view_search_advanced',
573
    'access arguments' => array('access cdm content'),
574
    'type' => MENU_DEFAULT_LOCAL_TASK,
575
  );
576
  $items['cdm_dataportal/search/blast'] = array(
577
    'title' => 'Blast', // will be passed through t()
578
    'page callback' => 'cdm_dataportal_view_search_blast',
579
    'access arguments' => array('access cdm content'),
580
    'type' => MENU_LOCAL_TASK,
581
  );
582

    
583
  $items['cdm_dataportal/search/taxon_by_description'] = array(
584
    'title' => 'By content category', // will be passed through t()
585
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
586
    'access arguments' => array('access cdm content'),
587
    'type' => MENU_LOCAL_TASK,
588
  );
589
  $items['cdm_dataportal/search/results/taxon'] = array(
590
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
591
    'access arguments' => array('access cdm content'),
592
    'type' => MENU_CALLBACK,
593
  );
594

    
595

    
596
  $items['cdm_dataportal/search/results/specimen'] = array(
597
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
598
      'access arguments' => array('access cdm content'),
599
      'type' => MENU_CALLBACK,
600
  );
601

    
602
  /*
603
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
604
   * tabs in the subordinate paths work, accessing this 'page' will cause the
605
   * MENU_DEFAULT_LOCAL_TASK being displayed
606
   */
607
  $items['cdm_dataportal/registration-search'] = array(
608
    'title' => 'Search', // will be passed through t()
609
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
610
    'page arguments' => array("filter"),
611
    'access arguments' => array('access cdm content'),
612
    'type' => MENU_CALLBACK,
613
  );
614
  /*
615
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
616
   * defined at a higher level of the path (cdm_dataportal/registration-search)
617
   */
618
  $items['cdm_dataportal/registration-search/filter'] = array(
619
    'title' => 'Search', // will be passed through t()
620
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
621
    'page arguments' => array("filter"),
622
    'access arguments' => array('access cdm content'),
623
    'type' => MENU_DEFAULT_LOCAL_TASK,
624
  );
625
  /*
626
   * the MENU_LOCAL_TASK creates another tab
627
   */
628
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
629
    'title' => 'Taxon graph search', // will be passed through t()
630
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
631
    'page arguments' => array("taxongraph"),
632
    'access arguments' => array('access cdm content'),
633
    'type' => MENU_LOCAL_TASK,
634
  );
635

    
636
  // Optional callback arguments: page.
637
  $items['cdm_dataportal/registration'] = array(
638
    'page callback' => 'cdm_dataportal_registration_page_view',
639
    'access arguments' => array('access cdm content'),
640
    'type' => MENU_CALLBACK,
641
    // Expected callback arguments: uuid.
642
  );
643

    
644
  /*
645
   $items['cdm/xml2json'] = array(
646
   'page callback' => 'cdm_view_xml2json',
647
   'access arguments' => array('access cdm content'),
648
   'type' => MENU_CALLBACK,
649
   );
650
   */
651

    
652
  // 'May not cache' in D5.
653
  $items['cdm_dataportal/name/%'] = array(
654
    // 'page callback' => 'cdm_dataportal_view_name',
655
    'page callback' => 'cdm_dataportal_name_page_view',
656
    'page arguments' => array(2, 3, 4, 5),
657
    'access arguments' => array('access cdm content'),
658
    'type' => MENU_CALLBACK,
659
  );
660

    
661
  // --- Local tasks for Taxon.
662
  // --- tabbed taxon page
663
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
664
    $items['cdm_dataportal/taxon/%'] = array(
665
      'title' => cdm_taxonpage_tab_label('General'),
666
      'page callback' => 'cdm_dataportal_taxon_page_view',
667
      'access arguments' => array('access cdm content'),
668
      'type' => MENU_CALLBACK,
669
      'weight' => 1,
670
      'page arguments' => array(2, "description")
671
      , // Expected callback arguments: taxon_uuid.
672
    );
673

    
674
    $items['cdm_dataportal/taxon/%/all'] = array(
675
      'title' => cdm_taxonpage_tab_label('General'),
676
      'page callback' => 'cdm_dataportal_taxon_page_view',
677
      'access arguments' => array('access cdm content'),
678
      'type' => MENU_CALLBACK,
679
      'weight' => 2,
680
      'page arguments' => array(2, "all")
681
      , // Expected callback arguments: taxon_uuid.
682
    );
683

    
684
    $items['cdm_dataportal/taxon/%/description'] = array(
685
      'title' => cdm_taxonpage_tab_label('General'),
686
      'page callback' => 'cdm_dataportal_taxon_page_view',
687
      'access arguments' => array('access cdm content'),
688
      'type' => MENU_DEFAULT_LOCAL_TASK,
689
      'weight' => 2,
690
      'page arguments' => array(2, "description")
691
      , // Expected callback arguments: taxon_uuid.
692
    );
693

    
694
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
695
      'title' => cdm_taxonpage_tab_label('Synonymy'),
696
      'page callback' => 'cdm_dataportal_taxon_page_view',
697
      'access arguments' => array('access cdm content'),
698
      'type' => MENU_LOCAL_TASK,
699
      'weight' => 4,
700
      'page arguments' => array(2, "synonymy", 4)
701
      , // Expected callback arguments: taxon_uuid and ...
702
    );
703
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
704
      'title' => cdm_taxonpage_tab_label('Images'),
705
      'page callback' => 'cdm_dataportal_taxon_page_view',
706
      'access arguments' => array('access cdm content'),
707
      'type' => MENU_LOCAL_TASK,
708
      'weight' => 5,
709
      'page arguments' => array(2, "images")
710
      , // Expected callback arguments: taxon_uuid.
711
    );
712

    
713
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
714
      'title' => cdm_taxonpage_tab_label('Specimens'),
715
      'page callback' => 'cdm_dataportal_taxon_page_view',
716
      'access arguments' => array('access cdm content'),
717
      'type' => MENU_LOCAL_TASK,
718
      'weight' => 6,
719
      'page arguments' => array(2, "specimens")
720
      , // Expected callback arguments: taxon_uuid.
721
    );
722

    
723
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
724
      'title' => cdm_taxonpage_tab_label('Keys'),
725
      'page callback' => 'cdm_dataportal_taxon_page_view',
726
      'access arguments' => array('access cdm content'),
727
      'type' => MENU_LOCAL_TASK,
728
      'weight' => 6,
729
      'page arguments' => array(2, "keys")
730
      , // Expected callback arguments: taxon_uuid.
731
    );
732

    
733
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
734
      'title' => cdm_taxonpage_tab_label('Experts'),
735
        'page callback' => 'cdm_dataportal_taxon_page_view',
736
        'access arguments' => array('access cdm content'),
737
        'type' => MENU_LOCAL_TASK,
738
        'weight' => 6,
739
        'page arguments' => array(2, "experts")
740
    , // Expected callback arguments: taxon_uuid.
741
    );
742

    
743
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
744
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
745
        'access arguments' => array('access cdm content'),
746
        'page arguments' => array(3,4,5),
747
        'type' => MENU_CALLBACK
748
    );
749
  }
750

    
751
  // --- refresh link for all cdmnode types
752
  foreach (cdm_get_nodetypes() as $type=>$name) {
753
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
754
        'title' => 'Refresh',
755
        'page callback' => 'cdm_dataportal_refresh_node',
756
        'access arguments' => array('administer cdm_dataportal'),
757
        'type' => MENU_LOCAL_TASK,
758
        'weight' => 100,
759
        'page arguments' => array($name, 2)
760
    );
761
  }
762

    
763
  return $items;
764
}
765

    
766
/**
767
 * Implements hook_init().
768
 *
769
 */
770
function cdm_dataportal_init() {
771
  if (!path_is_admin(current_path())) {
772
    //FIXME To add CSS or JS that should be present on all pages, modules
773
    //      should not implement this hook, but declare these files in their .info file.
774
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
775
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
776
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
777
  } else {
778
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
779
  }
780

    
781
  if(variable_get('cdm_debug_mode', FALSE)){
782
    $file = 'temporary://drupal_debug.txt';
783
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
784
  }
785

    
786
  $bibliography_settings = get_bibliography_settings();
787
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
788
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
789
}
790

    
791
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
792

    
793
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
794

    
795
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
796
    // force reloading of all and notify user about this special loading
797
    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: ')
798
        . l('Back to tabbed taxon page', $base_path));
799
    $base_path .= '/all';
800
  } else {
801
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
802
  }
803

    
804
  $parameters['cacheL2_refresh'] ='1';
805

    
806

    
807
  drupal_goto($base_path, array('query' => $parameters));
808
}
809

    
810
/**
811
 * Implements hook_requirements($phase)
812
 */
813
function cdm_dataportal_requirements($phase) {
814
    $requirements = array();
815
    if($phase == 'runtime'){
816

    
817
    }
818
    return $requirements;
819
}
820

    
821
/**
822
 * Implements hook_block_info().
823
 */
824
function cdm_dataportal_block_info() {
825

    
826
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
827
    // $block[1]["info"] = t("CDM DataPortal Credits");
828
    $block["2"] = array(
829
        "info" => t("CDM - Search Taxa"),
830
        "cache" => DRUPAL_NO_CACHE
831
      );
832
    // $block[3]["info"] = t("CDM Filters");
833
    $block["4"]["info"] = t("CDM  - Dataportal Print");
834
    $block["keys"]["info"] = t("CDM - Identification keys");
835
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
836
    $block["classification_breadcrumbs"] =  array(
837
        'info' => t('CDM - Classification breadcrumbs'),
838
        'cache' => DRUPAL_CACHE_PER_PAGE
839
      );
840
    $block["taxonomic_children"] =  array(
841
      'info' => t('CDM - Taxonomic children'),
842
      'cache' => DRUPAL_CACHE_PER_PAGE
843
    );
844
    $block["back_to_search_results"] =  array(
845
      'title' => '<none>',
846
      'info' => t('CDM - Back to search Results'),
847
      'cache' => DRUPAL_CACHE_PER_PAGE,
848
      'visibility' => BLOCK_VISIBILITY_LISTED,
849
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
850
    );
851
  $block['registrations_search_filter'] =  array(
852
    'title' => 'Filter registrations',
853
    'info' => t('CDM - Registrations search filter'),
854
    'cache' => DRUPAL_CACHE_PER_PAGE,
855
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
856
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
857
  );
858
  $block['registrations_search_taxongraph'] =  array(
859
    'title' => 'Taxonomic registration search',
860
    'info' => t('CDM - Registrations search by taxon graph'),
861
    'cache' => DRUPAL_CACHE_PER_PAGE,
862
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
863
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
864
  );
865
  $block['registrations_search'] =  array(
866
    'title' => 'Search',
867
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
868
    'cache' => DRUPAL_CACHE_PER_PAGE,
869
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
870
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
871
  );
872
  $block['utis_search'] =  array(
873
    'title' => 'UTIS Search',
874
    'info' => t('Query the Unified Taxonomic Information Service (UTIS)' ),
875
    'cache' => DRUPAL_CACHE_PER_PAGE,
876
    'visibility' => BLOCK_VISIBILITY_NOTLISTED
877
  );
878
  return $block;
879
}
880

    
881
/**
882
 * Implements hook_block_view().
883
 */
884
function cdm_dataportal_block_view($delta) {
885
  // TODO Rename block deltas (e.g. '2') to readable strings.
886
  switch ($delta) {
887
    // case 'delta-1':
888
    // $block['subject'] = t('Credits');
889
    // $block['content'] = theme('cdm_credits');
890
    // return $block;
891
    case '2':
892
      $block['subject'] = t('Search taxa');
893
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
894
      $block['content'] = drupal_render($form);
895

    
896
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
897
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
898
      }
899
      if (variable_get(CDM_SEARCH_BLAST_ENABLED)){
900
          $block['content'] .= '<div>' . l(t('Blast Search'), 'cdm_dataportal/search/blast') . '</div>';
901
      }
902
      return $block;
903
    case '4':
904
      $block['subject'] = '';
905
      $block['content'] = theme('cdm_print_button');
906
      return $block;
907
    case "keys":
908
      $block['subject'] = t('Identification Keys');
909
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
910
      return $block;
911
    case "fundedByEDIT":
912
      // t('Funded by EDIT');
913
      $text = '<none>';
914
      $block['subject'] = $text;
915
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
916
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
917
        'attributes' => array("target" => "EDIT"),
918
        'absolute' => TRUE,
919
        'html' => TRUE,
920
      ));
921
      return $block;
922
    case 'classification_breadcrumbs':
923
      $taxon_uuid = get_current_taxon_uuid();
924
      $block['subject'] = '<none>';
925
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
926
      return $block;
927
    case 'taxonomic_children':
928
      $taxon_uuid = get_current_taxon_uuid();
929
      $block['subject'] = '<none>';
930
      $block['content'] = compose_taxonomic_children($taxon_uuid);
931
      return $block;
932
    case 'back_to_search_results':
933
      $block['subject'] = '<none>';
934
      if (isset($_SESSION['cdm']['search'])) {
935
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
936
      }
937
      return $block;
938
    case 'registrations_search_filter':
939
      $block['subject'] = '<none>';
940
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
941
      return $block;
942
    case 'registrations_search_taxongraph':
943
      $block['subject'] = '<none>';
944
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
945
      return $block;
946
    case 'registrations_search':
947
      _add_js_ui_accordion();
948
      _add_font_awesome_font();
949
      $block['subject'] = '<none>';
950
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
951
      $filter_form['#prefix'] = '<div>';
952
      $filter_form['#suffix'] = '</div>';
953
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
954
      $taxongraph_form['#prefix'] = '<div>';
955
      $taxongraph_form['#suffix'] = '</div>';
956
      $block['content'] = array(
957
        'accordion' => array(
958
          '#markup' => '',
959
          '#prefix' => '<div id="accordion">',
960
          '#suffix' => '</div>',
961
          'content' => array(
962
            array('#markup' => '<h3>Filter</h3>'),
963
            $filter_form,
964
            array('#markup' => '<h3>Taxon graph</h3>'),
965
            $taxongraph_form,
966
          )
967
        )
968
    );
969
       return $block;
970
    case 'utis_search':
971
      _add_js_utis_client('.utis_client');
972
      $block['subject'] = '<none>';
973
      $block['content'] = '<div class="utis_client"></div>';
974
      return $block;
975
    default:
976
      return null;
977
  }
978
}
979

    
980

    
981
/**
982
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
983
 *
984
 * @return string
985
 *   the taxon uuid or NULL
986
 */
987
function get_current_taxon_uuid()
988
{
989
  static $taxon_uuid;
990

    
991
  if(!isset($taxon_uuid)){
992
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
993
      $taxon_uuid = $_REQUEST['currentTaxon'];
994
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
995
      $taxon_uuid = arg(2);
996
    } else {
997
      $taxon_uuid = null;
998
    }
999
  }
1000

    
1001
  return $taxon_uuid;
1002
}
1003

    
1004
/**
1005
 * Returns the currently classification tree in use.
1006
 *
1007
 * @return string
1008
 *   The uuid of the currently focused classification
1009
 */
1010
function get_current_classification_uuid() {
1011
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1012
    return $_SESSION['cdm']['taxonomictree_uuid'];
1013
  }
1014
  else {
1015
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1016
  }
1017
}
1018

    
1019
/*
1020
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
1021
 $_SESSION['cdm'] = NULL;
1022
 if(is_string($cdm_ws_uri_update)){
1023
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
1024
 }
1025
 }
1026

    
1027
 function cdm_dataportal_session_validate(){
1028
 if(!isset($_SESSION['cdm']['ws_uri'])){
1029
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
1030
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
1031
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
1032
 }
1033
 }
1034
 */
1035

    
1036
/**
1037
 * creates a  selector form for taxonomic trees.
1038
 *
1039
 * @return array
1040
 *  a drupal form array
1041
 */
1042
function cdm_taxonomictree_selector() {
1043
  _add_js_treeselector();
1044

    
1045
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1046
  return $form;
1047
}
1048

    
1049
/**
1050
 * @todo Please document this function.
1051
 * @see http://drupal.org/node/1354
1052
 *
1053
 * @deprecated use compose_classification_selector instead
1054
 */
1055
function cdm_taxonomictree_selector_form($form, &$form_state) {
1056

    
1057
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1058
  $form['#action'] = $url;
1059

    
1060
  $form['var'] = array(
1061
    '#weight' => -3,
1062
    '#type' => 'hidden',
1063
    '#value' => '[cdm][taxonomictree_uuid]',
1064
  );
1065

    
1066
  $destination_array = drupal_get_destination();
1067
  $destination = $destination_array['destination'];
1068

    
1069
  $form['destination'] = array(
1070
    '#weight' => -3,
1071
    '#type' => 'hidden',
1072
    '#value' =>  $destination,
1073
  );
1074

    
1075
  $options = cdm_get_taxontrees_as_options();
1076
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1077
  if($taxontree_includes){
1078
    $filtered_options = array();
1079
    foreach($options as $uuid=>$label){
1080
      if(!empty($taxontree_includes[$uuid])){
1081
        $filtered_options[$uuid] = $label;
1082
      }
1083
    }
1084
    $options = $filtered_options;
1085
  }
1086

    
1087
  $form['val'] = array(
1088
    '#type' => 'select',
1089
    '#title' => t('Available classifications'),
1090
    '#default_value' => get_current_classification_uuid(),
1091
    '#options' => $options,
1092
    '#attributes' => array('class' => array('highlite-first-child')),
1093
  );
1094

    
1095
  return $form;
1096

    
1097
}
1098

    
1099
/**
1100
 *
1101
 * @ingroup compose
1102
 */
1103
function compose_classification_selector() {
1104

    
1105
  $destination_array = drupal_get_destination();
1106
  $destination = $destination_array['destination'];
1107

    
1108
  $options = cdm_get_taxontrees_as_options();
1109
  $items = array();
1110
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1111

    
1112
  $current_classification_uuid = get_current_classification_uuid();
1113

    
1114

    
1115
  foreach($options as $uuid=>$label){
1116
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1117

    
1118
      $class_attributes = '';
1119
      if($current_classification_uuid == $uuid){
1120
        $class_attributes  = array('focused');
1121
      }
1122
      $items[] = array(
1123
        'data' => l($label,
1124
          'cdm_api/setvalue/session',
1125
          array(
1126
            'query' => array(
1127
              'destination' => $destination,
1128
              'val' => $uuid,
1129
              'var' => '[cdm][taxonomictree_uuid]'
1130
            ),
1131
          )
1132
        ),
1133
        'class' => $class_attributes
1134
      );
1135
    }
1136
  }
1137

    
1138
  $render_array = array(
1139
    '#theme' => 'item_list',
1140
    '#type' => 'ul',
1141
    '#items' => $items
1142
  );
1143

    
1144
  return $render_array;
1145
}
1146

    
1147

    
1148
/* UNREACHABLE since action of form directly links to view.
1149
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1150

    
1151
 $_SESSION['cdm']['search'] = $form_values;
1152
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1153
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1154
 //$paramstr = compose_url_prameterstr($form_values);
1155
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1156
 }
1157
 */
1158
/* ====================== menu callback functions ====================== */
1159
/**
1160
 * @todo Please document this function.
1161
 * @see http://drupal.org/node/1354
1162
 */
1163
/*
1164
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1165
  static $comment_node_disabled =  0;
1166
  static $comment_node_read_only =  1;
1167
  static $comment_node_read_write =  2;
1168

    
1169
  if ($form_id == 'node_type_form'
1170
   && isset($form['identity']['type'])
1171
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1172
  ) {
1173
    $form['workflow']['comment'] = array(
1174
      '#type' => 'radios',
1175
      '#title' => t('Default comment setting'),
1176
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1177
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1178
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1179
    );
1180
  }
1181
}
1182
*/
1183

    
1184
/**
1185
 * Displays a list of the known taxonomic names.
1186
 *
1187
 * When the list of taxonomic names is displayed, long lists are split up into
1188
 * multiple pages.
1189
 *
1190
 * TODO: Parameters are still preliminary.
1191
 *
1192
 * @param string $beginsWith
1193
 * @param string $page
1194
 *   Page number to diplay defaults to page 1.
1195
 * @param bool $onlyAccepted
1196
 */
1197
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1198

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

    
1201
  /*
1202
  // FIXME the filter for accepted names will be a form element, thus this
1203
  // widget should be generated via form api preferably as block.
1204
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1205
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1206
  $out .= theme('cdm_listof_taxa', $taxonPager);
1207
  return $out;
1208
  */
1209
}
1210

    
1211
/**
1212
 * @todo Please document this function.
1213
 * @see http://drupal.org/node/1354
1214
 * @throws Exception
1215
 */
1216
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1217

    
1218
  cdm_check_valid_portal_page();
1219

    
1220
  return compose_cdm_reference_page($uuid);
1221
}
1222

    
1223
/**
1224
 * Creates a view on a all references contained in the portal.
1225
 *
1226
 * This function is used at the path cdm_dataportal/reference/list
1227
 */
1228
function cdm_dataportal_view_reference_list($pageNumber) {
1229
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1230
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1231
}
1232

    
1233
/**
1234
 * @todo Please document this function.
1235
 * @see http://drupal.org/node/1354
1236
 */
1237
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1238

    
1239
  cdm_check_valid_portal_page();
1240

    
1241
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1242
  if (!$media) {
1243
    drupal_set_title(t('Media does not exist'), PASS_THROUGH);
1244
    return "";
1245
  }
1246
  return theme('cdm_media_page', array(
1247
    'media' => $media,
1248
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1249
    'partId' => $part,
1250
    ));
1251
}
1252

    
1253
/**
1254
 * @todo Please document this function.
1255
 * @see http://drupal.org/node/1354
1256
 */
1257
function _load_taxonBase(&$taxonBase) {
1258
  if (isset($taxonBase->uuid)) {
1259
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1260
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1261
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1262
  }
1263
}
1264

    
1265
/**
1266
 * Loads the media associated to the given taxon from the cdm server.
1267
 * The aggregation settings regarding taxon relathionships and
1268
 * taxonnomic childen are taken into account.
1269
 *
1270
 * The media lists are cached in a static variable.
1271
 *
1272
 * @param Taxon $taxon
1273
 *   A CDM Taxon entitiy
1274
 *
1275
 * @return array
1276
 *   An array of CDM Media entities
1277
 *
1278
 */
1279
function _load_media_for_taxon($taxon) {
1280

    
1281
  static $media = NULL;
1282

    
1283
  if(!isset($media)) {
1284
    $media = array();
1285
  }
1286
  if (!isset($media[$taxon->uuid])) {
1287

    
1288
    // --- GET Images --- //
1289
    $mediaQueryParameters = array(
1290
        "type" => "ImageFile",
1291
    );
1292

    
1293
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1294
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1295
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1296

    
1297
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1298
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1299
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1300
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1301

    
1302
    $ws_endpoint = NULL;
1303
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1304
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1305
    } else {
1306
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1307
    }
1308

    
1309
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1310
        array(
1311
            $taxon->uuid,
1312
        ),
1313
        queryString($mediaQueryParameters)
1314
       );
1315
  }
1316

    
1317
  return $media[$taxon->uuid];
1318
}
1319

    
1320
/**
1321
 *
1322
 * @param Taxon $taxon
1323
 *   A CDM Taxon entitiy
1324
 *
1325
 * @return array
1326
 *   An array of CDM SpecimenOrObservation entities
1327
 *
1328
function _load_occurences_for_taxon($taxon){
1329

    
1330
  static $occurences = NULL;
1331

    
1332
  if(!isset($occurences)) {
1333
    $occurences = array();
1334
  }
1335

    
1336
  if (!isset($occurences[$taxon->uuid])){
1337

    
1338
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1339
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1340
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1341

    
1342
    $by_associatedtaxon_query = http_build_query(array(
1343
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1344
        'relationships' => implode(',', $relationship_choice['direct']),
1345
        'pageSize' => null // all hits in one page
1346
    )
1347
    );
1348

    
1349
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1350
        null,
1351
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1352
    );
1353

    
1354

    
1355
    if(isset($pager->records[0])){
1356
      $occurences[$taxon->uuid] =  $pager->records;
1357
    }
1358
  }
1359
  return $occurences[$taxon->uuid];
1360
}
1361
 */
1362

    
1363
/**
1364
 * Gets a Drupal variable, string or array and returns it.
1365
 *
1366
 * Similar to the variable_get() function of Drupal, except that this function
1367
 * is able to handle arrays correctly. This function is especially useful
1368
 * when dealing with collections of settings form elements (#tree = TRUE).
1369
 *
1370
 * @param string $variableKey
1371
 *   The Unique key of the Drupal variable in the Drupal variables table.
1372
 * @param string $defaultValueString
1373
 *   A string as for example derived from a CONSTANT.
1374
 *
1375
 * @return mixed
1376
 *   usually an array, depending on the nature of the variable.
1377
 *
1378
 * TODO compare with get_array_variable_merged() duplicate functions?
1379
 * @deprecated rather use get_array_variable_merged() since this function
1380
 * used an array as second parameter
1381
 */
1382
function mixed_variable_get($variableKey, $defaultValueString) {
1383
  $systemDefaults = unserialize($defaultValueString);
1384
  $storedSettings = variable_get($variableKey, array());
1385
  if (is_array($storedSettings)) {
1386
    // TODO better use drupal_array_merge_deep() ?
1387
    $settings = array_merge($systemDefaults, $storedSettings);
1388
  }
1389
  else {
1390
    $settings = $systemDefaults;
1391
  }
1392
  return $settings;
1393
}
1394

    
1395
/**
1396
 * Recursive function to convert an object into an array.
1397
 * also subordinate objects will be converted.
1398
 *
1399
 * @param object $object
1400
 *  the object to be converted
1401
 * @return array
1402
 *  The array
1403
 */
1404
function object_to_array($object) {
1405
  if(is_object($object) || is_array($object)) {
1406
    $array = (array)$object;
1407
    foreach ($array as $key=>$value){
1408
      $array[$key] = object_to_array($value);
1409
    }
1410
    return $array;
1411
  } else {
1412
    return $object;
1413
  }
1414
}
1415

    
1416
/**
1417
 * Searches the $collection for the cdm entitiy given as $element.
1418
 *
1419
 * The elements are compared by their UUID.
1420
 *
1421
 * @param $element
1422
 *  the CDM entitiy to search for
1423
 * @param $collection
1424
 *  the list of CDM entities to search in
1425
 *
1426
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1427
 *
1428
 */
1429
function contains_cdm_entitiy($element, $collection) {
1430
  $result = FALSE;
1431
  foreach ($collection as $a) {
1432
    if ($a->uuid == $element->uuid) {
1433
      $result = TRUE;
1434
    }
1435
  }
1436
  return $result;
1437
}
1438

    
1439
/**
1440
 * Filters the array $entity_list of CDM entities by the list
1441
 * of $excludes. Any element contained in the $excludes will be removed
1442
 * from included int the returned list.
1443
 *
1444
 * If the $entity_list is not an array the $excludes will be returned.
1445
 */
1446
function filter_cdm_entity_list($entity_list, $excludes) {
1447
  if (is_array($entity_list)) {
1448
    $result = $entity_list;
1449
    if ($excludes) {
1450
      foreach ($excludes as $exclude) {
1451
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1452
          $result[] = $exclude;
1453
        }
1454
      }
1455
    }
1456
  }
1457
  else {
1458
    $result = $excludes;
1459
  }
1460
  return $result;
1461
}
1462

    
1463
/**
1464
 * Wraps the given $html string into a render array suitable for drupal_render()
1465
 *
1466
 * @param $html
1467
 *   the html string, see
1468
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1469
 * @param $weight
1470
 *   A positive or negative number (integer or decimal).
1471
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1472
 * @param $prefix
1473
 *   Optional markup for the '#prefix' element of the render array
1474
 * @param $suffix
1475
 *   Optional markup for the '#suffix' element of the render array
1476
 *
1477
 * @return array
1478
 *   A render array
1479
 *
1480
 */
1481
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1482
  $render_array = array(
1483
    '#markup' => $html
1484
      );
1485
  if (is_numeric($weight)) {
1486
    $render_array['#weight'] = $weight;
1487
  }
1488
  if($prefix){
1489
    $render_array['#prefix'] = $prefix;
1490
  }
1491
  if($suffix) {
1492
    $render_array['#suffix'] = $suffix;
1493
  }
1494
  return $render_array;
1495
}
1496

    
1497
/**
1498
 * Loads the subgraph of a given PolytomousKeyNode.
1499
 *
1500
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1501
 * the CDM REST service.
1502
 *
1503
 * @param mixed $polytomousKeyNode
1504
 *   PolytomousKeyNode passed by reference.
1505
 *
1506
 * @return void
1507
 */
1508
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1509

    
1510
  if (!$polytomousKeyNode) {
1511
    return;
1512
  }
1513
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1514
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1515
    return;
1516
  }
1517
  if (!is_uuid($polytomousKeyNode->uuid)) {
1518
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1519
    return;
1520
  }
1521

    
1522
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1523

    
1524
  if (!$polytomousKeyNode) {
1525
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1526
    return;
1527
  }
1528

    
1529
  // Load children.
1530
  foreach ($polytomousKeyNode->children as &$childNode) {
1531
    _load_polytomousKeySubGraph($childNode);
1532
  }
1533

    
1534
  // Load subkey.
1535
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1536

    
1537
  // Load taxon.
1538
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1539
  _load_taxonBase($polytomousKeyNode->taxon);
1540
  return;
1541
}
1542

    
1543
/**
1544
 * @todo Please document this function.
1545
 * @see http://drupal.org/node/1354
1546
 */
1547
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1548

    
1549
  cdm_check_valid_portal_page();
1550

    
1551
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1552
  if (!$polytomousKey) {
1553
    drupal_set_title(t('Polytomous key does not exist'), PASS_THROUGH);
1554
    return "";
1555
  }
1556

    
1557
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1558
  if (is_array($sourcePager->records)) {
1559
    $polytomousKey->sources = $sourcePager->records;
1560
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1561
  }
1562

    
1563
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1564
  if (is_array($annotationPager->records)) {
1565
    $polytomousKey->annotations = $annotationPager->records;
1566
  }
1567

    
1568
  _load_polytomousKeySubGraph($polytomousKey->root);
1569
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1570
}
1571

    
1572
/**
1573
 * Creates a taxon page view or a chapter of it.
1574
 *
1575
 * The taxon page gives detailed information on a taxon, it shows:
1576
 *  - Taxon name.
1577
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1578
 *    heterotypic and finally followed by misapplied names.
1579
 *    The list is ordered historically.
1580
 *  - All description associated with the taxon.
1581
 *
1582
 * @param string $uuid
1583
 * @param string $chapter
1584
 *   Name of the part to display, valid values are:
1585
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1586
 *
1587
 * @return string
1588
 */
1589
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1590

    
1591
  cdm_check_valid_taxon_page($chapter);
1592
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1593

    
1594

    
1595
  // Display the page for the taxon defined by $uuid.
1596
  // set_last_taxon_page_tab(arg(3));
1597
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1598
  if (!empty($taxonpage)) {
1599
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1600
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1601
  }
1602
  else {
1603
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1604
    return '';
1605
  }
1606
}
1607

    
1608
/**
1609
 * This function will generate the taxon page part ($chapter) and returns a taxonpage object
1610
 * which has two fields, one for the page title and one for the content. Later on in the
1611
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1612
 * function as the function parameters $title and $content.
1613
 *
1614
 * @param string $uuid
1615
 *   the uuid of the taxon to show
1616
 * @param string $chapter
1617
 *   Name of the part to display, valid values are:
1618
 *   'description', 'images', 'synonymy', 'all'.
1619
 *
1620
 * @return object with the following fields:
1621
 *   - title : the title of the page
1622
 *   - content: the content of the page
1623
 *
1624
 * @throws Exception
1625
 *
1626
 */
1627
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1628
  // Taxon object.
1629
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1630
  if (empty($taxon)) {
1631
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1632
    return null;
1633
  }
1634
  $taxonpage = new stdClass();
1635

    
1636
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1637
    'taxon' => $taxon
1638
  ));
1639

    
1640
  // Check if the taxon id contained in the currently selected tree.
1641
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1642

    
1643
  if (!$taxon_in_current_classification) {
1644
    $classifications = get_classifications_for_taxon($taxon);
1645
    RenderHints::pushToRenderStack('not_in_current_classification');
1646
    $taxon_name_markup = render_taxon_or_name($taxon);
1647

    
1648
    if (count($classifications) == 0) {
1649
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1650
        array(
1651
        '!taxonname' => $taxon_name_markup,
1652
        )
1653
      ), 'warning');
1654
    }
1655
    else {
1656
      $trees = '';
1657
      foreach ($classifications as $classification) {
1658
        if (isset($classification->titleCache)) {
1659
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1660
        }
1661
      }
1662

    
1663
      drupal_set_message(format_plural(count($trees),
1664
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1665
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1666
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1667
        ) ,
1668
        'warning');
1669
    }
1670
    RenderHints::popFromRenderStack();
1671
  }
1672

    
1673
  // Render the taxon page.
1674
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1675
  $taxonpage->content = drupal_render($render_array);
1676

    
1677
  return $taxonpage;
1678
}
1679

    
1680

    
1681
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1682
{
1683
  cdm_check_valid_portal_page();
1684

    
1685
  $specimenpage = specimen_by_accession_number_view($accession_number);
1686

    
1687
  if (!empty($specimenpage)) {
1688
    return cdm_node_show_simulate($specimenpage->content);
1689
  }
1690
  else {
1691
    return '';
1692
  }
1693

    
1694

    
1695
}
1696

    
1697
/**
1698
 * Creates a specimen page view.
1699
 * @param string $uuid the UUID of the specimen
1700
 * @return array|string
1701
 */
1702
function cdm_dataportal_specimen_page_view($uuid) {
1703

    
1704
    cdm_check_valid_portal_page();
1705
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1706
    if (!empty($specimenpage)) {
1707
        return cdm_node_show_simulate($specimenpage->content);
1708
    }
1709
    else {
1710
        return '';
1711
    }
1712
}
1713

    
1714

    
1715
/**
1716
 * Creates a specimen page view.
1717
 * @param string $uuid the UUID of the specimen
1718
 * @return object
1719
 *  The page object with the following fields:
1720
 *   - 'title': the page title
1721
 *   - 'content' : the page content rendered as markup
1722
 */
1723
function specimen_by_accession_number_view($accession_number = null) {
1724

    
1725
  $field_unit_dto = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1726

    
1727
  // Display the page for the specimen defined by $uuid.
1728
  if (isset($field_unit_dto)){
1729
    $dto_array = array($field_unit_dto);
1730
    $specimen_array = specimen_render_array_items($dto_array);
1731
    $specimen_table = array(
1732
      '#theme' => 'table',
1733
      '#weight' => 2,
1734
      // prefix attributes and rows with '#' to let it pass toF the theme function,
1735
      // otherwise it is handled as child render array
1736
      '#attributes' => array('class' => 'specimens'),
1737
      '#rows' => array(),
1738
      '#prefix' => '<div id="specimens">',
1739
      '#suffix' => '</div>',
1740
    );
1741
    foreach($specimen_array as $value){
1742
      $renderArray = array(
1743
        '#theme' => 'item_list',
1744
        '#items' => array($value),
1745
        '#type' => 'ul');
1746
      $output = drupal_render($renderArray);
1747
      $specimen_table['#rows'][] = array(
1748
        // An array of table rows. Every row is an array of cells, or an associative array
1749
        'data' => array($output),
1750
        'class' =>  array(
1751
          'descriptionElement',
1752
          'descriptionElement_IndividualsAssociation'
1753
        ),
1754
      );
1755

    
1756

    
1757
    }
1758
    $specimenpage = new stdClass();
1759

    
1760
    $specimenpage->title = theme('theme_cdm_specimen_dto_page_title', array(
1761
      'specimen' => $field_unit_dto
1762
    ));
1763

    
1764
     $render_array['markup'] = $specimen_table;
1765
     $specimenpage->content = drupal_render($render_array);
1766
  }
1767

    
1768
  return $specimenpage;
1769
}
1770

    
1771

    
1772
/**
1773
 *
1774
 * Creates a specimen view.
1775
 * @param string $uuid the UUID of the specimen
1776
 * @return object
1777
 *    Page object with the fields
1778
 *    - title
1779
 *    - content
1780
 */
1781
function cdm_dataportal_specimen_view($uuid) {
1782
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1783
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1784
    if (empty($specimen)) {
1785
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1786
        return FALSE;
1787
    }
1788
    $specimenpage = new stdClass();
1789

    
1790
    $specimenpage->title = specimen_page_title($specimen);
1791

    
1792
    // Render the specimen page.
1793
    $render_array = compose_cdm_specimen_page($specimen);
1794
    $specimenpage->content = drupal_render($render_array);
1795

    
1796
    return $specimenpage;
1797
}
1798

    
1799
/**
1800
 *
1801
 * Creates a description view.
1802
 *
1803
 * @param string $uuid the UUID of the description
1804
 * @param null $descriptive_dataset_uuid the uuid of the data set which defines
1805
 * the display of the description detail page
1806
 *
1807
 * @return object Page object with the fields
1808
 * Page object with the fields
1809
 * - title
1810
 * - content
1811
 */
1812
function cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid = NULL) {
1813
    $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, $uuid);
1814
    $description_page = new stdClass();
1815
    if (empty($description)) {
1816
      $description_page->title = t('Description does not exist');
1817
      drupal_set_title($description_page->title, PASS_THROUGH); // not necessary if correctly implemented as drupal node
1818
      $description_page->content = "";
1819

    
1820
    } else {
1821
      $description_page->title = $description->titleCache;
1822
      drupal_set_title($description_page->title); // not necessary if correctly implemented as drupal node
1823

    
1824
      // Render the description page.
1825
      $render_array = compose_description_table($description->uuid, $descriptive_dataset_uuid);
1826
      if($render_array['title']){
1827
        $page_title = strip_tags($render_array['title']['#markup']);
1828
        drupal_set_title($page_title);
1829
        unset($render_array['title']);
1830
      }
1831
      $description_page->content = drupal_render($render_array);
1832
    }
1833

    
1834
    return $description_page;
1835
}
1836

    
1837
function cdm_dataportal_description_page_view($uuid, $descriptive_dataset_uuid = NULL) {
1838

    
1839
  cdm_check_valid_portal_page();
1840
  $descriptionpage = cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid);
1841
  if (!empty($descriptionpage)) {
1842
    return cdm_node_show_simulate($descriptionpage->content);
1843
  }
1844
  else {
1845
    return NULL;
1846
  }
1847
}
1848

    
1849
/**
1850
 *
1851
 * Creates a named area view.
1852
 * @param string $uuid the UUID of the specimen
1853
 *  * @return object
1854
 *   An object with two fields:
1855
 *     - title: the page title
1856
 *     - content: the page content
1857
 */
1858

    
1859
function cdm_dataportal_named_area_view($uuid) {
1860
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1861
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1862
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1863
    return null;
1864
  }
1865
  $named_area_page = new stdClass();
1866

    
1867
  $named_area_page->title = $named_area->representation_L10n;
1868

    
1869
  // Render the specimen page.
1870
  $render_array = compose_cdm_named_area_page($uuid);
1871
  $named_area_page->content = drupal_render($render_array);
1872

    
1873
  return $named_area_page;
1874
}
1875

    
1876
function cdm_dataportal_named_area_page_view($uuid) {
1877

    
1878
  cdm_check_valid_portal_page();
1879

    
1880
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1881
  if (!empty($named_area_page)) {
1882
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1883
  }
1884
  else {
1885
    return '';
1886
  }
1887

    
1888

    
1889
}
1890

    
1891
/**
1892
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1893
 *
1894
 * The node page shows the taxon name title and the list of taxon related
1895
 * with such taxon. Name on the tree already in use.
1896
 *
1897
 * @param string $taxon_name_uuid
1898
 *   The uuid of the CDM TaxonName to show a name page for
1899
 * @param string $taxon_to_hide_uuid
1900
 *   A taxon which should not be displayed in the taxon list
1901
 * @param $redirect_to_taxon
1902
 *   Automatically redirect to the related taxon if there is only one
1903
 *   accepted taxon for this name.
1904
 * @param string $highlite_synonym_uuid
1905
 *   Optinal parameter wich takes another taxon uuid, if given the
1906
 *   target taxon pages will show the syonymy tab where the taxon
1907
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1908
 *   in case it is found on this page.
1909
 *
1910
 * @return mixed
1911
 *   The formatted name page as node.
1912
 */
1913
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = false) {
1914

    
1915
  cdm_check_valid_portal_page();
1916

    
1917
  $taxonname_page = cdm_dataportal_name_view(
1918
    is_uuid($taxon_name_uuid) ? $taxon_name_uuid : null,
1919
    is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : null,
1920
    $redirect_to_taxon == 'redirect_to_taxon',
1921
    is_uuid($synonym_uuid) ? $synonym_uuid : null);
1922
  if (!empty($taxonname_page)) {
1923
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1924
  }
1925
  else {
1926
    return '';
1927
  }
1928
}
1929

    
1930
/**
1931
 * View function for a TaxonName page.
1932
 *
1933
 * The name page lists all taxa for which the name specified by the
1934
 * $taxon_name_uuid is being used. I case there is only one name the
1935
 * page automatically redirects ti the according taxon page. Otherwise
1936
 * the list of names is displayed.
1937
 *
1938
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1939
 * list of taxa. This is useful for example when referencing from a taxon
1940
 * to the name page and the referring taxon should not be repeaded in the
1941
 * name page.
1942
 *
1943
 *
1944
 * @param string $taxon_name_uuid
1945
 *   The uuid of the CDM TaxonName to show a name page for
1946
 * @param string $taxon_to_hide_uuid
1947
 *   A taxon which should not be displayed in the taxon list
1948
 * @param $redirect_to_taxon
1949
 *   Automatically redirect to the related taxon if there is only one
1950
 *   accepted taxon for this name.
1951
 * @param string $highlite_synonym_uuid
1952
 *   Optional parameter which takes another taxon uuid, if given the
1953
 *   target taxon pages will show the synonymy tab where the taxon
1954
 *   referenced by the $highlite_synonym_uuid will be highlighted
1955
 *   in case it is found on this page.
1956
 *
1957
 * @return object|boolean
1958
 *   An object with two fields:
1959
 *     - title: the page title
1960
 *     - content: the page content
1961
 *   or FALSE
1962
 *
1963
 */
1964
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $redirect_to_taxon, $highlite_synonym_uuid = NULL) {
1965
  // Getting the full taxonname object from the server.
1966
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1967
  if (!$taxon_name) {
1968
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1969
    return FALSE;
1970
  }
1971
  cdm_load_tagged_full_title($taxon_name);
1972
  // Searching for all the taxa connected with the taxon name on the tree
1973
  // in use.
1974
  $name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1975
  $restrictions = array(new Restriction("name.titleCache","EXACT", array($name->titleCache), 'AND'));
1976
  $init_strategy = array(
1977
    "name.titleCache",
1978
    "name.nomenclaturalReference.authorship",
1979
    "name.nomenclaturalReference.inReference.authorship",
1980
    "name.nomenclaturalReference.inReference.inReference.authorship",
1981
    "name.nomenclaturalReference.inReference.inReference.inReference.authorship"
1982
  );
1983
  $taxa = cdm_ws_fetch_all_by_restriction("Taxon", $restrictions, $init_strategy);
1984

    
1985
  // Removing the name where we came from.
1986
  foreach ($taxa as $k => &$taxon) {
1987
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1988
      unset($taxa[$k]);
1989
    }
1990
  }
1991
  // Show the taxa list or go to the singular taxon.
1992
  if (sizeof($taxa) == 1 && $redirect_to_taxon) {
1993
    // redirect to the taxon if there is only one.
1994
    $singleTaxon = array_pop($taxa);
1995
    if ($singleTaxon->class != "Taxon") {
1996
      // It is a Synonym -> look for the accepted.
1997
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1998
      if (!empty($highlite_synonym_uuid)) {
1999
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2000
      }
2001
      else {
2002
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
2003
      }
2004
    }
2005
    else {
2006
      // It is an accepted taxon.
2007
      if (!empty($highlite_synonym_uuid)) {
2008
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2009
      }
2010
      else {
2011
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
2012
      }
2013
    }
2014
  }
2015
  else {
2016
    // display the name page content
2017
    $taxon_name_page = new stdClass();
2018
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
2019
    $content = array();
2020

    
2021
    RenderHints::pushToRenderStack('name_page');
2022
    RenderHints::setFootnoteListKey('name_page');
2023
    $content['taxon_name'] = markup_to_render_array(render_taxon_or_name($taxon_name), null, '<div class="name-page-name">', '</div>');
2024

    
2025

    
2026
    // name relationships
2027
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $taxon_name->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
2028
    if(count($name_relations) > 0){
2029
      $content['name_relationships'] = compose_name_relationships_list($name_relations, $taxon_name->uuid, null);
2030
    }
2031

    
2032
    // type designations
2033
    $type_designations_render_array = compose_type_designations($taxon_name->uuid);
2034
    $content = array_merge($content, $type_designations_render_array);
2035
    // registrations
2036
    $registrationDTOs= cdm_ws_fetch_all(CDM_WS_REGISTRATION_DTO,  array('nameUuid' => $taxon_name_uuid));
2037
    if(isset($registrationDTOs) && count($registrationDTOs ) > 0 ){
2038
      $content['registrations'][] = markup_to_render_array('<h2>' . t("Registrations") . '</h2>') ;
2039
      foreach ($registrationDTOs as $regDTO){
2040
        $content['registrations'][] = compose_registration_dto_compact($regDTO);
2041
      }
2042
    }
2043

    
2044

    
2045
    // related taxa
2046
    $show_taxa_section = variable_get(CDM_NAME_PAGE_SECTION_TAXA, CDM_NAME_PAGE_SECTION_TAXA_DEFAULT);
2047
    if($show_taxa_section){
2048
      if ($taxa) {
2049
        $content['related_taxa_header'] = markup_to_render_array("<h2>Taxa for this name</h2>");
2050
        $content['related_taxa'] = compose_list_of_taxa($taxa);
2051
      }
2052
      else {
2053
        $content['related_taxa'] = markup_to_render_array('This name is not assigned to a taxon.', null, '<div class="no-taxon-message">', '</div>');
2054
      }
2055
    }
2056

    
2057
    $content['footnotes'] = markup_to_render_array(theme('cdm_footnotes', array('footnoteListKey' => RenderHints::getFootnoteListKey())));
2058

    
2059
    $taxon_name_page->content = $content;
2060
    RenderHints::popFromRenderStack();
2061
    RenderHints::clearFootnoteListKey();
2062
    return $taxon_name_page;
2063
  }
2064
}
2065

    
2066

    
2067
/**
2068
 * Returns a registration page as a Drupal node to be rendered by Drupal.
2069
 *
2070
 * @param string  $registration_identifier_encoded
2071
 *   The persistent identifier of the registration urlencoded.
2072
 * @return mixed
2073
 *   The formatted registration page as node.
2074
 */
2075
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
2076

    
2077
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
2078
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
2079
  return cdm_node_show_simulate($registration_page);
2080
}
2081

    
2082
/**
2083
 * @param $registration_identifier_encoded
2084
 * @return array
2085
 *   The drupal render array for the registration view.
2086
 */
2087
function cdm_dataportal_registration_view($registration_identifier_encoded) {
2088

    
2089
  $registration_identifier = urldecode($registration_identifier_encoded);
2090

    
2091
  RenderHints::pushToRenderStack('registration_page');
2092
  RenderHints::setFootnoteListKey('registration_page');
2093

    
2094
  $render_array = array();
2095
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
2096
  if($registration_dto){
2097

    
2098
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
2099
    $render_array = compose_registration_dto_full($registration_dto, true);
2100

    
2101
  } else {
2102
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
2103
    if(isset($status_text->String)) {
2104
      $status_text = strtolower($status_text->String);
2105
      if($status_text == 'preparation' || $status_text == 'curation'){
2106
        $status_text = 'in ' . $status_text;
2107
      }
2108
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
2109
      //$status_message;
2110
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
2111
    } else {
2112
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
2113
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
2114
    }
2115
  }
2116

    
2117
  $render_array = array(
2118
    '#prefix' => '<div id="registration">',
2119
    'registration' => $render_array,
2120
    '#suffix' => '</div>',
2121
  );
2122

    
2123
  RenderHints::popFromRenderStack();
2124
  RenderHints::clearFootnoteListKey();
2125

    
2126
  return $render_array ;
2127
}
2128

    
2129

    
2130
/**
2131
 * Creates a page with the advance search form.
2132
 *
2133
 * NOTE: The advance search form allows searching for taxa.
2134
 */
2135
function cdm_dataportal_view_search_advanced() {
2136
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2137
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2138
}
2139

    
2140
/**
2141
 * Creates a page with the blast search form.
2142
 *
2143
 * NOTE: The advance search form allows searching for specimen in blast DB.
2144
 */
2145
function cdm_dataportal_view_search_blast() {
2146
    drupal_set_title(t('Blast search'), PASS_THROUGH);
2147
    return drupal_get_form('cdm_dataportal_search_blast_form');
2148
}
2149

    
2150
/**
2151
 * Creates a page with the search form for searching by taxon descriptions.
2152
 */
2153
function cdm_dataportal_view_search_taxon_by_description() {
2154
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2155
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2156
}
2157

    
2158
/**
2159
 * Executes the search and generates the result list of taxa.
2160
 */
2161
function cdm_dataportal_view_search_results_taxon() {
2162

    
2163
  $taxonPager = cdm_dataportal_search_taxon_execute();
2164

    
2165
  $showThumbnails = do_showThumbnails();
2166

    
2167
  $setSessionUri = url('cdm_api/setvalue/session', array(
2168
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2169
  ));
2170

    
2171
  drupal_add_js('jQuery(document).ready(function() {
2172

    
2173
      // init
2174
      if(' . $showThumbnails . ' == 1){
2175
          jQuery(\'.media_gallery\').show(20);
2176
      } else {
2177
          jQuery(\'.media_gallery\').hide(20);
2178
      }
2179

    
2180
      // add change handler
2181
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2182
      function(event){
2183
        var state = 0;
2184
        if(jQuery(this).is(\':checked\')){
2185
          jQuery(\'.media_gallery\').show(20);
2186
          state = 1;
2187
        } else {
2188
          jQuery(\'.media_gallery\').hide(20);
2189
        }
2190
        // store state in session variable
2191
        var uri = \'' . $setSessionUri . '\' + state;
2192
        jQuery.get(uri);
2193
      });
2194
  });',
2195
  array('type' => "inline", 'scope' => JS_DEFAULT));
2196

    
2197
  drupal_set_title(t('Search results'), PASS_THROUGH);
2198

    
2199
  return theme('cdm_search_taxa_results', array(
2200
    'pager' => $taxonPager,
2201
    'path' => 'cdm_dataportal/search/results/taxon',
2202
    ));
2203
}
2204

    
2205
/**
2206
 * Executes the blast search and generates the result list of specimen.
2207
 */
2208
function cdm_dataportal_view_search_results_specimen() {
2209

    
2210
    $specimenPager = cdm_dataportal_search_blast_execute();
2211

    
2212
    return theme('cdm_search_specimen_results', array(
2213
        'pager' => $specimenPager,
2214
        'path' => 'cdm_dataportal/search/results/specimen',
2215
    ));
2216
}
2217

    
2218

    
2219
/**
2220
 * Executes the search for registrations and generates the result list..
2221
 */
2222
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2223

    
2224
  switch($mode ){
2225
    case 'taxongraph':
2226
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2227
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2228
      break;
2229
    case 'filter':
2230
    default:
2231
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2232
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2233
  }
2234
  $block->title = null;
2235

    
2236
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2237

    
2238
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2239
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2240
  $render_array = array_merge($render_array, $registrations_pager_array);
2241

    
2242
  return $render_array;
2243
}
2244

    
2245

    
2246
/**
2247
 * Provides the standard image which indicated a loading process
2248
 *
2249
 * @return string
2250
 *  The img html tag
2251
 */
2252
function loading_image_html() {
2253
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2254
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2255
}
2256

    
2257
/**
2258
 * Returns the state of the the showThumbnails flag set in the
2259
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2260
 *
2261
 * @return boolean
2262
 *    returns 1 if the flag is set
2263
 */
2264
function do_showThumbnails() {
2265
  static $showThumbnails = null;
2266

    
2267
  if($showThumbnails == null) {
2268
    $showThumbnails = 0;
2269
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2270
      $showThumbnails = 0;
2271
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2272
      $showThumbnails = is_array($search_gallery_settings)
2273
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2274
        && (
2275
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2276
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2277
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2278
            )
2279
         ? 1 : 0;
2280

    
2281
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2282
    }
2283
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2284
    if (!is_numeric($showThumbnails)) {
2285
      $showThumbnails = 1;
2286
    }
2287
  }
2288

    
2289
  return $showThumbnails;
2290
}
2291

    
2292

    
2293

    
2294
/* ====================== other functions ====================== */
2295
/**
2296
 * Creates a URL to the taxon page specified by the $uuid parameter.
2297
 *
2298
 * The URL will be prepended with a path element to a specific taxon page tab.
2299
 *
2300
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2301
 * be set globally in the administrative settings or individually in the user
2302
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2303
 * the last portal will stay on this last tab.
2304
 *
2305
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2306
 * internal mechanism by a specific value.
2307
 *
2308
 * @param string $uuid
2309
 *   The UUID of the taxon.
2310
 * @param string $page_tab
2311
 *   Overwriting the preset mechanism by defining specific value for the
2312
 *   taxon page tab.
2313
 * @return string
2314
 *   The created URL.
2315
 */
2316
function path_to_taxon($uuid, $page_tab = FALSE) {
2317

    
2318
  $tab = get_default_taxon_tab();
2319
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2320

    
2321
  if (!$uuid) {
2322
    return FALSE;
2323
  }
2324

    
2325
  if ($page_tab) {
2326
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2327
  }
2328
  elseif (!$tab || strtolower($tab) == 'general') {
2329
    $url = 'cdm_dataportal/taxon/' . $uuid;
2330
  }
2331
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2332
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2333
  }
2334
  else {
2335
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2336
  }
2337
  return $url;
2338
}
2339

    
2340
function path_to_description($uuid, $descriptive_dataset_uuid = NULL) {
2341

    
2342
    if (!$uuid) {
2343
        return FALSE;
2344
    }
2345
    else {
2346
      return 'cdm_dataportal/description/' . $uuid
2347
        . (is_uuid($descriptive_dataset_uuid) ? '/' . $descriptive_dataset_uuid : '');
2348
    }
2349
}
2350

    
2351
function path_to_specimen($uuid) {
2352

    
2353
    if (!$uuid) {
2354
        return FALSE;
2355
    }
2356
    else {
2357
        return 'cdm_dataportal/occurrence/' . $uuid;
2358
    }
2359
}
2360

    
2361
function path_to_specimen_by_accession_number($accession_number) {
2362

    
2363
    if (!$accession_number) {
2364
        return FALSE;
2365
    }
2366
    else {
2367
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2368
    }
2369
}
2370

    
2371
function path_to_named_area($uuid) {
2372

    
2373
  if (!$uuid) {
2374
    return FALSE;
2375
  }
2376
  else {
2377
    return 'cdm_dataportal/named_area/' . $uuid;
2378
  }
2379
}
2380

    
2381
/**
2382
 * Creates a URL to show a synonmy in the according taxon page.
2383
 *
2384
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2385
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2386
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2387
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2388
 * in the page
2389
 *
2390
 * @param string $synonymUuid
2391
 *    The uuid of the synonym
2392
 * @param string $acceptedUuid
2393
 *    The uuid of the according accepted taxon
2394
 * @return string
2395
 *    The URL to show a synonmy in the according taxon page
2396
 */
2397
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2398
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2399
  return url($acceptedPath, array(
2400
      'query' => array(
2401
        // highlite the synony in the synonymy
2402
        'highlite' => $synonymUuid,
2403
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2404
        // see theme_taxon_page_title()
2405
        'acceptedFor' => $synonymUuid
2406
      ),
2407
      'fragment' => $synonymUuid
2408
  ));
2409

    
2410
}
2411

    
2412
/**
2413
 * Composes the drupal path to the key identified by the uuid.
2414
 *
2415
 * @param string $keyType
2416
 *    the key typer corresponds to the specific class of the CDM
2417
 *    IdentificationKey. Possible values are
2418
 *      -PolytomousKey
2419
 *      -MultimediaKey
2420
 *      - ...
2421
 * @param string $keyUuid
2422
 *   The UUID of the key
2423
 */
2424
function path_to_key($keyType, $keyUuid) {
2425
  if (!$keyUuid || !$keyType) {
2426
    return FALSE;
2427
  }
2428
  $keyType{0} = strtolower($keyType{0});
2429
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2430
}
2431

    
2432
/**
2433
 * Composes the drupal path to the reference identified by the uuid.
2434
 *
2435
 * @param $uuid string String representation of the registration entity uuid.
2436
 *
2437
 * @return string
2438
 *  The drupal path
2439
 *
2440
 */
2441
function path_to_reference($uuid) {
2442
  if (!$uuid) {
2443
    return FALSE;
2444
  }
2445
  return 'cdm_dataportal/reference/' . $uuid;
2446
}
2447

    
2448
/**
2449
 * Composes the drupal path to the reference identified by the uuid.
2450
 *
2451
 * @param string $identifier
2452
 *  The persistent identifier of the registration entity (Registration.identifier).
2453
 * @return string
2454
 *  The drupal path
2455
 */
2456
function path_to_registration($identifier) {
2457

    
2458
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2459
    return $identifier;
2460
  } else {
2461
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2462
  }
2463
}
2464

    
2465
/**
2466
 * Creates the path to a cdm_dataportal taxon name page.
2467
 *
2468
 * @param string $taxon_name_uuid
2469
 *   The uuid as string of the CDM TaxonName to show a name page for
2470
 * @param string $taxon_to_hide_uuid
2471
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2472
 * @param string $highlited_synonym_uuid
2473
 *   Optional parameter which takes another taxon uuid, if given the
2474
 *   target taxon pages will show the synonymy tab where the taxon
2475
 *   referenced by the $highlite_synonym_uuid will be highlighted
2476
 *   in case it is found on this page.
2477
 * @param $redirect_to_taxon
2478
 *   If true, the name page will redirect to the related taxon if there is a single one
2479
 *   for this name only.
2480
 *
2481
 * @return string
2482
 *  URI path element as string
2483
 */
2484
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2485
  $res = FALSE;
2486
  if ($name_uuid) {
2487
    $res = 'cdm_dataportal/name/' . $name_uuid .
2488
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2489
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2490
    '/' . ($redirect_to_taxon || variable_get(CDM_NAME_PAGE_AUTOREDIRECT, 0) ? "redirect_to_taxon" : "");
2491
  }
2492

    
2493
  return $res;
2494
}
2495

    
2496
/**
2497
 * Composes the drupal path to the media entity identified by the uuid.
2498
 *
2499
 * @param string $uuid
2500
 *  The persistent identifier of the entity entity
2501
 * @return string
2502
 *  The drupal path
2503
 */
2504
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2505
  if (!$uuid) {
2506
    return FALSE;
2507
  }
2508
  $out = 'cdm_dataportal/media/' . $uuid;
2509
  if ($representaion_uuid) {
2510
    $out .= '/' . $representaion_uuid;
2511
    if (is_numeric($partId)) {
2512
      $out .= '/' . $partId;
2513
    }
2514
  }
2515
  return $out;
2516
}
2517

    
2518
/**
2519
 * Compares thisRank with thatRank.
2520
 *
2521
 * Returns a negative integer, zero, or a positive integer
2522
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2523
 * e.g:
2524
 * <ul>
2525
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2526
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2527
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2528
 * </ul>
2529
 * <p>
2530
 * This compare logic of the underlying webservice is the
2531
 * <b>inverse logic</b> of the the one implemented in
2532
 * java.lang.Comparable#compareTo(java.lang.Object)
2533
 *
2534
 * @param $thisRankUuid
2535
 * @param $thatRankUuid
2536
 *
2537
 * @return int
2538
 *   A negative integer, zero, or a positive integer
2539
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2540
 */
2541
function rank_compare($thisRankUuid, $thatRankUuid) {
2542
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2543
  return $result->Integer;
2544
}
2545

    
2546
/**
2547
 * Creates a short version of a taxonname.
2548
 *
2549
 * The short name is created by using the taggedTitle field of
2550
 * TaxonNodeDTO instances.
2551
 * If the taggedTitle if empty the fullname will be returned.
2552
 *
2553
 * @param object $taxonNodeDTO
2554
 *   A TaxonNodeDTO object
2555
 *
2556
 * @return string
2557
 */
2558
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2559

    
2560
  $nameStr = '';
2561

    
2562
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2563

    
2564
  // Get all tagged text tokens of the scientific name.
2565
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2566
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2567
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2568
    }
2569
  }
2570
  $nameStr = trim($nameStr);
2571

    
2572
  if ($nameStr) {
2573

    
2574
    // Do not return short names for these.
2575
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2576
      return $nameStr;
2577
    }
2578

    
2579
    /*
2580
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2581
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2582
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2583
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2584
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2585
    */
2586
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2587
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2588
      return $matches[1][0] . "." . $matches[3][0];
2589
    }
2590
    else {
2591
      return $nameStr;
2592
    }
2593
  }
2594
  else {
2595
    return $taxonNodeDTO->titleCache;
2596
  }
2597
}
2598

    
2599
/**
2600
 * Check if a taxon is accepted by the current taxonomic tree.
2601
 *
2602
 * @param mixed $taxon
2603
 *   The Taxon obkect to check.
2604
 *
2605
 * @return bool
2606
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2607
 */
2608
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2609

    
2610
  $defaultTreeUuid = get_current_classification_uuid();
2611

    
2612
  if (isset($taxon->taxonNodes)) {
2613
    $taxonNodes = $taxon->taxonNodes;
2614
  }
2615
  else {
2616
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2617
  }
2618

    
2619
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2620
    foreach ($taxonNodes as $node) {
2621
      if (isset($node->classification)){
2622
        if(is_object($node->classification)) {
2623
          if ($node->classification->uuid == $defaultTreeUuid) {
2624
            return TRUE;
2625
          }
2626
        }
2627
        else {
2628
          if ($node->classification == $defaultTreeUuid) {
2629
            return TRUE;
2630
          }
2631
        }
2632
      }
2633
    }
2634
  }
2635

    
2636
  return FALSE;
2637
}
2638

    
2639
/**
2640
 * Checks is the source has one of the given types.
2641
 *
2642
 * @param object $source
2643
 *   The original source entity
2644
 * @param array $types
2645
 *   An array of element of the OriginalSourceType enumeration
2646
 *   If not set the default will be used which is:
2647
 *    - Lineage
2648
 *    - PrimaryMediaSource
2649
 *    - PrimaryTaxonomicSource
2650
 *    - Unknown
2651
 *    - Other
2652
 * @return boolean
2653
 */
2654
  function _is_original_source_type($source, $types = null) {
2655
    // this is the default
2656
    // maybe this should also be put into the settings
2657
    static $default = array(
2658
      OriginalSourceType::Lineage,
2659
      OriginalSourceType::PrimaryMediaSource,
2660
      OriginalSourceType::PrimaryTaxonomicSource,
2661
      OriginalSourceType::Unknown,
2662
      OriginalSourceType::Other,
2663
      OriginalSourceType::Aggregation
2664
    );
2665

    
2666
    if(!$types){
2667
      $types = $default;
2668
    }
2669
    return isset($source->type) && in_array($source->type, $types);
2670
  }
2671

    
2672
/**
2673
 * Collects all the media from a list of description elements.
2674
 *
2675
 * @param array $descriptionElements
2676
 *   The description elements from which to collect the media.
2677
 *
2678
 * @return array
2679
 *   The output with all the collected media.
2680
 */
2681
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2682

    
2683
  $outArrayOfMedia = array();
2684

    
2685
  // Avoiding a warning box in Drupal for Flora Malesiana.
2686
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2687
    foreach ($descriptionElements as $descriptionElement) {
2688
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2689
        foreach ($descriptionElement->media as $media) {
2690
          if (is_object($media)) {
2691
            $outArrayOfMedia[] = $media;
2692
          }
2693
        }
2694
      }
2695
    }
2696
  }
2697
  return $outArrayOfMedia;
2698
}
2699

    
2700
/**
2701
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2702
 *
2703
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2704
 *
2705
 * @see cdm_fetch_visible_annotations()
2706
 *
2707
 * @param array $cdm_entities
2708
 *   An array of CdmBase instances or a single instance.
2709
 * @param $footnote_list_key_suggestion string
2710
 *    optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be determined be set to
2711
 *    RenderHints::getFootnoteListKey().'-annotations' otherwise the supplied key will be used.
2712
 *
2713
 * @return array of footnote keys
2714
 */
2715
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2716

    
2717
  $footNoteKeys = array();
2718

    
2719
  // Is argument cdmBase an array?
2720
  if (!is_array($cdm_entities)) {
2721
    $cdmBase_array = array();
2722
    $cdmBase_array[] = $cdm_entities;
2723
  }
2724
  else {
2725
    $cdmBase_array = $cdm_entities;
2726
  }
2727

    
2728
  // Getting the key for the footnotemanager.
2729
  if (isset($footnote_list_key_suggestion)) {
2730
    $footnote_list_key = $footnote_list_key_suggestion;
2731
  }
2732
  else {
2733
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2734
  }
2735

    
2736
  // Adding the footnotes keys.
2737
  foreach ($cdmBase_array as $cdmBase_element) {
2738
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2739
    if (is_array($annotations)) {
2740
      foreach ($annotations as $annotation) {
2741
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2742
      }
2743
    }
2744
  }
2745

    
2746
  return $footNoteKeys;
2747
}
2748

    
2749

    
2750
/**
2751
 * Creates a CDM Dynabox.
2752
 *
2753
 * @param string $dynabox_id
2754
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2755
 * @param string $label
2756
 *   The clickable text to show.
2757
 * @param string $content_url
2758
 *   The cdm REST service request url wich will deliver the content to be shown
2759
 *   once the dynabox toggles open.
2760
 * @param string $theme
2761
 *   The theme to be used for rendering the cdm REST service response with is
2762
 *   returned from the $content_url.
2763
 * @param string $link_alt_text
2764
 *   The value for the alt attribute of the dynabox link.
2765
 * @param array $enclosingtags
2766
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2767
 *   element itself, $enclosingtags[1] is the tag to be used for the
2768
 *   dynabox_content (optional)
2769
 * @param array $attributes
2770
 * @param $content_element_selector
2771
 *   Optional jQuery selector which can be used to reference a dom element which should
2772
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2773
 *  element will be placed in this container.
2774
 *
2775
 * @param string $open_callback
2776
 *   optional javascript call back function to be triggered after toggling the box to
2777
 *   the open state.
2778
 * @param string $close_callback
2779
 *   optional javascript call back function to be triggered after toggling the box to
2780
 *   the closed state.
2781
 * @return string Returns HTML for a dynabox.
2782
 * Returns HTML for a dynabox.
2783
 */
2784
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2785
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2786
                     $content_element_selector = null,
2787
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2788
  $out = '';
2789

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

    
2793
  if(!array_key_exists('class', $attributes)) {
2794
    $attributes['class'] = array();
2795
  }
2796
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2797
  $dynabox_attributes = drupal_attributes($attributes);
2798

    
2799

    
2800
  _add_js_domEvent(); // requires domEvent.js
2801
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2802
  drupal_add_js("
2803
  jQuery(document).ready(
2804
      function() {
2805
        dynabox('". $dynabox_id ."',
2806
          {
2807
            open_callback: " . $open_callback .",
2808
            close_callback: " . $close_callback .
2809
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2810
          }
2811
        );
2812
      }
2813
   );",
2814
   array(
2815
    'type'=>'inline',
2816
    'scope'=>'footer'
2817
    )
2818
  );
2819

    
2820

    
2821
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2822
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2823
  $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>';
2824
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2825
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2826
  $out .= '    </' . $enclosingtags[1] . '>';
2827
  $out .= '  </' . $enclosingtags[0] . '>';
2828
  $out .= '<!-- dynabox end -->';
2829
  return $out;
2830
}
2831

    
2832
/**
2833
 * Checks whether a feature has any description elements.
2834
 *
2835
 * @param mixed $featureNode
2836
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2837
 *
2838
 * @see _mergeFeatureTreeDescriptions()
2839
 *
2840
 * @return bool
2841
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2842
 *   contains at least one non empty TextData or at least one DescriptionElement
2843
 *   of an other type. A TextData element holding a multilanguageText or a
2844
 *   source reference is considered to be not empty.
2845
 *
2846
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2847
 *       see $block_content_is_not_empty in make_feature_block_list() and
2848
 *       $feature_block_has_content in compose_feature_block_items_generic
2849
 */
2850
function has_feature_node_description_elements($featureNode) {
2851

    
2852
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2853
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2854
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2855
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2856
          && $descriptionElement->multilanguageText_L10n->text != ''
2857
          || isset($descriptionElement->sources[0])
2858
          || isset($descriptionElement->media[0]) ) {
2859
          return TRUE;
2860
        }
2861
      }
2862
    }
2863
  }
2864
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2865
    foreach ($featureNode->childNodes as $child) {
2866
      if (has_feature_node_description_elements($child)) {
2867
        return TRUE;
2868
      }
2869
    }
2870
  }
2871
  return FALSE;
2872
}
2873

    
2874
/**
2875
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2876
 *
2877
 * @param $chapter
2878
 *   The taxon page chapter or part
2879
 */
2880
function cdm_check_valid_taxon_page($chapter){
2881
  static $taxon_tabs = null;
2882

    
2883
  cdm_check_valid_portal_page();
2884

    
2885
  if($taxon_tabs == null){
2886
    $taxon_tabs = array('all', 'description');
2887
    foreach(get_taxon_tabs_list() as $tab){
2888
      $taxon_tabs[] = strtolower($tab);
2889
    }
2890
  }
2891

    
2892
  if(!in_array($chapter, $taxon_tabs)){
2893
    // oops this is not a valid chapter name
2894
    http_response_code(404); // 404 = Not Found
2895
  }
2896

    
2897
}
2898

    
2899
function check_js_devel_mode_disabled() {
2900
  if(variable_get('cdm_js_devel_mode', FALSE)) {
2901
    drupal_set_message(t('The !url1 is enabled.
2902
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
2903
      '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
2904
    )),
2905
      'warning'
2906
    );
2907
  }
2908
}
2909

    
2910
/**
2911
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2912
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2913
 *
2914
 * @param $preg_pattern
2915
 *   Optional regular expression pattern to be used in preg_match().
2916
 */
2917
function cdm_check_valid_portal_page($preg_pattern = null){
2918
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2919
  if($preg_pattern === null){
2920
    $preg_pattern = $ends_with_file_suffix_pattern;
2921
  }
2922
  if(preg_match($preg_pattern, $_GET['q'])){
2923
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2924
    http_response_code(404); // 404 = Not Found
2925
    exit('HTTP 404');
2926
  }
2927
  check_js_devel_mode_disabled();
2928
}
2929

    
2930
/**
2931
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2932
 *
2933
 * @param $text_a
2934
 * @param $text_b
2935
 * @return string
2936
 */
2937
function diff_viewer($text_a, $text_b) {
2938

    
2939
  static $diff_viewer_count = 0;
2940

    
2941
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2942

    
2943
  // http://code.stephenmorley.org/php/diff-implementation/
2944
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2945
  drupal_add_css(drupal_get_path('module',
2946
      'cdm_dataportal') . '/css/diff.css');
2947
  _add_jquery_ui();
2948
  drupal_add_js(
2949
    'jQuery(document).ready( function(){
2950
        jQuery(\'#' . $element_id . '\').accordion({
2951
        collapsible: true,
2952
        active: false,
2953
        fillSpace: true,
2954
        }).children(\'div\').css({ \'height\': \'auto\' });
2955
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2956
     });'
2957
    , array(
2958
    'type' => 'inline',
2959
    'scope' => 'footer'
2960
  ));
2961

    
2962
  $diff = Diff::compare($text_a,
2963
    $text_b);
2964
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2965
    . Diff::toTable($diff, '', '')
2966
    . '</div></div>';
2967
  return $diff_viewer_markup;
2968
}
2969

    
2970

    
(10-10/18)