Project

General

Profile

Download (94.5 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/specimen/accession_number'] = array(
502
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
503
        'access arguments' => array('access cdm content'),
504
        'type' => MENU_CALLBACK,
505
        // Expected callback arguments: accession number.
506
    );
507
  $items['cdm_dataportal/named_area'] = array(
508
    'page callback' => 'cdm_dataportal_named_area_page_view',
509
    'access arguments' => array('access cdm content'),
510
    'type' => MENU_CALLBACK,
511
    // Expected callback arguments: uuid.
512
  );
513

    
514
  $items['cdm_dataportal/name'] = array(
515
    'page callback' => 'cdm_dataportal_name_page_view',
516
      /*
517
    'page arguments' => array(
518
       'taxon_name_uuid',
519
       'taxon_to_hide_uuid',
520
       'synonym_uuid' => NULL
521
      ),
522
      */
523
    'access arguments' => array('access cdm content'),
524
    'type' => MENU_CALLBACK,
525
    // Expected callback arguments: uuid.
526
  );
527

    
528
  $items['cdm_dataportal/reference'] = array(
529
    'page callback' => 'cdm_dataportal_view_reference',
530
    'access arguments' => array('access cdm content'),
531
    'type' => MENU_CALLBACK,
532
    // Expected callback arguments: uuid.
533
  );
534

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

    
542
  $items['cdm_dataportal/media'] = array(
543
    'page callback' => 'cdm_dataportal_view_media',
544
    'access arguments' => array('access cdm content'),
545
    'type' => MENU_CALLBACK,
546
    // Expected callback arguments:
547
    // uuid, mediarepresentation_uuid, part_uuid or part#.
548
  );
549

    
550
  $items['cdm_dataportal/polytomousKey'] = array(
551
    'page callback' => 'cdm_dataportal_view_polytomousKey',
552
    'access arguments' => array('access cdm content'),
553
    'type' => MENU_CALLBACK,
554
    // Expected callback arguments: polytomousKey->uuid.
555
  );
556

    
557
  $items['cdm_dataportal/search'] = array(
558
    'page callback' => 'cdm_dataportal_view_search_advanced',
559
    'access arguments' => array('access cdm content'),
560
    'type' => MENU_CALLBACK,
561
  );
562

    
563
  $items['cdm_dataportal/search/advanced'] = array(
564
    'title' => 'Advanced', // will be passed through t()
565
    'page callback' => 'cdm_dataportal_view_search_advanced',
566
    'access arguments' => array('access cdm content'),
567
    'type' => MENU_DEFAULT_LOCAL_TASK,
568
  );
569
  $items['cdm_dataportal/search/blast'] = array(
570
    'title' => 'Blast', // will be passed through t()
571
    'page callback' => 'cdm_dataportal_view_search_blast',
572
    'access arguments' => array('access cdm content'),
573
    'type' => MENU_LOCAL_TASK,
574
  );
575

    
576
  $items['cdm_dataportal/search/taxon_by_description'] = array(
577
    'title' => 'By content category', // will be passed through t()
578
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
579
    'access arguments' => array('access cdm content'),
580
    'type' => MENU_LOCAL_TASK,
581
  );
582
  $items['cdm_dataportal/search/results/taxon'] = array(
583
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
584
    'access arguments' => array('access cdm content'),
585
    'type' => MENU_CALLBACK,
586
  );
587

    
588

    
589
  $items['cdm_dataportal/search/results/specimen'] = array(
590
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
591
      'access arguments' => array('access cdm content'),
592
      'type' => MENU_CALLBACK,
593
  );
594

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

    
629
  // Optional callback arguments: page.
630
  $items['cdm_dataportal/registration'] = array(
631
    'page callback' => 'cdm_dataportal_registration_page_view',
632
    'access arguments' => array('access cdm content'),
633
    'type' => MENU_CALLBACK,
634
    // Expected callback arguments: uuid.
635
  );
636

    
637
  /*
638
   $items['cdm/xml2json'] = array(
639
   'page callback' => 'cdm_view_xml2json',
640
   'access arguments' => array('access cdm content'),
641
   'type' => MENU_CALLBACK,
642
   );
643
   */
644

    
645
  // 'May not cache' in D5.
646
  $items['cdm_dataportal/name/%'] = array(
647
    // 'page callback' => 'cdm_dataportal_view_name',
648
    'page callback' => 'cdm_dataportal_name_page_view',
649
    'page arguments' => array(2, 3, 4, 5),
650
    'access arguments' => array('access cdm content'),
651
    'type' => MENU_CALLBACK,
652
  );
653

    
654
  // --- Local tasks for Taxon.
655
  // --- tabbed taxon page
656
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
657
    $items['cdm_dataportal/taxon/%'] = array(
658
      'title' => cdm_taxonpage_tab_label('General'),
659
      'page callback' => 'cdm_dataportal_taxon_page_view',
660
      'access arguments' => array('access cdm content'),
661
      'type' => MENU_CALLBACK,
662
      'weight' => 1,
663
      'page arguments' => array(2, "description")
664
      , // Expected callback arguments: taxon_uuid.
665
    );
666

    
667
    $items['cdm_dataportal/taxon/%/all'] = array(
668
      'title' => cdm_taxonpage_tab_label('General'),
669
      'page callback' => 'cdm_dataportal_taxon_page_view',
670
      'access arguments' => array('access cdm content'),
671
      'type' => MENU_CALLBACK,
672
      'weight' => 2,
673
      'page arguments' => array(2, "all")
674
      , // Expected callback arguments: taxon_uuid.
675
    );
676

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

    
687
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
688
      'title' => cdm_taxonpage_tab_label('Synonymy'),
689
      'page callback' => 'cdm_dataportal_taxon_page_view',
690
      'access arguments' => array('access cdm content'),
691
      'type' => MENU_LOCAL_TASK,
692
      'weight' => 4,
693
      'page arguments' => array(2, "synonymy", 4)
694
      , // Expected callback arguments: taxon_uuid and ...
695
    );
696
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
697
      'title' => cdm_taxonpage_tab_label('Images'),
698
      'page callback' => 'cdm_dataportal_taxon_page_view',
699
      'access arguments' => array('access cdm content'),
700
      'type' => MENU_LOCAL_TASK,
701
      'weight' => 5,
702
      'page arguments' => array(2, "images")
703
      , // Expected callback arguments: taxon_uuid.
704
    );
705

    
706
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
707
      'title' => cdm_taxonpage_tab_label('Specimens'),
708
      'page callback' => 'cdm_dataportal_taxon_page_view',
709
      'access arguments' => array('access cdm content'),
710
      'type' => MENU_LOCAL_TASK,
711
      'weight' => 6,
712
      'page arguments' => array(2, "specimens")
713
      , // Expected callback arguments: taxon_uuid.
714
    );
715

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

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

    
736
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
737
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
738
        'access arguments' => array('access cdm content'),
739
        'page arguments' => array(3,4,5),
740
        'type' => MENU_CALLBACK
741
    );
742
  }
743

    
744
  // --- refresh link for all cdmnode types
745
  foreach (cdm_get_nodetypes() as $type=>$name) {
746
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
747
        'title' => 'Refresh',
748
        'page callback' => 'cdm_dataportal_refresh_node',
749
        'access arguments' => array('administer cdm_dataportal'),
750
        'type' => MENU_LOCAL_TASK,
751
        'weight' => 100,
752
        'page arguments' => array($name, 2)
753
    );
754
  }
755

    
756
  return $items;
757
}
758

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

    
774
  if(variable_get('cdm_debug_mode', FALSE)){
775
    $file = 'temporary://drupal_debug.txt';
776
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
777
  }
778

    
779
  $bibliography_settings = get_bibliography_settings();
780
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
781
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
782
}
783

    
784
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
785

    
786
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
787

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

    
797
  $parameters['cacheL2_refresh'] ='1';
798

    
799

    
800
  drupal_goto($base_path, array('query' => $parameters));
801
}
802

    
803
/**
804
 * Implements hook_requirements($phase)
805
 */
806
function cdm_dataportal_requirements($phase) {
807
    $requirements = array();
808
    if($phase == 'runtime'){
809

    
810
    }
811
    return $requirements;
812
}
813

    
814
/**
815
 * Implements hook_block_info().
816
 */
817
function cdm_dataportal_block_info() {
818

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

    
874
/**
875
 * Implements hook_block_view().
876
 */
877
function cdm_dataportal_block_view($delta) {
878
  // TODO Rename block deltas (e.g. '2') to readable strings.
879
  switch ($delta) {
880
    // case 'delta-1':
881
    // $block['subject'] = t('Credits');
882
    // $block['content'] = theme('cdm_credits');
883
    // return $block;
884
    case '2':
885
      $block['subject'] = t('Search taxa');
886
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
887
      $block['content'] = drupal_render($form);
888

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

    
973

    
974
/**
975
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
976
 *
977
 * @return string
978
 *   the taxon uuid or NULL
979
 */
980
function get_current_taxon_uuid()
981
{
982
  static $taxon_uuid;
983

    
984
  if(!isset($taxon_uuid)){
985
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
986
      $taxon_uuid = $_REQUEST['currentTaxon'];
987
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
988
      $taxon_uuid = arg(2);
989
    } else {
990
      $taxon_uuid = null;
991
    }
992
  }
993

    
994
  return $taxon_uuid;
995
}
996

    
997
/**
998
 * Returns the currently classification tree in use.
999
 *
1000
 * @return string
1001
 *   The uuid of the currently focused classification
1002
 */
1003
function get_current_classification_uuid() {
1004
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1005
    return $_SESSION['cdm']['taxonomictree_uuid'];
1006
  }
1007
  else {
1008
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1009
  }
1010
}
1011

    
1012
/*
1013
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
1014
 $_SESSION['cdm'] = NULL;
1015
 if(is_string($cdm_ws_uri_update)){
1016
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
1017
 }
1018
 }
1019

    
1020
 function cdm_dataportal_session_validate(){
1021
 if(!isset($_SESSION['cdm']['ws_uri'])){
1022
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
1023
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
1024
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
1025
 }
1026
 }
1027
 */
1028

    
1029
/**
1030
 * creates a  selector form for taxonomic trees.
1031
 *
1032
 * @return array
1033
 *  a drupal form array
1034
 */
1035
function cdm_taxonomictree_selector() {
1036
  _add_js_treeselector();
1037

    
1038
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1039
  return $form;
1040
}
1041

    
1042
/**
1043
 * @todo Please document this function.
1044
 * @see http://drupal.org/node/1354
1045
 *
1046
 * @deprecated use compose_classification_selector instead
1047
 */
1048
function cdm_taxonomictree_selector_form($form, &$form_state) {
1049

    
1050
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1051
  $form['#action'] = $url;
1052

    
1053
  $form['var'] = array(
1054
    '#weight' => -3,
1055
    '#type' => 'hidden',
1056
    '#value' => '[cdm][taxonomictree_uuid]',
1057
  );
1058

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

    
1062
  $form['destination'] = array(
1063
    '#weight' => -3,
1064
    '#type' => 'hidden',
1065
    '#value' =>  $destination,
1066
  );
1067

    
1068
  $options = cdm_get_taxontrees_as_options();
1069
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1070
  if($taxontree_includes){
1071
    $filtered_options = array();
1072
    foreach($options as $uuid=>$label){
1073
      if(!empty($taxontree_includes[$uuid])){
1074
        $filtered_options[$uuid] = $label;
1075
      }
1076
    }
1077
    $options = $filtered_options;
1078
  }
1079

    
1080
  $form['val'] = array(
1081
    '#type' => 'select',
1082
    '#title' => t('Available classifications'),
1083
    '#default_value' => get_current_classification_uuid(),
1084
    '#options' => $options,
1085
    '#attributes' => array('class' => array('highlite-first-child')),
1086
  );
1087

    
1088
  return $form;
1089

    
1090
}
1091

    
1092
/**
1093
 *
1094
 * @ingroup compose
1095
 */
1096
function compose_classification_selector() {
1097

    
1098
  $destination_array = drupal_get_destination();
1099
  $destination = $destination_array['destination'];
1100

    
1101
  $options = cdm_get_taxontrees_as_options();
1102
  $items = array();
1103
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1104

    
1105
  $current_classification_uuid = get_current_classification_uuid();
1106

    
1107

    
1108
  foreach($options as $uuid=>$label){
1109
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1110

    
1111
      $class_attributes = '';
1112
      if($current_classification_uuid == $uuid){
1113
        $class_attributes  = array('focused');
1114
      }
1115
      $items[] = array(
1116
        'data' => l($label,
1117
          'cdm_api/setvalue/session',
1118
          array(
1119
            'query' => array(
1120
              'destination' => $destination,
1121
              'val' => $uuid,
1122
              'var' => '[cdm][taxonomictree_uuid]'
1123
            ),
1124
          )
1125
        ),
1126
        'class' => $class_attributes
1127
      );
1128
    }
1129
  }
1130

    
1131
  $render_array = array(
1132
    '#theme' => 'item_list',
1133
    '#type' => 'ul',
1134
    '#items' => $items
1135
  );
1136

    
1137
  return $render_array;
1138
}
1139

    
1140

    
1141
/* UNREACHABLE since action of form directly links to view.
1142
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1143

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

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

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

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

    
1194
  /*
1195
  // FIXME the filter for accepted names will be a form element, thus this
1196
  // widget should be generated via form api preferably as block.
1197
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1198
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1199
  $out .= theme('cdm_listof_taxa', $taxonPager);
1200
  return $out;
1201
  */
1202
}
1203

    
1204
/**
1205
 * @todo Please document this function.
1206
 * @see http://drupal.org/node/1354
1207
 * @throws Exception
1208
 */
1209
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1210

    
1211
  cdm_check_valid_portal_page();
1212

    
1213
  return compose_cdm_reference_page($uuid);
1214
}
1215

    
1216
/**
1217
 * Creates a view on a all references contained in the portal.
1218
 *
1219
 * This function is used at the path cdm_dataportal/reference/list
1220
 */
1221
function cdm_dataportal_view_reference_list($pageNumber) {
1222
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1223
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1224
}
1225

    
1226
/**
1227
 * @todo Please document this function.
1228
 * @see http://drupal.org/node/1354
1229
 */
1230
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1231

    
1232
  cdm_check_valid_portal_page();
1233

    
1234
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1235
  return theme('cdm_media_page', array(
1236
    'media' => $media,
1237
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1238
    'partId' => $part,
1239
    ));
1240
}
1241

    
1242
/**
1243
 * @todo Please document this function.
1244
 * @see http://drupal.org/node/1354
1245
 */
1246
function _load_taxonBase(&$taxonBase) {
1247
  if (isset($taxonBase->uuid)) {
1248
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1249
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1250
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1251
  }
1252
}
1253

    
1254
/**
1255
 * Loads the media associated to the given taxon from the cdm server.
1256
 * The aggregation settings regarding taxon relathionships and
1257
 * taxonnomic childen are taken into account.
1258
 *
1259
 * The media lists are cached in a static variable.
1260
 *
1261
 * @param Taxon $taxon
1262
 *   A CDM Taxon entitiy
1263
 *
1264
 * @return array
1265
 *   An array of CDM Media entities
1266
 *
1267
 */
1268
function _load_media_for_taxon($taxon) {
1269

    
1270
  static $media = NULL;
1271

    
1272
  if(!isset($media)) {
1273
    $media = array();
1274
  }
1275
  if (!isset($media[$taxon->uuid])) {
1276

    
1277
    // --- GET Images --- //
1278
    $mediaQueryParameters = array(
1279
        "type" => "ImageFile",
1280
    );
1281

    
1282
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1283
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1284
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1285

    
1286
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1287
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1288
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1289
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1290

    
1291
    $ws_endpoint = NULL;
1292
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1293
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1294
    } else {
1295
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1296
    }
1297

    
1298
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1299
        array(
1300
            $taxon->uuid,
1301
        ),
1302
        queryString($mediaQueryParameters)
1303
       );
1304
  }
1305

    
1306
  return $media[$taxon->uuid];
1307
}
1308

    
1309
/**
1310
 *
1311
 * @param Taxon $taxon
1312
 *   A CDM Taxon entitiy
1313
 *
1314
 * @return array
1315
 *   An array of CDM SpecimenOrObservation entities
1316
 *
1317
function _load_occurences_for_taxon($taxon){
1318

    
1319
  static $occurences = NULL;
1320

    
1321
  if(!isset($occurences)) {
1322
    $occurences = array();
1323
  }
1324

    
1325
  if (!isset($occurences[$taxon->uuid])){
1326

    
1327
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1328
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1329
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1330

    
1331
    $by_associatedtaxon_query = http_build_query(array(
1332
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1333
        'relationships' => implode(',', $relationship_choice['direct']),
1334
        'pageSize' => null // all hits in one page
1335
    )
1336
    );
1337

    
1338
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1339
        null,
1340
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1341
    );
1342

    
1343

    
1344
    if(isset($pager->records[0])){
1345
      $occurences[$taxon->uuid] =  $pager->records;
1346
    }
1347
  }
1348
  return $occurences[$taxon->uuid];
1349
}
1350
 */
1351

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

    
1384
/**
1385
 * Recursive function to convert an object into an array.
1386
 * also subordinate objects will be converted.
1387
 *
1388
 * @param object $object
1389
 *  the object to be converted
1390
 * @return array
1391
 *  The array
1392
 */
1393
function object_to_array($object) {
1394
  if(is_object($object) || is_array($object)) {
1395
    $array = (array)$object;
1396
    foreach ($array as $key=>$value){
1397
      $array[$key] = object_to_array($value);
1398
    }
1399
    return $array;
1400
  } else {
1401
    return $object;
1402
  }
1403
}
1404

    
1405
/**
1406
 * Searches the $collection for the cdm entitiy given as $element.
1407
 *
1408
 * The elements are compared by their UUID.
1409
 *
1410
 * @param $element
1411
 *  the CDM entitiy to search for
1412
 * @param $collection
1413
 *  the list of CDM entities to search in
1414
 *
1415
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1416
 *
1417
 */
1418
function contains_cdm_entitiy($element, $collection) {
1419
  $result = FALSE;
1420
  foreach ($collection as $a) {
1421
    if ($a->uuid == $element->uuid) {
1422
      $result = TRUE;
1423
    }
1424
  }
1425
  return $result;
1426
}
1427

    
1428
/**
1429
 * Filters the array $entity_list of CDM entities by the list
1430
 * of $excludes. Any element contained in the $excludes will be removed
1431
 * from included int the returned list.
1432
 *
1433
 * If the $entity_list is not an array the $excludes will be returned.
1434
 */
1435
function filter_cdm_entity_list($entity_list, $excludes) {
1436
  if (is_array($entity_list)) {
1437
    $result = $entity_list;
1438
    if ($excludes) {
1439
      foreach ($excludes as $exclude) {
1440
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1441
          $result[] = $exclude;
1442
        }
1443
      }
1444
    }
1445
  }
1446
  else {
1447
    $result = $excludes;
1448
  }
1449
  return $result;
1450
}
1451

    
1452
/**
1453
 * Wraps the given $html string into a render array suitable for drupal_render()
1454
 *
1455
 * @param $html
1456
 *   the html string, see
1457
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1458
 * @param $weight
1459
 *   A positive or negative number (integer or decimal).
1460
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1461
 * @param $prefix
1462
 *   Optional markup for the '#prefix' element of the render array
1463
 * @param $suffix
1464
 *   Optional markup for the '#suffix' element of the render array
1465
 *
1466
 * @return array
1467
 *   A render array
1468
 *
1469
 */
1470
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1471
  $render_array = array(
1472
    '#markup' => $html
1473
      );
1474
  if (is_numeric($weight)) {
1475
    $render_array['#weight'] = $weight;
1476
  }
1477
  if($prefix){
1478
    $render_array['#prefix'] = $prefix;
1479
  }
1480
  if($suffix) {
1481
    $render_array['#suffix'] = $suffix;
1482
  }
1483
  return $render_array;
1484
}
1485

    
1486
/**
1487
 * Loads the subgraph of a given PolytomousKeyNode.
1488
 *
1489
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1490
 * the CDM REST service.
1491
 *
1492
 * @param mixed $polytomousKeyNode
1493
 *   PolytomousKeyNode passed by reference.
1494
 *
1495
 * @return void
1496
 */
1497
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1498

    
1499
  if (!$polytomousKeyNode) {
1500
    return;
1501
  }
1502
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1503
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1504
    return;
1505
  }
1506
  if (!is_uuid($polytomousKeyNode->uuid)) {
1507
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1508
    return;
1509
  }
1510

    
1511
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1512

    
1513
  if (!$polytomousKeyNode) {
1514
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1515
    return;
1516
  }
1517

    
1518
  // Load children.
1519
  foreach ($polytomousKeyNode->children as &$childNode) {
1520
    _load_polytomousKeySubGraph($childNode);
1521
  }
1522

    
1523
  // Load subkey.
1524
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1525

    
1526
  // Load taxon.
1527
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1528
  _load_taxonBase($polytomousKeyNode->taxon);
1529
  return;
1530
}
1531

    
1532
/**
1533
 * @todo Please document this function.
1534
 * @see http://drupal.org/node/1354
1535
 */
1536
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1537

    
1538
  cdm_check_valid_portal_page();
1539

    
1540
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1541

    
1542
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1543
  if (is_array($sourcePager->records)) {
1544
    $polytomousKey->sources = $sourcePager->records;
1545
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1546
  }
1547

    
1548
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1549
  if (is_array($annotationPager->records)) {
1550
    $polytomousKey->annotations = $annotationPager->records;
1551
  }
1552

    
1553
  _load_polytomousKeySubGraph($polytomousKey->root);
1554
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1555
}
1556

    
1557
/**
1558
 * Creates a taxon page view or a chapter of it.
1559
 *
1560
 * The taxon page gives detailed information on a taxon, it shows:
1561
 *  - Taxon name.
1562
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1563
 *    heterotypic and finally followed by misapplied names.
1564
 *    The list is ordered historically.
1565
 *  - All description associated with the taxon.
1566
 *
1567
 * @param string $uuid
1568
 * @param string $chapter
1569
 *   Name of the part to display, valid values are:
1570
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1571
 *
1572
 * @return string
1573
 */
1574
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1575

    
1576
  cdm_check_valid_taxon_page($chapter);
1577
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1578

    
1579

    
1580
  // Display the page for the taxon defined by $uuid.
1581
  // set_last_taxon_page_tab(arg(3));
1582
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1583
  if (!empty($taxonpage)) {
1584
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1585
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1586
  }
1587
  else {
1588
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1589
    return '';
1590
  }
1591
}
1592

    
1593
/**
1594
 * This function will generate the taxon page part ($chapter) and returns a taxonpage object
1595
 * which has two fields, one for the page title and one for the content. Later on in the
1596
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1597
 * function as the function parameters $title and $content.
1598
 *
1599
 * @param string $uuid
1600
 *   the uuid of the taxon to show
1601
 * @param string $chapter
1602
 *   Name of the part to display, valid values are:
1603
 *   'description', 'images', 'synonymy', 'all'.
1604
 *
1605
 * @return object with the following fields:
1606
 *   - title : the title of the page
1607
 *   - content: the content of the page
1608
 *
1609
 * @throws Exception
1610
 *
1611
 */
1612
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1613
  // Taxon object.
1614
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1615
  if (empty($taxon)) {
1616
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1617
    return null;
1618
  }
1619
  $taxonpage = new stdClass();
1620

    
1621
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1622
    'taxon' => $taxon
1623
  ));
1624

    
1625
  // Check if the taxon id contained in the currently selected tree.
1626
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1627

    
1628
  if (!$taxon_in_current_classification) {
1629
    $classifications = get_classifications_for_taxon($taxon);
1630
    RenderHints::pushToRenderStack('not_in_current_classification');
1631
    $taxon_name_markup = render_taxon_or_name($taxon);
1632

    
1633
    if (count($classifications) == 0) {
1634
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1635
        array(
1636
        '!taxonname' => $taxon_name_markup,
1637
        )
1638
      ), 'warning');
1639
    }
1640
    else {
1641
      $trees = '';
1642
      foreach ($classifications as $classification) {
1643
        if (isset($classification->titleCache)) {
1644
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1645
        }
1646
      }
1647

    
1648
      drupal_set_message(format_plural(count($trees),
1649
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1650
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1651
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1652
        ) ,
1653
        'warning');
1654
    }
1655
    RenderHints::popFromRenderStack();
1656
  }
1657

    
1658
  // Render the taxon page.
1659
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1660
  $taxonpage->content = drupal_render($render_array);
1661

    
1662
  return $taxonpage;
1663
}
1664
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1665
{
1666
    if (isset($accession_number)) {
1667
        $specimen_or_observation = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1668

    
1669
        if (isset($specimen_or_observation) && $specimen_or_observation){
1670

    
1671
            $nodes = cdm_dataportal_specimen_page_view($specimen_or_observation->uuid, $specimen_or_observation);
1672
            return $nodes;
1673
        }else{
1674
            return '';
1675
        }
1676

    
1677
    }
1678
}
1679
/**
1680
 * Creates a specimen page view.
1681
 * @param string $uuid the UUID of the specimen
1682
 * @return array|string
1683
 */
1684
function cdm_dataportal_specimen_page_view($uuid, $specimenDTO = null) {
1685

    
1686
    cdm_check_valid_portal_page();
1687

    
1688
    // Display the page for the specimen defined by $uuid.
1689
    if (isset($specimenDTO)){
1690
        //$specimenpage = compose_specimen_array($specimenDTO);
1691
        $dto_array = array($specimenDTO);
1692
        $specimen_array = compose_specimen_array($dto_array);
1693
        $specimen_table = array(
1694
            '#theme' => 'table',
1695
            '#weight' => 2,
1696
            // prefix attributes and rows with '#' to let it pass toF the theme function,
1697
            // otherwise it is handled as child render array
1698

    
1699
            '#attributes' => array('class' => 'specimens'),
1700
            '#rows' => array(),
1701
            '#prefix' => '<div id="specimens">',
1702
            '#suffix' => '</div>',
1703

    
1704

    
1705
        );
1706
        foreach($specimen_array as $value){
1707
            $renderArray = array(
1708
                '#theme' => 'item_list',
1709
                '#items' => array($value),
1710
                '#type' => 'ul');
1711
            $output = drupal_render($renderArray);
1712
//            $specimen_table['#rows'][] = array(
1713
//                // An array of table rows. collabsible row
1714
//                'data' => "",
1715
//                'class' => array('expand_column')
1716
//            );
1717
            $specimen_table['#rows'][] = array(
1718
                // An array of table rows. Every row is an array of cells, or an associative array
1719
                'data' => array($output),
1720
                'class' =>  array(
1721
                    'descriptionElement',
1722
                    'descriptionElement_IndividualsAssociation'
1723
                ),
1724
            );
1725

    
1726

    
1727
        }
1728
        $specimenpage = new stdClass();
1729

    
1730
        $specimenpage->title = theme('theme_cdm_specimen_dto_page_title', array(
1731
            'specimen' => $specimenDTO
1732
        ));
1733

    
1734
        $render_array['markup'] = $specimen_table;
1735

    
1736
//        $render_array['specimens'] = array(
1737
//            '#prefix' => '<div id="specimens" class="page-part">' . ($page_part == 'all' ? '<h2>' . t(cdm_taxonpage_tab_label('Specimens')) . '</h2>' : ''),
1738
//            'content' => $specimen_table, // returns render array
1739
//            '#suffix' => '</div>',
1740
//        );
1741
        $specimenpage->content = drupal_render($render_array);
1742
    }else{
1743
        $specimenpage = cdm_dataportal_specimen_view($uuid);
1744
    }
1745

    
1746
    if (!empty($specimenpage)) {
1747
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1748
    }
1749
    else {
1750
        return '';
1751
    }
1752
}
1753

    
1754
/**
1755
 *
1756
 * Creates a specimen view.
1757
 * @param string $uuid the UUID of the specimen
1758
 * @return array|string
1759
 */
1760
function cdm_dataportal_specimen_view($uuid) {
1761
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1762
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1763
    if (empty($specimen)) {
1764
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1765
        return FALSE;
1766
    }
1767
    $specimenpage = new stdClass();
1768

    
1769
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1770
        'specimen' => $specimen
1771
    ));
1772

    
1773
    // Render the specimen page.
1774
    $render_array = compose_cdm_specimen_page($specimen);
1775
    $specimenpage->content = drupal_render($render_array);
1776

    
1777
    return $specimenpage;
1778
}
1779

    
1780
/**
1781
 *
1782
 * Creates a named area view.
1783
 * @param string $uuid the UUID of the specimen
1784
 *  * @return object
1785
 *   An object with two fields:
1786
 *     - title: the page title
1787
 *     - content: the page content
1788
 */
1789

    
1790
function cdm_dataportal_named_area_view($uuid) {
1791
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1792
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1793
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1794
    return FALSE;
1795
  }
1796
  $named_area_page = new stdClass();
1797

    
1798
  $named_area_page->title = $named_area->representation_L10n;
1799

    
1800
  // Render the specimen page.
1801
  $render_array = compose_cdm_named_area_page($uuid);
1802
  $named_area_page->content = drupal_render($render_array);
1803

    
1804
  return $named_area_page;
1805
}
1806

    
1807
function cdm_dataportal_named_area_page_view($uuid) {
1808

    
1809
  cdm_check_valid_portal_page();
1810

    
1811
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1812
  if (!empty($named_area_page)) {
1813
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1814
  }
1815
  else {
1816
    return '';
1817
  }
1818

    
1819

    
1820
}
1821

    
1822
/**
1823
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1824
 *
1825
 * The node page shows the taxon name title and the list of taxon related
1826
 * with such taxon. Name on the tree already in use.
1827
 *
1828
 * @param string $taxon_name_uuid
1829
 *   The uuid of the CDM TaxonName to show a name page for
1830
 * @param string $taxon_to_hide_uuid
1831
 *   A taxon which should not be displayed in the taxon list
1832
 * @param $redirect_to_taxon
1833
 *   Automatically redirect to the related taxon if there is only one
1834
 *   accepted taxon for this name.
1835
 * @param string $highlite_synonym_uuid
1836
 *   Optinal parameter wich takes another taxon uuid, if given the
1837
 *   target taxon pages will show the syonymy tab where the taxon
1838
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1839
 *   in case it is found on this page.
1840
 *
1841
 * @return mixed
1842
 *   The formatted name page as node.
1843
 */
1844
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = false) {
1845

    
1846
  cdm_check_valid_portal_page();
1847

    
1848
  $taxonname_page = cdm_dataportal_name_view(
1849
    is_uuid($taxon_name_uuid) ? $taxon_name_uuid : null,
1850
    is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : null,
1851
    $redirect_to_taxon == 'redirect_to_taxon',
1852
    is_uuid($synonym_uuid) ? $synonym_uuid : null);
1853
  if (!empty($taxonname_page)) {
1854
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1855
  }
1856
  else {
1857
    return '';
1858
  }
1859
}
1860

    
1861
/**
1862
 * View function for a TaxonName page.
1863
 *
1864
 * The name page lists all taxa for which the name specified by the
1865
 * $taxon_name_uuid is being used. I case there is only one name the
1866
 * page automatically redirects ti the according taxon page. Otherwise
1867
 * the list of names is displayed.
1868
 *
1869
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1870
 * list of taxa. This is useful for example when referencing from a taxon
1871
 * to the name page and the referring taxon should not be repeaded in the
1872
 * name page.
1873
 *
1874
 *
1875
 * @param string $taxon_name_uuid
1876
 *   The uuid of the CDM TaxonName to show a name page for
1877
 * @param string $taxon_to_hide_uuid
1878
 *   A taxon which should not be displayed in the taxon list
1879
 * @param $redirect_to_taxon
1880
 *   Automatically redirect to the related taxon if there is only one
1881
 *   accepted taxon for this name.
1882
 * @param string $highlite_synonym_uuid
1883
 *   Optional parameter which takes another taxon uuid, if given the
1884
 *   target taxon pages will show the synonymy tab where the taxon
1885
 *   referenced by the $highlite_synonym_uuid will be highlighted
1886
 *   in case it is found on this page.
1887
 *
1888
 * @return object|boolean
1889
 *   An object with two fields:
1890
 *     - title: the page title
1891
 *     - content: the page content
1892
 *   or FALSE
1893
 *
1894
 */
1895
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $redirect_to_taxon, $highlite_synonym_uuid = NULL) {
1896
  // Getting the full taxonname object from the server.
1897
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1898
  if (!$taxon_name) {
1899
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1900
    return FALSE;
1901
  }
1902
  cdm_load_tagged_full_title($taxon_name);
1903
  // Searching for all the taxa connected with the taxon name on the tree
1904
  // in use.
1905
  $name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1906
  $restrictions = array(new Restriction("name.titleCache","EXACT", array($name->titleCache), 'AND'));
1907
  $init_strategy = array(
1908
    "name.titleCache",
1909
    "name.nomenclaturalReference.authorship",
1910
    "name.nomenclaturalReference.inReference.authorship",
1911
    "name.nomenclaturalReference.inReference.inReference.authorship",
1912
    "name.nomenclaturalReference.inReference.inReference.inReference.authorship"
1913
  );
1914
  $taxa = cdm_ws_fetch_all_by_restriction("Taxon", $restrictions, $init_strategy);
1915

    
1916
  // Removing the name where we came from.
1917
  foreach ($taxa as $k => &$taxon) {
1918
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1919
      unset($taxa[$k]);
1920
    }
1921
  }
1922
  // Show the taxa list or go to the singular taxon.
1923
  if (sizeof($taxa) == 1 && $redirect_to_taxon) {
1924
    // redirect to the taxon if there is only one.
1925
    $singleTaxon = array_pop($taxa);
1926
    if ($singleTaxon->class != "Taxon") {
1927
      // It is a Synonym -> look for the accepted.
1928
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1929
      if (!empty($highlite_synonym_uuid)) {
1930
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1931
      }
1932
      else {
1933
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1934
      }
1935
    }
1936
    else {
1937
      // It is an accepted taxon.
1938
      if (!empty($highlite_synonym_uuid)) {
1939
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1940
      }
1941
      else {
1942
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1943
      }
1944
    }
1945
  }
1946
  else {
1947
    // display the name page content
1948
    $taxon_name_page = new stdClass();
1949
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1950
    $content = array();
1951

    
1952
    RenderHints::pushToRenderStack('name_page');
1953
    RenderHints::setFootnoteListKey('name_page');
1954
    $content['taxon_name'] = markup_to_render_array(render_taxon_or_name($taxon_name));
1955

    
1956

    
1957
    // name relationships
1958
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $taxon_name->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1959
    if(count($name_relations) > 0){
1960
      $content['name_relationships'] = compose_name_relationships_list($name_relations, $taxon_name->uuid, null);
1961
    }
1962

    
1963
    // type designations
1964
    $type_designations_render_array = compose_type_designations($taxon_name->uuid);
1965

    
1966
    $content['type_designations'] = $type_designations_render_array['type_designations'];
1967
    $content['map'] = $type_designations_render_array['map'];
1968
    // registrations
1969
    $registrationDTOs= cdm_ws_fetch_all(CDM_WS_REGISTRATION_DTO,  array('nameUuid' => $taxon_name_uuid));
1970
    if(isset($registrationDTOs) && count($registrationDTOs ) > 0 ){
1971
      $content['registrations'][] = markup_to_render_array('<h2>' . t("Registrations") . '</h2>') ;
1972
      foreach ($registrationDTOs as $regDTO){
1973
        $content['registrations'][] = compose_registration_dto_compact($regDTO);
1974
      }
1975
    }
1976

    
1977

    
1978
    // related taxa
1979
    if ($taxa) {
1980
      $content['related_taxa_header'] = markup_to_render_array("<h2>Taxa for this name</h2>");
1981
      $content['related_taxa'] = compose_list_of_taxa($taxa);
1982
    }
1983
    else {
1984
      $content['related_taxa'] = markup_to_render_array('This name is not assigned to a taxon.', null, '<div class="no-taxon-message">', '</div>');
1985
    }
1986

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

    
1989
    $taxon_name_page->content = $content;
1990
    RenderHints::popFromRenderStack();
1991
    RenderHints::clearFootnoteListKey();
1992
    return $taxon_name_page;
1993
  }
1994
}
1995

    
1996

    
1997
/**
1998
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1999
 *
2000
 * @param string  $registration_identifier_encoded
2001
 *   The persistent identifier of the registration urlencoded.
2002
 * @return mixed
2003
 *   The formatted registration page as node.
2004
 */
2005
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
2006

    
2007
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
2008
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
2009
  return cdm_node_show_simulate($registration_page);
2010
}
2011

    
2012
function cdm_dataportal_registration_view($registration_identifier_encoded) {
2013

    
2014
  $registration_identifier = urldecode($registration_identifier_encoded);
2015

    
2016
  RenderHints::pushToRenderStack('registration_page');
2017
  RenderHints::setFootnoteListKey('registration_page');
2018

    
2019
  $render_array = array();
2020
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
2021
  if($registration_dto){
2022

    
2023
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
2024
    $render_array = compose_registration_dto_full($registration_dto, true);
2025

    
2026
  } else {
2027
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
2028
    if(isset($status_text->String)) {
2029
      $status_text = strtolower($status_text->String);
2030
      if($status_text == 'preparation' || $status_text == 'curation'){
2031
        $status_text = 'in ' . $status_text;
2032
      }
2033
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
2034
      //$status_message;
2035
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
2036
    } else {
2037
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
2038
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
2039
    }
2040
  }
2041

    
2042
  $render_array = array(
2043
    '#prefix' => '<div id="registration">',
2044
    'registration' => $render_array,
2045
    '#suffix' => '</div>',
2046
  );
2047

    
2048
  RenderHints::popFromRenderStack();
2049
  RenderHints::clearFootnoteListKey();
2050

    
2051
  return $render_array ;
2052
}
2053

    
2054

    
2055
/**
2056
 * Creates a page with the advance search form.
2057
 *
2058
 * NOTE: The advance search form allows searching for taxa.
2059
 */
2060
function cdm_dataportal_view_search_advanced() {
2061
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2062
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2063
}
2064

    
2065
/**
2066
 * Creates a page with the blast search form.
2067
 *
2068
 * NOTE: The advance search form allows searching for specimen in blast DB.
2069
 */
2070
function cdm_dataportal_view_search_blast() {
2071
    drupal_set_title(t('Blast search'), PASS_THROUGH);
2072
    return drupal_get_form('cdm_dataportal_search_blast_form');
2073
}
2074

    
2075
/**
2076
 * Creates a page with the search form for searching by taxon descriptions.
2077
 */
2078
function cdm_dataportal_view_search_taxon_by_description() {
2079
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2080
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2081
}
2082

    
2083
/**
2084
 * Executes the search and generates the result list of taxa.
2085
 */
2086
function cdm_dataportal_view_search_results_taxon() {
2087

    
2088
  $taxonPager = cdm_dataportal_search_taxon_execute();
2089

    
2090
  $showThumbnails = do_showThumbnails();
2091

    
2092
  $setSessionUri = url('cdm_api/setvalue/session', array(
2093
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2094
  ));
2095

    
2096
  drupal_add_js('jQuery(document).ready(function() {
2097

    
2098
      // init
2099
      if(' . $showThumbnails . ' == 1){
2100
          jQuery(\'.media_gallery\').show(20);
2101
      } else {
2102
          jQuery(\'.media_gallery\').hide(20);
2103
      }
2104

    
2105
      // add change handler
2106
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2107
      function(event){
2108
        var state = 0;
2109
        if(jQuery(this).is(\':checked\')){
2110
          jQuery(\'.media_gallery\').show(20);
2111
          state = 1;
2112
        } else {
2113
          jQuery(\'.media_gallery\').hide(20);
2114
        }
2115
        // store state in session variable
2116
        var uri = \'' . $setSessionUri . '\' + state;
2117
        jQuery.get(uri);
2118
      });
2119
  });',
2120
  array('type' => "inline", 'scope' => JS_DEFAULT));
2121

    
2122
  drupal_set_title(t('Search results'), PASS_THROUGH);
2123

    
2124
  return theme('cdm_search_taxa_results', array(
2125
    'pager' => $taxonPager,
2126
    'path' => 'cdm_dataportal/search/results/taxon',
2127
    ));
2128
}
2129

    
2130
/**
2131
 * Executes the blast search and generates the result list of specimen.
2132
 */
2133
function cdm_dataportal_view_search_results_specimen() {
2134

    
2135
    $specimenPager = cdm_dataportal_search_blast_execute();
2136

    
2137
    return theme('cdm_search_specimen_results', array(
2138
        'pager' => $specimenPager,
2139
        'path' => 'cdm_dataportal/search/results/specimen',
2140
    ));
2141
}
2142

    
2143

    
2144
/**
2145
 * Executes the search for registrations and generates the result list..
2146
 */
2147
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2148

    
2149
  switch($mode ){
2150
    case 'taxongraph':
2151
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2152
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2153
      break;
2154
    case 'filter':
2155
    default:
2156
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2157
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2158
  }
2159
  $block->title = null;
2160

    
2161
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2162

    
2163
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2164
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2165
  $render_array = array_merge($render_array, $registrations_pager_array);
2166

    
2167
  return $render_array;
2168
}
2169

    
2170

    
2171
/**
2172
 * Provides the standard image which indicated a loading process
2173
 *
2174
 * @return string
2175
 *  The img html tag
2176
 */
2177
function loading_image_html() {
2178
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2179
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2180
}
2181

    
2182
/**
2183
 * Returns the state of the the showThumbnails flag set in the
2184
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2185
 *
2186
 * @return boolean
2187
 *    returns 1 if the flag is set
2188
 */
2189
function do_showThumbnails() {
2190
  static $showThumbnails = null;
2191

    
2192
  if($showThumbnails == null) {
2193
    $showThumbnails = 0;
2194
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2195
      $showThumbnails = 0;
2196
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2197
      $showThumbnails = is_array($search_gallery_settings)
2198
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2199
        && (
2200
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2201
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2202
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2203
            )
2204
         ? 1 : 0;
2205

    
2206
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2207
    }
2208
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2209
    if (!is_numeric($showThumbnails)) {
2210
      $showThumbnails = 1;
2211
    }
2212
  }
2213

    
2214
  return $showThumbnails;
2215
}
2216

    
2217

    
2218

    
2219
/* ====================== other functions ====================== */
2220
/**
2221
 * Creates a URL to the taxon page specified by the $uuid parameter.
2222
 *
2223
 * The URL will be prepended with a path element to a specific taxon page tab.
2224
 *
2225
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2226
 * be set globally in the administrative settings or individually in the user
2227
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2228
 * the last portal will stay on this last tab.
2229
 *
2230
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2231
 * internal mechanism by a specific value.
2232
 *
2233
 * @param string $uuid
2234
 *   The UUID of the taxon.
2235
 * @param string $page_tab
2236
 *   Overwriting the preset mechanism by defining specific value for the
2237
 *   taxon page tab.
2238
 *
2239
 * @return string
2240
 *   The created URL.
2241
 */
2242
function path_to_taxon($uuid, $page_tab = FALSE) {
2243

    
2244
  $tab = get_default_taxon_tab();
2245
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2246

    
2247
  if (!$uuid) {
2248
    return FALSE;
2249
  }
2250

    
2251
  if ($page_tab) {
2252
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2253
  }
2254
  elseif (!$tab || strtolower($tab) == 'general') {
2255
    return 'cdm_dataportal/taxon/' . $uuid;
2256
  }
2257
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2258
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2259
  }
2260
  else {
2261
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2262
  }
2263
}
2264

    
2265
function path_to_specimen($uuid) {
2266

    
2267
    if (!$uuid) {
2268
        return FALSE;
2269
    }
2270
    else {
2271
        return 'cdm_dataportal/occurrence/' . $uuid;
2272
    }
2273
}
2274

    
2275
function path_to_specimen_by_accession_number($accession_number) {
2276

    
2277
    if (!$accession_number) {
2278
        return FALSE;
2279
    }
2280
    else {
2281
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2282
    }
2283
}
2284

    
2285
function path_to_named_area($uuid) {
2286

    
2287
  if (!$uuid) {
2288
    return FALSE;
2289
  }
2290
  else {
2291
    return 'cdm_dataportal/named_area/' . $uuid;
2292
  }
2293
}
2294

    
2295
/**
2296
 * Creates a URL to show a synonmy in the according taxon page.
2297
 *
2298
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2299
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2300
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2301
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2302
 * in the page
2303
 *
2304
 * @param string $synonymUuid
2305
 *    The uuid of the synonym
2306
 * @param string $acceptedUuid
2307
 *    The uuid of the according accepted taxon
2308
 * @return string
2309
 *    The URL to show a synonmy in the according taxon page
2310
 */
2311
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2312
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2313
  return url($acceptedPath, array(
2314
      'query' => array(
2315
        // highlite the synony in the synonymy
2316
        'highlite' => $synonymUuid,
2317
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2318
        // see theme_taxon_page_title()
2319
        'acceptedFor' => $synonymUuid
2320
      ),
2321
      'fragment' => $synonymUuid
2322
  ));
2323

    
2324
}
2325

    
2326
/**
2327
 * Composes the drupal path to the key identified by the uuid.
2328
 *
2329
 * @param string $keyType
2330
 *    the key typer corresponds to the specific class of the CDM
2331
 *    IdentificationKey. Possible values are
2332
 *      -PolytomousKey
2333
 *      -MultimediaKey
2334
 *      - ...
2335
 * @param string $keyUuid
2336
 *   The UUID of the key
2337
 */
2338
function path_to_key($keyType, $keyUuid) {
2339
  if (!$keyUuid || !$keyType) {
2340
    return FALSE;
2341
  }
2342
  $keyType{0} = strtolower($keyType{0});
2343
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2344
}
2345

    
2346
/**
2347
 * Composes the drupal path to the reference identified by the uuid.
2348
 *
2349
 * @param $uuid string String representation of the registration entity uuid.
2350
 *
2351
 * @return string
2352
 *  The drupal path
2353
 *
2354
 */
2355
function path_to_reference($uuid) {
2356
  if (!$uuid) {
2357
    return FALSE;
2358
  }
2359
  return 'cdm_dataportal/reference/' . $uuid;
2360
}
2361

    
2362
/**
2363
 * Composes the drupal path to the reference identified by the uuid.
2364
 *
2365
 * @param string $identifier
2366
 *  The persistent identifier of the registration entity (Registration.identifier).
2367
 * @return string
2368
 *  The drupal path
2369
 */
2370
function path_to_registration($identifier) {
2371

    
2372
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2373
    return $identifier;
2374
  } else {
2375
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2376
  }
2377
}
2378

    
2379
/**
2380
 * Creates the path to a cdm_dataportal taxon name page.
2381
 *
2382
 * @param string $taxon_name_uuid
2383
 *   The uuid as string of the CDM TaxonName to show a name page for
2384
 * @param string $taxon_to_hide_uuid
2385
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2386
 * @param string $highlited_synonym_uuid
2387
 *   Optional parameter which takes another taxon uuid, if given the
2388
 *   target taxon pages will show the synonymy tab where the taxon
2389
 *   referenced by the $highlite_synonym_uuid will be highlighted
2390
 *   in case it is found on this page.
2391
 * @param $redirect_to_taxon
2392
 *   If true, the name page will redirect to the related taxon if there is a single one
2393
 *   for this name only.
2394
 *
2395
 * @return string
2396
 *  URI path element as string
2397
 */
2398
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2399
  $res = FALSE;
2400
  if ($name_uuid) {
2401
    $res = 'cdm_dataportal/name/' . $name_uuid .
2402
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2403
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2404
    '/' . ($redirect_to_taxon || variable_get(CDM_NAME_PAGE_AUTOREDIRECT, 0) ? "redirect_to_taxon" : "");
2405
  }
2406

    
2407
  return $res;
2408
}
2409

    
2410
/**
2411
 * Composes the drupal path to the media entity identified by the uuid.
2412
 *
2413
 * @param string $uuid
2414
 *  The persistent identifier of the entity entity
2415
 * @return string
2416
 *  The drupal path
2417
 */
2418
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2419
  if (!$uuid) {
2420
    return FALSE;
2421
  }
2422
  $out = 'cdm_dataportal/media/' . $uuid;
2423
  if ($representaion_uuid) {
2424
    $out .= '/' . $representaion_uuid;
2425
    if (is_numeric($partId)) {
2426
      $out .= '/' . $partId;
2427
    }
2428
  }
2429
  return $out;
2430
}
2431

    
2432
/**
2433
 * Compares thisRank with thatRank.
2434
 *
2435
 * Returns a negative integer, zero, or a positive integer
2436
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2437
 * e.g:
2438
 * <ul>
2439
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2440
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2441
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2442
 * </ul>
2443
 * <p>
2444
 * This compare logic of the underlying webservice is the
2445
 * <b>inverse logic</b> of the the one implemented in
2446
 * java.lang.Comparable#compareTo(java.lang.Object)
2447
 *
2448
 * @param $thisRankUuid
2449
 * @param $thatRankUuid
2450
 *
2451
 * @return int
2452
 *   A negative integer, zero, or a positive integer
2453
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2454
 */
2455
function rank_compare($thisRankUuid, $thatRankUuid) {
2456
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2457
  return $result->Integer;
2458
}
2459

    
2460
/**
2461
 * Composes an HTML element class attribute value composed of
2462
 * the short-name of the cdm class and the uuid of the entity.
2463
 * This class attribute should be used wherever an cdm-entity is rendered.
2464
 *
2465
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2466
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2467
 * Taxon uuid is added also as taxon_uuid:<uuid>
2468
 *
2469
 * These according class selectors in css must be escaped, eg:
2470
 *    .cdm\:TextData
2471
 *
2472
 * @param $cdm_entity
2473
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2474
 */
2475
function html_class_attribute_ref($cdm_entity) {
2476

    
2477
  $attributes = '';
2478
  if (is_cdm_entity($cdm_entity)) {
2479
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2480
  } else if($cdm_entity->class == 'TypedEntityReference') {
2481
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2482
  }
2483
  if($cdm_entity->class == 'TaxonNodeDto'){
2484
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2485
  }
2486
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2487
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2488
  }
2489
  return $attributes;
2490
}
2491

    
2492

    
2493
/**
2494
 * Creates a short version of a taxonname.
2495
 *
2496
 * The short name is created by using the taggedTitle field of
2497
 * TaxonNodeDTO instances.
2498
 * If the taggedTitle if empty the fullname will be returned.
2499
 *
2500
 * @param object $taxonNodeDTO
2501
 *   A TaxonNodeDTO object
2502
 *
2503
 * @return string
2504
 */
2505
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2506

    
2507
  $nameStr = '';
2508

    
2509
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2510

    
2511
  // Get all tagged text tokens of the scientific name.
2512
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2513
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2514
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2515
    }
2516
  }
2517
  $nameStr = trim($nameStr);
2518

    
2519
  if ($nameStr) {
2520

    
2521
    // Do not return short names for these.
2522
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2523
      return $nameStr;
2524
    }
2525

    
2526
    /*
2527
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2528
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2529
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2530
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2531
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2532
    */
2533
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2534
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2535
      return $matches[1][0] . "." . $matches[3][0];
2536
    }
2537
    else {
2538
      return $nameStr;
2539
    }
2540
  }
2541
  else {
2542
    return $taxonNodeDTO->titleCache;
2543
  }
2544
}
2545

    
2546
/**
2547
 * Check if a taxon is accepted by the current taxonomic tree.
2548
 *
2549
 * @param mixed $taxon
2550
 *   The Taxon obkect to check.
2551
 *
2552
 * @return bool
2553
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2554
 */
2555
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2556

    
2557
  $defaultTreeUuid = get_current_classification_uuid();
2558

    
2559
  if (isset($taxon->taxonNodes)) {
2560
    $taxonNodes = $taxon->taxonNodes;
2561
  }
2562
  else {
2563
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2564
  }
2565

    
2566
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2567
    foreach ($taxonNodes as $node) {
2568
      if (isset($node->classification)){
2569
        if(is_object($node->classification)) {
2570
          if ($node->classification->uuid == $defaultTreeUuid) {
2571
            return TRUE;
2572
          }
2573
        }
2574
        else {
2575
          if ($node->classification == $defaultTreeUuid) {
2576
            return TRUE;
2577
          }
2578
        }
2579
      }
2580
    }
2581
  }
2582

    
2583
  return FALSE;
2584
}
2585

    
2586
/**
2587
 * Checks is the source has one of the given types.
2588
 *
2589
 * @param object $source
2590
 *   The original source entity
2591
 * @param array $types
2592
 *   An array of elementd of the OriginalSourceType enumeration
2593
 *   If not set the default will be used which is:
2594
 *    - Lineage
2595
 *    - PrimaryMediaSource
2596
 *    - PrimaryTaxonomicSource
2597
 *    - Unknown
2598
 *    - Other
2599
 * @return boolean
2600
 */
2601
  function _is_original_source_type($source, $types = null) {
2602
    // this is the default
2603
    // maybe this should also be put into the settings
2604
    static $default = array(
2605
      OriginalSourceType::Lineage,
2606
      OriginalSourceType::PrimaryMediaSource,
2607
      OriginalSourceType::PrimaryTaxonomicSource,
2608
      OriginalSourceType::Unknown,
2609
      OriginalSourceType::Other,
2610
    );
2611

    
2612
    if(!$types){
2613
      $types = $default;
2614
    }
2615
    return isset($source->type) && in_array($source->type, $types);
2616
  }
2617

    
2618
/**
2619
 * Collects all the media from a list of description elements.
2620
 *
2621
 * @param array $descriptionElements
2622
 *   The description elements from which to collect the media.
2623
 *
2624
 * @return array
2625
 *   The output with all the collected media.
2626
 */
2627
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2628

    
2629
  $outArrayOfMedia = array();
2630

    
2631
  // Avoiding a warning box in Drupal for Flora Malesiana.
2632
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2633
    foreach ($descriptionElements as $descriptionElement) {
2634
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2635
        foreach ($descriptionElement->media as $media) {
2636
          if (is_object($media)) {
2637
            $outArrayOfMedia[] = $media;
2638
          }
2639
        }
2640
      }
2641
    }
2642
  }
2643
  return $outArrayOfMedia;
2644
}
2645

    
2646
/**
2647
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2648
 *
2649
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2650
 *
2651
 * @see cdm_fetch_visible_annotations()
2652
 *
2653
 * @param array $cdm_entities
2654
 *   An array of CdmBase instances or a single instance.
2655
 * @param string $footnote_list_key_suggestion
2656
 *
2657
 * @return array of footnote keys
2658
 */
2659
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2660

    
2661
  $footNoteKeys = array();
2662

    
2663
  // Is argument cdmBase an array?
2664
  if (!is_array($cdm_entities)) {
2665
    $cdmBase_array = array();
2666
    $cdmBase_array[] = $cdm_entities;
2667
  }
2668
  else {
2669
    $cdmBase_array = $cdm_entities;
2670
  }
2671

    
2672
  // Getting the key for the footnotemanager.
2673
  if (isset($footnote_list_key_suggestion)) {
2674
    $footnote_list_key = $footnote_list_key_suggestion;
2675
  }
2676
  else {
2677
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2678
  }
2679

    
2680
  // Adding the footnotes keys.
2681
  foreach ($cdmBase_array as $cdmBase_element) {
2682
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2683
    if (is_array($annotations)) {
2684
      foreach ($annotations as $annotation) {
2685
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2686
      }
2687
    }
2688
  }
2689

    
2690
  return $footNoteKeys;
2691
}
2692

    
2693

    
2694
/**
2695
 * Creates a CDM Dynabox.
2696
 *
2697
 * @param string $dynabox_id
2698
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2699
 * @param string $label
2700
 *   The clickable text to show.
2701
 * @param string $content_url
2702
 *   The cdm REST service request url wich will deliver the content to be shown
2703
 *   once the dynabox toggles open.
2704
 * @param string $theme
2705
 *   The theme to be used for rendering the cdm REST service response with is
2706
 *   returned from the $content_url.
2707
 * @param string $link_alt_text
2708
 *   The value for the alt attribute of the dynabox link.
2709
 * @param array $enclosingtags
2710
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2711
 *   element itself, $enclosingtags[1] is the tag to be used for the
2712
 *   dynabox_content (optional)
2713
 * @param array $attributes
2714
 * @param $content_element_selector
2715
 *   Optional jQuery selector which can be used to reference a dom element which should
2716
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2717
 *  element will be placed in this container.
2718
 *
2719
 * @param string $open_callback
2720
 *   optional javascript call back function to be triggered after toggling the box to
2721
 *   the open state.
2722
 * @param string $close_callback
2723
 *   optional javascript call back function to be triggered after toggling the box to
2724
 *   the closed state.
2725
 * @return string Returns HTML for a dynabox.
2726
 * Returns HTML for a dynabox.
2727
 */
2728
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2729
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2730
                     $content_element_selector = null,
2731
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2732
  $out = '';
2733

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

    
2737
  if(!array_key_exists('class', $attributes)) {
2738
    $attributes['class'] = array();
2739
  }
2740
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2741
  $dynabox_attributes = drupal_attributes($attributes);
2742

    
2743

    
2744
  _add_js_domEvent(); // requires domEvent.js
2745
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2746
  drupal_add_js("
2747
  jQuery(document).ready(
2748
      function() {
2749
        dynabox('". $dynabox_id ."',
2750
          {
2751
            open_callback: " . $open_callback .",
2752
            close_callback: " . $close_callback .
2753
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2754
          }
2755
        );
2756
      }
2757
   );",
2758
   array(
2759
    'type'=>'inline',
2760
    'scope'=>'footer'
2761
    )
2762
  );
2763

    
2764

    
2765
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2766
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2767
  $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>';
2768
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2769
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2770
  $out .= '    </' . $enclosingtags[1] . '>';
2771
  $out .= '  </' . $enclosingtags[0] . '>';
2772
  $out .= '<!-- dynabox end -->';
2773
  return $out;
2774
}
2775

    
2776
/**
2777
 * Checks whether a feature has any description elements.
2778
 *
2779
 * @param mixed $featureNode
2780
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2781
 *
2782
 * @see _mergeFeatureTreeDescriptions()
2783
 *
2784
 * @return bool
2785
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2786
 *   contains at least one non empty TextData or at least one DescriptionElement
2787
 *   of an other type. A TextData element holding a multilanguageText or a
2788
 *   source reference is considered to be not empty.
2789
 *
2790
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2791
 *       see $block_content_is_not_empty in make_feature_block_list() and
2792
 *       $feature_block_has_content in compose_feature_block_items_generic
2793
 */
2794
function has_feature_node_description_elements($featureNode) {
2795

    
2796
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2797
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2798
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2799
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2800
          && $descriptionElement->multilanguageText_L10n->text != ''
2801
          || isset($descriptionElement->sources[0])
2802
          || isset($descriptionElement->media[0]) ) {
2803
          return TRUE;
2804
        }
2805
      }
2806
    }
2807
  }
2808
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2809
    foreach ($featureNode->childNodes as $child) {
2810
      if (has_feature_node_description_elements($child)) {
2811
        return TRUE;
2812
      }
2813
    }
2814
  }
2815
  return FALSE;
2816
}
2817

    
2818
/**
2819
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2820
 *
2821
 * @param $chapter
2822
 *   The taxon page chapter or part
2823
 */
2824
function cdm_check_valid_taxon_page($chapter){
2825
  static $taxon_tabs = null;
2826

    
2827
  cdm_check_valid_portal_page();
2828

    
2829
  if($taxon_tabs == null){
2830
    $taxon_tabs = array('all', 'description');
2831
    foreach(get_taxon_tabs_list() as $tab){
2832
      $taxon_tabs[] = strtolower($tab);
2833
    }
2834
  }
2835

    
2836
  if(!in_array($chapter, $taxon_tabs)){
2837
    // oops this is not a valid chapter name
2838
    http_response_code(404); // 404 = Not Found
2839
  }
2840

    
2841
}
2842

    
2843
function check_js_devel_mode_disabled() {
2844
  if(variable_get('cdm_js_devel_mode', FALSE)) {
2845
    drupal_set_message(t('The !url1 is enabled.
2846
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
2847
      '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
2848
    )),
2849
      'warning'
2850
    );
2851
  }
2852
}
2853

    
2854
/**
2855
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2856
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2857
 *
2858
 * @param $preg_pattern
2859
 *   Optional regular expression pattern to be used in preg_match().
2860
 */
2861
function cdm_check_valid_portal_page($preg_pattern = null){
2862
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2863
  if($preg_pattern === null){
2864
    $preg_pattern = $ends_with_file_suffix_pattern;
2865
  }
2866
  if(preg_match($preg_pattern, $_GET['q'])){
2867
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2868
    http_response_code(404); // 404 = Not Found
2869
    exit('HTTP 404');
2870
  }
2871
  check_js_devel_mode_disabled();
2872
}
2873

    
2874
/**
2875
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2876
 *
2877
 * @param $text_a
2878
 * @param $text_b
2879
 * @return string
2880
 */
2881
function diff_viewer($text_a, $text_b) {
2882

    
2883
  static $diff_viewer_count = 0;
2884

    
2885
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2886

    
2887
  // http://code.stephenmorley.org/php/diff-implementation/
2888
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2889
  drupal_add_css(drupal_get_path('module',
2890
      'cdm_dataportal') . '/css/diff.css');
2891
  _add_jquery_ui();
2892
  drupal_add_js(
2893
    'jQuery(document).ready( function(){
2894
        jQuery(\'#' . $element_id . '\').accordion({
2895
        collapsible: true,
2896
        active: false,
2897
        fillSpace: true,
2898
        }).children(\'div\').css({ \'height\': \'auto\' });
2899
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2900
     });'
2901
    , array(
2902
    'type' => 'inline',
2903
    'scope' => 'footer'
2904
  ));
2905

    
2906
  $diff = Diff::compare($text_a,
2907
    $text_b);
2908
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2909
    . Diff::toTable($diff, '', '')
2910
    . '</div></div>';
2911
  return $diff_viewer_markup;
2912
}
2913

    
2914

    
(10-10/18)