Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_dataportal.module @ 2f65af04

History | View | Annotate | Download (89.3 KB)

1
<?php
2
/**
3
 * @file
4
 * Module to provide a CDM Dataportal.
5
 *
6
 * @copyright
7
 *   (C) 2007-2012 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
18
 */
19

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

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

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

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

    
282
  global $base_url;
283

    
284

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

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

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

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

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

    
354

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

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

    
365
    return '';
366
  }
367

    
368
/**
369
 * Adds the css  containing the font awesome icons to the html header.
370
 */
371
function _add_font_awesome_font()
372
{
373
//<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
374

    
375
  $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/font-awesome-4.6.3/css/font-awesome.min.css';
376
  //$font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css";
377

    
378
  drupal_add_html_head_link(
379
    array(
380
      'href' => $font_awesome_css_uri,
381
      'rel' => 'stylesheet'
382
    )
383
  );
384
}
385

    
386

    
387
/* ====================== hook implementations ====================== */
388
  /**
389
   * Implements hook_permission().
390
   *
391
   * Valid permissions for this module.
392
   *
393
   * @return array
394
   *   An array of valid permissions for the cdm_dataportal module.
395
   */
396
  function cdm_dataportal_permission() {
397
    return array(
398
      'administer cdm_dataportal' => array(
399
        'title' => t('Administer CDM DataPortal settings'),
400
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
401
      ),
402
      'access cdm content' => array(
403
        'title' => t('Access CDM content'),
404
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
405
      ),
406
    );
407
  }
408

    
409
/**
410
 * Implements hook_menu().
411
 */
412
function cdm_dataportal_menu() {
413
  $items = array();
414

    
415
  // @see settings.php.
416
  cdm_dataportal_menu_admin($items);
417
  cdm_dataportal_menu_help($items);
418

    
419
  $items['cdm_dataportal/names'] = array(
420
    'page callback' => 'cdm_dataportal_view_names',
421
    'access arguments' => array('access cdm content'),
422
    'type' => MENU_CALLBACK,
423
  );
424

    
425
  // Optional callback arguments: page.
426
  $items['cdm_dataportal/taxon'] = array(
427
    'page callback' => 'cdm_dataportal_taxon_page_view',
428
    'access arguments' => array('access cdm content'),
429
    'type' => MENU_CALLBACK,
430
    // Expected callback arguments: uuid.
431
  );
432

    
433
  $items['cdm_dataportal/occurrence'] = array(
434
        'page callback' => 'cdm_dataportal_specimen_page_view',
435
        'access arguments' => array('access cdm content'),
436
        'type' => MENU_CALLBACK,
437
        // Expected callback arguments: uuid.
438
    );
439

    
440
    $items['cdm_dataportal/specimen/accession_number'] = array(
441
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
442
        'access arguments' => array('access cdm content'),
443
        'type' => MENU_CALLBACK,
444
        // Expected callback arguments: accession number.
445
    );
446
  $items['cdm_dataportal/named_area'] = array(
447
    'page callback' => 'cdm_dataportal_named_area_page_view',
448
    'access arguments' => array('access cdm content'),
449
    'type' => MENU_CALLBACK,
450
    // Expected callback arguments: uuid.
451
  );
452

    
453
  $items['cdm_dataportal/name'] = array(
454
    'page callback' => 'cdm_dataportal_name_page_view',
455
      /*
456
    'page arguments' => array(
457
       'taxon_name_uuid',
458
       'taxon_to_hide_uuid',
459
       'synonym_uuid' => NULL
460
      ),
461
      */
462
    'access arguments' => array('access cdm content'),
463
    'type' => MENU_CALLBACK,
464
    // Expected callback arguments: uuid.
465
  );
466

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

    
474
  $items['cdm_dataportal/reference/list'] = array(
475
    'page callback' => 'cdm_dataportal_view_reference_list',
476
    'access arguments' => array('access cdm content'),
477
    'type' => MENU_CALLBACK,
478
    // Expected callback arguments: uuid.
479
  );
480

    
481
  $items['cdm_dataportal/media'] = array(
482
    'page callback' => 'cdm_dataportal_view_media',
483
    'access arguments' => array('access cdm content'),
484
    'type' => MENU_CALLBACK,
485
    // Expected callback arguments:
486
    // uuid, mediarepresentation_uuid, part_uuid or part#.
487
  );
488

    
489
  $items['cdm_dataportal/polytomousKey'] = array(
490
    'page callback' => 'cdm_dataportal_view_polytomousKey',
491
    'access arguments' => array('access cdm content'),
492
    'type' => MENU_CALLBACK,
493
    // Expected callback arguments: polytomousKey->uuid.
494
  );
495

    
496
  $items['cdm_dataportal/search'] = array(
497
    'page callback' => 'cdm_dataportal_view_search_advanced',
498
    'access arguments' => array('access cdm content'),
499
    'type' => MENU_CALLBACK,
500
  );
501

    
502
  $items['cdm_dataportal/search/advanced'] = array(
503
    'title' => 'Advanced', // will be passed through t()
504
    'page callback' => 'cdm_dataportal_view_search_advanced',
505
    'access arguments' => array('access cdm content'),
506
    'type' => MENU_DEFAULT_LOCAL_TASK,
507
  );
508
  if (variable_get(CDM_SEARCH_BLAST_ENABLED)) {
509
    $items['cdm_dataportal/search/blast'] = array(
510
        'title' => 'Blast', // will be passed through t()
511
        'page callback' => 'cdm_dataportal_view_search_blast',
512
        'access arguments' => array('access cdm content'),
513
        'type' => MENU_LOCAL_TASK,
514
    );
515
  }
516
  $items['cdm_dataportal/search/taxon_by_description'] = array(
517
    'title' => 'By content category', // will be passed through t()
518
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
519
    'access arguments' => array('access cdm content'),
520
    'type' => MENU_LOCAL_TASK,
521
  );
522
  $items['cdm_dataportal/search/results/taxon'] = array(
523
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
524
    'access arguments' => array('access cdm content'),
525
    'type' => MENU_CALLBACK,
526
  );
527

    
528

    
529
  $items['cdm_dataportal/search/results/specimen'] = array(
530
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
531
      'access arguments' => array('access cdm content'),
532
      'type' => MENU_CALLBACK,
533
  );
534

    
535
  /*
536
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
537
   * tabs in the subordinate paths work, accessing this 'page' will cause the
538
   * MENU_DEFAULT_LOCAL_TASK being displayed
539
   */
540
  $items['cdm_dataportal/registration-search'] = array(
541
    'title' => 'Search', // will be passed through t()
542
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
543
    'page arguments' => array("filter"),
544
    'access arguments' => array('access cdm content'),
545
    'type' => MENU_CALLBACK,
546
  );
547
  /*
548
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
549
   * defined at a higher level of the path (cdm_dataportal/registration-search)
550
   */
551
  $items['cdm_dataportal/registration-search/filter'] = array(
552
    'title' => 'Search', // will be passed through t()
553
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
554
    'page arguments' => array("filter"),
555
    'access arguments' => array('access cdm content'),
556
    'type' => MENU_DEFAULT_LOCAL_TASK,
557
  );
558
  /*
559
   * the MENU_LOCAL_TASK creates another tab
560
   */
561
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
562
    'title' => 'Taxonomic search', // will be passed through t()
563
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
564
    'page arguments' => array("taxongraph"),
565
    'access arguments' => array('access cdm content'),
566
    'type' => MENU_LOCAL_TASK,
567
  );
568

    
569
  // Optional callback arguments: page.
570
  $items['cdm_dataportal/registration'] = array(
571
    'page callback' => 'cdm_dataportal_registration_page_view',
572
    'access arguments' => array('access cdm content'),
573
    'type' => MENU_CALLBACK,
574
    // Expected callback arguments: uuid.
575
  );
576

    
577
  /*
578
   $items['cdm/xml2json'] = array(
579
   'page callback' => 'cdm_view_xml2json',
580
   'access arguments' => array('access cdm content'),
581
   'type' => MENU_CALLBACK,
582
   );
583
   */
584

    
585
  // 'May not cache' in D5.
586
  $items['cdm_dataportal/name/%'] = array(
587
    // 'page callback' => 'cdm_dataportal_view_name',
588
    'page callback' => 'cdm_dataportal_name_page_view',
589
    'page arguments' => array(2, 3, 4, 5),
590
    'access arguments' => array('access cdm content'),
591
    'type' => MENU_CALLBACK,
592
  );
593

    
594
  // --- Local tasks for Taxon.
595
  // --- tabbed taxon page
596
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
597
    $items['cdm_dataportal/taxon/%'] = array(
598
      'title' => cdm_taxonpage_tab_label('General'),
599
      'page callback' => 'cdm_dataportal_taxon_page_view',
600
      'access arguments' => array('access cdm content'),
601
      'type' => MENU_CALLBACK,
602
      'weight' => 1,
603
      'page arguments' => array(2, "description")
604
      , // Expected callback arguments: taxon_uuid.
605
    );
606

    
607
    $items['cdm_dataportal/taxon/%/all'] = array(
608
      'title' => cdm_taxonpage_tab_label('General'),
609
      'page callback' => 'cdm_dataportal_taxon_page_view',
610
      'access arguments' => array('access cdm content'),
611
      'type' => MENU_CALLBACK,
612
      'weight' => 2,
613
      'page arguments' => array(2, "all")
614
      , // Expected callback arguments: taxon_uuid.
615
    );
616

    
617
    $items['cdm_dataportal/taxon/%/description'] = array(
618
      'title' => cdm_taxonpage_tab_label('General'),
619
      'page callback' => 'cdm_dataportal_taxon_page_view',
620
      'access arguments' => array('access cdm content'),
621
      'type' => MENU_DEFAULT_LOCAL_TASK,
622
      'weight' => 2,
623
      'page arguments' => array(2, "description")
624
      , // Expected callback arguments: taxon_uuid.
625
    );
626

    
627
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
628
      'title' => cdm_taxonpage_tab_label('Synonymy'),
629
      'page callback' => 'cdm_dataportal_taxon_page_view',
630
      'access arguments' => array('access cdm content'),
631
      'type' => MENU_LOCAL_TASK,
632
      'weight' => 4,
633
      'page arguments' => array(2, "synonymy", 4)
634
      , // Expected callback arguments: taxon_uuid and ...
635
    );
636
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
637
      'title' => cdm_taxonpage_tab_label('Images'),
638
      'page callback' => 'cdm_dataportal_taxon_page_view',
639
      'access arguments' => array('access cdm content'),
640
      'type' => MENU_LOCAL_TASK,
641
      'weight' => 5,
642
      'page arguments' => array(2, "images")
643
      , // Expected callback arguments: taxon_uuid.
644
    );
645

    
646
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
647
      'title' => cdm_taxonpage_tab_label('Specimens'),
648
      'page callback' => 'cdm_dataportal_taxon_page_view',
649
      'access arguments' => array('access cdm content'),
650
      'type' => MENU_LOCAL_TASK,
651
      'weight' => 6,
652
      'page arguments' => array(2, "specimens")
653
      , // Expected callback arguments: taxon_uuid.
654
    );
655

    
656
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
657
      'title' => cdm_taxonpage_tab_label('Keys'),
658
      'page callback' => 'cdm_dataportal_taxon_page_view',
659
      'access arguments' => array('access cdm content'),
660
      'type' => MENU_LOCAL_TASK,
661
      'weight' => 6,
662
      'page arguments' => array(2, "keys")
663
      , // Expected callback arguments: taxon_uuid.
664
    );
665

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

    
676
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
677
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
678
        'access arguments' => array('access cdm content'),
679
        'page arguments' => array(3,4,5),
680
        'type' => MENU_CALLBACK
681
    );
682
  }
683

    
684
  // --- refresh link for all cdmnode types
685
  foreach (cdm_get_nodetypes() as $type=>$name) {
686
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
687
        'title' => 'Refresh',
688
        'page callback' => 'cdm_dataportal_refresh_node',
689
        'access arguments' => array('administer cdm_dataportal'),
690
        'type' => MENU_LOCAL_TASK,
691
        'weight' => 100,
692
        'page arguments' => array($name, 2)
693
    );
694
  }
695

    
696
  return $items;
697
}
698

    
699
/**
700
 * Implements hook_init().
701
 *
702
 */
703
function cdm_dataportal_init() {
704
  if (!path_is_admin(current_path())) {
705
    //FIXME To add CSS or JS that should be present on all pages, modules
706
    //      should not implement this hook, but declare these files in their .info file.
707
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
708
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
709
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
710
  } else {
711
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
712
  }
713

    
714
  if(variable_get('cdm_debug_mode', FALSE)){
715
    $file = 'temporary://drupal_debug.txt';
716
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
717
  }
718

    
719
  $bibliography_settings = get_bibliography_settings();
720
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
721
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
722
}
723

    
724
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
725

    
726
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
727

    
728
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
729
    // force reloading of all and notify user about this special loading
730
    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: ')
731
        . l('Back to tabbed taxon page', $base_path));
732
    $base_path .= '/all';
733
  } else {
734
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
735
  }
736

    
737
  $parameters['cacheL2_refresh'] ='1';
738

    
739

    
740
  drupal_goto($base_path, array('query' => $parameters));
741
}
742

    
743
/**
744
 * Implements hook_requirements($phase)
745
 */
746
function cdm_dataportal_requirements($phase) {
747
    $requirements = array();
748
    if($phase == 'runtime'){
749

    
750
    }
751
    return $requirements;
752
}
753

    
754
/**
755
 * Implements hook_block_info().
756
 */
757
function cdm_dataportal_block_info() {
758

    
759
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
760
    // $block[1]["info"] = t("CDM DataPortal Credits");
761
    $block["2"] = array(
762
        "info" => t("CDM - Search Taxa"),
763
        "cache" => DRUPAL_NO_CACHE
764
      );
765
    // $block[3]["info"] = t("CDM Filters");
766
    $block["4"]["info"] = t("CDM  - Dataportal Print");
767
    $block["keys"]["info"] = t("CDM - Identification keys");
768
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
769
    $block["classification_breadcrumbs"] =  array(
770
        'info' => t('CDM - Classification breadcrumbs'),
771
        'cache' => DRUPAL_CACHE_PER_PAGE
772
      );
773
    $block["taxonomic_children"] =  array(
774
      'info' => t('CDM - Taxonomic children'),
775
      'cache' => DRUPAL_CACHE_PER_PAGE
776
    );
777
    $block["back_to_search_results"] =  array(
778
      'title' => '<none>',
779
      'info' => t('CDM - Back to search Results'),
780
      'cache' => DRUPAL_CACHE_PER_PAGE,
781
      'visibility' => BLOCK_VISIBILITY_LISTED,
782
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
783
    );
784
  $block['registrations_search_filter'] =  array(
785
    'title' => 'Filter registrations',
786
    'info' => t('CDM - Registrations search filter'),
787
    'cache' => DRUPAL_CACHE_PER_PAGE,
788
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
789
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
790
  );
791
  $block['registrations_search_taxongraph'] =  array(
792
    'title' => 'Taxonomic registration search',
793
    'info' => t('CDM - Registrations search by taxon graph'),
794
    'cache' => DRUPAL_CACHE_PER_PAGE,
795
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
796
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
797
  );
798
  $block['registrations_search'] =  array(
799
    'title' => 'Search',
800
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
801
    'cache' => DRUPAL_CACHE_PER_PAGE,
802
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
803
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
804
  );
805
  return $block;
806
}
807

    
808
/**
809
 * Implements hook_block_view().
810
 */
811
function cdm_dataportal_block_view($delta) {
812
  // TODO Rename block deltas (e.g. '2') to readable strings.
813
  switch ($delta) {
814
    // case 'delta-1':
815
    // $block['subject'] = t('Credits');
816
    // $block['content'] = theme('cdm_credits');
817
    // return $block;
818
    case '2':
819
      $block['subject'] = t('Search taxa');
820
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
821
      $block['content'] = drupal_render($form);
822

    
823
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
824
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
825
      }
826
      if (variable_get(CDM_SEARCH_BLAST_ENABLED)){
827
          $block['content'] .= '<div>' . l(t('Blast Search'), 'cdm_dataportal/search/blast') . '</div>';
828
      }
829
      return $block;
830
    case '4':
831
      $block['subject'] = '';
832
      $block['content'] = theme('cdm_print_button');
833
      return $block;
834
    case "keys":
835
      $block['subject'] = t('Identification Keys');
836
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
837
      return $block;
838
    case "fundedByEDIT":
839
      // t('Funded by EDIT');
840
      $text = '<none>';
841
      $block['subject'] = $text;
842
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
843
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
844
        'attributes' => array("target" => "EDIT"),
845
        'absolute' => TRUE,
846
        'html' => TRUE,
847
      ));
848
      return $block;
849
    case 'classification_breadcrumbs':
850
      $taxon_uuid = get_current_taxon_uuid();
851
      $block['subject'] = '<none>';
852
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
853
      return $block;
854
    case 'taxonomic_children':
855
      $taxon_uuid = get_current_taxon_uuid();
856
      $block['subject'] = '<none>';
857
      $block['content'] = compose_taxonomic_children($taxon_uuid);
858
      return $block;
859
    case 'back_to_search_results':
860
      $block['subject'] = '<none>';
861
      if (isset($_SESSION['cdm']['search'])) {
862
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
863
      }
864
      return $block;
865
    case 'registrations_search_filter':
866
      $block['subject'] = '<none>';
867
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
868
      return $block;
869
    case 'registrations_search_taxongraph':
870
      $block['subject'] = '<none>';
871
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
872
      return $block;
873
    case 'registrations_search':
874
      _add_js_ui_accordion();
875
      _add_font_awesome_font();
876
      $block['subject'] = '<none>';
877
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
878
      $filter_form['#prefix'] = '<div>';
879
      $filter_form['#suffix'] = '</div>';
880
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
881
      $taxongraph_form['#prefix'] = '<div>';
882
      $taxongraph_form['#suffix'] = '</div>';
883
      $block['content'] = array(
884
        'accordion' => array(
885
          '#markup' => '',
886
          '#prefix' => '<div id="accordion">',
887
          '#suffix' => '</div>',
888
          'content' => array(
889
            array('#markup' => '<h3>Filter</h3>'),
890
            $filter_form,
891
            array('#markup' => '<h3>Taxon graph</h3>'),
892
            $taxongraph_form,
893
          )
894
        )
895
    );
896
       return $block;
897
    default:
898
      return null;
899
  }
900
}
901

    
902
/**
903
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
904
 *
905
 * @return string
906
 *   the taxon uuid or NULL
907
 */
908
function get_current_taxon_uuid()
909
{
910
  static $taxon_uuid;
911

    
912
  if(!isset($taxon_uuid)){
913
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
914
      $taxon_uuid = $_REQUEST['currentTaxon'];
915
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
916
      $taxon_uuid = arg(2);
917
    } else {
918
      $taxon_uuid = null;
919
    }
920
  }
921

    
922
  return $taxon_uuid;
923
}
924

    
925
/**
926
 * Returns the currently classification tree in use.
927
 *
928
 * @return string
929
 *   The uuid of the currently focused classification
930
 */
931
function get_current_classification_uuid() {
932
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
933
    return $_SESSION['cdm']['taxonomictree_uuid'];
934
  }
935
  else {
936
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
937
  }
938
}
939

    
940
/*
941
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
942
 $_SESSION['cdm'] = NULL;
943
 if(is_string($cdm_ws_uri_update)){
944
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
945
 }
946
 }
947

    
948
 function cdm_dataportal_session_validate(){
949
 if(!isset($_SESSION['cdm']['ws_uri'])){
950
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
951
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
952
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
953
 }
954
 }
955
 */
956

    
957
/**
958
 * creates a  selector form for taxonomic trees.
959
 *
960
 * @return array
961
 *  a drupal form array
962
 */
963
function cdm_taxonomictree_selector() {
964
  _add_js_treeselector();
965

    
966
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
967
  return $form;
968
}
969

    
970
/**
971
 * @todo Please document this function.
972
 * @see http://drupal.org/node/1354
973
 *
974
 * @deprecated use compose_classification_selector instead
975
 */
976
function cdm_taxonomictree_selector_form($form, &$form_state) {
977

    
978
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
979
  $form['#action'] = $url;
980

    
981
  $form['var'] = array(
982
    '#weight' => -3,
983
    '#type' => 'hidden',
984
    '#value' => '[cdm][taxonomictree_uuid]',
985
  );
986

    
987
  $destination_array = drupal_get_destination();
988
  $destination = $destination_array['destination'];
989

    
990
  $form['destination'] = array(
991
    '#weight' => -3,
992
    '#type' => 'hidden',
993
    '#value' =>  $destination,
994
  );
995

    
996
  $options = cdm_get_taxontrees_as_options();
997
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
998
  if($taxontree_includes){
999
    $filtered_options = array();
1000
    foreach($options as $uuid=>$label){
1001
      if(!empty($taxontree_includes[$uuid])){
1002
        $filtered_options[$uuid] = $label;
1003
      }
1004
    }
1005
    $options = $filtered_options;
1006
  }
1007

    
1008
  $form['val'] = array(
1009
    '#type' => 'select',
1010
    '#title' => t('Available classifications'),
1011
    '#default_value' => get_current_classification_uuid(),
1012
    '#options' => $options,
1013
    '#attributes' => array('class' => array('highlite-first-child')),
1014
  );
1015

    
1016
  return $form;
1017

    
1018
}
1019

    
1020
/**
1021
 *
1022
 * @ingroup compose
1023
 */
1024
function compose_classification_selector() {
1025

    
1026
  $destination_array = drupal_get_destination();
1027
  $destination = $destination_array['destination'];
1028

    
1029
  $options = cdm_get_taxontrees_as_options();
1030
  $items = array();
1031
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1032

    
1033
  $current_classification_uuid = get_current_classification_uuid();
1034

    
1035

    
1036
  foreach($options as $uuid=>$label){
1037
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1038

    
1039
      $class_attributes = '';
1040
      if($current_classification_uuid == $uuid){
1041
        $class_attributes  = array('focused');
1042
      }
1043
      $items[] = array(
1044
        'data' => l($label,
1045
          'cdm_api/setvalue/session',
1046
          array(
1047
            'query' => array(
1048
              'destination' => $destination,
1049
              'val' => $uuid,
1050
              'var' => '[cdm][taxonomictree_uuid]'
1051
            ),
1052
          )
1053
        ),
1054
        'class' => $class_attributes
1055
      );
1056
    }
1057
  }
1058

    
1059
  $render_array = array(
1060
    '#theme' => 'item_list',
1061
    '#type' => 'ul',
1062
    '#items' => $items
1063
  );
1064

    
1065
  return $render_array;
1066
}
1067

    
1068

    
1069
/* UNREACHABLE since action of form directly links to view.
1070
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1071

    
1072
 $_SESSION['cdm']['search'] = $form_values;
1073
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1074
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1075
 //$paramstr = compose_url_prameterstr($form_values);
1076
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1077
 }
1078
 */
1079
/* ====================== menu callback functions ====================== */
1080
/**
1081
 * @todo Please document this function.
1082
 * @see http://drupal.org/node/1354
1083
 */
1084
/*
1085
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1086
  static $comment_node_disabled =  0;
1087
  static $comment_node_read_only =  1;
1088
  static $comment_node_read_write =  2;
1089

    
1090
  if ($form_id == 'node_type_form'
1091
   && isset($form['identity']['type'])
1092
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1093
  ) {
1094
    $form['workflow']['comment'] = array(
1095
      '#type' => 'radios',
1096
      '#title' => t('Default comment setting'),
1097
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1098
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1099
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1100
    );
1101
  }
1102
}
1103
*/
1104

    
1105
/**
1106
 * Displays a list of the known taxonomic names.
1107
 *
1108
 * When the list of taxonomic names is displayed, long lists are split up into
1109
 * multiple pages.
1110
 *
1111
 * TODO: Parameters are still preliminary.
1112
 *
1113
 * @param string $beginsWith
1114
 * @param string $page
1115
 *   Page number to diplay defaults to page 1.
1116
 * @param bool $onlyAccepted
1117
 */
1118
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1119

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

    
1122
  /*
1123
  // FIXME the filter for accepted names will be a form element, thus this
1124
  // widget should be generated via form api preferably as block.
1125
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1126
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1127
  $out .= theme('cdm_listof_taxa', $taxonPager);
1128
  return $out;
1129
  */
1130
}
1131

    
1132
/**
1133
 * @todo Please document this function.
1134
 * @see http://drupal.org/node/1354
1135
 * @throws Exception
1136
 */
1137
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1138

    
1139
  cdm_check_valid_portal_page();
1140

    
1141
  return compose_cdm_reference_page($uuid);
1142
}
1143

    
1144
/**
1145
 * Creates a view on a all references contained in the portal.
1146
 *
1147
 * This function is used at the path cdm_dataportal/reference/list
1148
 */
1149
function cdm_dataportal_view_reference_list($pageNumber) {
1150
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1151
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1152
}
1153

    
1154
/**
1155
 * @todo Please document this function.
1156
 * @see http://drupal.org/node/1354
1157
 */
1158
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1159

    
1160
  cdm_check_valid_portal_page();
1161

    
1162
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1163
  return theme('cdm_media_page', array(
1164
    'media' => $media,
1165
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1166
    'partId' => $part,
1167
    ));
1168
}
1169

    
1170
/**
1171
 * @todo Please document this function.
1172
 * @see http://drupal.org/node/1354
1173
 */
1174
function _load_taxonBase(&$taxonBase) {
1175
  if (isset($taxonBase->uuid)) {
1176
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1177
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1178
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1179
  }
1180
}
1181

    
1182
/**
1183
 * Loads the media associated to the given taxon from the cdm server.
1184
 * The aggregation settings regarding taxon relathionships and
1185
 * taxonnomic childen are taken into account.
1186
 *
1187
 * The media lists are cached in a static variable.
1188
 *
1189
 * @param Taxon $taxon
1190
 *   A CDM Taxon entitiy
1191
 *
1192
 * @return array
1193
 *   An array of CDM Media entities
1194
 *
1195
 */
1196
function _load_media_for_taxon($taxon) {
1197

    
1198
  static $media = NULL;
1199

    
1200
  if(!isset($media)) {
1201
    $media = array();
1202
  }
1203
  if (!isset($media[$taxon->uuid])) {
1204

    
1205
    // --- GET Images --- //
1206
    $mediaQueryParameters = array(
1207
        "type" => "ImageFile",
1208
    );
1209

    
1210
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1211
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1212
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1213

    
1214
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1215
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1216
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1217
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1218

    
1219
    $ws_endpoint = NULL;
1220
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1221
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1222
    } else {
1223
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1224
    }
1225

    
1226
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1227
        array(
1228
            $taxon->uuid,
1229
        ),
1230
        queryString($mediaQueryParameters)
1231
       );
1232
  }
1233

    
1234
  return $media[$taxon->uuid];
1235
}
1236

    
1237
/**
1238
 *
1239
 * @param Taxon $taxon
1240
 *   A CDM Taxon entitiy
1241
 *
1242
 * @return array
1243
 *   An array of CDM SpecimenOrObservation entities
1244
 *
1245
function _load_occurences_for_taxon($taxon){
1246

    
1247
  static $occurences = NULL;
1248

    
1249
  if(!isset($occurences)) {
1250
    $occurences = array();
1251
  }
1252

    
1253
  if (!isset($occurences[$taxon->uuid])){
1254

    
1255
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1256
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1257
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1258

    
1259
    $by_associatedtaxon_query = http_build_query(array(
1260
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1261
        'relationships' => implode(',', $relationship_choice['direct']),
1262
        'pageSize' => null // all hits in one page
1263
    )
1264
    );
1265

    
1266
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1267
        null,
1268
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1269
    );
1270

    
1271

    
1272
    if(isset($pager->records[0])){
1273
      $occurences[$taxon->uuid] =  $pager->records;
1274
    }
1275
  }
1276
  return $occurences[$taxon->uuid];
1277
}
1278
 */
1279

    
1280
/**
1281
 * Gets a Drupal variable, string or array and returns it.
1282
 *
1283
 * Similar to the variable_get() function of Drupal, except that this function
1284
 * is able to handle arrays correctly. This function is especially useful
1285
 * when dealing with collections of settings form elements (#tree = TRUE).
1286
 *
1287
 * @param string $variableKey
1288
 *   The Unique key of the Drupal variable in the Drupal variables table.
1289
 * @param string $defaultValueString
1290
 *   A string as for example derived from a CONSTANT.
1291
 *
1292
 * @return mixed
1293
 *   usually an array, depending on the nature of the variable.
1294
 *
1295
 * TODO compare with get_array_variable_merged() duplicate functions?
1296
 * @deprecated rather use get_array_variable_merged() since this function
1297
 * used an array as second parameter
1298
 */
1299
function mixed_variable_get($variableKey, $defaultValueString) {
1300
  $systemDefaults = unserialize($defaultValueString);
1301
  $storedSettings = variable_get($variableKey, array());
1302
  if (is_array($storedSettings)) {
1303
    // TODO better use drupal_array_merge_deep() ?
1304
    $settings = array_merge($systemDefaults, $storedSettings);
1305
  }
1306
  else {
1307
    $settings = $systemDefaults;
1308
  }
1309
  return $settings;
1310
}
1311

    
1312
/**
1313
 * Recursive function to convert an object into an array.
1314
 * also subordinate objects will be converted.
1315
 *
1316
 * @param object $object
1317
 *  the object to be converted
1318
 * @return array
1319
 *  The array
1320
 */
1321
function object_to_array($object) {
1322
  if(is_object($object) || is_array($object)) {
1323
    $array = (array)$object;
1324
    foreach ($array as $key=>$value){
1325
      $array[$key] = object_to_array($value);
1326
    }
1327
    return $array;
1328
  } else {
1329
    return $object;
1330
  }
1331
}
1332

    
1333
/**
1334
 * Searches the $collection for the cdm entitiy given as $element.
1335
 *
1336
 * The elements are compared by their UUID.
1337
 *
1338
 * @param $element
1339
 *  the CDM entitiy to search for
1340
 * @param $collection
1341
 *  the list of CDM entities to search in
1342
 *
1343
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1344
 *
1345
 */
1346
function contains_cdm_entitiy($element, $collection) {
1347
  $result = FALSE;
1348
  foreach ($collection as $a) {
1349
    if ($a->uuid == $element->uuid) {
1350
      $result = TRUE;
1351
    }
1352
  }
1353
  return $result;
1354
}
1355

    
1356
/**
1357
 * Fiters the array $entity_list of CDM entities by the list
1358
 * of $excludes. Any element contained in the $excludes will be removed
1359
 * from included int the retuned list.
1360
 *
1361
 * If the $entity_list is not an array the $excludes will be returned.
1362
 */
1363
function filter_cdm_entity_list($entity_list, $excludes) {
1364
  if (is_array($entity_list)) {
1365
    $result = $entity_list;
1366
    if ($excludes) {
1367
      foreach ($excludes as $exclude) {
1368
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1369
          $result[] = $exclude;
1370
        }
1371
      }
1372
    }
1373
  }
1374
  else {
1375
    $result = $excludes;
1376
  }
1377
  return $result;
1378
}
1379

    
1380
/**
1381
 * Wraps the given $html string into a render array suitable for drupal_render()
1382
 *
1383
 * @param $html
1384
 *   the html string, see
1385
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1386
 * @param $weight
1387
 *   A positive or negative number (integer or decimal).
1388
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1389
 * @param $prefix
1390
 *   Optional markup for the '#prefix' element of the render array
1391
 * @param $suffix
1392
 *   Optional markup for the '#suffix' element of the render array
1393
 *
1394
 * @return array
1395
 *   A render array
1396
 *
1397
 */
1398
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1399
  $render_array = array(
1400
    '#markup' => $html
1401
      );
1402
  if (is_numeric($weight)) {
1403
    $render_array['#weight'] = $weight;
1404
  }
1405
  if($prefix){
1406
    $render_array['#prefix'] = $prefix;
1407
  }
1408
  if($suffix) {
1409
    $render_array['#suffix'] = $suffix;
1410
  }
1411
  return $render_array;
1412
}
1413

    
1414
/**
1415
 * Loads the subgraph of a given PolytomousKeyNode.
1416
 *
1417
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1418
 * the CDM REST service.
1419
 *
1420
 * @param mixed $polytomousKeyNode
1421
 *   PolytomousKeyNode passed by reference.
1422
 *
1423
 * @return void
1424
 */
1425
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1426

    
1427
  if (!$polytomousKeyNode) {
1428
    return;
1429
  }
1430
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1431
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1432
    return;
1433
  }
1434
  if (!is_uuid($polytomousKeyNode->uuid)) {
1435
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1436
    return;
1437
  }
1438

    
1439
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1440

    
1441
  if (!$polytomousKeyNode) {
1442
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1443
    return;
1444
  }
1445

    
1446
  // Load children.
1447
  foreach ($polytomousKeyNode->children as &$childNode) {
1448
    _load_polytomousKeySubGraph($childNode);
1449
  }
1450

    
1451
  // Load subkey.
1452
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1453

    
1454
  // Load taxon.
1455
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1456
  _load_taxonBase($polytomousKeyNode->taxon);
1457
  return;
1458
}
1459

    
1460
/**
1461
 * @todo Please document this function.
1462
 * @see http://drupal.org/node/1354
1463
 */
1464
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1465

    
1466
  cdm_check_valid_portal_page();
1467

    
1468
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1469

    
1470
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1471
  if (is_array($sourcePager->records)) {
1472
    $polytomousKey->sources = $sourcePager->records;
1473
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1474
  }
1475

    
1476
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1477
  if (is_array($annotationPager->records)) {
1478
    $polytomousKey->annotations = $annotationPager->records;
1479
  }
1480

    
1481
  _load_polytomousKeySubGraph($polytomousKey->root);
1482
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1483
}
1484

    
1485
/**
1486
 * Creates a taxon page view or a chapter of it.
1487
 *
1488
 * The taxon page gives detailed information on a taxon, it shows:
1489
 *  - Taxon name.
1490
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1491
 *    heterotypic and finally followed by misapplied names.
1492
 *    The list is ordered historically.
1493
 *  - All description associated with the taxon.
1494
 *
1495
 * @param string $uuid
1496
 * @param string $chapter
1497
 *   Name of the part to display, valid values are:
1498
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1499
 *
1500
 * @return string
1501
 */
1502
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1503

    
1504
  cdm_check_valid_taxon_page($chapter);
1505
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1506
  // show a warning in case the javascript development mode is anabled
1507
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1508
    drupal_set_message(t('The !url1 is enabled.
1509
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1510
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1511
    )),
1512
    'warning'
1513
        );
1514
  }
1515

    
1516
  // Display the page for the taxon defined by $uuid.
1517
  // set_last_taxon_page_tab(arg(3));
1518
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1519
  if (!empty($taxonpage)) {
1520
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1521
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1522
  }
1523
  else {
1524
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1525
    return '';
1526
  }
1527
}
1528

    
1529
/**
1530
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1531
 * which has two fields, one for the page title and one for the content. Later on in the
1532
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1533
 * function as the function parameters $title and $content.
1534
 *
1535
 * @param string $uuid
1536
 *   the uuid of the taxon to show
1537
 * @param string $chapter
1538
 *   Name of the part to display, valid values are:
1539
 *   'description', 'images', 'synonymy', 'all'.
1540
 *
1541
 * @return object with the following fields:
1542
 *   - title : the title of the page
1543
 *   - content: the content of the page
1544
 *
1545
 * @throws Exception
1546
 *
1547
 */
1548
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1549
  // Taxon object.
1550
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1551
  if (empty($taxon)) {
1552
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1553
    return null;
1554
  }
1555
  $taxonpage = new stdClass();
1556

    
1557
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1558
    'taxon' => $taxon
1559
  ));
1560

    
1561
  // Check if the taxon id contained in the currently selected tree.
1562
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1563

    
1564
  if (!$taxon_in_current_classification) {
1565
    $classifications = get_classifications_for_taxon($taxon);
1566
    RenderHints::pushToRenderStack('not_in_current_classification');
1567
    $taxon_name_markup = render_taxon_or_name($taxon);
1568

    
1569
    if (count($classifications) == 0) {
1570
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1571
        array(
1572
        '!taxonname' => $taxon_name_markup,
1573
        )
1574
      ), 'warning');
1575
    }
1576
    else {
1577
      $trees = '';
1578
      foreach ($classifications as $classification) {
1579
        if (isset($classification->titleCache)) {
1580
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1581
        }
1582
      }
1583

    
1584
      drupal_set_message(format_plural(count($trees),
1585
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1586
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1587
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1588
        ) ,
1589
        'warning');
1590
    }
1591
    RenderHints::popFromRenderStack();
1592
  }
1593

    
1594
  // Render the taxon page.
1595
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1596
  $taxonpage->content = drupal_render($render_array);
1597

    
1598
  return $taxonpage;
1599
}
1600
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1601
{
1602
    if (isset($accession_number)) {
1603
        $specimen_or_observation = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1604

    
1605
        if (isset($specimen_or_observation) && $specimen_or_observation){
1606
            cdm_dataportal_specimen_page_view($specimen_or_observation->uuid, $specimen_or_observation);
1607
        }
1608

    
1609
    }
1610
}
1611
/**
1612
 * Creates a specimen page view.
1613
 * @param string $uuid the UUID of the specimen
1614
 * @return array|string
1615
 */
1616
function cdm_dataportal_specimen_page_view($uuid) {
1617

    
1618
    //cdm_check_valid_taxon_page($chapter);
1619
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1620
    // show a warning in case the javascript development mode is anabled
1621
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1622
        drupal_set_message(t('The !url1 is enabled.
1623
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1624
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1625
        )),
1626
            'warning'
1627
        );
1628
    }
1629

    
1630
    // Display the page for the specimen defined by $uuid.
1631
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1632
    if (!empty($specimenpage)) {
1633
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1634
    }
1635
    else {
1636
        return '';
1637
    }
1638
}
1639

    
1640
/**
1641
 *
1642
 * Creates a specimen view.
1643
 * @param string $uuid the UUID of the specimen
1644
 * @return array|string
1645
 */
1646
function cdm_dataportal_specimen_view($uuid) {
1647
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1648
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1649
    if (empty($specimen)) {
1650
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1651
        return FALSE;
1652
    }
1653
    $specimenpage = new stdClass();
1654

    
1655
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1656
        'specimen' => $specimen
1657
    ));
1658

    
1659
    // Render the specimen page.
1660
    $render_array = compose_cdm_specimen_page($specimen);
1661
    $specimenpage->content = drupal_render($render_array);
1662

    
1663
    return $specimenpage;
1664
}
1665

    
1666
/**
1667
 *
1668
 * Creates a named area view.
1669
 * @param string $uuid the UUID of the specimen
1670
 *  * @return object
1671
 *   An object with two fields:
1672
 *     - title: the page title
1673
 *     - content: the page content
1674
 */
1675

    
1676
function cdm_dataportal_named_area_view($uuid) {
1677
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1678
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1679
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1680
    return FALSE;
1681
  }
1682
  $named_area_page = new stdClass();
1683

    
1684
  $named_area_page->title = $named_area->representation_L10n;
1685

    
1686
  // Render the specimen page.
1687
  $render_array = compose_cdm_named_area_page($uuid);
1688
  $named_area_page->content = drupal_render($render_array);
1689

    
1690
  return $named_area_page;
1691
}
1692

    
1693
function cdm_dataportal_named_area_page_view($uuid) {
1694

    
1695
  cdm_check_valid_portal_page();
1696

    
1697
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1698
  if (!empty($named_area_page)) {
1699
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1700
  }
1701
  else {
1702
    return '';
1703
  }
1704

    
1705

    
1706
}
1707

    
1708
/**
1709
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1710
 *
1711
 * The node page shows the taxon name title and the list of taxon related
1712
 * with such taxon. Name on the tree already in use.
1713
 *
1714
 * @param string $taxon_name_uuid
1715
 *   The uuid of the CDM TaxonName to show a name page for
1716
 * @param string $taxon_to_hide_uuid
1717
 *   A taxon which should not be displayed in the taxon list
1718
 * @param $redirect_to_taxon
1719
 *   Automatically redirect to the related taxon if there is only one
1720
 *   accepted taxon for this name.
1721
 * @param string $highlite_synonym_uuid
1722
 *   Optinal parameter wich takes another taxon uuid, if given the
1723
 *   target taxon pages will show the syonymy tab where the taxon
1724
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1725
 *   in case it is found on this page.
1726
 *
1727
 * @return mixed
1728
 *   The formatted name page as node.
1729
 */
1730
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = '') {
1731

    
1732
  cdm_check_valid_portal_page();
1733

    
1734
  // redirect_to_taxon is a path element of the name page path, see path_to_name()
1735
  $do_redirect_to_taxon = $redirect_to_taxon == 'redirect_to_taxon';
1736
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $do_redirect_to_taxon, $synonym_uuid);
1737
  if (!empty($taxonname_page)) {
1738
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1739
  }
1740
  else {
1741
    return '';
1742
  }
1743
}
1744

    
1745
/**
1746
 * View function for a TaxonName page.
1747
 *
1748
 * The name page lists all taxa for which the name specified by the
1749
 * $taxon_name_uuid is being used. I case there is only one name the
1750
 * page automatically redirects ti the according taxon page. Otherwise
1751
 * the list of names is displayed.
1752
 *
1753
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1754
 * list of taxa. This is useful for example when referencing from a taxon
1755
 * to the name page and the referring taxon should not be repeaded in the
1756
 * name page.
1757
 *
1758
 *
1759
 * @param string $taxon_name_uuid
1760
 *   The uuid of the CDM TaxonName to show a name page for
1761
 * @param string $taxon_to_hide_uuid
1762
 *   A taxon which should not be displayed in the taxon list
1763
 * @param $redirect_to_taxon
1764
 *   Automatically redirect to the related taxon if there is only one
1765
 *   accepted taxon for this name.
1766
 * @param string $highlite_synonym_uuid
1767
 *   Optional parameter which takes another taxon uuid, if given the
1768
 *   target taxon pages will show the synonymy tab where the taxon
1769
 *   referenced by the $highlite_synonym_uuid will be highlighted
1770
 *   in case it is found on this page.
1771
 *
1772
 * @return object|boolean
1773
 *   An object with two fields:
1774
 *     - title: the page title
1775
 *     - content: the page content
1776
 *   or FALSE
1777
 *
1778
 */
1779
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $redirect_to_taxon, $highlite_synonym_uuid = NULL) {
1780
  // Getting the full taxonname object from the server.
1781
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1782
  if (!$taxon_name) {
1783
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1784
    return FALSE;
1785
  }
1786
  // Searching for all the taxa connected with the taxon name on the tree
1787
  // in use.
1788
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1789
  $request_params = array();
1790
  $request_params['query'] = $name_cache;
1791
  $request_params['tree'] = get_current_classification_uuid();
1792
  $request_params['doTaxa'] = 1;
1793
  $request_params['doSynonyms'] = 1;
1794
  $request_params['doTaxaByCommonNames'] = 0;
1795
  $request_params['matchMode'] = "EXACT";
1796
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1797

    
1798
  // Removing the name where we came from.
1799
  foreach ($taxon_pager->records as $k => &$taxon) {
1800
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1801
      unset($taxon_pager->records[$k]);
1802
    }
1803
  }
1804
  // Show the taxa list or go to the singular taxon.
1805
  if (sizeof($taxon_pager->records) == 1 && $redirect_to_taxon) {
1806
    // redirect to the taxon if there is only one.
1807
    $singleTaxon = array_pop($taxon_pager->records);
1808
    if ($singleTaxon->class != "Taxon") {
1809
      // It is a Synonym -> look for the accepted.
1810
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1811
      if (!empty($highlite_synonym_uuid)) {
1812
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1813
      }
1814
      else {
1815
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1816
      }
1817
    }
1818
    else {
1819
      // It is an accepted taxon.
1820
      if (!empty($highlite_synonym_uuid)) {
1821
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1822
      }
1823
      else {
1824
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1825
      }
1826
    }
1827
  }
1828
  else {
1829
    // display the name page content
1830
    $taxon_name_page = new stdClass();
1831
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1832
    $content = array();
1833

    
1834
    // name relationships
1835
    // TODO ....
1836
    // related taxa
1837
    if ($taxon_pager->records) {
1838
      $content['related_taxa'] = compose_list_of_taxa($taxon_pager->records);
1839
    }
1840
    else {
1841
      $content['related_taxa'] = markup_to_render_array('This name is not assigned to a taxon.');
1842
    }
1843
    $taxon_name_page->content = $content;
1844
    return $taxon_name_page;
1845
  }
1846
}
1847

    
1848
/**
1849
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1850
 *
1851
 * @param string  $registration_identifier_encoded
1852
 *   The persistent identifier of the registration urlencoded.
1853
 * @return mixed
1854
 *   The formatted registration page as node.
1855
 */
1856
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
1857

    
1858
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
1859
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
1860
  return cdm_node_show_simulate($registration_page);
1861
}
1862

    
1863
function cdm_dataportal_registration_view($registration_identifier_encoded) {
1864

    
1865
  $registration_identifier = urldecode($registration_identifier_encoded);
1866

    
1867
  $render_array = array();
1868
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
1869
  if($registration_dto){
1870
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
1871

    
1872
    $render_array = compose_registration_dto_full($registration_dto, true);
1873

    
1874
  } else {
1875
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
1876
    if(isset($status_text->String)) {
1877
      $status_text = strtolower($status_text->String);
1878
      if($status_text == 'preparation' || $status_text == 'curation'){
1879
        $status_text = 'in ' . $status_text;
1880
      }
1881
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
1882
      //$status_message;
1883
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
1884
    } else {
1885
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
1886
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
1887
    }
1888
  }
1889

    
1890
  $render_array = array(
1891
    '#prefix' => '<div id="registration">',
1892
    'registration' => $render_array,
1893
    '#suffix' => '</div>',
1894
  );
1895

    
1896
  return $render_array ;
1897
}
1898

    
1899

    
1900
/**
1901
 * Creates a page with the advance search form.
1902
 *
1903
 * NOTE: The advance search form allows searching for taxa.
1904
 */
1905
function cdm_dataportal_view_search_advanced() {
1906
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1907
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1908
}
1909

    
1910
/**
1911
 * Creates a page with the blast search form.
1912
 *
1913
 * NOTE: The advance search form allows searching for specimen in blast DB.
1914
 */
1915
function cdm_dataportal_view_search_blast() {
1916
    drupal_set_title(t('Blast search'), PASS_THROUGH);
1917
    return drupal_get_form('cdm_dataportal_search_blast_form');
1918
}
1919

    
1920
/**
1921
 * Creates a page with the search form for searching by taxon descriptions.
1922
 */
1923
function cdm_dataportal_view_search_taxon_by_description() {
1924
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1925
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1926
}
1927

    
1928
/**
1929
 * Executes the search and generates the result list of taxa.
1930
 */
1931
function cdm_dataportal_view_search_results_taxon() {
1932

    
1933
  $taxonPager = cdm_dataportal_search_taxon_execute();
1934

    
1935
  $showThumbnails = do_showThumbnails();
1936

    
1937
  $setSessionUri = url('cdm_api/setvalue/session', array(
1938
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1939
  ));
1940

    
1941
  drupal_add_js('jQuery(document).ready(function() {
1942

    
1943
      // init
1944
      if(' . $showThumbnails . ' == 1){
1945
          jQuery(\'.media_gallery\').show(20);
1946
      } else {
1947
          jQuery(\'.media_gallery\').hide(20);
1948
      }
1949

    
1950
      // add change handler
1951
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1952
      function(event){
1953
        var state = 0;
1954
        if(jQuery(this).is(\':checked\')){
1955
          jQuery(\'.media_gallery\').show(20);
1956
          state = 1;
1957
        } else {
1958
          jQuery(\'.media_gallery\').hide(20);
1959
        }
1960
        // store state in session variable
1961
        var uri = \'' . $setSessionUri . '\' + state;
1962
        jQuery.get(uri);
1963
      });
1964
  });',
1965
  array('type' => "inline", 'scope' => JS_DEFAULT));
1966

    
1967
  drupal_set_title(t('Search results'), PASS_THROUGH);
1968

    
1969
  return theme('cdm_search_taxa_results', array(
1970
    'pager' => $taxonPager,
1971
    'path' => 'cdm_dataportal/search/results/taxon',
1972
    ));
1973
}
1974

    
1975
/**
1976
 * Executes the blast search and generates the result list of specimen.
1977
 */
1978
function cdm_dataportal_view_search_results_specimen() {
1979

    
1980
    $specimenPager = cdm_dataportal_search_blast_execute();
1981

    
1982
    return theme('cdm_search_specimen_results', array(
1983
        'pager' => $specimenPager,
1984
        'path' => 'cdm_dataportal/search/results/specimen',
1985
    ));
1986
}
1987

    
1988

    
1989
/**
1990
 * Executes the search for registrations and generates the result list..
1991
 */
1992
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
1993

    
1994
  switch($mode ){
1995
    case 'taxongraph':
1996
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
1997
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
1998
      break;
1999
    case 'filter':
2000
    default:
2001
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2002
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2003
  }
2004
  $block->title = null;
2005

    
2006
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2007

    
2008
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2009
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2010
  $render_array = array_merge($render_array, $registrations_pager_array);
2011

    
2012
  return $render_array;
2013
}
2014

    
2015

    
2016
/**
2017
 * Provides the standart image wich indicated a loading process
2018
 *
2019
 * @return string
2020
 *  The img html tag
2021
 */
2022
function loading_image_html() {
2023
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2024
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2025
}
2026

    
2027
/**
2028
 * Returns the state of the the showThumbnails flag set in the
2029
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2030
 *
2031
 * @return boolean
2032
 *    returns 1 if the flag is set
2033
 */
2034
function do_showThumbnails() {
2035
  static $showThumbnails = null;
2036

    
2037
  if($showThumbnails == null) {
2038
    $showThumbnails = 0;
2039
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2040
      $showThumbnails = 0;
2041
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2042
      $showThumbnails = is_array($search_gallery_settings)
2043
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2044
        && (
2045
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2046
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2047
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2048
            )
2049
         ? 1 : 0;
2050

    
2051
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2052
    }
2053
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2054
    if (!is_numeric($showThumbnails)) {
2055
      $showThumbnails = 1;
2056
    }
2057
  }
2058

    
2059
  return $showThumbnails;
2060
}
2061

    
2062

    
2063

    
2064
/* ====================== other functions ====================== */
2065
/**
2066
 * Creates a URL to the taxon page specified by the $uuid parameter.
2067
 *
2068
 * The URL will be prepended with a path element to a specific taxon page tab.
2069
 *
2070
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2071
 * be set globally in the administrative settings or individually in the user
2072
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2073
 * the last portal will stay on this last tab.
2074
 *
2075
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2076
 * internal mechanism by a specific value.
2077
 *
2078
 * @param string $uuid
2079
 *   The UUID of the taxon.
2080
 * @param string $page_tab
2081
 *   Overwriting the preset mechanism by defining specific value for the
2082
 *   taxon page tab.
2083
 *
2084
 * @return string
2085
 *   The created URL.
2086
 */
2087
function path_to_taxon($uuid, $page_tab = FALSE) {
2088

    
2089
  $tab = get_default_taxon_tab();
2090
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2091

    
2092
  if (!$uuid) {
2093
    return FALSE;
2094
  }
2095

    
2096
  if ($page_tab) {
2097
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2098
  }
2099
  elseif (!$tab || strtolower($tab) == 'general') {
2100
    return 'cdm_dataportal/taxon/' . $uuid;
2101
  }
2102
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2103
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2104
  }
2105
  else {
2106
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2107
  }
2108
}
2109

    
2110
function path_to_specimen($uuid) {
2111

    
2112
    if (!$uuid) {
2113
        return FALSE;
2114
    }
2115
    else {
2116
        return 'cdm_dataportal/occurrence/' . $uuid;
2117
    }
2118
}
2119

    
2120
function path_to_specimen_by_accession_number($accession_number) {
2121

    
2122
    if (!$accession_number) {
2123
        return FALSE;
2124
    }
2125
    else {
2126
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2127
    }
2128
}
2129

    
2130
function path_to_named_area($uuid) {
2131

    
2132
  if (!$uuid) {
2133
    return FALSE;
2134
  }
2135
  else {
2136
    return 'cdm_dataportal/named_area/' . $uuid;
2137
  }
2138
}
2139

    
2140
/**
2141
 * Creates a URL to show a synonmy in the according taxon page.
2142
 *
2143
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2144
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2145
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2146
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2147
 * in the page
2148
 *
2149
 * @param string $synonymUuid
2150
 *    The uuid of the synonym
2151
 * @param string $acceptedUuid
2152
 *    The uuid of the according accepted taxon
2153
 * @return string
2154
 *    The URL to show a synonmy in the according taxon page
2155
 */
2156
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2157
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2158
  return url($acceptedPath, array(
2159
      'query' => array(
2160
        // highlite the synony in the synonymy
2161
        'highlite' => $synonymUuid,
2162
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2163
        // see theme_taxon_page_title()
2164
        'acceptedFor' => $synonymUuid
2165
      ),
2166
      'fragment' => $synonymUuid
2167
  ));
2168

    
2169
}
2170

    
2171
/**
2172
 * Composes the drupal path to the key identified by the uuid.
2173
 *
2174
 * @param string $keyType
2175
 *    the key typer corresponds to the specific class of the CDM
2176
 *    IdentificationKey. Possible values are
2177
 *      -PolytomousKey
2178
 *      -MultimediaKey
2179
 *      - ...
2180
 * @param string $keyUuid
2181
 *   The UUID of the key
2182
 */
2183
function path_to_key($keyType, $keyUuid) {
2184
  if (!$keyUuid || !$keyType) {
2185
    return FALSE;
2186
  }
2187
  $keyType{0} = strtolower($keyType{0});
2188
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2189
}
2190

    
2191
/**
2192
 * Composes the drupal path to the reference identified by the uuid.
2193
 *
2194
 * @param $uuid string String representation of the registration entity uuid.
2195
 *
2196
 * @return string
2197
 *  The drupal path
2198
 *
2199
 */
2200
function path_to_reference($uuid) {
2201
  if (!$uuid) {
2202
    return FALSE;
2203
  }
2204
  return 'cdm_dataportal/reference/' . $uuid;
2205
}
2206

    
2207
/**
2208
 * Composes the drupal path to the reference identified by the uuid.
2209
 *
2210
 * @param string $identifier
2211
 *  The persistent identifier of the registration entity (Registration.identifier).
2212
 * @return string
2213
 *  The drupal path
2214
 */
2215
function path_to_registration($identifier) {
2216

    
2217
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2218
    return $identifier;
2219
  } else {
2220
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2221
  }
2222
}
2223

    
2224
/**
2225
 * Creates the path to a cdm_dataportal taxon name page.
2226
 *
2227
 * @param string $taxon_name_uuid
2228
 *   The uuid as string of the CDM TaxonName to show a name page for
2229
 * @param string $taxon_to_hide_uuid
2230
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2231
 * @param string $highlited_synonym_uuid
2232
 *   Optional parameter which takes another taxon uuid, if given the
2233
 *   target taxon pages will show the synonymy tab where the taxon
2234
 *   referenced by the $highlite_synonym_uuid will be highlighted
2235
 *   in case it is found on this page.
2236
 * @param $redirect_to_taxon
2237
 *   If true, the name page will redirect to the related taxon if there is a single one
2238
 *   for this name only.
2239
 *
2240
 * @return string
2241
 *  URI path element as string
2242
 */
2243
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2244
  $res = FALSE;
2245
  if ($name_uuid) {
2246
    $res = 'cdm_dataportal/name/' . $name_uuid .
2247
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2248
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2249
    '/' . ($redirect_to_taxon ? "redirect_to_taxon" : "");
2250
  }
2251

    
2252
  return $res;
2253
}
2254

    
2255
/**
2256
 * Composes the drupal path to the media entity identified by the uuid.
2257
 *
2258
 * @param string $uuid
2259
 *  The persistent identifier of the entity entity
2260
 * @return string
2261
 *  The drupal path
2262
 */
2263
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2264
  if (!$uuid) {
2265
    return FALSE;
2266
  }
2267
  $out = 'cdm_dataportal/media/' . $uuid;
2268
  if ($representaion_uuid) {
2269
    $out .= '/' . $representaion_uuid;
2270
    if (is_numeric($partId)) {
2271
      $out .= '/' . $partId;
2272
    }
2273
  }
2274
  return $out;
2275
}
2276

    
2277
/**
2278
 * Compares thisRank with thatRank.
2279
 *
2280
 * Returns a negative integer, zero, or a positive integer
2281
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2282
 * e.g:
2283
 * <ul>
2284
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2285
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2286
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2287
 * </ul>
2288
 * <p>
2289
 * This compare logic of the underlying webservice is the
2290
 * <b>inverse logic</b> of the the one implemented in
2291
 * java.lang.Comparable#compareTo(java.lang.Object)
2292
 *
2293
 * @param $thisRankUuid
2294
 * @param $thatRankUuid
2295
 *
2296
 * @return int
2297
 *   A negative integer, zero, or a positive integer
2298
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2299
 */
2300
function rank_compare($thisRankUuid, $thatRankUuid) {
2301
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2302
  return $result->Integer;
2303
}
2304

    
2305
/**
2306
 * Composes an HTML element class attribute value composed of
2307
 * the short-name of the cdm class and the uuid of the entity.
2308
 * This class attribute should be used wherever an cdm-entity is rendered.
2309
 *
2310
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2311
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2312
 * Taxon uuid is added also as taxon_uuid:<uuid>
2313
 *
2314
 * These according class selectors in css must be escaped, eg:
2315
 *    .cdm\:TextData
2316
 *
2317
 * @param $cdm_entity
2318
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2319
 */
2320
function html_class_attribute_ref($cdm_entity) {
2321

    
2322
  $attributes = '';
2323
  if (is_cdm_entity($cdm_entity)) {
2324
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2325
  } else if($cdm_entity->class == 'TypedEntityReference') {
2326
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2327
  }
2328
  if($cdm_entity->class == 'TaxonNodeDto'){
2329
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2330
  }
2331
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2332
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2333
  }
2334
  return $attributes;
2335
}
2336

    
2337

    
2338
/**
2339
 * Creates a short version of a taxonname.
2340
 *
2341
 * The short name is created by using the taggedTitle field of
2342
 * TaxonNodeDTO instances.
2343
 * If the taggedTitle if empty the fullname will be returned.
2344
 *
2345
 * @param object $taxonNodeDTO
2346
 *   A TaxonNodeDTO object
2347
 *
2348
 * @return string
2349
 */
2350
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2351

    
2352
  $nameStr = '';
2353

    
2354
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2355

    
2356
  // Get all tagged text tokens of the scientific name.
2357
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2358
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2359
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2360
    }
2361
  }
2362
  $nameStr = trim($nameStr);
2363

    
2364
  if ($nameStr) {
2365

    
2366
    // Do not return short names for these.
2367
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2368
      return $nameStr;
2369
    }
2370

    
2371
    /*
2372
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2373
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2374
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2375
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2376
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2377
    */
2378
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2379
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2380
      return $matches[1][0] . "." . $matches[3][0];
2381
    }
2382
    else {
2383
      return $nameStr;
2384
    }
2385
  }
2386
  else {
2387
    return $taxonNodeDTO->titleCache;
2388
  }
2389
}
2390

    
2391
/**
2392
 * Check if a taxon is accepted by the current taxonomic tree.
2393
 *
2394
 * @param mixed $taxon
2395
 *   The Taxon obkect to check.
2396
 *
2397
 * @return bool
2398
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2399
 */
2400
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2401

    
2402
  $defaultTreeUuid = get_current_classification_uuid();
2403

    
2404
  if (isset($taxon->taxonNodes)) {
2405
    $taxonNodes = $taxon->taxonNodes;
2406
  }
2407
  else {
2408
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2409
  }
2410

    
2411
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2412
    foreach ($taxonNodes as $node) {
2413
      if (isset($node->classification)){
2414
        if(is_object($node->classification)) {
2415
          if ($node->classification->uuid == $defaultTreeUuid) {
2416
            return TRUE;
2417
          }
2418
        }
2419
        else {
2420
          if ($node->classification == $defaultTreeUuid) {
2421
            return TRUE;
2422
          }
2423
        }
2424
      }
2425
    }
2426
  }
2427

    
2428
  return FALSE;
2429
}
2430

    
2431
/**
2432
 * Checks is the source has one of the given types.
2433
 *
2434
 * @param object $source
2435
 *   The original source entity
2436
 * @param array $types
2437
 *   An array of elementd of the OriginalSourceType enumeration
2438
 *   If not set the default will be used which is:
2439
 *    - Lineage
2440
 *    - PrimaryMediaSource
2441
 *    - PrimaryTaxonomicSource
2442
 *    - Unknown
2443
 *    - Other
2444
 * @return boolean
2445
 */
2446
  function _is_original_source_type($source, $types = null) {
2447
    // this is the default
2448
    // maybe this should also be put into the settings
2449
    static $default = array(
2450
      OriginalSourceType::Lineage,
2451
      OriginalSourceType::PrimaryMediaSource,
2452
      OriginalSourceType::PrimaryTaxonomicSource,
2453
      OriginalSourceType::Unknown,
2454
      OriginalSourceType::Other,
2455
    );
2456

    
2457
    if(!$types){
2458
      $types = $default;
2459
    }
2460
    return isset($source->type) && in_array($source->type, $types);
2461
  }
2462

    
2463
/**
2464
 * Collects all the media from a list of description elements.
2465
 *
2466
 * @param array $descriptionElements
2467
 *   The description elements from which to collect the media.
2468
 *
2469
 * @return array
2470
 *   The output with all the collected media.
2471
 */
2472
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2473

    
2474
  $outArrayOfMedia = array();
2475

    
2476
  // Avoiding a warning box in Drupal for Flora Malesiana.
2477
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2478
    foreach ($descriptionElements as $descriptionElement) {
2479
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2480
        foreach ($descriptionElement->media as $media) {
2481
          if (is_object($media)) {
2482
            $outArrayOfMedia[] = $media;
2483
          }
2484
        }
2485
      }
2486
    }
2487
  }
2488
  return $outArrayOfMedia;
2489
}
2490

    
2491
/**
2492
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2493
 *
2494
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2495
 *
2496
 * @see cdm_fetch_visible_annotations()
2497
 *
2498
 * @param array $cdm_entities
2499
 *   An array of CdmBase instances or a single instance.
2500
 * @param string $footnote_list_key_suggestion
2501
 *
2502
 * @return array of footnote keys
2503
 */
2504
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2505

    
2506
  $footNoteKeys = array();
2507

    
2508
  // Is argument cdmBase an array?
2509
  if (!is_array($cdm_entities)) {
2510
    $cdmBase_array = array();
2511
    $cdmBase_array[] = $cdm_entities;
2512
  }
2513
  else {
2514
    $cdmBase_array = $cdm_entities;
2515
  }
2516

    
2517
  // Getting the key for the footnotemanager.
2518
  if (isset($footnote_list_key_suggestion)) {
2519
    $footnote_list_key = $footnote_list_key_suggestion;
2520
  }
2521
  else {
2522
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2523
  }
2524

    
2525
  // Adding the footnotes keys.
2526
  foreach ($cdmBase_array as $cdmBase_element) {
2527
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2528
    if (is_array($annotations)) {
2529
      foreach ($annotations as $annotation) {
2530
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2531
      }
2532
    }
2533
  }
2534

    
2535
  return $footNoteKeys;
2536
}
2537

    
2538

    
2539
/**
2540
 * Creates a CDM Dynabox.
2541
 *
2542
 * @param string $dynabox_id
2543
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2544
 * @param string $label
2545
 *   The clickable text to show.
2546
 * @param string $content_url
2547
 *   The cdm REST service request url wich will deliver the content to be shown
2548
 *   once the dynabox toggles open.
2549
 * @param string $theme
2550
 *   The theme to be used for rendering the cdm REST service response with is
2551
 *   returned from the $content_url.
2552
 * @param string $link_alt_text
2553
 *   The value for the alt attribute of the dynabox link.
2554
 * @param array $enclosingtags
2555
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2556
 *   element itself, $enclosingtags[1] is the tag to be used for the
2557
 *   dynabox_content (optional)
2558
 * @param array $attributes
2559
 * @param $content_element_selector
2560
 *   Optional jQuery selector which can be used to reference a dom element which should
2561
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2562
 *  element will be placed in this container.
2563
 *
2564
 * @param string $open_callback
2565
 *   optional javascript call back function to be triggered after toggling the box to
2566
 *   the open state.
2567
 * @param string $close_callback
2568
 *   optional javascript call back function to be triggered after toggling the box to
2569
 *   the closed state.
2570
 * @return string Returns HTML for a dynabox.
2571
 * Returns HTML for a dynabox.
2572
 */
2573
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2574
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2575
                     $content_element_selector = null,
2576
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2577
  $out = '';
2578

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

    
2582
  if(!array_key_exists('class', $attributes)) {
2583
    $attributes['class'] = array();
2584
  }
2585
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2586
  $dynabox_attributes = drupal_attributes($attributes);
2587

    
2588

    
2589
  _add_js_domEvent(); // requires domEvent.js
2590
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2591
  drupal_add_js("
2592
  jQuery(document).ready(
2593
      function() {
2594
        dynabox('". $dynabox_id ."',
2595
          {
2596
            open_callback: " . $open_callback .",
2597
            close_callback: " . $close_callback .
2598
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2599
          }
2600
        );
2601
      }
2602
   );",
2603
   array(
2604
    'type'=>'inline',
2605
    'scope'=>'footer'
2606
    )
2607
  );
2608

    
2609

    
2610
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2611
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2612
  $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>';
2613
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2614
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2615
  $out .= '    </' . $enclosingtags[1] . '>';
2616
  $out .= '  </' . $enclosingtags[0] . '>';
2617
  $out .= '<!-- dynabox end -->';
2618
  return $out;
2619
}
2620

    
2621
/**
2622
 * Checks whether a feature has any description elements.
2623
 *
2624
 * @param mixed $featureNode
2625
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2626
 *
2627
 * @see _mergeFeatureTreeDescriptions()
2628
 *
2629
 * @return bool
2630
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2631
 *   contains at least one non empty TextData or at least one DescriptionElement
2632
 *   of an other type. A TextData element holding a multilanguageText or a
2633
 *   source reference is considered to be not empty.
2634
 *
2635
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2636
 *       see $block_content_is_not_empty in make_feature_block_list() and
2637
 *       $feature_block_has_content in compose_feature_block_items_generic
2638
 */
2639
function has_feature_node_description_elements($featureNode) {
2640

    
2641
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2642
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2643
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2644
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2645
          && $descriptionElement->multilanguageText_L10n->text != ''
2646
          || isset($descriptionElement->sources[0])
2647
          || isset($descriptionElement->media[0]) ) {
2648
          return TRUE;
2649
        }
2650
      }
2651
    }
2652
  }
2653
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2654
    foreach ($featureNode->childNodes as $child) {
2655
      if (has_feature_node_description_elements($child)) {
2656
        return TRUE;
2657
      }
2658
    }
2659
  }
2660
  return FALSE;
2661
}
2662

    
2663
/**
2664
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2665
 *
2666
 * @param $chapter
2667
 *   The taxon page chapter or part
2668
 */
2669
function cdm_check_valid_taxon_page($chapter){
2670
  static $taxon_tabs = null;
2671

    
2672
  cdm_check_valid_portal_page();
2673

    
2674
  if($taxon_tabs == null){
2675
    $taxon_tabs = array('all', 'description');
2676
    foreach(get_taxon_tabs_list() as $tab){
2677
      $taxon_tabs[] = strtolower($tab);
2678
    }
2679
  }
2680

    
2681
  if(!in_array($chapter, $taxon_tabs)){
2682
    // oops this is not a valid chapter name
2683
    http_response_code(404); // 404 = Not Found
2684
  }
2685

    
2686
}
2687

    
2688
/**
2689
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2690
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2691
 *
2692
 * @param $preg_pattern
2693
 *   Optional regular expression pattern to be used in preg_match().
2694
 */
2695
function cdm_check_valid_portal_page($preg_pattern = null){
2696
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2697
  if($preg_pattern === null){
2698
    $preg_pattern = $ends_with_file_suffix_pattern;
2699
  }
2700
  if(preg_match($preg_pattern, $_GET['q'])){
2701
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2702
    http_response_code(404); // 404 = Not Found
2703
    exit('HTTP 404');
2704
  }
2705
}
2706

    
2707
/**
2708
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2709
 *
2710
 * @param $text_a
2711
 * @param $text_b
2712
 * @return string
2713
 */
2714
function diff_viewer($text_a, $text_b) {
2715

    
2716
  static $diff_viewer_count = 0;
2717

    
2718
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2719

    
2720
  // http://code.stephenmorley.org/php/diff-implementation/
2721
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2722
  drupal_add_css(drupal_get_path('module',
2723
      'cdm_dataportal') . '/css/diff.css');
2724
  _add_jquery_ui();
2725
  drupal_add_js(
2726
    'jQuery(document).ready( function(){
2727
        jQuery(\'#' . $element_id . '\').accordion({
2728
        collapsible: true,
2729
        active: false,
2730
        fillSpace: true,
2731
        }).children(\'div\').css({ \'height\': \'auto\' });
2732
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2733
     });'
2734
    , array(
2735
    'type' => 'inline',
2736
    'scope' => 'footer'
2737
  ));
2738

    
2739
  $diff = Diff::compare($text_a,
2740
    $text_b);
2741
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2742
    . Diff::toTable($diff, '', '')
2743
    . '</div></div>';
2744
  return $diff_viewer_markup;
2745
}
2746

    
2747

    
Add picture from clipboard (Maximum size: 40 MB)