Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

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

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

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

    
282
  global $base_url;
283

    
284

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

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

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

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

    
334

    
335
function _add_js_utis_client($jquery_selector){
336

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

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

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

    
377

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

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

    
388
    return '';
389
  }
390

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

    
401

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

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

    
411
    return '';
412
  }
413

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

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

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

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

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

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

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

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

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

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

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

    
500
   $items['cdm_dataportal/specimen/accession_number'] = array(
501
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
502
        'access arguments' => array('access cdm content'),
503
        'type' => MENU_CALLBACK,
504
        // Expected callback arguments: accession number.
505
    );
506
  $items['cdm_dataportal/named_area'] = array(
507
    'page callback' => 'cdm_dataportal_named_area_page_view',
508
    'access arguments' => array('access cdm content'),
509
    'type' => MENU_CALLBACK,
510
    // Expected callback arguments: uuid.
511
  );
512

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

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

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

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

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

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

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

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

    
587

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
755
  return $items;
756
}
757

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

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

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

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

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

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

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

    
798

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

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

    
809
    }
810
    return $requirements;
811
}
812

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

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

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

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

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

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

    
992
  return $taxon_uuid;
993
}
994

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

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

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

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

    
1036
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1037
  return $form;
1038
}
1039

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

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

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

    
1057
  $destination_array = drupal_get_destination();
1058
  $destination = $destination_array['destination'];
1059

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

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

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

    
1086
  return $form;
1087

    
1088
}
1089

    
1090
/**
1091
 *
1092
 * @ingroup compose
1093
 */
1094
function compose_classification_selector() {
1095

    
1096
  $destination_array = drupal_get_destination();
1097
  $destination = $destination_array['destination'];
1098

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

    
1103
  $current_classification_uuid = get_current_classification_uuid();
1104

    
1105

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

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

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

    
1135
  return $render_array;
1136
}
1137

    
1138

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

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

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

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

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

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

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

    
1209
  cdm_check_valid_portal_page();
1210

    
1211
  return compose_cdm_reference_page($uuid);
1212
}
1213

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

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

    
1230
  cdm_check_valid_portal_page();
1231

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

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

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

    
1268
  static $media = NULL;
1269

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

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

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

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

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

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

    
1304
  return $media[$taxon->uuid];
1305
}
1306

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

    
1317
  static $occurences = NULL;
1318

    
1319
  if(!isset($occurences)) {
1320
    $occurences = array();
1321
  }
1322

    
1323
  if (!isset($occurences[$taxon->uuid])){
1324

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

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

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

    
1341

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

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

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

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

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

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

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

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

    
1509
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1510

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

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

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

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

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

    
1536
  cdm_check_valid_portal_page();
1537

    
1538
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1539

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

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

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

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

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

    
1577

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

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

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

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

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

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

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

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

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

    
1667
        if (isset($specimen_or_observation) && $specimen_or_observation){
1668

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

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

    
1684
    cdm_check_valid_portal_page();
1685

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

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

    
1702

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

    
1724

    
1725
        }
1726
        $specimenpage = new stdClass();
1727

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

    
1732
        $render_array['markup'] = $specimen_table;
1733

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

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

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

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

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

    
1775
    return $specimenpage;
1776
}
1777

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

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

    
1796
  $named_area_page->title = $named_area->representation_L10n;
1797

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

    
1802
  return $named_area_page;
1803
}
1804

    
1805
function cdm_dataportal_named_area_page_view($uuid) {
1806

    
1807
  cdm_check_valid_portal_page();
1808

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

    
1817

    
1818
}
1819

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

    
1844
  cdm_check_valid_portal_page();
1845

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

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

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

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

    
1954

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

    
1961
    // type designations
1962
    $type_designations_render_array = compose_type_designations($taxon_name->uuid);
1963

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

    
1975

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

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

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

    
1994

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

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

    
2010
function cdm_dataportal_registration_view($registration_identifier_encoded) {
2011

    
2012
  $registration_identifier = urldecode($registration_identifier_encoded);
2013

    
2014
  RenderHints::pushToRenderStack('registration_page');
2015
  RenderHints::setFootnoteListKey('registration_page');
2016

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

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

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

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

    
2046
  RenderHints::popFromRenderStack();
2047
  RenderHints::clearFootnoteListKey();
2048

    
2049
  return $render_array ;
2050
}
2051

    
2052

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

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

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

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

    
2086
  $taxonPager = cdm_dataportal_search_taxon_execute();
2087

    
2088
  $showThumbnails = do_showThumbnails();
2089

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

    
2094
  drupal_add_js('jQuery(document).ready(function() {
2095

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

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

    
2120
  drupal_set_title(t('Search results'), PASS_THROUGH);
2121

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

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

    
2133
    $specimenPager = cdm_dataportal_search_blast_execute();
2134

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

    
2141

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

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

    
2159
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2160

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

    
2165
  return $render_array;
2166
}
2167

    
2168

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

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

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

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

    
2212
  return $showThumbnails;
2213
}
2214

    
2215

    
2216

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

    
2242
  $tab = get_default_taxon_tab();
2243
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2244

    
2245
  if (!$uuid) {
2246
    return FALSE;
2247
  }
2248

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

    
2263
function path_to_specimen($uuid) {
2264

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

    
2273
function path_to_specimen_by_accession_number($accession_number) {
2274

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

    
2283
function path_to_named_area($uuid) {
2284

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

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

    
2322
}
2323

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

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

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

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

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

    
2405
  return $res;
2406
}
2407

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

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

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

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

    
2490

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

    
2505
  $nameStr = '';
2506

    
2507
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2508

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

    
2517
  if ($nameStr) {
2518

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

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

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

    
2555
  $defaultTreeUuid = get_current_classification_uuid();
2556

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

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

    
2581
  return FALSE;
2582
}
2583

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

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

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

    
2627
  $outArrayOfMedia = array();
2628

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

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

    
2659
  $footNoteKeys = array();
2660

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

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

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

    
2688
  return $footNoteKeys;
2689
}
2690

    
2691

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

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

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

    
2741

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

    
2762

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

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

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

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

    
2825
  cdm_check_valid_portal_page();
2826

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

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

    
2839
}
2840

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

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

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

    
2881
  static $diff_viewer_count = 0;
2882

    
2883
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2884

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

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

    
2912

    
(10-10/18)