Project

General

Profile

Download (97.8 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/symbols');
26
  module_load_include('inc', 'cdm_dataportal', 'includes/common');
27
  module_load_include('inc', 'cdm_dataportal', 'includes/footnotes');
28
  module_load_include('inc', 'cdm_dataportal', 'includes/agent');
29
  module_load_include('inc', 'cdm_dataportal', 'includes/name');
30
  module_load_include('inc', 'cdm_dataportal', 'includes/taxon');
31
  module_load_include('inc', 'cdm_dataportal', 'includes/taxon-node');
32
  module_load_include('inc', 'cdm_dataportal', 'includes/references');
33
  module_load_include('inc', 'cdm_dataportal', 'includes/pages');
34
  module_load_include('inc', 'cdm_dataportal', 'includes/media');
35
  module_load_include('inc', 'cdm_dataportal', 'includes/maps');
36
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
37
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences_new'); // tmp file, should be merged later with occurrences.inc
38
  module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
39
  module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
40

    
41
  module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
42
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
43
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
44
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
45
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
46
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
47
  module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
48

    
49
  module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
50
  module_load_include('php', 'cdm_dataportal', 'classes/footnote');
51
  module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
52
  module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
53

    
54
  /* ============================ java script functions ============================= */
55

    
56

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

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

    
78
  /**
79
   */
80
  function drupal_add_js_rowToggle($tableId){
81

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

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

    
95
    $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
96

    
97
    drupal_add_js_async(cdm_webservice_url(). 'js/cdm_ws_progress.js', $callback);
98

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

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

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

    
128
  function _add_js_resizable_element($selector, $y_axis_only) {
129

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

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

    
151
  function _add_js_openlayers() {
152

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

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

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

    
173

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

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

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

    
204
  }
205

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

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

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

    
269
  /**
270
   * @todo Please document this function.
271
   * @see http://drupal.org/node/1354
272
   */
273
  function _add_js_ahah() {
274

    
275
    _add_js_domEvent(); // requires domEvent.js
276
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
277
  }
278

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

    
285
  global $base_url;
286

    
287

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

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

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

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

    
337

    
338
function _add_js_utis_client($jquery_selector){
339

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

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

    
361
function _add_js_universalviewer($jquery_selector, $manifest_uri){
362

    
363
  $universalviewer_path  = drupal_get_path('module',    'cdm_dataportal') . '/js/universalviewer';
364

    
365
  drupal_add_css($universalviewer_path . '/uv/uv.css');
366
  drupal_add_css($universalviewer_path . '/uv-fix.css');
367

    
368
  // offline.js is all of these dependencies concatenated (jQuery, CoreJS, and JSViews)
369
  drupal_add_js($universalviewer_path . '/uv/lib/offline.js',
370
      array(
371
      'type' => 'file',
372
      'group' => JS_LIBRARY,
373
      'cache' => TRUE,
374
      'preprocess' => FALSE
375
    )
376
  );
377
  drupal_add_js($universalviewer_path . '/uv/helpers.js',
378
    array(
379
      'type' => 'file',
380
      'group' => JS_LIBRARY,
381
      'cache' => TRUE,
382
      'preprocess' => FALSE
383
    )
384
  );
385
  // from UV 3.x documentation:
386
  // "root:
387
  // The path to the uv directory. Use a relative path e.g. root: '../../uv'
388
  // Don't start your path with a / otherwise requirejs will not append .js to
389
  // dependencies and they won't load."
390
  //
391
  // universalviewerPath will be used to build the root config variable.
392
  $iCleanUrlRequest = strpos($_SERVER['REQUEST_URI'], 'q=cdm_dataportal/') === false;
393
  if($iCleanUrlRequest){
394
    $folders_up = preg_replace('/[^\/]+/', '..', $_GET['q']);
395
    $folders_up = preg_replace('/\.\.$/', '', $folders_up);
396
  } else {
397
    $folders_up = '';
398
  }
399
  $basePath = base_path();
400
  $config_file = 'uv-config.json';
401
  drupal_add_js('
402
      console.log(\'jQuery inline: \' + jQuery.fn.jquery);
403
      jQuery(window).on(\'uvLoaded\', function() {
404
        jQuery( "' . $jquery_selector . '" ).jqUniversalviewer(
405
        {
406
          root: \'' . $folders_up . $universalviewer_path . '/uv\',
407
          configUri: \'' . $basePath . $universalviewer_path . '/'. $config_file . '\',
408
          manifestUri: \'' . $manifest_uri . '\'
409
        }
410
        );
411
      });',
412
    array(
413
      'type' => 'inline',
414
      'scope' => 'footer',
415
      'group' => JS_DEFAULT,
416
      'weight' => 0,
417
    )
418
  );
419
  drupal_add_js($universalviewer_path . '/jq-universalviewer.js',
420
    array(
421
      'type' => 'file',
422
      'scope' => 'footer',
423
      'group' => JS_DEFAULT,
424
      'weight' => 10,
425
      'cache' => TRUE,
426
      'preprocess' => FALSE
427
    )
428
  );
429
  // ui.js must be last
430
  drupal_add_js($universalviewer_path . '/uv/uv.js',
431
    array(
432
      'type' => 'file',
433
      'scope' => 'footer',
434
      'group' => 300, // IMPORTANT!
435
      'cache' => TRUE,
436
      'preprocess' => FALSE
437
    )
438
  );
439
}
440

    
441
function _add_js_derivation_tree($jquery_selector){
442
  drupal_add_js(drupal_get_path('module','cdm_dataportal') . '/js/derivation-tree.js');
443
  drupal_add_js('jQuery(document).ready(function() {
444
      jQuery( "' . $jquery_selector . '" ).derivationTree();
445
    });',
446
    array('type' => 'inline')
447
  );
448
}
449

    
450
  /**
451
   * Provides the markup for an font awesome icon.
452
   *
453
   * The icons is created in default size without any extra features.
454
   *
455
   * The available icons are listed here http://fontawesome.io/cheatsheet/
456
   * fontawesome icons have much more features than implemented here in this function,
457
   * for spinning icons, fixed width icons, rotation, etc please checkout the
458
   * examples at http://fontawesome.io/examples/
459
   *
460
   * @parameter $icon_name
461
   *  The name of the icon which starts with 'fa-'
462
   *
463
   * @return String
464
   *    the markup for the icon in an <i> tag
465
   *
466
   */
467
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
468
    _add_font_awesome_font();
469

    
470
    if($icon_name){
471
      if(!isset($attributes['class'])){
472
        $attributes['class'] = array();
473
      }
474
      $attributes['class'][] = 'fa';
475
      $attributes['class'][] = $icon_name;
476

    
477
      return '<i ' . drupal_attributes($attributes) . '></i>';
478
    }
479

    
480
    return '';
481
  }
482

    
483
/**
484
 * see https://fontawesome.com/how-to-use/on-the-web/styling/stacking-icons
485
 * @param array $fa_icons_markup
486
 *  Array of font awesome icon markup preferably created by font_awesome_icon_markup()
487
 *
488
 * @return string
489
 *  The markup
490
 */
491
function font_awesome_icon_stack($fa_icons_markup, $attributes = array(), $no_resize = TRUE){
492

    
493

    
494
    if(!isset($attributes['class'])){
495
      $attributes['class'] = array();
496
    }
497
    if($no_resize){
498
      $attributes['class'][] = 'fa-stack-no-resize';
499
    } else {
500
      $attributes['class'][] = 'fa-stack';
501
    }
502

    
503
    return '<span ' . drupal_attributes($attributes) . '>' . join('', $fa_icons_markup) . '</span>';
504
}
505

    
506
/**
507
 * @param string $glyph_name
508
 *   The name of the gloyph (e.g. 'icon-interal-link-alt-solid') for the foll list please
509
 *   refer to modules/cdm_dataportal/fonts/custom-icon-font
510
 * @param array $attributes
511
 * @return string
512
 */
513
  function custom_icon_font_markup($glyph_name = NULL, $attributes = array()){
514
    _add_font_custom_icon_font();
515

    
516

    
517
    if($glyph_name){
518
      if(!isset($attributes['class'])){
519
        $attributes['class'] = array();
520
      }
521
      $attributes['class'][] = $glyph_name;
522

    
523
      return '<i ' . drupal_attributes($attributes) . '></i>';
524
    }
525

    
526
    return '';
527
  }
528

    
529
/**
530
 * Adds the css  containing the font awesome icons to the html header.
531
 */
532
function _add_font_awesome_font()
533
{
534
  // $fa_font_version = 'font-awesome-4.6.3/css/font-awesome.min.css';
535
  $fa_font_version = 'fontawesome-free-5.9.0-web/css/all.css';
536
  $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/' . $fa_font_version;
537

    
538
  drupal_add_html_head_link(
539
    array(
540
      'href' => $font_awesome_css_uri,
541
      'rel' => 'stylesheet'
542
    )
543
  );
544
}
545

    
546
/**
547
 * Adds the css  containing the font awesome icons to the html header.
548
 */
549
function _add_font_custom_icon_font()
550
{
551

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

    
554
  drupal_add_html_head_link(
555
    array(
556
      'href' => $custom_icon_font_css_uri,
557
      'rel' => 'stylesheet'
558
    )
559
  );
560
}
561

    
562
/* ====================== hook implementations ====================== */
563
  /**
564
   * Implements hook_permission().
565
   *
566
   * Valid permissions for this module.
567
   *
568
   * @return array
569
   *   An array of valid permissions for the cdm_dataportal module.
570
   */
571
  function cdm_dataportal_permission() {
572
    return array(
573
      'administer cdm_dataportal' => array(
574
        'title' => t('Administer CDM DataPortal settings'),
575
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
576
      ),
577
      'access cdm content' => array(
578
        'title' => t('Access CDM content'),
579
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
580
      ),
581
    );
582
  }
583

    
584
/**
585
 * Implements hook_menu().
586
 */
587
function cdm_dataportal_menu() {
588
  $items = array();
589

    
590
  // @see settings.php.
591
  cdm_dataportal_menu_admin($items);
592
  cdm_dataportal_menu_help($items);
593

    
594
  $items['cdm_dataportal/names'] = array(
595
    'page callback' => 'cdm_dataportal_view_names',
596
    'access arguments' => array('access cdm content'),
597
    'type' => MENU_CALLBACK,
598
  );
599

    
600
  // Optional callback arguments: page.
601
  $items['cdm_dataportal/taxon'] = array(
602
    'page callback' => 'cdm_dataportal_taxon_page_view',
603
    'access arguments' => array('access cdm content'),
604
    'type' => MENU_CALLBACK,
605
    // Expected callback arguments: uuid.
606
  );
607

    
608
  $items['cdm_dataportal/occurrence'] = array(
609
        'page callback' => 'cdm_dataportal_specimen_page_view',
610
        'access arguments' => array('access cdm content'),
611
        'type' => MENU_CALLBACK,
612
        // Expected callback arguments: uuid.
613
    );
614

    
615
  $items['cdm_dataportal/description'] = array(
616
        'page callback' => 'cdm_dataportal_description_page_view',
617
        'access arguments' => array('access cdm content'),
618
        'type' => MENU_CALLBACK,
619
        // Expected callback arguments: uuid.
620
    );
621

    
622
   $items['cdm_dataportal/specimen/accession_number'] = array(
623
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
624
        'access arguments' => array('access cdm content'),
625
        'type' => MENU_CALLBACK,
626
        // Expected callback arguments: accession number.
627
    );
628
  $items['cdm_dataportal/named_area'] = array(
629
    'page callback' => 'cdm_dataportal_named_area_page_view',
630
    'access arguments' => array('access cdm content'),
631
    'type' => MENU_CALLBACK,
632
    // Expected callback arguments: uuid.
633
  );
634

    
635
  $items['cdm_dataportal/name'] = array(
636
    'page callback' => 'cdm_dataportal_name_page_view',
637
      /*
638
    'page arguments' => array(
639
       'taxon_name_uuid',
640
       'taxon_to_hide_uuid',
641
       'synonym_uuid' => NULL
642
      ),
643
      */
644
    'access arguments' => array('access cdm content'),
645
    'type' => MENU_CALLBACK,
646
    // Expected callback arguments: uuid.
647
  );
648

    
649
  $items['cdm_dataportal/reference'] = array(
650
    'page callback' => 'cdm_dataportal_view_reference',
651
    'access arguments' => array('access cdm content'),
652
    'type' => MENU_CALLBACK,
653
    // Expected callback arguments: uuid.
654
  );
655

    
656
  $items['cdm_dataportal/reference/list'] = array(
657
    'page callback' => 'cdm_dataportal_view_reference_list',
658
    'access arguments' => array('access cdm content'),
659
    'type' => MENU_CALLBACK,
660
    // Expected callback arguments: uuid.
661
  );
662

    
663
  $items['cdm_dataportal/media'] = array(
664
    'page callback' => 'cdm_dataportal_view_media',
665
    'access arguments' => array('access cdm content'),
666
    'type' => MENU_CALLBACK,
667
    // Expected callback arguments:
668
    // uuid, mediarepresentation_uuid, part_uuid or part#.
669
  );
670

    
671
  $items['cdm_dataportal/polytomousKey'] = array(
672
    'page callback' => 'cdm_dataportal_view_polytomousKey',
673
    'access arguments' => array('access cdm content'),
674
    'type' => MENU_CALLBACK,
675
    // Expected callback arguments: polytomousKey->uuid.
676
  );
677

    
678
  $items['cdm_dataportal/search'] = array(
679
    'page callback' => 'cdm_dataportal_view_search_advanced',
680
    'access arguments' => array('access cdm content'),
681
    'type' => MENU_CALLBACK,
682
  );
683

    
684
  // Optional callback arguments: page.
685
  $items['cdm_dataportal/registration'] = array(
686
    'page callback' => 'cdm_dataportal_registration_page_view',
687
    'access arguments' => array('access cdm content'),
688
    'type' => MENU_CALLBACK,
689
    // Expected callback arguments: uuid.
690
  );
691

    
692
  // ------------ SEARCH -----------
693
  $items['cdm_dataportal/search/advanced'] = array(
694
    'title' => 'Advanced', // will be passed through t()
695
    'page callback' => 'cdm_dataportal_view_search_advanced',
696
    'access arguments' => array('access cdm content'),
697
    'type' => MENU_DEFAULT_LOCAL_TASK,
698
  );
699
  $items['cdm_dataportal/search/blast'] = array(
700
    'title' => 'Blast', // will be passed through t()
701
    'page callback' => 'cdm_dataportal_view_search_blast',
702
    'access arguments' => array('access cdm content'),
703
    'type' => MENU_LOCAL_TASK,
704
  );
705

    
706
  $items['cdm_dataportal/search/taxon_by_description'] = array(
707
    'title' => 'By content category', // will be passed through t()
708
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
709
    'access arguments' => array('access cdm content'),
710
    'type' => MENU_LOCAL_TASK,
711
  );
712
  $items['cdm_dataportal/search/results/taxon'] = array(
713
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
714
    'access arguments' => array('access cdm content'),
715
    'type' => MENU_CALLBACK,
716
  );
717

    
718
  $items['cdm_dataportal/search/results/specimen'] = array(
719
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
720
      'access arguments' => array('access cdm content'),
721
      'type' => MENU_CALLBACK,
722
  );
723

    
724
  /*
725
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
726
   * tabs in the subordinate paths work, accessing this 'page' will cause the
727
   * MENU_DEFAULT_LOCAL_TASK being displayed
728
   */
729
  $items['cdm_dataportal/registration-search'] = array(
730
    'title' => 'Search', // will be passed through t()
731
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
732
    'page arguments' => array("filter"),
733
    'access arguments' => array('access cdm content'),
734
    'type' => MENU_CALLBACK,
735
  );
736
  /*
737
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
738
   * defined at a higher level of the path (cdm_dataportal/registration-search)
739
   */
740
  $items['cdm_dataportal/registration-search/filter'] = array(
741
    'title' => 'Search', // will be passed through t()
742
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
743
    'page arguments' => array("filter"),
744
    'access arguments' => array('access cdm content'),
745
    'type' => MENU_DEFAULT_LOCAL_TASK,
746
  );
747
  /*
748
   * the MENU_LOCAL_TASK creates another tab
749
   */
750
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
751
    'title' => 'Taxon graph search', // will be passed through t()
752
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
753
    'page arguments' => array("taxongraph"),
754
    'access arguments' => array('access cdm content'),
755
    'type' => MENU_LOCAL_TASK,
756
  );
757

    
758
  // Optional callback arguments: page.
759
  $items['cdm_dataportal/search/agent'] = array(
760
    'page callback' => 'cdm_dataportal_view_search_agent',
761
    'access arguments' => array('access cdm content'),
762
    'type' => MENU_CALLBACK,
763
    // Expected callback arguments: uuid.
764
  );
765

    
766
  // ------------ menu items with variable path elements -----------
767

    
768
  // 'May not cache' in D5.
769
  $items['cdm_dataportal/name/%'] = array(
770
    // 'page callback' => 'cdm_dataportal_view_name',
771
    'page callback' => 'cdm_dataportal_name_page_view',
772
    'page arguments' => array(2, 3, 4, 5),
773
    'access arguments' => array('access cdm content'),
774
    'type' => MENU_CALLBACK,
775
  );
776

    
777
  // --- Local tasks for Taxon.
778
  // --- tabbed taxon page
779
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
780
    $items['cdm_dataportal/taxon/%'] = array(
781
      'title' => cdm_taxonpage_tab_label('General'),
782
      'page callback' => 'cdm_dataportal_taxon_page_view',
783
      'access arguments' => array('access cdm content'),
784
      'type' => MENU_CALLBACK,
785
      'weight' => 1,
786
      'page arguments' => array(2, "description")
787
      , // Expected callback arguments: taxon_uuid.
788
    );
789

    
790
    $items['cdm_dataportal/taxon/%/all'] = array(
791
      'title' => cdm_taxonpage_tab_label('General'),
792
      'page callback' => 'cdm_dataportal_taxon_page_view',
793
      'access arguments' => array('access cdm content'),
794
      'type' => MENU_CALLBACK,
795
      'weight' => 2,
796
      'page arguments' => array(2, "all")
797
      , // Expected callback arguments: taxon_uuid.
798
    );
799

    
800
    $items['cdm_dataportal/taxon/%/description'] = array(
801
      'title' => cdm_taxonpage_tab_label('General'),
802
      'page callback' => 'cdm_dataportal_taxon_page_view',
803
      'access arguments' => array('access cdm content'),
804
      'type' => MENU_DEFAULT_LOCAL_TASK,
805
      'weight' => 2,
806
      'page arguments' => array(2, "description")
807
      , // Expected callback arguments: taxon_uuid.
808
    );
809

    
810
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
811
      'title' => cdm_taxonpage_tab_label('Synonymy'),
812
      'page callback' => 'cdm_dataportal_taxon_page_view',
813
      'access arguments' => array('access cdm content'),
814
      'type' => MENU_LOCAL_TASK,
815
      'weight' => 4,
816
      'page arguments' => array(2, "synonymy", 4)
817
      , // Expected callback arguments: taxon_uuid and ...
818
    );
819
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
820
      'title' => cdm_taxonpage_tab_label('Images'),
821
      'page callback' => 'cdm_dataportal_taxon_page_view',
822
      'access arguments' => array('access cdm content'),
823
      'type' => MENU_LOCAL_TASK,
824
      'weight' => 5,
825
      'page arguments' => array(2, "images")
826
      , // Expected callback arguments: taxon_uuid.
827
    );
828

    
829
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
830
      'title' => cdm_taxonpage_tab_label('Specimens'),
831
      'page callback' => 'cdm_dataportal_taxon_page_view',
832
      'access arguments' => array('access cdm content'),
833
      'type' => MENU_LOCAL_TASK,
834
      'weight' => 6,
835
      'page arguments' => array(2, "specimens")
836
      , // Expected callback arguments: taxon_uuid.
837
    );
838

    
839
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
840
      'title' => cdm_taxonpage_tab_label('Keys'),
841
      'page callback' => 'cdm_dataportal_taxon_page_view',
842
      'access arguments' => array('access cdm content'),
843
      'type' => MENU_LOCAL_TASK,
844
      'weight' => 6,
845
      'page arguments' => array(2, "keys")
846
      , // Expected callback arguments: taxon_uuid.
847
    );
848

    
849
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
850
      'title' => cdm_taxonpage_tab_label('Experts'),
851
        'page callback' => 'cdm_dataportal_taxon_page_view',
852
        'access arguments' => array('access cdm content'),
853
        'type' => MENU_LOCAL_TASK,
854
        'weight' => 6,
855
        'page arguments' => array(2, "experts")
856
    , // Expected callback arguments: taxon_uuid.
857
    );
858

    
859
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
860
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
861
        'access arguments' => array('access cdm content'),
862
        'page arguments' => array(3,4,5),
863
        'type' => MENU_CALLBACK
864
    );
865
  }
866

    
867
  // --- refresh link for all cdmnode types
868
  foreach (cdm_get_nodetypes() as $type=>$name) {
869
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
870
        'title' => 'Refresh',
871
        'page callback' => 'cdm_dataportal_refresh_node',
872
        'access arguments' => array('administer cdm_dataportal'),
873
        'type' => MENU_LOCAL_TASK,
874
        'weight' => 100,
875
        'page arguments' => array($name, 2)
876
    );
877
  }
878

    
879
  return $items;
880
}
881

    
882
/**
883
 * Implements hook_init().
884
 *
885
 */
886
function cdm_dataportal_init() {
887
  if (!path_is_admin(current_path())) {
888
    //FIXME To add CSS or JS that should be present on all pages, modules
889
    //      should not implement this hook, but declare these files in their .info file.
890
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
891
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
892
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
893
  } else {
894
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
895
  }
896

    
897
  if(variable_get('cdm_debug_mode', FALSE)){
898
    $file = 'temporary://drupal_debug.txt';
899
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
900
  }
901

    
902
  $bibliography_settings = get_bibliography_settings();
903
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
904
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
905
}
906

    
907
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
908

    
909
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
910

    
911
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
912
    // force reloading of all and notify user about this special loading
913
    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: ')
914
        . l('Back to tabbed taxon page', $base_path));
915
    $base_path .= '/all';
916
  } else {
917
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
918
  }
919

    
920
  $parameters['cacheL2_refresh'] ='1';
921

    
922

    
923
  drupal_goto($base_path, array('query' => $parameters));
924
}
925

    
926
/**
927
 * Implements hook_requirements($phase)
928
 */
929
function cdm_dataportal_requirements($phase) {
930
    $requirements = array();
931
    if($phase == 'runtime'){
932

    
933
    }
934
    return $requirements;
935
}
936

    
937
/**
938
 * Implements hook_block_info().
939
 */
940
function cdm_dataportal_block_info() {
941

    
942
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
943
    // $block[1]["info"] = t("CDM DataPortal Credits");
944
    $block["2"] = array(
945
        "info" => t("CDM - Search Taxa"),
946
        "cache" => DRUPAL_NO_CACHE
947
      );
948
    // $block[3]["info"] = t("CDM Filters");
949
    $block["4"]["info"] = t("CDM  - Dataportal Print");
950
    $block["keys"]["info"] = t("CDM - Identification keys");
951
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
952
    $block["classification_breadcrumbs"] =  array(
953
        'info' => t('CDM - Classification breadcrumbs'),
954
        'cache' => DRUPAL_CACHE_PER_PAGE
955
      );
956
    $block["taxonomic_children"] =  array(
957
      'info' => t('CDM - Taxonomic children'),
958
      'cache' => DRUPAL_CACHE_PER_PAGE
959
    );
960
    $block["back_to_search_results"] =  array(
961
      'title' => '<none>',
962
      'info' => t('CDM - Back to search Results'),
963
      'cache' => DRUPAL_CACHE_PER_PAGE,
964
      'visibility' => BLOCK_VISIBILITY_LISTED,
965
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
966
    );
967
  $block['registrations_search_filter'] =  array(
968
    'title' => 'Filter registrations',
969
    'info' => t('CDM - Registrations search filter'),
970
    'cache' => DRUPAL_CACHE_PER_PAGE,
971
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
972
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
973
  );
974
  $block['registrations_search_taxongraph'] =  array(
975
    'title' => 'Taxonomic registration search',
976
    'info' => t('CDM - Registrations search by taxon graph'),
977
    'cache' => DRUPAL_CACHE_PER_PAGE,
978
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
979
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
980
  );
981
  $block['registrations_search'] =  array(
982
    'title' => 'Search',
983
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
984
    'cache' => DRUPAL_CACHE_PER_PAGE,
985
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
986
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
987
  );
988
  $block['utis_search'] =  array(
989
    'title' => 'UTIS Search',
990
    'info' => t('Query the Unified Taxonomic Information Service (UTIS)' ),
991
    'cache' => DRUPAL_CACHE_PER_PAGE,
992
    'visibility' => BLOCK_VISIBILITY_NOTLISTED
993
  );
994
  return $block;
995
}
996

    
997
/**
998
 * Implements hook_block_view().
999
 */
1000
function cdm_dataportal_block_view($delta) {
1001
  // TODO Rename block deltas (e.g. '2') to readable strings.
1002
  switch ($delta) {
1003
    // case 'delta-1':
1004
    // $block['subject'] = t('Credits');
1005
    // $block['content'] = theme('cdm_credits');
1006
    // return $block;
1007
    case '2':
1008
      $block['subject'] = t('Search taxa');
1009
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
1010
      $block['content'] = drupal_render($form);
1011

    
1012
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
1013
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
1014
      }
1015
      if (variable_get(CDM_SEARCH_BLAST_ENABLED)){
1016
          $block['content'] .= '<div>' . l(t('Blast Search'), 'cdm_dataportal/search/blast') . '</div>';
1017
      }
1018
      return $block;
1019
    case '4':
1020
      $block['subject'] = '';
1021
      $block['content'] = theme('cdm_print_button');
1022
      return $block;
1023
    case "keys":
1024
      $block['subject'] = t('Identification Keys');
1025
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
1026
      return $block;
1027
    case "fundedByEDIT":
1028
      // t('Funded by EDIT');
1029
      $text = '<none>';
1030
      $block['subject'] = $text;
1031
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
1032
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
1033
        'attributes' => array("target" => "EDIT"),
1034
        'absolute' => TRUE,
1035
        'html' => TRUE,
1036
      ));
1037
      return $block;
1038
    case 'classification_breadcrumbs':
1039
      $taxon_uuid = get_current_taxon_uuid();
1040
      $block['subject'] = '<none>';
1041
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
1042
      return $block;
1043
    case 'taxonomic_children':
1044
      $taxon_uuid = get_current_taxon_uuid();
1045
      $block['subject'] = '<none>';
1046
      $block['content'] = compose_taxonomic_children($taxon_uuid);
1047
      return $block;
1048
    case 'back_to_search_results':
1049
      $block['subject'] = '<none>';
1050
      if (isset_not_empty($_SESSION['cdm']['last_search'])) {
1051
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
1052
      }
1053
      return $block;
1054
    case 'registrations_search_filter':
1055
      $block['subject'] = '<none>';
1056
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
1057
      return $block;
1058
    case 'registrations_search_taxongraph':
1059
      $block['subject'] = '<none>';
1060
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
1061
      return $block;
1062
    case 'registrations_search':
1063
      _add_js_ui_accordion();
1064
      _add_font_awesome_font();
1065
      $block['subject'] = '<none>';
1066
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
1067
      $filter_form['#prefix'] = '<div>';
1068
      $filter_form['#suffix'] = '</div>';
1069
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
1070
      $taxongraph_form['#prefix'] = '<div>';
1071
      $taxongraph_form['#suffix'] = '</div>';
1072
      $block['content'] = array(
1073
        'accordion' => array(
1074
          '#markup' => '',
1075
          '#prefix' => '<div id="accordion">',
1076
          '#suffix' => '</div>',
1077
          'content' => array(
1078
            array('#markup' => '<h3>Filter</h3>'),
1079
            $filter_form,
1080
            array('#markup' => '<h3>Taxon graph</h3>'),
1081
            $taxongraph_form,
1082
          )
1083
        )
1084
    );
1085
       return $block;
1086
    case 'utis_search':
1087
      _add_js_utis_client('.utis_client');
1088
      $block['subject'] = '<none>';
1089
      $block['content'] = '<div class="utis_client"></div>';
1090
      return $block;
1091
    default:
1092
      return null;
1093
  }
1094
}
1095

    
1096

    
1097
/**
1098
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
1099
 *
1100
 * @return string
1101
 *   the taxon uuid or NULL
1102
 */
1103
function get_current_taxon_uuid()
1104
{
1105
  static $taxon_uuid;
1106

    
1107
  if(!isset($taxon_uuid)){
1108
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
1109
      $taxon_uuid = $_REQUEST['currentTaxon'];
1110
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
1111
      $taxon_uuid = arg(2);
1112
    } else {
1113
      $taxon_uuid = null;
1114
    }
1115
  }
1116
  return $taxon_uuid;
1117
}
1118

    
1119
/**
1120
 * Provides the uuid of the name for pages with the path ./name/{name_uuid}
1121
 *
1122
 * @return string
1123
 *   the name uuid or NULL
1124
 */
1125
function get_current_name_uuid()
1126
{
1127
  static $name_uuid;
1128
  if(!isset($name_uuid)){
1129
    if(arg(1) == 'name' && is_uuid(arg(2))) {
1130
      $name_uuid = arg(2);
1131
    } else {
1132
      $name_uuid = null;
1133
    }
1134
  }
1135
  return $name_uuid;
1136
}
1137

    
1138
/**
1139
 * Returns the currently classification tree in use.
1140
 *
1141
 * @return string
1142
 *   The uuid of the currently focused classification
1143
 */
1144
function get_current_classification_uuid() {
1145
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1146
    return $_SESSION['cdm']['taxonomictree_uuid'];
1147
  }
1148
  else {
1149
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1150
  }
1151
}
1152

    
1153
/*
1154
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
1155
 $_SESSION['cdm'] = NULL;
1156
 if(is_string($cdm_ws_uri_update)){
1157
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
1158
 }
1159
 }
1160

    
1161
 function cdm_dataportal_session_validate(){
1162
 if(!isset($_SESSION['cdm']['ws_uri'])){
1163
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
1164
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
1165
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
1166
 }
1167
 }
1168
 */
1169

    
1170
/**
1171
 * creates a  selector form for taxonomic trees.
1172
 *
1173
 * @return array
1174
 *  a drupal form array
1175
 */
1176
function cdm_taxonomictree_selector() {
1177
  _add_js_treeselector();
1178

    
1179
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1180
  return $form;
1181
}
1182

    
1183
/**
1184
 * @todo Please document this function.
1185
 * @see http://drupal.org/node/1354
1186
 *
1187
 * used by cdm_taxonomictree_selector()
1188
 *
1189
 * @deprecated use compose_classification_selector instead
1190
 */
1191
function cdm_taxonomictree_selector_form($form, &$form_state) {
1192

    
1193
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1194
  $form['#action'] = $url;
1195

    
1196
  $form['var'] = array(
1197
    '#weight' => -3,
1198
    '#type' => 'hidden',
1199
    '#value' => '[cdm][taxonomictree_uuid]',
1200
  );
1201

    
1202
  $destination_array = drupal_get_destination();
1203
  $destination = $destination_array['destination'];
1204

    
1205
  $form['destination'] = array(
1206
    '#weight' => -3,
1207
    '#type' => 'hidden',
1208
    '#value' =>  $destination,
1209
  );
1210
  $options = cdm_get_taxontrees_as_options(
1211
    FALSE,
1212
    variable_get(CDM_TAXONTREE_INCLUDES, [])
1213
  );
1214
  $form['val'] = array(
1215
    '#type' => 'select',
1216
    '#title' => t('Available classifications'),
1217
    '#default_value' => get_current_classification_uuid(),
1218
    '#options' => $options,
1219
    '#attributes' => array('class' => array('highlite-first-child')),
1220
  );
1221

    
1222
  return $form;
1223

    
1224
}
1225

    
1226
/**
1227
 *
1228
 * @ingroup compose
1229
 */
1230
function compose_classification_selector() {
1231

    
1232
  $destination_array = drupal_get_destination();
1233
  $destination = $destination_array['destination'];
1234

    
1235
  $options = cdm_get_taxontrees_as_options(
1236
    FALSE,
1237
    variable_get(CDM_TAXONTREE_INCLUDES, [])
1238
  );
1239
  $items = array();
1240

    
1241
  $current_classification_uuid = get_current_classification_uuid();
1242

    
1243

    
1244
  foreach($options as $uuid=>$label){
1245
    $class_attributes = '';
1246
    if($current_classification_uuid == $uuid){
1247
      $class_attributes  = array('focused');
1248
    }
1249
    $items[] = array(
1250
      'data' => l($label,
1251
        'cdm_api/setvalue/session',
1252
        array(
1253
          'query' => array(
1254
            'destination' => $destination,
1255
            'val' => $uuid,
1256
            'var' => '[cdm][taxonomictree_uuid]'
1257
          ),
1258
        )
1259
      ),
1260
      'class' => $class_attributes
1261
    );
1262
  }
1263

    
1264
  $render_array = array(
1265
    '#theme' => 'item_list',
1266
    '#type' => 'ul',
1267
    '#items' => $items
1268
  );
1269

    
1270
  return $render_array;
1271
}
1272

    
1273

    
1274
/* ====================== menu callback functions ====================== */
1275
/**
1276
 * @todo Please document this function.
1277
 * @see http://drupal.org/node/1354
1278
 */
1279
/*
1280
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1281
  static $comment_node_disabled =  0;
1282
  static $comment_node_read_only =  1;
1283
  static $comment_node_read_write =  2;
1284

    
1285
  if ($form_id == 'node_type_form'
1286
   && isset($form['identity']['type'])
1287
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1288
  ) {
1289
    $form['workflow']['comment'] = array(
1290
      '#type' => 'radios',
1291
      '#title' => t('Default comment setting'),
1292
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1293
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1294
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1295
    );
1296
  }
1297
}
1298
*/
1299

    
1300
/**
1301
 * Displays a list of the known taxonomic names.
1302
 *
1303
 * When the list of taxonomic names is displayed, long lists are split up into
1304
 * multiple pages.
1305
 *
1306
 * TODO: Parameters are still preliminary.
1307
 *
1308
 * @param string $beginsWith
1309
 * @param string $page
1310
 *   Page number to diplay defaults to page 1.
1311
 * @param bool $onlyAccepted
1312
 */
1313
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1314

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

    
1317
  /*
1318
  // FIXME the filter for accepted names will be a form element, thus this
1319
  // widget should be generated via form api preferably as block.
1320
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1321
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1322
  $out .= theme('cdm_listof_taxa', $taxonPager);
1323
  return $out;
1324
  */
1325
}
1326

    
1327
/**
1328
 * @todo Please document this function.
1329
 * @see http://drupal.org/node/1354
1330
 * @throws Exception
1331
 */
1332
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1333

    
1334
  cdm_check_valid_portal_page();
1335

    
1336
  return compose_cdm_reference_page($uuid);
1337
}
1338

    
1339
/**
1340
 * Creates a view on a all references contained in the portal.
1341
 *
1342
 * This function is used at the path cdm_dataportal/reference/list
1343
 */
1344
function cdm_dataportal_view_reference_list($page_index) {
1345
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get(CDM_SEARCH_RESULT_PAGE_SIZE, CDM_SEARCH_RESULT_PAGE_SIZE_DEFAULT), $page_index);
1346
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1347
}
1348

    
1349
/**
1350
 * @todo Please document this function.
1351
 * @see http://drupal.org/node/1354
1352
 */
1353
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1354

    
1355
  cdm_check_valid_portal_page();
1356

    
1357
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1358
  if (!$media) {
1359
    drupal_set_title(t('Media does not exist'), PASS_THROUGH);
1360
    return "";
1361
  }
1362
  return theme('cdm_media_page', array(
1363
    'media' => $media,
1364
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1365
    'partId' => $part,
1366
    ));
1367
}
1368

    
1369
/**
1370
 * Loads the media associated to the given taxon from the cdm server.
1371
 * The aggregation settings regarding taxon relathionships and
1372
 * taxonnomic childen are taken into account.
1373
 *
1374
 * The media lists are cached in a static variable.
1375
 *
1376
 * @param Taxon $taxon
1377
 *   A CDM Taxon entity
1378
 *
1379
 * @return array
1380
 *   An array of CDM Media entities
1381
 *
1382
 */
1383
  function _load_media_for_taxon($taxon) {
1384

    
1385
  static $media = NULL;
1386

    
1387
  if(!isset($media)) {
1388
    $media = array();
1389
  }
1390
  if (!isset($media[$taxon->uuid])) {
1391

    
1392

    
1393
    $mediaQueryParameters = taxon_media_query_parameters();
1394

    
1395
    $ws_endpoint = NULL;
1396
    if ( $mediaQueryParameters['includeTaxonomicChildren']) {
1397
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1398
    } else {
1399
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1400
    }
1401
    // this parameter is not yet used by the CDM_WS_PORTAL_TAXON_*MEDIA
1402
    // services
1403
    unset($mediaQueryParameters['includeTaxonomicChildren']);
1404

    
1405
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1406
        array(
1407
            $taxon->uuid,
1408
        ),
1409
        queryString($mediaQueryParameters)
1410
       );
1411
  }
1412

    
1413
  return $media[$taxon->uuid];
1414
}
1415

    
1416
/**
1417
 *
1418
 * @param Taxon $taxon
1419
 *   A CDM Taxon entitiy
1420
 *
1421
 * @return array
1422
 *   An array of CDM SpecimenOrObservation entities
1423
 *
1424
function _load_occurences_for_taxon($taxon){
1425

    
1426
  static $occurences = NULL;
1427

    
1428
  if(!isset($occurences)) {
1429
    $occurences = array();
1430
  }
1431

    
1432
  if (!isset($occurences[$taxon->uuid])){
1433

    
1434
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1435
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1436
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1437

    
1438
    $by_associatedtaxon_query = http_build_query(array(
1439
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1440
        'relationships' => implode(',', $relationship_choice['direct']),
1441
        'pageSize' => null // all hits in one page
1442
    )
1443
    );
1444

    
1445
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1446
        null,
1447
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1448
    );
1449

    
1450

    
1451
    if(isset($pager->records[0])){
1452
      $occurences[$taxon->uuid] =  $pager->records;
1453
    }
1454
  }
1455
  return $occurences[$taxon->uuid];
1456
}
1457
 */
1458

    
1459
/**
1460
 * Gets a Drupal variable, string or array and returns it.
1461
 *
1462
 * Similar to the variable_get() function of Drupal, except that this function
1463
 * is able to handle arrays correctly. This function is especially useful
1464
 * when dealing with collections of settings form elements (#tree = TRUE).
1465
 *
1466
 * @param string $variableKey
1467
 *   The Unique key of the Drupal variable in the Drupal variables table.
1468
 * @param string $defaultValueString
1469
 *   A string as for example derived from a CONSTANT.
1470
 *
1471
 * @return mixed
1472
 *   usually an array, depending on the nature of the variable.
1473
 *
1474
 * TODO compare with get_array_variable_merged() duplicate functions?
1475
 * @deprecated rather use get_array_variable_merged() since this function
1476
 * used an array as second parameter
1477
 */
1478
function mixed_variable_get($variableKey, $defaultValueString) {
1479
  $systemDefaults = unserialize($defaultValueString);
1480
  $storedSettings = variable_get($variableKey, array());
1481
  if (is_array($storedSettings)) {
1482
    // TODO better use drupal_array_merge_deep() ?
1483
    $settings = array_merge($systemDefaults, $storedSettings);
1484
  }
1485
  else {
1486
    $settings = $systemDefaults;
1487
  }
1488
  return $settings;
1489
}
1490

    
1491
/**
1492
 * Recursive function to convert an object into an array.
1493
 * also subordinate objects will be converted.
1494
 *
1495
 * @param object $object
1496
 *  the object to be converted
1497
 * @return array
1498
 *  The array
1499
 */
1500
function object_to_array($object) {
1501
  if(is_object($object) || is_array($object)) {
1502
    $array = (array)$object;
1503
    foreach ($array as $key=>$value){
1504
      $array[$key] = object_to_array($value);
1505
    }
1506
    return $array;
1507
  } else {
1508
    return $object;
1509
  }
1510
}
1511

    
1512
/**
1513
 * Searches the $collection for the cdm entitiy given as $element.
1514
 *
1515
 * The elements are compared by their UUID.
1516
 *
1517
 * @param $element
1518
 *  the CDM entitiy to search for
1519
 * @param $collection
1520
 *  the list of CDM entities to search in
1521
 *
1522
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1523
 *
1524
 */
1525
function contains_cdm_entitiy($element, $collection) {
1526
  $result = FALSE;
1527
  foreach ($collection as $a) {
1528
    if ($a->uuid == $element->uuid) {
1529
      $result = TRUE;
1530
    }
1531
  }
1532
  return $result;
1533
}
1534

    
1535
/**
1536
 * Filters the array $entity_list of CDM entities by the list
1537
 * of $excludes. Any element contained in the $excludes will be removed
1538
 * from included int the returned list.
1539
 *
1540
 * If the $entity_list is not an array the $excludes will be returned.
1541
 */
1542
function filter_cdm_entity_list($entity_list, $excludes) {
1543
  if (is_array($entity_list)) {
1544
    $result = $entity_list;
1545
    if ($excludes) {
1546
      foreach ($excludes as $exclude) {
1547
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1548
          $result[] = $exclude;
1549
        }
1550
      }
1551
    }
1552
  }
1553
  else {
1554
    $result = $excludes;
1555
  }
1556
  return $result;
1557
}
1558

    
1559
/**
1560
 * Wraps the given $html string into a render array suitable for drupal_render()
1561
 *
1562
 * @param $html
1563
 *   the html string, see
1564
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1565
 * @param $weight
1566
 *   A positive or negative number (integer or decimal).
1567
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1568
 * @param $prefix
1569
 *   Optional markup for the '#prefix' element of the render array
1570
 * @param $suffix
1571
 *   Optional markup for the '#suffix' element of the render array
1572
 *
1573
 * @return array
1574
 *   A render array
1575
 *
1576
 */
1577
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1578
  $render_array = array(
1579
    '#markup' => $html
1580
      );
1581
  if (is_numeric($weight)) {
1582
    $render_array['#weight'] = $weight;
1583
  }
1584
  if($prefix){
1585
    $render_array['#prefix'] = $prefix;
1586
  }
1587
  if($suffix) {
1588
    $render_array['#suffix'] = $suffix;
1589
  }
1590
  return $render_array;
1591
}
1592

    
1593
/**
1594
 * Loads the subgraph of a given PolytomousKeyNode.
1595
 *
1596
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1597
 * the CDM REST service.
1598
 *
1599
 * @param mixed $polytomousKeyNode
1600
 *   PolytomousKeyNode passed by reference.
1601
 *
1602
 * @return void
1603
 */
1604
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1605

    
1606
  if (!$polytomousKeyNode) {
1607
    return;
1608
  }
1609
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1610
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1611
    return;
1612
  }
1613
  if (!is_uuid($polytomousKeyNode->uuid)) {
1614
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1615
    return;
1616
  }
1617

    
1618
  $polytomousKeyNode = cdm_ws_get(CDM_WS_PORTAL_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1619

    
1620
  if (!$polytomousKeyNode) {
1621
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1622
    return;
1623
  }
1624

    
1625
  // Load children.
1626
  foreach ($polytomousKeyNode->children as &$childNode) {
1627
    _load_polytomousKeySubGraph($childNode);
1628
  }
1629
  return;
1630
}
1631

    
1632
/**
1633
 * @todo Please document this function.
1634
 * @see http://drupal.org/node/1354
1635
 */
1636
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1637

    
1638
  cdm_check_valid_portal_page();
1639

    
1640
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1641
  if (!$polytomousKey) {
1642
    drupal_set_title(t('Polytomous key does not exist'), PASS_THROUGH);
1643
    return "";
1644
  }
1645

    
1646
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1647
  if (is_array($sourcePager->records)) {
1648
    $polytomousKey->sources = $sourcePager->records;
1649
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1650
  }
1651

    
1652
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1653
  if (is_array($annotationPager->records)) {
1654
    $polytomousKey->annotations = $annotationPager->records;
1655
  }
1656

    
1657
  _load_polytomousKeySubGraph($polytomousKey->root);
1658
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1659
}
1660

    
1661
/**
1662
 * Creates a taxon page view or a chapter of it.
1663
 *
1664
 * The taxon page gives detailed information on a taxon, it shows:
1665
 *  - Taxon name.
1666
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1667
 *    heterotypic and finally followed by misapplied names.
1668
 *    The list is ordered historically.
1669
 *  - All description associated with the taxon.
1670
 *
1671
 * @param string $uuid
1672
 * @param string $chapter
1673
 *   Name of the part to display, valid values are:
1674
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1675
 *
1676
 * @return string
1677
 */
1678
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1679

    
1680
  cdm_check_valid_taxon_page($chapter);
1681

    
1682
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1683

    
1684

    
1685
  // Display the page for the taxon defined by $uuid.
1686
  // set_last_taxon_page_tab(arg(3));
1687
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1688
  if (!empty($taxonpage)) {
1689
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1690
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1691
  }
1692
  else {
1693
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1694
    return '';
1695
  }
1696
}
1697

    
1698
/**
1699
 * This function will generate the taxon page part ($chapter) and returns a taxonpage object
1700
 * which has two fields, one for the page title and one for the content. Later on in the
1701
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1702
 * function as the function parameters $title and $content.
1703
 *
1704
 * @param string $uuid
1705
 *   the uuid of the taxon to show
1706
 * @param string $chapter
1707
 *   Name of the part to display, valid values are:
1708
 *   'description', 'images', 'synonymy', 'all'.
1709
 *
1710
 * @return object with the following fields:
1711
 *   - title : the title of the page
1712
 *   - content: the content of the page
1713
 *
1714
 * @throws Exception
1715
 *
1716
 */
1717
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1718
  // Taxon object.
1719
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1720
  if (empty($taxon)) {
1721
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1722
    return null;
1723
  }
1724
  $taxonpage = new stdClass();
1725

    
1726
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1727
    'taxon' => $taxon
1728
  ));
1729

    
1730
  // Check if the taxon id contained in the currently selected tree.
1731
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1732

    
1733
  if (!$taxon_in_current_classification) {
1734
    $classifications = get_classifications_for_taxon($taxon);
1735
    RenderHints::pushToRenderStack('not_in_current_classification');
1736
    RenderHints::setFootnoteListKey('not_in_current_classification');
1737
    FootnoteManager::blockFootnotesFor('not_in_current_classification');
1738
    $taxon_name_markup = render_taxon_or_name($taxon);
1739
    FootnoteManager::unblockFootnotesFor('not_in_current_classification');
1740
    RenderHints::clearFootnoteListKey();
1741

    
1742
    if (count($classifications) == 0) {
1743
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1744
        array(
1745
        '!taxonname' => $taxon_name_markup,
1746
        )
1747
      ), 'warning');
1748
    }
1749
    else {
1750
      $trees = [];
1751
      foreach ($classifications as $classification) {
1752
        if (isset($classification->titleCache)) {
1753
          $trees[] = '<strong>' . $classification->titleCache . '</strong>';
1754
        }
1755
      }
1756

    
1757
      drupal_set_message(format_plural(count($trees),
1758
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1759
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1760
          array('!taxonname' => $taxon_name_markup, '!trees' => join(', ', $trees))
1761
        ) ,
1762
        'warning');
1763
    }
1764
    RenderHints::popFromRenderStack();
1765
  }
1766

    
1767
  // Render the taxon page.
1768
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1769
  $taxonpage->content = drupal_render($render_array);
1770

    
1771
  return $taxonpage;
1772
}
1773

    
1774

    
1775
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1776
{
1777
  cdm_check_valid_portal_page();
1778

    
1779
  $specimenpage = specimen_by_accession_number_view($accession_number);
1780

    
1781
  if (!empty($specimenpage)) {
1782
    return cdm_node_show_simulate($specimenpage->content);
1783
  }
1784
  else {
1785
    return '';
1786
  }
1787

    
1788

    
1789
}
1790

    
1791
/**
1792
 * Creates a specimen page view.
1793
 * @param string $uuid the UUID of the specimen
1794
 * @return array|string
1795
 */
1796
function cdm_dataportal_specimen_page_view($uuid) {
1797

    
1798
    cdm_check_valid_portal_page();
1799
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1800
    if (!empty($specimenpage)) {
1801
        return cdm_node_show_simulate($specimenpage->content);
1802
    }
1803
    else {
1804
        return '';
1805
    }
1806
}
1807

    
1808

    
1809
/**
1810
 * Creates a specimen page view.
1811
 * @param string $uuid the UUID of the specimen
1812
 * @return object
1813
 *  The page object with the following fields:
1814
 *   - 'title': the page title
1815
 *   - 'content' : the page content rendered as markup
1816
 */
1817
function specimen_by_accession_number_view($accession_number = null) {
1818

    
1819
  $field_unit_dto = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1820

    
1821
  // Display the page for the specimen defined by $uuid.
1822
  if (isset($field_unit_dto)){
1823
    $dto_array = array($field_unit_dto);
1824
    $specimen_array = specimen_render_array_items($dto_array);
1825
    $specimen_table = array(
1826
      '#theme' => 'table',
1827
      '#weight' => 2,
1828
      // prefix attributes and rows with '#' to let it pass toF the theme function,
1829
      // otherwise it is handled as child render array
1830
      '#attributes' => array('class' => 'specimens'),
1831
      '#rows' => array(),
1832
      '#prefix' => '<div id="specimens">',
1833
      '#suffix' => '</div>',
1834
    );
1835
    foreach($specimen_array as $value){
1836
      $renderArray = array(
1837
        '#theme' => 'item_list',
1838
        '#items' => array($value),
1839
        '#type' => 'ul');
1840
      $output = drupal_render($renderArray);
1841
      $specimen_table['#rows'][] = array(
1842
        // An array of table rows. Every row is an array of cells, or an associative array
1843
        'data' => array($output),
1844
        'class' =>  array(
1845
          'descriptionElement',
1846
          'descriptionElement_IndividualsAssociation'
1847
        ),
1848
      );
1849

    
1850

    
1851
    }
1852
    $specimenpage = new stdClass();
1853

    
1854
    $specimenpage->title = render_cdm_specimen_dto_page_title($field_unit_dto);
1855

    
1856
     $render_array['markup'] = $specimen_table;
1857
     $specimenpage->content = drupal_render($render_array);
1858
  }
1859

    
1860
  return $specimenpage;
1861
}
1862

    
1863

    
1864
/**
1865
 *
1866
 * Creates a specimen view.
1867
 * @param string $uuid the UUID of the specimen
1868
 * @return object
1869
 *    Page object with the fields
1870
 *    - title
1871
 *    - content
1872
 */
1873
function cdm_dataportal_specimen_view($uuid) {
1874

    
1875
    $sob_dto = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE_AS_DTO, $uuid);
1876
    if (empty($sob_dto)) {
1877
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1878
        return FALSE;
1879
    }
1880
    $specimenpage = new stdClass();
1881
    $specimenpage->title = render_specimen_page_title($sob_dto);
1882

    
1883
    // Render the specimen page.
1884
    $render_array = compose_cdm_specimen_page($sob_dto);
1885
    $specimenpage->content = drupal_render($render_array);
1886

    
1887
    return $specimenpage;
1888
}
1889

    
1890
/**
1891
 *
1892
 * Creates a description view.
1893
 *
1894
 * @param string $uuid the UUID of the description
1895
 * @param null $descriptive_dataset_uuid the uuid of the data set which defines
1896
 * the display of the description detail page
1897
 *
1898
 * @return object Page object with the fields
1899
 * Page object with the fields
1900
 * - title
1901
 * - content
1902
 */
1903
function cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid = NULL) {
1904
    $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, $uuid);
1905
    $description_page = new stdClass();
1906
    if (empty($description)) {
1907
      $description_page->title = t('Description does not exist');
1908
      drupal_set_title($description_page->title, PASS_THROUGH); // not necessary if correctly implemented as drupal node
1909
      $description_page->content = "";
1910

    
1911
    } else {
1912
      $description_page->title = $description->titleCache;
1913
      drupal_set_title($description_page->title); // not necessary if correctly implemented as drupal node
1914

    
1915
      // Render the description page.
1916
      $render_array = compose_description_table($description->uuid, $descriptive_dataset_uuid);
1917
      if($render_array['title']){
1918
        $page_title = strip_tags($render_array['title']['#markup']);
1919
        drupal_set_title($page_title);
1920
        unset($render_array['title']);
1921
      }
1922
      $description_page->content = drupal_render($render_array);
1923
    }
1924

    
1925
    return $description_page;
1926
}
1927

    
1928
function cdm_dataportal_description_page_view($uuid, $descriptive_dataset_uuid = NULL) {
1929

    
1930
  cdm_check_valid_portal_page();
1931
  $descriptionpage = cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid);
1932
  if (!empty($descriptionpage)) {
1933
    return cdm_node_show_simulate($descriptionpage->content);
1934
  }
1935
  else {
1936
    return NULL;
1937
  }
1938
}
1939

    
1940
/**
1941
 *
1942
 * Creates a named area view.
1943
 * @param string $uuid the UUID of the specimen
1944
 *  * @return object
1945
 *   An object with two fields:
1946
 *     - title: the page title
1947
 *     - content: the page content
1948
 */
1949

    
1950
function cdm_dataportal_named_area_view($uuid) {
1951
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1952
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1953
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1954
    return null;
1955
  }
1956
  $named_area_page = new stdClass();
1957

    
1958
  $named_area_page->title = $named_area->representation_L10n;
1959

    
1960
  // Render the specimen page.
1961
  $render_array = compose_cdm_named_area_page($uuid);
1962
  $named_area_page->content = drupal_render($render_array);
1963

    
1964
  return $named_area_page;
1965
}
1966

    
1967
function cdm_dataportal_named_area_page_view($uuid) {
1968

    
1969
  cdm_check_valid_portal_page();
1970

    
1971
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1972
  if (!empty($named_area_page)) {
1973
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1974
  }
1975
  else {
1976
    return '';
1977
  }
1978

    
1979

    
1980
}
1981

    
1982
/**
1983
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1984
 *
1985
 * The node page shows the taxon name title and the list of taxon related
1986
 * with such taxon. Name on the tree already in use.
1987
 *
1988
 * @param string $taxon_name_uuid
1989
 *   The uuid of the CDM TaxonName to show a name page for
1990
 * @param string $taxon_to_hide_uuid
1991
 *   A taxon which should not be displayed in the taxon list
1992
 * @param $redirect_to_taxon
1993
 *   Automatically redirect to the related taxon if there is only one
1994
 *   accepted taxon for this name.
1995
 * @param string $highlite_synonym_uuid
1996
 *   Optinal parameter wich takes another taxon uuid, if given the
1997
 *   target taxon pages will show the syonymy tab where the taxon
1998
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1999
 *   in case it is found on this page.
2000
 *
2001
 * @return mixed
2002
 *   The formatted name page as node.
2003
 */
2004
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = false) {
2005

    
2006
  cdm_check_valid_portal_page();
2007

    
2008
  $taxonname_page = cdm_dataportal_name_view(
2009
    is_uuid($taxon_name_uuid) ? $taxon_name_uuid : null,
2010
    is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : null,
2011
    $redirect_to_taxon == 'redirect_to_taxon',
2012
    is_uuid($synonym_uuid) ? $synonym_uuid : null);
2013
  if (!empty($taxonname_page)) {
2014
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
2015
  }
2016
  else {
2017
    return '';
2018
  }
2019
}
2020

    
2021
/**
2022
 * View function for a TaxonName page.
2023
 *
2024
 * The name page lists all taxa for which the name specified by the
2025
 * $taxon_name_uuid is being used. I case there is only one name the
2026
 * page automatically redirects ti the according taxon page. Otherwise
2027
 * the list of names is displayed.
2028
 *
2029
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
2030
 * list of taxa. This is useful for example when referencing from a taxon
2031
 * to the name page and the referring taxon should not be repeaded in the
2032
 * name page.
2033
 *
2034
 *
2035
 * @param string $taxon_name_uuid
2036
 *   The uuid of the CDM TaxonName to show a name page for
2037
 * @param string $taxon_to_hide_uuid
2038
 *   A taxon which should not be displayed in the taxon list
2039
 * @param $redirect_to_taxon
2040
 *   Automatically redirect to the related taxon if there is only one
2041
 *   accepted taxon for this name.
2042
 * @param string $highlite_synonym_uuid
2043
 *   Optional parameter which takes another taxon uuid, if given the
2044
 *   target taxon pages will show the synonymy tab where the taxon
2045
 *   referenced by the $highlite_synonym_uuid will be highlighted
2046
 *   in case it is found on this page.
2047
 *
2048
 * @return object|boolean
2049
 *   An object with two fields:
2050
 *     - title: the page title
2051
 *     - content: the page content
2052
 *   or FALSE
2053
 *
2054
 */
2055
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $redirect_to_taxon, $highlite_synonym_uuid = NULL) {
2056
  // Getting the full taxonname object from the server.
2057
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
2058
  if (!$taxon_name) {
2059
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
2060
    return FALSE;
2061
  }
2062
  cdm_load_tagged_full_title($taxon_name);
2063
  // Searching for all the taxa connected with the taxon name on the tree
2064
  // in use.
2065
  $name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
2066
  $restrictions = array(new Restriction("name.titleCache","EXACT", array($name->titleCache), 'AND'));
2067
  $init_strategy = array(
2068
    "name.titleCache",
2069
    "name.nomenclaturalReference.authorship",
2070
    "name.nomenclaturalReference.inReference.authorship",
2071
    "name.nomenclaturalReference.inReference.inReference.authorship",
2072
    "name.nomenclaturalReference.inReference.inReference.inReference.authorship"
2073
  );
2074
  $taxa = cdm_ws_fetch_all_by_restriction("Taxon", NULL, $restrictions, $init_strategy);
2075

    
2076
  // Removing the name where we came from.
2077
  foreach ($taxa as $k => &$taxon) {
2078
    if ($taxon->uuid == $taxon_to_hide_uuid) {
2079
      unset($taxa[$k]);
2080
    }
2081
  }
2082
  // Show the taxa list or go to the singular taxon.
2083
  if (sizeof($taxa) == 1 && $redirect_to_taxon) {
2084
    // redirect to the taxon if there is only one.
2085
    $singleTaxon = array_pop($taxa);
2086
    if ($singleTaxon->class != "Taxon") {
2087
      // It is a Synonym -> look for the accepted.
2088
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
2089
      if (!empty($highlite_synonym_uuid)) {
2090
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2091
      }
2092
      else {
2093
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
2094
      }
2095
    }
2096
    else {
2097
      // It is an accepted taxon.
2098
      if (!empty($highlite_synonym_uuid)) {
2099
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2100
      }
2101
      else {
2102
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
2103
      }
2104
    }
2105
  }
2106
  else {
2107
    // display the name page content
2108
    $taxon_name_page = new stdClass();
2109
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
2110
    $content = array();
2111

    
2112
    RenderHints::pushToRenderStack('name_page');
2113
    RenderHints::setFootnoteListKey('name_page');
2114
    $content['taxon_name'] = markup_to_render_array(render_taxon_or_name($taxon_name), null, '<div class="name-page-name">', '</div>');
2115

    
2116

    
2117
    // name relationships
2118
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $taxon_name->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
2119
    if(count($name_relations) > 0){
2120
      $content['name_relationships'] = compose_name_relationships_list($name_relations, $taxon_name->uuid, null);
2121
    }
2122

    
2123
    // type designations
2124
    $type_designations_render_array = compose_type_designations($taxon_name->uuid);
2125
    $content = array_merge($content, $type_designations_render_array);
2126
    // registrations
2127
    $registrationDTOs= cdm_ws_fetch_all(CDM_WS_REGISTRATION_DTO,  array('nameUuid' => $taxon_name_uuid));
2128
    if(isset($registrationDTOs) && count($registrationDTOs ) > 0 ){
2129
      $content['registrations'][] = markup_to_render_array('<h2>' . t("Registrations") . '</h2>') ;
2130
      foreach ($registrationDTOs as $regDTO){
2131
        $content['registrations'][] = compose_registration_dto_compact($regDTO);
2132
      }
2133
    }
2134

    
2135

    
2136
    // related taxa
2137
    $show_taxa_section = variable_get(CDM_NAME_PAGE_SECTION_TAXA, CDM_NAME_PAGE_SECTION_TAXA_DEFAULT);
2138
    if($show_taxa_section){
2139
      if ($taxa) {
2140
        $content['related_taxa_header'] = markup_to_render_array("<h2>" . count($taxa) > 1 ? t("Taxa for this name") :  t("Taxon for this name") . "</h2>");
2141
        $content['related_taxa'] = compose_list_of_taxa($taxa);
2142
      }
2143
      else {
2144
        $content['related_taxa'] = markup_to_render_array('This name is not assigned to any taxon.', null, '<div class="no-taxon-message">', '</div>');
2145
      }
2146
    }
2147

    
2148
    $content['footnotes'] = markup_to_render_array(render_footnotes());
2149

    
2150
    $taxon_name_page->content = $content;
2151
    RenderHints::popFromRenderStack();
2152
    RenderHints::clearFootnoteListKey();
2153
    return $taxon_name_page;
2154
  }
2155
}
2156

    
2157

    
2158
/**
2159
 * Returns a registration page as a Drupal node to be rendered by Drupal.
2160
 *
2161
 * @param string  $registration_identifie
2162
 *   The persistent identifier of the registration urlencoded.
2163
 * @return mixed
2164
 *   The formatted registration page as node.
2165
 */
2166
function cdm_dataportal_registration_page_view() {
2167

    
2168
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration/");
2169
  $registration_identifier = $_REQUEST['identifier'];
2170
  $registration_page = cdm_dataportal_registration_view($registration_identifier);
2171
  return cdm_node_show_simulate($registration_page);
2172
}
2173

    
2174
/**
2175
 * @param $registration_identifier
2176
 * @return array
2177
 *   The drupal render array for the registration view.
2178
 */
2179
function cdm_dataportal_registration_view($registration_identifier) {
2180

    
2181
  RenderHints::pushToRenderStack('registration_page');
2182
  RenderHints::setFootnoteListKey('registration_page');
2183

    
2184
  $render_array = array();
2185
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO, null, 'identifier=' . $registration_identifier);
2186
  if($registration_dto){
2187

    
2188
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
2189
    $render_array = compose_registration_dto_full($registration_dto, true);
2190

    
2191
  } else {
2192
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS, null, 'identifier=' . $registration_identifier);
2193
    if(isset($status_text->String)) {
2194
      $status_text = strtolower($status_text->String);
2195
      if($status_text == 'preparation' || $status_text == 'curation'){
2196
        $status_text = 'in ' . $status_text;
2197
      }
2198
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
2199
      //$status_message;
2200
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
2201
    } else {
2202
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
2203
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
2204
    }
2205
  }
2206

    
2207
  $render_array = array(
2208
    '#prefix' => '<div id="registration">',
2209
    'registration' => $render_array,
2210
    '#suffix' => '</div>',
2211
  );
2212

    
2213
  RenderHints::popFromRenderStack();
2214
  RenderHints::clearFootnoteListKey();
2215

    
2216
  return $render_array ;
2217
}
2218

    
2219

    
2220
/**
2221
 * Creates a page with the advance search form.
2222
 *
2223
 * NOTE: The advance search form allows searching for taxa.
2224
 */
2225
function cdm_dataportal_view_search_advanced() {
2226
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2227
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2228
}
2229

    
2230
/**
2231
 * Creates a page with the blast search form.
2232
 *
2233
 * NOTE: The advance search form allows searching for specimen in blast DB.
2234
 */
2235
function cdm_dataportal_view_search_blast() {
2236
    drupal_set_title(t('Blast search'), PASS_THROUGH);
2237
    return drupal_get_form('cdm_dataportal_search_blast_form');
2238
}
2239

    
2240
/**
2241
 * Creates a page with the search form for searching by taxon descriptions.
2242
 */
2243
function cdm_dataportal_view_search_taxon_by_description() {
2244
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2245
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2246
}
2247

    
2248
/**
2249
 * Executes the search and generates the result list of taxa.
2250
 */
2251
function cdm_dataportal_view_search_results_taxon() {
2252

    
2253
  $taxonPager = cdm_dataportal_search_taxon_execute();
2254

    
2255
  $showThumbnails = do_showThumbnails();
2256

    
2257
  $setSessionUri = url('cdm_api/setvalue/session', array(
2258
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2259
  ));
2260

    
2261
  drupal_add_js('jQuery(document).ready(function() {
2262

    
2263
      // init
2264
      if(' . $showThumbnails . ' == 1){
2265
          jQuery(\'.media_gallery\').show(20);
2266
      } else {
2267
          jQuery(\'.media_gallery\').hide(20);
2268
      }
2269

    
2270
      // add change handler
2271
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2272
      function(event){
2273
        var state = 0;
2274
        if(jQuery(this).is(\':checked\')){
2275
          jQuery(\'.media_gallery\').show(20);
2276
          state = 1;
2277
        } else {
2278
          jQuery(\'.media_gallery\').hide(20);
2279
        }
2280
        // store state in session variable
2281
        var uri = \'' . $setSessionUri . '\' + state;
2282
        jQuery.get(uri);
2283
      });
2284
  });',
2285
  array('type' => "inline", 'scope' => JS_DEFAULT));
2286

    
2287
  drupal_set_title(t('Search results'), PASS_THROUGH);
2288

    
2289
  return theme('cdm_search_taxa_results', array(
2290
    'pager' => $taxonPager,
2291
    'path' => 'cdm_dataportal/search/results/taxon',
2292
    ));
2293
}
2294

    
2295
/**
2296
 * Executes the blast search and generates the result list of specimen.
2297
 */
2298
function cdm_dataportal_view_search_results_specimen() {
2299

    
2300
    $specimenPager = cdm_dataportal_search_blast_execute();
2301

    
2302
    return theme('cdm_search_specimen_results', array(
2303
        'pager' => $specimenPager,
2304
        'path' => 'cdm_dataportal/search/results/specimen',
2305
    ));
2306
}
2307

    
2308

    
2309
/**
2310
 * Executes the search for registrations and generates the result list..
2311
 */
2312
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2313

    
2314
  switch($mode ){
2315
    case 'taxongraph':
2316
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2317
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2318
      break;
2319
    case 'filter':
2320
    default:
2321
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2322
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2323
  }
2324
  $block->title = null;
2325

    
2326
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2327

    
2328
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2329
  $registrations_pager_array = compose_search_results($registration_pager, new RegistrationDTOComposeHandler());
2330
  $render_array = array_merge($render_array, $registrations_pager_array);
2331

    
2332
  return $render_array;
2333
}
2334

    
2335
/**
2336
 * Executes the search for registrations and generates the result list..
2337
 */
2338
function cdm_dataportal_view_search_agent() {
2339

    
2340
  $render_array = [];
2341
  $title = isset($_REQUEST['class']) && $_REQUEST['class'] ? $_REQUEST['class'] : 'Persons & Teams';
2342
  drupal_set_title(t($title), PASS_THROUGH);
2343
  // TODO $block = block_load('cdm_dataportal', 'search_agent_filter');
2344
  // $block->title = null;
2345
  // $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2346
  $pager = cdm_dataportal_search_agent_execute();
2347
  $pager_render_array = compose_search_results($pager, new AgentComposeHandler());
2348
  $render_array = array_merge($render_array, $pager_render_array);
2349
  return $render_array;
2350
}
2351

    
2352

    
2353
/**
2354
 * Provides the standard image which indicated a loading process
2355
 *
2356
 * @return string
2357
 *  The img html tag
2358
 */
2359
function loading_image_html() {
2360
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2361
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2362
}
2363

    
2364
/**
2365
 * Returns the state of the the showThumbnails flag set in the
2366
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2367
 *
2368
 * @return boolean
2369
 *    returns 1 if the flag is set
2370
 */
2371
function do_showThumbnails() {
2372
  static $showThumbnails = null;
2373

    
2374
  if($showThumbnails == null) {
2375
    $showThumbnails = 0;
2376
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2377
      $showThumbnails = 0;
2378
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2379
      $showThumbnails = is_array($search_gallery_settings)
2380
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2381
        && (
2382
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2383
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2384
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2385
            )
2386
         ? 1 : 0;
2387

    
2388
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2389
    }
2390
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2391
    if (!is_numeric($showThumbnails)) {
2392
      $showThumbnails = 1;
2393
    }
2394
  }
2395

    
2396
  return $showThumbnails;
2397
}
2398

    
2399

    
2400

    
2401
/* ====================== other functions ====================== */
2402
/**
2403
 * Creates a URL to the taxon page specified by the $uuid parameter.
2404
 *
2405
 * The URL will be prepended with a path element to a specific taxon page tab.
2406
 *
2407
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2408
 * be set globally in the administrative settings or individually in the user
2409
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2410
 * the last portal will stay on this last tab.
2411
 *
2412
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2413
 * internal mechanism by a specific value.
2414
 *
2415
 * @param string $uuid
2416
 *   The UUID of the taxon.
2417
 * @param string $page_tab
2418
 *   Overwriting the preset mechanism by defining specific value for the
2419
 *   taxon page tab.
2420
 * @return string
2421
 *   The created URL.
2422
 */
2423
function path_to_taxon($uuid, $page_tab = FALSE) {
2424

    
2425
  $tab = get_default_taxon_tab();
2426
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2427

    
2428
  if (!$uuid) {
2429
    return FALSE;
2430
  }
2431

    
2432
  if ($page_tab) {
2433
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2434
  }
2435
  elseif (!$tab || strtolower($tab) == 'general') {
2436
    $url = 'cdm_dataportal/taxon/' . $uuid;
2437
  }
2438
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2439
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2440
  }
2441
  else {
2442
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2443
  }
2444
  return $url;
2445
}
2446

    
2447
function path_to_description($uuid, $descriptive_dataset_uuid = NULL) {
2448

    
2449
    if (!$uuid) {
2450
        return FALSE;
2451
    }
2452
    else {
2453
      return 'cdm_dataportal/description/' . $uuid
2454
        . (is_uuid($descriptive_dataset_uuid) ? '/' . $descriptive_dataset_uuid : '');
2455
    }
2456
}
2457

    
2458
function path_to_specimen($uuid) {
2459

    
2460
    if (!$uuid) {
2461
        return FALSE;
2462
    }
2463
    else {
2464
        return 'cdm_dataportal/occurrence/' . $uuid;
2465
    }
2466
}
2467

    
2468
function path_to_specimen_by_accession_number($accession_number) {
2469

    
2470
    if (!$accession_number) {
2471
        return FALSE;
2472
    }
2473
    else {
2474
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2475
    }
2476
}
2477

    
2478
function path_to_named_area($uuid) {
2479

    
2480
  if (!$uuid) {
2481
    return FALSE;
2482
  }
2483
  else {
2484
    return 'cdm_dataportal/named_area/' . $uuid;
2485
  }
2486
}
2487

    
2488
/**
2489
 * @param $uuid
2490
 *
2491
 * @return string
2492
 */
2493
function path_to_collection($uuid) {
2494
  if (!$uuid) {
2495
    return '';
2496
  }
2497
  else {
2498
    return 'cdm_dataportal/collection/' . $uuid;
2499
  }
2500
}
2501

    
2502
/**
2503
 * Creates a URL to show a synonmy in the according taxon page.
2504
 *
2505
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2506
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2507
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2508
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2509
 * in the page
2510
 *
2511
 * @param string $synonymUuid
2512
 *    The uuid of the synonym
2513
 * @param string $acceptedUuid
2514
 *    The uuid of the according accepted taxon
2515
 * @return string
2516
 *    The URL to show a synonmy in the according taxon page
2517
 */
2518
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2519
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2520
  return url($acceptedPath, array(
2521
      'query' => array(
2522
        // highlite the synony in the synonymy
2523
        'highlite' => $synonymUuid,
2524
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2525
        // see theme_taxon_page_title()
2526
        'acceptedFor' => $synonymUuid
2527
      ),
2528
      'fragment' => $synonymUuid
2529
  ));
2530

    
2531
}
2532

    
2533
/**
2534
 * Composes the drupal path to the key identified by the uuid.
2535
 *
2536
 * @param string $keyType
2537
 *    the key typer corresponds to the specific class of the CDM
2538
 *    IdentificationKey. Possible values are
2539
 *      -PolytomousKey
2540
 *      -MultimediaKey
2541
 *      - ...
2542
 * @param string $keyUuid
2543
 *   The UUID of the key
2544
 */
2545
function path_to_key($keyType, $keyUuid) {
2546
  if (!$keyUuid || !$keyType) {
2547
    return FALSE;
2548
  }
2549
  $keyType[0] = strtolower($keyType[0]);
2550
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2551
}
2552

    
2553
/**
2554
 * Composes the drupal path to the reference identified by the uuid.
2555
 *
2556
 * @param $uuid string String representation of the registration entity uuid.
2557
 *
2558
 * @return string
2559
 *  The drupal path
2560
 *
2561
 */
2562
function path_to_reference($uuid) {
2563
  if (!$uuid) {
2564
    return FALSE;
2565
  }
2566
  return 'cdm_dataportal/reference/' . $uuid;
2567
}
2568

    
2569
/**
2570
 * @param string $registration_identifier
2571
 *  The persistent identifier of the registration entity (Registration.identifier).
2572
 *
2573
 * @return string
2574
 *  the markup for a HTML link
2575
 */
2576
function render_link_to_registration($registration_identifier) {
2577

    
2578
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2579
    $path = $registration_identifier;
2580
    $query = [];
2581
  } else {
2582
    $path = 'cdm_dataportal/registration';
2583
    $query = ['identifier' => $registration_identifier];
2584
  }
2585
  return l($registration_identifier, $path, array('attributes' => array('class' => array('identifier')), 'query' => $query));
2586
}
2587

    
2588

    
2589
/**
2590
 * Creates the path to a cdm_dataportal taxon name page.
2591
 *
2592
 * @param string $taxon_name_uuid
2593
 *   The uuid as string of the CDM TaxonName to show a name page for
2594
 * @param string $taxon_to_hide_uuid
2595
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2596
 * @param string $highlited_synonym_uuid
2597
 *   Optional parameter which takes another taxon uuid, if given the
2598
 *   target taxon pages will show the synonymy tab where the taxon
2599
 *   referenced by the $highlite_synonym_uuid will be highlighted
2600
 *   in case it is found on this page.
2601
 * @param $redirect_to_taxon
2602
 *   If true, the name page will redirect to the related taxon if there is a single one
2603
 *   for this name only.
2604
 *
2605
 * @return string
2606
 *  URI path element as string
2607
 */
2608
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2609
  $res = FALSE;
2610
  if ($name_uuid) {
2611
    $res = 'cdm_dataportal/name/' . $name_uuid .
2612
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2613
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2614
    '/' . ($redirect_to_taxon || variable_get(CDM_NAME_PAGE_AUTOREDIRECT, 0) ? "redirect_to_taxon" : "");
2615
  }
2616

    
2617
  return $res;
2618
}
2619

    
2620
/**
2621
 * Composes the drupal path to the media entity identified by the uuid.
2622
 *
2623
 * @param string $uuid
2624
 *  The persistent identifier of the entity entity
2625
 * @return string
2626
 *  The drupal path
2627
 */
2628
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2629
  if (!$uuid) {
2630
    return FALSE;
2631
  }
2632
  $out = 'cdm_dataportal/media/' . $uuid;
2633
  if ($representaion_uuid) {
2634
    $out .= '/' . $representaion_uuid;
2635
    if (is_numeric($partId)) {
2636
      $out .= '/' . $partId;
2637
    }
2638
  }
2639
  return $out;
2640
}
2641

    
2642
/**
2643
 * Compares thisRank with thatRank.
2644
 *
2645
 * Returns a negative integer, zero, or a positive integer
2646
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2647
 * e.g:
2648
 * <ul>
2649
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2650
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2651
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2652
 * </ul>
2653
 * <p>
2654
 * This compare logic of the underlying webservice is the
2655
 * <b>inverse logic</b> of the the one implemented in
2656
 * java.lang.Comparable#compareTo(java.lang.Object)
2657
 *
2658
 * @param $thisRankUuid
2659
 * @param $thatRankUuid
2660
 *
2661
 * @return int
2662
 *   A negative integer, zero, or a positive integer
2663
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2664
 */
2665
function rank_compare($thisRankUuid, $thatRankUuid) {
2666
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2667
  return $result->Integer;
2668
}
2669

    
2670
/**
2671
 * Creates a short version of a taxonname.
2672
 *
2673
 * The short name is created by using the taggedTitle field of
2674
 * TaxonNodeDTO instances.
2675
 * If the taggedTitle if empty the fullname will be returned.
2676
 *
2677
 * @param object $taxonNodeDTO
2678
 *   A TaxonNodeDTO object
2679
 *
2680
 * @return string
2681
 */
2682
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2683

    
2684
  $nameStr = '';
2685

    
2686
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2687

    
2688
  // Get all tagged text tokens of the scientific name.
2689
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2690
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2691
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2692
    }
2693
  }
2694
  $nameStr = trim($nameStr);
2695

    
2696
  if ($nameStr) {
2697
    if(isset($taxonNodeDTO->status->symbol)){
2698
      $nameStr = $taxonNodeDTO->status->symbol . ' ' . $nameStr;
2699
    }
2700
    // Do not return short names for these.
2701
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2702
      return $nameStr;
2703
    }
2704

    
2705
    /*
2706
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2707
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2708
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2709
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2710
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2711
    */
2712
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2713
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2714
      return $matches[1][0] . "." . $matches[3][0];
2715
    }
2716
    else {
2717
      return $nameStr;
2718
    }
2719
  }
2720
  else {
2721
    return $taxonNodeDTO->titleCache;
2722
  }
2723
}
2724

    
2725
/**
2726
 * Check if a taxon is accepted by the current taxonomic tree.
2727
 *
2728
 * @param mixed $taxon
2729
 *   The Taxon obkect to check.
2730
 *
2731
 * @return bool
2732
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2733
 */
2734
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2735

    
2736
  $default_classification_uuid = get_current_classification_uuid();
2737

    
2738
  if (isset($taxon->taxonNodes)) {
2739
    $taxon_nodes = $taxon->taxonNodes;
2740
  }
2741
  else {
2742
    $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2743
  }
2744

    
2745
  if ($taxon->class == "Taxon" && isset($taxon_nodes)) {
2746
    foreach ($taxon_nodes as $node) {
2747
      if($node->class == 'TaxonNodeDto' && isset($node->classificationUUID)){
2748
        // case of TaxonNodeDto
2749
        return $node->classificationUUID == $default_classification_uuid;
2750
      } else if($node->class == 'TaxonNode' && isset($node->classification->uuid)) {
2751
         return $node->classification->uuid == $default_classification_uuid;
2752
      }
2753
    }
2754
  }
2755
  return FALSE;
2756
}
2757

    
2758
/**
2759
 * Checks is the source has one of the given types.
2760
 *
2761
 * @param object $source
2762
 *   The original source entity
2763
 * @param array $types
2764
 *   An array of element of the OriginalSourceType enumeration
2765
 *   If not set the default will be used which is:
2766
 *    - Lineage
2767
 *    - PrimaryMediaSource
2768
 *    - PrimaryTaxonomicSource
2769
 *    - Unknown
2770
 *    - Other
2771
 * @return boolean
2772
 */
2773
  function _is_original_source_type($source, $types = null) {
2774
    // this is the default
2775
    // maybe this should also be put into the settings
2776
    static $default = array(
2777
      OriginalSourceType::Lineage,
2778
      OriginalSourceType::PrimaryMediaSource,
2779
      OriginalSourceType::PrimaryTaxonomicSource,
2780
      OriginalSourceType::Unknown,
2781
      OriginalSourceType::Other,
2782
      OriginalSourceType::Aggregation
2783
    );
2784

    
2785
    if(!$types){
2786
      $types = $default;
2787
    }
2788
    return isset($source->type) && in_array($source->type, $types);
2789
  }
2790

    
2791
/**
2792
 * Collects all the media from a list of description elements.
2793
 *
2794
 * @param array $descriptionElements
2795
 *   The description elements from which to collect the media.
2796
 *
2797
 * @return array
2798
 *   The output with all the collected media.
2799
 */
2800
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2801

    
2802
  $outArrayOfMedia = array();
2803

    
2804
  // Avoiding a warning box in Drupal for Flora Malesiana.
2805
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2806
    foreach ($descriptionElements as $descriptionElement) {
2807
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2808
        foreach ($descriptionElement->media as $media) {
2809
          if (is_object($media)) {
2810
            $outArrayOfMedia[] = $media;
2811
          }
2812
        }
2813
      }
2814
    }
2815
  }
2816
  return $outArrayOfMedia;
2817
}
2818

    
2819

    
2820

    
2821

    
2822
/**
2823
 * Creates a CDM Dynabox.
2824
 *
2825
 * @param string $dynabox_id
2826
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2827
 * @param string $label
2828
 *   The clickable text to show.
2829
 * @param string $content_url
2830
 *   The cdm REST service request url wich will deliver the content to be shown
2831
 *   once the dynabox toggles open.
2832
 * @param string $theme
2833
 *   The theme to be used for rendering the cdm REST service response with is
2834
 *   returned from the $content_url.
2835
 * @param string $link_alt_text
2836
 *   The value for the alt attribute of the dynabox link.
2837
 * @param array $enclosingtags
2838
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2839
 *   element itself, $enclosingtags[1] is the tag to be used for the
2840
 *   dynabox_content (optional)
2841
 * @param array $attributes
2842
 * @param $content_element_selector
2843
 *   Optional jQuery selector which can be used to reference a dom element which should
2844
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2845
 *  element will be placed in this container.
2846
 *
2847
 * @param string $open_callback
2848
 *   optional javascript call back function to be triggered after toggling the box to
2849
 *   the open state.
2850
 * @param string $close_callback
2851
 *   optional javascript call back function to be triggered after toggling the box to
2852
 *   the closed state.
2853
 * @return string Returns HTML for a dynabox.
2854
 * Returns HTML for a dynabox.
2855
 */
2856
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2857
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2858
                     $content_element_selector = null,
2859
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2860
  $out = '';
2861

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

    
2865
  if(!array_key_exists('class', $attributes)) {
2866
    $attributes['class'] = ["dynabox"];
2867
  } else {
2868
    $attributes['class'] = array_merge($attributes['class'], ["dynabox"]);
2869
  }
2870
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2871
  $dynabox_attributes = drupal_attributes($attributes);
2872

    
2873

    
2874
  _add_js_domEvent(); // requires domEvent.js
2875
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2876
  drupal_add_js("
2877
  jQuery(document).ready(
2878
      function() {
2879
        dynabox('". $dynabox_id ."',
2880
          {
2881
            open_callback: " . $open_callback .",
2882
            close_callback: " . $close_callback .
2883
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2884
          }
2885
        );
2886
      }
2887
   );",
2888
   array(
2889
    'type'=>'inline',
2890
    'scope'=>'footer'
2891
    )
2892
  );
2893

    
2894

    
2895
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2896
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2897
  $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>';
2898
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2899
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2900
  $out .= '    </' . $enclosingtags[1] . '>';
2901
  $out .= '  </' . $enclosingtags[0] . '>';
2902
  $out .= '<!-- dynabox end -->';
2903
  return $out;
2904
}
2905

    
2906
/**
2907
 * Checks whether a feature has any description elements.
2908
 *
2909
 * @param mixed $featureNode
2910
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2911
 *
2912
 * @see _mergeFeatureTreeDescriptions()
2913
 *
2914
 * @return bool
2915
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2916
 *   contains at least one non empty TextData or at least one DescriptionElement
2917
 *   of an other type. A TextData element holding a multilanguageText or a
2918
 *   source reference is considered to be not empty.
2919
 *
2920
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2921
 *       see $block_content_is_not_empty in make_feature_block_list() and
2922
 *       $feature_block_has_content in compose_feature_block_items_generic
2923
 */
2924
function has_feature_node_description_elements($featureNode) {
2925

    
2926
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2927
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2928
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2929
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2930
          && $descriptionElement->multilanguageText_L10n->text != ''
2931
          || isset($descriptionElement->sources[0])
2932
          || isset($descriptionElement->media[0]) ) {
2933
          return TRUE;
2934
        }
2935
      }
2936
    }
2937
  }
2938
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2939
    foreach ($featureNode->childNodes as $child) {
2940
      if (has_feature_node_description_elements($child)) {
2941
        return TRUE;
2942
      }
2943
    }
2944
  }
2945
  return FALSE;
2946
}
2947

    
2948
/**
2949
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2950
 *
2951
 * @param $chapter
2952
 *   The taxon page chapter or part
2953
 */
2954
function cdm_check_valid_taxon_page($chapter){
2955
  static $taxon_tabs = null;
2956

    
2957
  cdm_check_valid_portal_page();
2958

    
2959
  if($taxon_tabs == null){
2960
    $taxon_tabs = array('all', 'description');
2961
    foreach(get_taxon_tabs_list() as $tab){
2962
      $taxon_tabs[] = strtolower($tab);
2963
    }
2964
  }
2965

    
2966
  if(!in_array($chapter, $taxon_tabs)){
2967
    // oops this is not a valid chapter name
2968
    http_response_code(404); // 404 = Not Found
2969
  }
2970

    
2971
}
2972

    
2973
function check_js_devel_mode_disabled() {
2974
  if(variable_get('cdm_js_devel_mode', FALSE)) {
2975
    drupal_set_message(t('The !url1 is enabled.
2976
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
2977
      '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
2978
    )),
2979
      'warning'
2980
    );
2981
  }
2982
}
2983

    
2984
/**
2985
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2986
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2987
 *
2988
 * @param $preg_pattern
2989
 *   Optional regular expression pattern to be used in preg_match().
2990
 */
2991
function cdm_check_valid_portal_page($preg_pattern = null){
2992
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2993
  if($preg_pattern === null){
2994
    $preg_pattern = $ends_with_file_suffix_pattern;
2995
  }
2996
  if(preg_match($preg_pattern, $_GET['q'])){
2997
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2998
    http_response_code(404); // 404 = Not Found
2999
    exit('HTTP 404');
3000
  }
3001
  check_js_devel_mode_disabled();
3002
}
3003

    
3004
/**
3005
 * Generates the diff of the texts and presents it in a HTML diff viewer.
3006
 *
3007
 * @param $text_a
3008
 * @param $text_b
3009
 * @return string
3010
 */
3011
function diff_viewer($text_a, $text_b) {
3012

    
3013
  static $diff_viewer_count = 0;
3014

    
3015
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
3016

    
3017
  // http://code.stephenmorley.org/php/diff-implementation/
3018
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
3019
  drupal_add_css(drupal_get_path('module',
3020
      'cdm_dataportal') . '/css/diff.css');
3021
  _add_jquery_ui();
3022
  drupal_add_js(
3023
    'jQuery(document).ready( function(){
3024
        jQuery(\'#' . $element_id . '\').accordion({
3025
        collapsible: true,
3026
        active: false,
3027
        fillSpace: true,
3028
        }).children(\'div\').css({ \'height\': \'auto\' });
3029
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
3030
     });'
3031
    , array(
3032
    'type' => 'inline',
3033
    'scope' => 'footer'
3034
  ));
3035

    
3036
  $diff = Diff::compare($text_a,
3037
    $text_b);
3038
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
3039
    . Diff::toTable($diff, '', '')
3040
    . '</div></div>';
3041
  return $diff_viewer_markup;
3042
}
3043

    
3044
/**
3045
 * ====== EXPERIMENTAL only used by Euro+Med ===============
3046
 */
3047

    
3048

    
3049
/**
3050
 * See
3051
 *  - https://dev.e-taxonomy.eu/redmine/issues/9233
3052
 *  - https://www.drupal.org/project/feedback_simple
3053
 *  - https://www.drupal.org/node/1299158
3054
 * Implements hook_preprocess_feedback_simple().
3055
 *
3056
 * TODO: move into separate module
3057
 */
3058
function cdm_dataportal_preprocess_feedback_simple(&$variables) {
3059
  // Add modal_forms classes.
3060
  $variables['class'][] = 'ctools-use-modal';
3061
  // Uncomment either small, medium or large.
3062
  $variables['class'][] = 'ctools-modal-modal-popup-small';
3063
  // $variables['class'][] = 'ctools-modal-modal-popup-medium';
3064
  // $variables['class'][] = 'ctools-modal-modal-popup-large';
3065
}
3066

    
3067

    
(10-10/19)