Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

    
171
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers_popup_extension,
172
      array(
173
        'type' => 'file',
174
        'group' => JS_LIBRARY,
175
        'weight' => 0,
176
        'cache' => TRUE,
177
        'preprocess' => FALSE
178
      )
179
    );
180

    
181
    // see https://github.com/proj4js/proj4js
182
    // http://openlayers.org/dev/examples/using-proj4js.html
183
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
184
      array(
185
        'type' => 'file',
186
        'group' => JS_LIBRARY,
187
        'weight' => -1, // before open layers
188
        'cache' => TRUE,
189
      )
190
    );
191

    
192
    // configure the theme
193
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
194
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
195
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
196
        'type' => 'inline',
197
        'group' => JS_LIBRARY,
198
        'weight' => 1, // after openlayers
199
        'cache' => TRUE,
200
        'preprocess' => FALSE
201
      ));
202

    
203
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
204
      array(
205
        'type' => 'file',
206
        'cache' => TRUE,
207
        'preprocess' => FALSE
208
      )
209
    );
210

    
211
  }
212

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

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

    
267
  /**
268
   * @todo Please document this function.
269
   * @see http://drupal.org/node/1354
270
   */
271
  function _add_js_footnotes() {
272
    _add_js_domEvent();
273
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
274
  }
275

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

    
282
    _add_js_domEvent(); // requires domEvent.js
283
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
284
  }
285

    
286
/**
287
 * @todo Please document this function.
288
 * @see http://drupal.org/node/1354
289
 */
290
function _add_js_taxonomic_children($jquery_selector) {
291

    
292
  global $base_url;
293

    
294

    
295
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
296
  
297
  drupal_add_js('jQuery(document).ready(function() {
298
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
299
          // hoverClass: "fa-rotate-90",
300
          // activeClass: "fa-rotate-90",
301
          classificationUuid: "' . get_current_classification_uuid() . '",
302
          taxonUuid: "' . get_current_taxon_uuid() . '",
303
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
304
          proxyBaseUri: "' . $base_url . '",
305
          
306
        });
307
      });
308
      ', array('type' => 'inline'));
309
}
310

    
311
  /**
312
   * Adds the external javascript file for domEvent.js.
313
   *
314
   * @see drupal_add_js()
315
   */
316
  function _add_js_domEvent() {
317
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
318
  }
319

    
320
  function _add_jquery_ui()
321
  {
322
    drupal_add_css(drupal_get_path('module',
323
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
324
    drupal_add_js(drupal_get_path('module',
325
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
326
      array(
327
        'type' => 'file',
328
        'weight' => JS_LIBRARY,
329
        'cache' => TRUE,
330
        'preprocess' => FALSE
331
      )
332
    );
333
  }
334

    
335
  function _add_js_ui_accordion(){
336
    _add_jquery_ui();
337
    drupal_add_js('jQuery(document).ready(function() {
338
        jQuery( "#accordion" ).accordion();
339
      });',
340
      array('type' => 'inline')
341
    );
342
  }
343

    
344

    
345
function _add_js_utis_client($jquery_selector){
346

    
347
  drupal_add_js(drupal_get_path('module',
348
      'cdm_dataportal') . '/js/utis-client/utis-client.js',
349
    array(
350
      'type' => 'file',
351
      'weight' => JS_LIBRARY,
352
      'cache' => TRUE,
353
      'preprocess' => FALSE
354
    )
355
  );
356

    
357
  drupal_add_js('jQuery(document).ready(function() {
358
        jQuery( "' . $jquery_selector . '" ).utis_client(
359
        {
360
          spinnerIcon: \'' . font_awesome_icon_markup('fa-sync', array('class' => array('fa-3x',  'fa-spin'), 'style' => array('opacity: 0.3;'))) . '\',
361
          externalLinkIcon: \'' . font_awesome_icon_markup('fa-external-link-alt') . '\'
362
        });
363
      });',
364
    array('type' => 'inline')
365
  );
366
}
367

    
368
function _add_js_universalviewer($jquery_selector, $manifest_uri){
369

    
370
  $universalviewer_path  = drupal_get_path('module',    'cdm_dataportal') . '/js/universalviewer';
371

    
372
  drupal_add_css($universalviewer_path . '/uv/uv.css');
373
  drupal_add_css($universalviewer_path . '/uv-fix.css');
374

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

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

    
462

    
463
    if($icon_name){
464
      if(!isset($attributes['class'])){
465
        $attributes['class'] = array();
466
      }
467
      $attributes['class'][] = 'fa';
468
      $attributes['class'][] = $icon_name;
469

    
470
      return '<i ' . drupal_attributes($attributes) . '></i>';
471
    }
472

    
473
    return '';
474
  }
475

    
476
/**
477
 * @param string $glyph_name
478
 *   The name of the gloyph (e.g. 'icon-interal-link-alt-solid') for the foll list please
479
 *   refer to modules/cdm_dataportal/fonts/custom-icon-font
480
 * @param array $attributes
481
 * @return string
482
 */
483
  function custom_icon_font_markup($glyph_name = NULL, $attributes = array()){
484
    _add_font_custom_icon_font();
485

    
486

    
487
    if($glyph_name){
488
      if(!isset($attributes['class'])){
489
        $attributes['class'] = array();
490
      }
491
      $attributes['class'][] = $glyph_name;
492

    
493
      return '<i ' . drupal_attributes($attributes) . '></i>';
494
    }
495

    
496
    return '';
497
  }
498

    
499
/**
500
 * Adds the css  containing the font awesome icons to the html header.
501
 */
502
function _add_font_awesome_font()
503
{
504
  // $fa_font_version = 'font-awesome-4.6.3/css/font-awesome.min.css';
505
  $fa_font_version = 'fontawesome-free-5.9.0-web/css/all.css';
506
  $font_awesome_css_uri = base_path() . drupal_get_path('module', 'cdm_dataportal') . '/fonts/' . $fa_font_version;
507

    
508
  drupal_add_html_head_link(
509
    array(
510
      'href' => $font_awesome_css_uri,
511
      'rel' => 'stylesheet'
512
    )
513
  );
514
}
515

    
516
/**
517
 * Adds the css  containing the font awesome icons to the html header.
518
 */
519
function _add_font_custom_icon_font()
520
{
521

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

    
524
  drupal_add_html_head_link(
525
    array(
526
      'href' => $custom_icon_font_css_uri,
527
      'rel' => 'stylesheet'
528
    )
529
  );
530
}
531

    
532
/* ====================== hook implementations ====================== */
533
  /**
534
   * Implements hook_permission().
535
   *
536
   * Valid permissions for this module.
537
   *
538
   * @return array
539
   *   An array of valid permissions for the cdm_dataportal module.
540
   */
541
  function cdm_dataportal_permission() {
542
    return array(
543
      'administer cdm_dataportal' => array(
544
        'title' => t('Administer CDM DataPortal settings'),
545
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
546
      ),
547
      'access cdm content' => array(
548
        'title' => t('Access CDM content'),
549
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
550
      ),
551
    );
552
  }
553

    
554
/**
555
 * Implements hook_menu().
556
 */
557
function cdm_dataportal_menu() {
558
  $items = array();
559

    
560
  // @see settings.php.
561
  cdm_dataportal_menu_admin($items);
562
  cdm_dataportal_menu_help($items);
563

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

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

    
578
  $items['cdm_dataportal/occurrence'] = array(
579
        'page callback' => 'cdm_dataportal_specimen_page_view',
580
        'access arguments' => array('access cdm content'),
581
        'type' => MENU_CALLBACK,
582
        // Expected callback arguments: uuid.
583
    );
584

    
585
  $items['cdm_dataportal/description'] = array(
586
        'page callback' => 'cdm_dataportal_description_page_view',
587
        'access arguments' => array('access cdm content'),
588
        'type' => MENU_CALLBACK,
589
        // Expected callback arguments: uuid.
590
    );
591

    
592
   $items['cdm_dataportal/specimen/accession_number'] = array(
593
        'page callback' => 'cdm_dataportal_specimen_by_accession_number_page_view',
594
        'access arguments' => array('access cdm content'),
595
        'type' => MENU_CALLBACK,
596
        // Expected callback arguments: accession number.
597
    );
598
  $items['cdm_dataportal/named_area'] = array(
599
    'page callback' => 'cdm_dataportal_named_area_page_view',
600
    'access arguments' => array('access cdm content'),
601
    'type' => MENU_CALLBACK,
602
    // Expected callback arguments: uuid.
603
  );
604

    
605
  $items['cdm_dataportal/name'] = array(
606
    'page callback' => 'cdm_dataportal_name_page_view',
607
      /*
608
    'page arguments' => array(
609
       'taxon_name_uuid',
610
       'taxon_to_hide_uuid',
611
       'synonym_uuid' => NULL
612
      ),
613
      */
614
    'access arguments' => array('access cdm content'),
615
    'type' => MENU_CALLBACK,
616
    // Expected callback arguments: uuid.
617
  );
618

    
619
  $items['cdm_dataportal/reference'] = array(
620
    'page callback' => 'cdm_dataportal_view_reference',
621
    'access arguments' => array('access cdm content'),
622
    'type' => MENU_CALLBACK,
623
    // Expected callback arguments: uuid.
624
  );
625

    
626
  $items['cdm_dataportal/reference/list'] = array(
627
    'page callback' => 'cdm_dataportal_view_reference_list',
628
    'access arguments' => array('access cdm content'),
629
    'type' => MENU_CALLBACK,
630
    // Expected callback arguments: uuid.
631
  );
632

    
633
  $items['cdm_dataportal/media'] = array(
634
    'page callback' => 'cdm_dataportal_view_media',
635
    'access arguments' => array('access cdm content'),
636
    'type' => MENU_CALLBACK,
637
    // Expected callback arguments:
638
    // uuid, mediarepresentation_uuid, part_uuid or part#.
639
  );
640

    
641
  $items['cdm_dataportal/polytomousKey'] = array(
642
    'page callback' => 'cdm_dataportal_view_polytomousKey',
643
    'access arguments' => array('access cdm content'),
644
    'type' => MENU_CALLBACK,
645
    // Expected callback arguments: polytomousKey->uuid.
646
  );
647

    
648
  $items['cdm_dataportal/search'] = array(
649
    'page callback' => 'cdm_dataportal_view_search_advanced',
650
    'access arguments' => array('access cdm content'),
651
    'type' => MENU_CALLBACK,
652
  );
653

    
654
  $items['cdm_dataportal/search/advanced'] = array(
655
    'title' => 'Advanced', // will be passed through t()
656
    'page callback' => 'cdm_dataportal_view_search_advanced',
657
    'access arguments' => array('access cdm content'),
658
    'type' => MENU_DEFAULT_LOCAL_TASK,
659
  );
660
  $items['cdm_dataportal/search/blast'] = array(
661
    'title' => 'Blast', // will be passed through t()
662
    'page callback' => 'cdm_dataportal_view_search_blast',
663
    'access arguments' => array('access cdm content'),
664
    'type' => MENU_LOCAL_TASK,
665
  );
666

    
667
  $items['cdm_dataportal/search/taxon_by_description'] = array(
668
    'title' => 'By content category', // will be passed through t()
669
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
670
    'access arguments' => array('access cdm content'),
671
    'type' => MENU_LOCAL_TASK,
672
  );
673
  $items['cdm_dataportal/search/results/taxon'] = array(
674
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
675
    'access arguments' => array('access cdm content'),
676
    'type' => MENU_CALLBACK,
677
  );
678

    
679

    
680
  $items['cdm_dataportal/search/results/specimen'] = array(
681
      'page callback' => 'cdm_dataportal_view_search_results_specimen',
682
      'access arguments' => array('access cdm content'),
683
      'type' => MENU_CALLBACK,
684
  );
685

    
686
  /*
687
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
688
   * tabs in the subordinate paths work, accessing this 'page' will cause the
689
   * MENU_DEFAULT_LOCAL_TASK being displayed
690
   */
691
  $items['cdm_dataportal/registration-search'] = array(
692
    'title' => 'Search', // will be passed through t()
693
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
694
    'page arguments' => array("filter"),
695
    'access arguments' => array('access cdm content'),
696
    'type' => MENU_CALLBACK,
697
  );
698
  /*
699
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
700
   * defined at a higher level of the path (cdm_dataportal/registration-search)
701
   */
702
  $items['cdm_dataportal/registration-search/filter'] = array(
703
    'title' => 'Search', // will be passed through t()
704
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
705
    'page arguments' => array("filter"),
706
    'access arguments' => array('access cdm content'),
707
    'type' => MENU_DEFAULT_LOCAL_TASK,
708
  );
709
  /*
710
   * the MENU_LOCAL_TASK creates another tab
711
   */
712
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
713
    'title' => 'Taxon graph search', // will be passed through t()
714
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
715
    'page arguments' => array("taxongraph"),
716
    'access arguments' => array('access cdm content'),
717
    'type' => MENU_LOCAL_TASK,
718
  );
719

    
720
  // Optional callback arguments: page.
721
  $items['cdm_dataportal/registration'] = array(
722
    'page callback' => 'cdm_dataportal_registration_page_view',
723
    'access arguments' => array('access cdm content'),
724
    'type' => MENU_CALLBACK,
725
    // Expected callback arguments: uuid.
726
  );
727

    
728
  /*
729
   $items['cdm/xml2json'] = array(
730
   'page callback' => 'cdm_view_xml2json',
731
   'access arguments' => array('access cdm content'),
732
   'type' => MENU_CALLBACK,
733
   );
734
   */
735

    
736
  // 'May not cache' in D5.
737
  $items['cdm_dataportal/name/%'] = array(
738
    // 'page callback' => 'cdm_dataportal_view_name',
739
    'page callback' => 'cdm_dataportal_name_page_view',
740
    'page arguments' => array(2, 3, 4, 5),
741
    'access arguments' => array('access cdm content'),
742
    'type' => MENU_CALLBACK,
743
  );
744

    
745
  // --- Local tasks for Taxon.
746
  // --- tabbed taxon page
747
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
748
    $items['cdm_dataportal/taxon/%'] = array(
749
      'title' => cdm_taxonpage_tab_label('General'),
750
      'page callback' => 'cdm_dataportal_taxon_page_view',
751
      'access arguments' => array('access cdm content'),
752
      'type' => MENU_CALLBACK,
753
      'weight' => 1,
754
      'page arguments' => array(2, "description")
755
      , // Expected callback arguments: taxon_uuid.
756
    );
757

    
758
    $items['cdm_dataportal/taxon/%/all'] = array(
759
      'title' => cdm_taxonpage_tab_label('General'),
760
      'page callback' => 'cdm_dataportal_taxon_page_view',
761
      'access arguments' => array('access cdm content'),
762
      'type' => MENU_CALLBACK,
763
      'weight' => 2,
764
      'page arguments' => array(2, "all")
765
      , // Expected callback arguments: taxon_uuid.
766
    );
767

    
768
    $items['cdm_dataportal/taxon/%/description'] = array(
769
      'title' => cdm_taxonpage_tab_label('General'),
770
      'page callback' => 'cdm_dataportal_taxon_page_view',
771
      'access arguments' => array('access cdm content'),
772
      'type' => MENU_DEFAULT_LOCAL_TASK,
773
      'weight' => 2,
774
      'page arguments' => array(2, "description")
775
      , // Expected callback arguments: taxon_uuid.
776
    );
777

    
778
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
779
      'title' => cdm_taxonpage_tab_label('Synonymy'),
780
      'page callback' => 'cdm_dataportal_taxon_page_view',
781
      'access arguments' => array('access cdm content'),
782
      'type' => MENU_LOCAL_TASK,
783
      'weight' => 4,
784
      'page arguments' => array(2, "synonymy", 4)
785
      , // Expected callback arguments: taxon_uuid and ...
786
    );
787
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
788
      'title' => cdm_taxonpage_tab_label('Images'),
789
      'page callback' => 'cdm_dataportal_taxon_page_view',
790
      'access arguments' => array('access cdm content'),
791
      'type' => MENU_LOCAL_TASK,
792
      'weight' => 5,
793
      'page arguments' => array(2, "images")
794
      , // Expected callback arguments: taxon_uuid.
795
    );
796

    
797
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
798
      'title' => cdm_taxonpage_tab_label('Specimens'),
799
      'page callback' => 'cdm_dataportal_taxon_page_view',
800
      'access arguments' => array('access cdm content'),
801
      'type' => MENU_LOCAL_TASK,
802
      'weight' => 6,
803
      'page arguments' => array(2, "specimens")
804
      , // Expected callback arguments: taxon_uuid.
805
    );
806

    
807
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
808
      'title' => cdm_taxonpage_tab_label('Keys'),
809
      'page callback' => 'cdm_dataportal_taxon_page_view',
810
      'access arguments' => array('access cdm content'),
811
      'type' => MENU_LOCAL_TASK,
812
      'weight' => 6,
813
      'page arguments' => array(2, "keys")
814
      , // Expected callback arguments: taxon_uuid.
815
    );
816

    
817
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
818
      'title' => cdm_taxonpage_tab_label('Experts'),
819
        'page callback' => 'cdm_dataportal_taxon_page_view',
820
        'access arguments' => array('access cdm content'),
821
        'type' => MENU_LOCAL_TASK,
822
        'weight' => 6,
823
        'page arguments' => array(2, "experts")
824
    , // Expected callback arguments: taxon_uuid.
825
    );
826

    
827
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
828
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
829
        'access arguments' => array('access cdm content'),
830
        'page arguments' => array(3,4,5),
831
        'type' => MENU_CALLBACK
832
    );
833
  }
834

    
835
  // --- refresh link for all cdmnode types
836
  foreach (cdm_get_nodetypes() as $type=>$name) {
837
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
838
        'title' => 'Refresh',
839
        'page callback' => 'cdm_dataportal_refresh_node',
840
        'access arguments' => array('administer cdm_dataportal'),
841
        'type' => MENU_LOCAL_TASK,
842
        'weight' => 100,
843
        'page arguments' => array($name, 2)
844
    );
845
  }
846

    
847
  return $items;
848
}
849

    
850
/**
851
 * Implements hook_init().
852
 *
853
 */
854
function cdm_dataportal_init() {
855
  if (!path_is_admin(current_path())) {
856
    //FIXME To add CSS or JS that should be present on all pages, modules
857
    //      should not implement this hook, but declare these files in their .info file.
858
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
859
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
860
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
861
  } else {
862
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
863
  }
864

    
865
  if(variable_get('cdm_debug_mode', FALSE)){
866
    $file = 'temporary://drupal_debug.txt';
867
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
868
  }
869

    
870
  $bibliography_settings = get_bibliography_settings();
871
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
872
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
873
}
874

    
875
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
876

    
877
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
878

    
879
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
880
    // force reloading of all and notify user about this special loading
881
    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: ')
882
        . l('Back to tabbed taxon page', $base_path));
883
    $base_path .= '/all';
884
  } else {
885
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
886
  }
887

    
888
  $parameters['cacheL2_refresh'] ='1';
889

    
890

    
891
  drupal_goto($base_path, array('query' => $parameters));
892
}
893

    
894
/**
895
 * Implements hook_requirements($phase)
896
 */
897
function cdm_dataportal_requirements($phase) {
898
    $requirements = array();
899
    if($phase == 'runtime'){
900

    
901
    }
902
    return $requirements;
903
}
904

    
905
/**
906
 * Implements hook_block_info().
907
 */
908
function cdm_dataportal_block_info() {
909

    
910
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
911
    // $block[1]["info"] = t("CDM DataPortal Credits");
912
    $block["2"] = array(
913
        "info" => t("CDM - Search Taxa"),
914
        "cache" => DRUPAL_NO_CACHE
915
      );
916
    // $block[3]["info"] = t("CDM Filters");
917
    $block["4"]["info"] = t("CDM  - Dataportal Print");
918
    $block["keys"]["info"] = t("CDM - Identification keys");
919
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
920
    $block["classification_breadcrumbs"] =  array(
921
        'info' => t('CDM - Classification breadcrumbs'),
922
        'cache' => DRUPAL_CACHE_PER_PAGE
923
      );
924
    $block["taxonomic_children"] =  array(
925
      'info' => t('CDM - Taxonomic children'),
926
      'cache' => DRUPAL_CACHE_PER_PAGE
927
    );
928
    $block["back_to_search_results"] =  array(
929
      'title' => '<none>',
930
      'info' => t('CDM - Back to search Results'),
931
      'cache' => DRUPAL_CACHE_PER_PAGE,
932
      'visibility' => BLOCK_VISIBILITY_LISTED,
933
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
934
    );
935
  $block['registrations_search_filter'] =  array(
936
    'title' => 'Filter registrations',
937
    'info' => t('CDM - Registrations search filter'),
938
    'cache' => DRUPAL_CACHE_PER_PAGE,
939
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
940
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
941
  );
942
  $block['registrations_search_taxongraph'] =  array(
943
    'title' => 'Taxonomic registration search',
944
    'info' => t('CDM - Registrations search by taxon graph'),
945
    'cache' => DRUPAL_CACHE_PER_PAGE,
946
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
947
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
948
  );
949
  $block['registrations_search'] =  array(
950
    'title' => 'Search',
951
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
952
    'cache' => DRUPAL_CACHE_PER_PAGE,
953
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
954
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
955
  );
956
  $block['utis_search'] =  array(
957
    'title' => 'UTIS Search',
958
    'info' => t('Query the Unified Taxonomic Information Service (UTIS)' ),
959
    'cache' => DRUPAL_CACHE_PER_PAGE,
960
    'visibility' => BLOCK_VISIBILITY_NOTLISTED
961
  );
962
  return $block;
963
}
964

    
965
/**
966
 * Implements hook_block_view().
967
 */
968
function cdm_dataportal_block_view($delta) {
969
  // TODO Rename block deltas (e.g. '2') to readable strings.
970
  switch ($delta) {
971
    // case 'delta-1':
972
    // $block['subject'] = t('Credits');
973
    // $block['content'] = theme('cdm_credits');
974
    // return $block;
975
    case '2':
976
      $block['subject'] = t('Search taxa');
977
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
978
      $block['content'] = drupal_render($form);
979

    
980
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
981
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
982
      }
983
      if (variable_get(CDM_SEARCH_BLAST_ENABLED)){
984
          $block['content'] .= '<div>' . l(t('Blast Search'), 'cdm_dataportal/search/blast') . '</div>';
985
      }
986
      return $block;
987
    case '4':
988
      $block['subject'] = '';
989
      $block['content'] = theme('cdm_print_button');
990
      return $block;
991
    case "keys":
992
      $block['subject'] = t('Identification Keys');
993
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
994
      return $block;
995
    case "fundedByEDIT":
996
      // t('Funded by EDIT');
997
      $text = '<none>';
998
      $block['subject'] = $text;
999
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
1000
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
1001
        'attributes' => array("target" => "EDIT"),
1002
        'absolute' => TRUE,
1003
        'html' => TRUE,
1004
      ));
1005
      return $block;
1006
    case 'classification_breadcrumbs':
1007
      $taxon_uuid = get_current_taxon_uuid();
1008
      $block['subject'] = '<none>';
1009
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
1010
      return $block;
1011
    case 'taxonomic_children':
1012
      $taxon_uuid = get_current_taxon_uuid();
1013
      $block['subject'] = '<none>';
1014
      $block['content'] = compose_taxonomic_children($taxon_uuid);
1015
      return $block;
1016
    case 'back_to_search_results':
1017
      $block['subject'] = '<none>';
1018
      if (isset($_SESSION['cdm']['search'])) {
1019
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
1020
      }
1021
      return $block;
1022
    case 'registrations_search_filter':
1023
      $block['subject'] = '<none>';
1024
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
1025
      return $block;
1026
    case 'registrations_search_taxongraph':
1027
      $block['subject'] = '<none>';
1028
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
1029
      return $block;
1030
    case 'registrations_search':
1031
      _add_js_ui_accordion();
1032
      _add_font_awesome_font();
1033
      $block['subject'] = '<none>';
1034
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
1035
      $filter_form['#prefix'] = '<div>';
1036
      $filter_form['#suffix'] = '</div>';
1037
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
1038
      $taxongraph_form['#prefix'] = '<div>';
1039
      $taxongraph_form['#suffix'] = '</div>';
1040
      $block['content'] = array(
1041
        'accordion' => array(
1042
          '#markup' => '',
1043
          '#prefix' => '<div id="accordion">',
1044
          '#suffix' => '</div>',
1045
          'content' => array(
1046
            array('#markup' => '<h3>Filter</h3>'),
1047
            $filter_form,
1048
            array('#markup' => '<h3>Taxon graph</h3>'),
1049
            $taxongraph_form,
1050
          )
1051
        )
1052
    );
1053
       return $block;
1054
    case 'utis_search':
1055
      _add_js_utis_client('.utis_client');
1056
      $block['subject'] = '<none>';
1057
      $block['content'] = '<div class="utis_client"></div>';
1058
      return $block;
1059
    default:
1060
      return null;
1061
  }
1062
}
1063

    
1064

    
1065
/**
1066
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
1067
 *
1068
 * @return string
1069
 *   the taxon uuid or NULL
1070
 */
1071
function get_current_taxon_uuid()
1072
{
1073
  static $taxon_uuid;
1074

    
1075
  if(!isset($taxon_uuid)){
1076
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
1077
      $taxon_uuid = $_REQUEST['currentTaxon'];
1078
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
1079
      $taxon_uuid = arg(2);
1080
    } else {
1081
      $taxon_uuid = null;
1082
    }
1083
  }
1084

    
1085
  return $taxon_uuid;
1086
}
1087

    
1088
/**
1089
 * Returns the currently classification tree in use.
1090
 *
1091
 * @return string
1092
 *   The uuid of the currently focused classification
1093
 */
1094
function get_current_classification_uuid() {
1095
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1096
    return $_SESSION['cdm']['taxonomictree_uuid'];
1097
  }
1098
  else {
1099
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1100
  }
1101
}
1102

    
1103
/*
1104
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
1105
 $_SESSION['cdm'] = NULL;
1106
 if(is_string($cdm_ws_uri_update)){
1107
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
1108
 }
1109
 }
1110

    
1111
 function cdm_dataportal_session_validate(){
1112
 if(!isset($_SESSION['cdm']['ws_uri'])){
1113
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
1114
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
1115
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
1116
 }
1117
 }
1118
 */
1119

    
1120
/**
1121
 * creates a  selector form for taxonomic trees.
1122
 *
1123
 * @return array
1124
 *  a drupal form array
1125
 */
1126
function cdm_taxonomictree_selector() {
1127
  _add_js_treeselector();
1128

    
1129
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1130
  return $form;
1131
}
1132

    
1133
/**
1134
 * @todo Please document this function.
1135
 * @see http://drupal.org/node/1354
1136
 *
1137
 * @deprecated use compose_classification_selector instead
1138
 */
1139
function cdm_taxonomictree_selector_form($form, &$form_state) {
1140

    
1141
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1142
  $form['#action'] = $url;
1143

    
1144
  $form['var'] = array(
1145
    '#weight' => -3,
1146
    '#type' => 'hidden',
1147
    '#value' => '[cdm][taxonomictree_uuid]',
1148
  );
1149

    
1150
  $destination_array = drupal_get_destination();
1151
  $destination = $destination_array['destination'];
1152

    
1153
  $form['destination'] = array(
1154
    '#weight' => -3,
1155
    '#type' => 'hidden',
1156
    '#value' =>  $destination,
1157
  );
1158

    
1159
  $options = cdm_get_taxontrees_as_options();
1160
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1161
  if($taxontree_includes){
1162
    $filtered_options = array();
1163
    foreach($options as $uuid=>$label){
1164
      if(!empty($taxontree_includes[$uuid])){
1165
        $filtered_options[$uuid] = $label;
1166
      }
1167
    }
1168
    $options = $filtered_options;
1169
  }
1170

    
1171
  $form['val'] = array(
1172
    '#type' => 'select',
1173
    '#title' => t('Available classifications'),
1174
    '#default_value' => get_current_classification_uuid(),
1175
    '#options' => $options,
1176
    '#attributes' => array('class' => array('highlite-first-child')),
1177
  );
1178

    
1179
  return $form;
1180

    
1181
}
1182

    
1183
/**
1184
 *
1185
 * @ingroup compose
1186
 */
1187
function compose_classification_selector() {
1188

    
1189
  $destination_array = drupal_get_destination();
1190
  $destination = $destination_array['destination'];
1191

    
1192
  $options = cdm_get_taxontrees_as_options();
1193
  $items = array();
1194
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1195

    
1196
  $current_classification_uuid = get_current_classification_uuid();
1197

    
1198

    
1199
  foreach($options as $uuid=>$label){
1200
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1201

    
1202
      $class_attributes = '';
1203
      if($current_classification_uuid == $uuid){
1204
        $class_attributes  = array('focused');
1205
      }
1206
      $items[] = array(
1207
        'data' => l($label,
1208
          'cdm_api/setvalue/session',
1209
          array(
1210
            'query' => array(
1211
              'destination' => $destination,
1212
              'val' => $uuid,
1213
              'var' => '[cdm][taxonomictree_uuid]'
1214
            ),
1215
          )
1216
        ),
1217
        'class' => $class_attributes
1218
      );
1219
    }
1220
  }
1221

    
1222
  $render_array = array(
1223
    '#theme' => 'item_list',
1224
    '#type' => 'ul',
1225
    '#items' => $items
1226
  );
1227

    
1228
  return $render_array;
1229
}
1230

    
1231

    
1232
/* UNREACHABLE since action of form directly links to view.
1233
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1234

    
1235
 $_SESSION['cdm']['search'] = $form_values;
1236
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1237
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1238
 //$paramstr = compose_url_prameterstr($form_values);
1239
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1240
 }
1241
 */
1242
/* ====================== menu callback functions ====================== */
1243
/**
1244
 * @todo Please document this function.
1245
 * @see http://drupal.org/node/1354
1246
 */
1247
/*
1248
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1249
  static $comment_node_disabled =  0;
1250
  static $comment_node_read_only =  1;
1251
  static $comment_node_read_write =  2;
1252

    
1253
  if ($form_id == 'node_type_form'
1254
   && isset($form['identity']['type'])
1255
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1256
  ) {
1257
    $form['workflow']['comment'] = array(
1258
      '#type' => 'radios',
1259
      '#title' => t('Default comment setting'),
1260
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1261
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1262
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1263
    );
1264
  }
1265
}
1266
*/
1267

    
1268
/**
1269
 * Displays a list of the known taxonomic names.
1270
 *
1271
 * When the list of taxonomic names is displayed, long lists are split up into
1272
 * multiple pages.
1273
 *
1274
 * TODO: Parameters are still preliminary.
1275
 *
1276
 * @param string $beginsWith
1277
 * @param string $page
1278
 *   Page number to diplay defaults to page 1.
1279
 * @param bool $onlyAccepted
1280
 */
1281
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1282

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

    
1285
  /*
1286
  // FIXME the filter for accepted names will be a form element, thus this
1287
  // widget should be generated via form api preferably as block.
1288
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1289
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1290
  $out .= theme('cdm_listof_taxa', $taxonPager);
1291
  return $out;
1292
  */
1293
}
1294

    
1295
/**
1296
 * @todo Please document this function.
1297
 * @see http://drupal.org/node/1354
1298
 * @throws Exception
1299
 */
1300
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1301

    
1302
  cdm_check_valid_portal_page();
1303

    
1304
  return compose_cdm_reference_page($uuid);
1305
}
1306

    
1307
/**
1308
 * Creates a view on a all references contained in the portal.
1309
 *
1310
 * This function is used at the path cdm_dataportal/reference/list
1311
 */
1312
function cdm_dataportal_view_reference_list($pageNumber) {
1313
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1314
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1315
}
1316

    
1317
/**
1318
 * @todo Please document this function.
1319
 * @see http://drupal.org/node/1354
1320
 */
1321
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1322

    
1323
  cdm_check_valid_portal_page();
1324

    
1325
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1326
  if (!$media) {
1327
    drupal_set_title(t('Media does not exist'), PASS_THROUGH);
1328
    return "";
1329
  }
1330
  return theme('cdm_media_page', array(
1331
    'media' => $media,
1332
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1333
    'partId' => $part,
1334
    ));
1335
}
1336

    
1337
/**
1338
 * @todo Please document this function.
1339
 * @see http://drupal.org/node/1354
1340
 */
1341
function _load_taxonBase(&$taxonBase) {
1342
  if (isset($taxonBase->uuid)) {
1343
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1344
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1345
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1346
  }
1347
}
1348

    
1349
/**
1350
 * Loads the media associated to the given taxon from the cdm server.
1351
 * The aggregation settings regarding taxon relathionships and
1352
 * taxonnomic childen are taken into account.
1353
 *
1354
 * The media lists are cached in a static variable.
1355
 *
1356
 * @param Taxon $taxon
1357
 *   A CDM Taxon entity
1358
 *
1359
 * @return array
1360
 *   An array of CDM Media entities
1361
 *
1362
 */
1363
  function _load_media_for_taxon($taxon) {
1364

    
1365
  static $media = NULL;
1366

    
1367
  if(!isset($media)) {
1368
    $media = array();
1369
  }
1370
  if (!isset($media[$taxon->uuid])) {
1371

    
1372

    
1373
    $mediaQueryParameters = taxon_media_query_parameters();
1374

    
1375
    $ws_endpoint = NULL;
1376
    if ( $mediaQueryParameters['includeTaxonomicChildren']) {
1377
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1378
    } else {
1379
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1380
    }
1381
    // this parameter is not yet used by the CDM_WS_PORTAL_TAXON_*MEDIA
1382
    // services
1383
    unset($mediaQueryParameters['includeTaxonomicChildren']);
1384

    
1385
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1386
        array(
1387
            $taxon->uuid,
1388
        ),
1389
        queryString($mediaQueryParameters)
1390
       );
1391
  }
1392

    
1393
  return $media[$taxon->uuid];
1394
}
1395

    
1396
/**
1397
 *
1398
 * @param Taxon $taxon
1399
 *   A CDM Taxon entitiy
1400
 *
1401
 * @return array
1402
 *   An array of CDM SpecimenOrObservation entities
1403
 *
1404
function _load_occurences_for_taxon($taxon){
1405

    
1406
  static $occurences = NULL;
1407

    
1408
  if(!isset($occurences)) {
1409
    $occurences = array();
1410
  }
1411

    
1412
  if (!isset($occurences[$taxon->uuid])){
1413

    
1414
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1415
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1416
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1417

    
1418
    $by_associatedtaxon_query = http_build_query(array(
1419
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1420
        'relationships' => implode(',', $relationship_choice['direct']),
1421
        'pageSize' => null // all hits in one page
1422
    )
1423
    );
1424

    
1425
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1426
        null,
1427
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1428
    );
1429

    
1430

    
1431
    if(isset($pager->records[0])){
1432
      $occurences[$taxon->uuid] =  $pager->records;
1433
    }
1434
  }
1435
  return $occurences[$taxon->uuid];
1436
}
1437
 */
1438

    
1439
/**
1440
 * Gets a Drupal variable, string or array and returns it.
1441
 *
1442
 * Similar to the variable_get() function of Drupal, except that this function
1443
 * is able to handle arrays correctly. This function is especially useful
1444
 * when dealing with collections of settings form elements (#tree = TRUE).
1445
 *
1446
 * @param string $variableKey
1447
 *   The Unique key of the Drupal variable in the Drupal variables table.
1448
 * @param string $defaultValueString
1449
 *   A string as for example derived from a CONSTANT.
1450
 *
1451
 * @return mixed
1452
 *   usually an array, depending on the nature of the variable.
1453
 *
1454
 * TODO compare with get_array_variable_merged() duplicate functions?
1455
 * @deprecated rather use get_array_variable_merged() since this function
1456
 * used an array as second parameter
1457
 */
1458
function mixed_variable_get($variableKey, $defaultValueString) {
1459
  $systemDefaults = unserialize($defaultValueString);
1460
  $storedSettings = variable_get($variableKey, array());
1461
  if (is_array($storedSettings)) {
1462
    // TODO better use drupal_array_merge_deep() ?
1463
    $settings = array_merge($systemDefaults, $storedSettings);
1464
  }
1465
  else {
1466
    $settings = $systemDefaults;
1467
  }
1468
  return $settings;
1469
}
1470

    
1471
/**
1472
 * Recursive function to convert an object into an array.
1473
 * also subordinate objects will be converted.
1474
 *
1475
 * @param object $object
1476
 *  the object to be converted
1477
 * @return array
1478
 *  The array
1479
 */
1480
function object_to_array($object) {
1481
  if(is_object($object) || is_array($object)) {
1482
    $array = (array)$object;
1483
    foreach ($array as $key=>$value){
1484
      $array[$key] = object_to_array($value);
1485
    }
1486
    return $array;
1487
  } else {
1488
    return $object;
1489
  }
1490
}
1491

    
1492
/**
1493
 * Searches the $collection for the cdm entitiy given as $element.
1494
 *
1495
 * The elements are compared by their UUID.
1496
 *
1497
 * @param $element
1498
 *  the CDM entitiy to search for
1499
 * @param $collection
1500
 *  the list of CDM entities to search in
1501
 *
1502
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1503
 *
1504
 */
1505
function contains_cdm_entitiy($element, $collection) {
1506
  $result = FALSE;
1507
  foreach ($collection as $a) {
1508
    if ($a->uuid == $element->uuid) {
1509
      $result = TRUE;
1510
    }
1511
  }
1512
  return $result;
1513
}
1514

    
1515
/**
1516
 * Filters the array $entity_list of CDM entities by the list
1517
 * of $excludes. Any element contained in the $excludes will be removed
1518
 * from included int the returned list.
1519
 *
1520
 * If the $entity_list is not an array the $excludes will be returned.
1521
 */
1522
function filter_cdm_entity_list($entity_list, $excludes) {
1523
  if (is_array($entity_list)) {
1524
    $result = $entity_list;
1525
    if ($excludes) {
1526
      foreach ($excludes as $exclude) {
1527
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1528
          $result[] = $exclude;
1529
        }
1530
      }
1531
    }
1532
  }
1533
  else {
1534
    $result = $excludes;
1535
  }
1536
  return $result;
1537
}
1538

    
1539
/**
1540
 * Wraps the given $html string into a render array suitable for drupal_render()
1541
 *
1542
 * @param $html
1543
 *   the html string, see
1544
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1545
 * @param $weight
1546
 *   A positive or negative number (integer or decimal).
1547
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1548
 * @param $prefix
1549
 *   Optional markup for the '#prefix' element of the render array
1550
 * @param $suffix
1551
 *   Optional markup for the '#suffix' element of the render array
1552
 *
1553
 * @return array
1554
 *   A render array
1555
 *
1556
 */
1557
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1558
  $render_array = array(
1559
    '#markup' => $html
1560
      );
1561
  if (is_numeric($weight)) {
1562
    $render_array['#weight'] = $weight;
1563
  }
1564
  if($prefix){
1565
    $render_array['#prefix'] = $prefix;
1566
  }
1567
  if($suffix) {
1568
    $render_array['#suffix'] = $suffix;
1569
  }
1570
  return $render_array;
1571
}
1572

    
1573
/**
1574
 * Loads the subgraph of a given PolytomousKeyNode.
1575
 *
1576
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1577
 * the CDM REST service.
1578
 *
1579
 * @param mixed $polytomousKeyNode
1580
 *   PolytomousKeyNode passed by reference.
1581
 *
1582
 * @return void
1583
 */
1584
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1585

    
1586
  if (!$polytomousKeyNode) {
1587
    return;
1588
  }
1589
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1590
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1591
    return;
1592
  }
1593
  if (!is_uuid($polytomousKeyNode->uuid)) {
1594
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1595
    return;
1596
  }
1597

    
1598
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1599

    
1600
  if (!$polytomousKeyNode) {
1601
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1602
    return;
1603
  }
1604

    
1605
  // Load children.
1606
  foreach ($polytomousKeyNode->children as &$childNode) {
1607
    _load_polytomousKeySubGraph($childNode);
1608
  }
1609

    
1610
  // Load subkey.
1611
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1612

    
1613
  // Load taxon.
1614
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1615
  _load_taxonBase($polytomousKeyNode->taxon);
1616
  return;
1617
}
1618

    
1619
/**
1620
 * @todo Please document this function.
1621
 * @see http://drupal.org/node/1354
1622
 */
1623
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1624

    
1625
  cdm_check_valid_portal_page();
1626

    
1627
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1628
  if (!$polytomousKey) {
1629
    drupal_set_title(t('Polytomous key does not exist'), PASS_THROUGH);
1630
    return "";
1631
  }
1632

    
1633
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1634
  if (is_array($sourcePager->records)) {
1635
    $polytomousKey->sources = $sourcePager->records;
1636
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1637
  }
1638

    
1639
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1640
  if (is_array($annotationPager->records)) {
1641
    $polytomousKey->annotations = $annotationPager->records;
1642
  }
1643

    
1644
  _load_polytomousKeySubGraph($polytomousKey->root);
1645
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1646
}
1647

    
1648
/**
1649
 * Creates a taxon page view or a chapter of it.
1650
 *
1651
 * The taxon page gives detailed information on a taxon, it shows:
1652
 *  - Taxon name.
1653
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1654
 *    heterotypic and finally followed by misapplied names.
1655
 *    The list is ordered historically.
1656
 *  - All description associated with the taxon.
1657
 *
1658
 * @param string $uuid
1659
 * @param string $chapter
1660
 *   Name of the part to display, valid values are:
1661
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1662
 *
1663
 * @return string
1664
 */
1665
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1666

    
1667
  cdm_check_valid_taxon_page($chapter);
1668
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1669

    
1670

    
1671
  // Display the page for the taxon defined by $uuid.
1672
  // set_last_taxon_page_tab(arg(3));
1673
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1674
  if (!empty($taxonpage)) {
1675
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1676
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1677
  }
1678
  else {
1679
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1680
    return '';
1681
  }
1682
}
1683

    
1684
/**
1685
 * This function will generate the taxon page part ($chapter) and returns a taxonpage object
1686
 * which has two fields, one for the page title and one for the content. Later on in the
1687
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1688
 * function as the function parameters $title and $content.
1689
 *
1690
 * @param string $uuid
1691
 *   the uuid of the taxon to show
1692
 * @param string $chapter
1693
 *   Name of the part to display, valid values are:
1694
 *   'description', 'images', 'synonymy', 'all'.
1695
 *
1696
 * @return object with the following fields:
1697
 *   - title : the title of the page
1698
 *   - content: the content of the page
1699
 *
1700
 * @throws Exception
1701
 *
1702
 */
1703
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1704
  // Taxon object.
1705
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1706
  if (empty($taxon)) {
1707
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1708
    return null;
1709
  }
1710
  $taxonpage = new stdClass();
1711

    
1712
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1713
    'taxon' => $taxon
1714
  ));
1715

    
1716
  // Check if the taxon id contained in the currently selected tree.
1717
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1718

    
1719
  if (!$taxon_in_current_classification) {
1720
    $classifications = get_classifications_for_taxon($taxon);
1721
    RenderHints::pushToRenderStack('not_in_current_classification');
1722
    $taxon_name_markup = render_taxon_or_name($taxon);
1723

    
1724
    if (count($classifications) == 0) {
1725
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1726
        array(
1727
        '!taxonname' => $taxon_name_markup,
1728
        )
1729
      ), 'warning');
1730
    }
1731
    else {
1732
      $trees = '';
1733
      foreach ($classifications as $classification) {
1734
        if (isset($classification->titleCache)) {
1735
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1736
        }
1737
      }
1738

    
1739
      drupal_set_message(format_plural(count($trees),
1740
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1741
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1742
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1743
        ) ,
1744
        'warning');
1745
    }
1746
    RenderHints::popFromRenderStack();
1747
  }
1748

    
1749
  // Render the taxon page.
1750
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1751
  $taxonpage->content = drupal_render($render_array);
1752

    
1753
  return $taxonpage;
1754
}
1755

    
1756

    
1757
function cdm_dataportal_specimen_by_accession_number_page_view($accession_number)
1758
{
1759
  cdm_check_valid_portal_page();
1760

    
1761
  $specimenpage = specimen_by_accession_number_view($accession_number);
1762

    
1763
  if (!empty($specimenpage)) {
1764
    return cdm_node_show_simulate($specimenpage->content);
1765
  }
1766
  else {
1767
    return '';
1768
  }
1769

    
1770

    
1771
}
1772

    
1773
/**
1774
 * Creates a specimen page view.
1775
 * @param string $uuid the UUID of the specimen
1776
 * @return array|string
1777
 */
1778
function cdm_dataportal_specimen_page_view($uuid) {
1779

    
1780
    cdm_check_valid_portal_page();
1781
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1782
    if (!empty($specimenpage)) {
1783
        return cdm_node_show_simulate($specimenpage->content);
1784
    }
1785
    else {
1786
        return '';
1787
    }
1788
}
1789

    
1790

    
1791
/**
1792
 * Creates a specimen page view.
1793
 * @param string $uuid the UUID of the specimen
1794
 * @return object
1795
 *  The page object with the following fields:
1796
 *   - 'title': the page title
1797
 *   - 'content' : the page content rendered as markup
1798
 */
1799
function specimen_by_accession_number_view($accession_number = null) {
1800

    
1801
  $field_unit_dto = cdm_ws_get(CDM_WS_OCCURRENCE_ACCESSION_NUMBER, null, 'accessionNumber=' . $accession_number);
1802

    
1803
  // Display the page for the specimen defined by $uuid.
1804
  if (isset($field_unit_dto)){
1805
    $dto_array = array($field_unit_dto);
1806
    $specimen_array = specimen_render_array_items($dto_array);
1807
    $specimen_table = array(
1808
      '#theme' => 'table',
1809
      '#weight' => 2,
1810
      // prefix attributes and rows with '#' to let it pass toF the theme function,
1811
      // otherwise it is handled as child render array
1812
      '#attributes' => array('class' => 'specimens'),
1813
      '#rows' => array(),
1814
      '#prefix' => '<div id="specimens">',
1815
      '#suffix' => '</div>',
1816
    );
1817
    foreach($specimen_array as $value){
1818
      $renderArray = array(
1819
        '#theme' => 'item_list',
1820
        '#items' => array($value),
1821
        '#type' => 'ul');
1822
      $output = drupal_render($renderArray);
1823
      $specimen_table['#rows'][] = array(
1824
        // An array of table rows. Every row is an array of cells, or an associative array
1825
        'data' => array($output),
1826
        'class' =>  array(
1827
          'descriptionElement',
1828
          'descriptionElement_IndividualsAssociation'
1829
        ),
1830
      );
1831

    
1832

    
1833
    }
1834
    $specimenpage = new stdClass();
1835

    
1836
    $specimenpage->title = theme('theme_cdm_specimen_dto_page_title', array(
1837
      'specimen' => $field_unit_dto
1838
    ));
1839

    
1840
     $render_array['markup'] = $specimen_table;
1841
     $specimenpage->content = drupal_render($render_array);
1842
  }
1843

    
1844
  return $specimenpage;
1845
}
1846

    
1847

    
1848
/**
1849
 *
1850
 * Creates a specimen view.
1851
 * @param string $uuid the UUID of the specimen
1852
 * @return object
1853
 *    Page object with the fields
1854
 *    - title
1855
 *    - content
1856
 */
1857
function cdm_dataportal_specimen_view($uuid) {
1858
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1859
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1860
    if (empty($specimen)) {
1861
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1862
        return FALSE;
1863
    }
1864
    $specimenpage = new stdClass();
1865

    
1866
    $specimenpage->title = specimen_page_title($specimen);
1867

    
1868
    // Render the specimen page.
1869
    $render_array = compose_cdm_specimen_page($specimen);
1870
    $specimenpage->content = drupal_render($render_array);
1871

    
1872
    return $specimenpage;
1873
}
1874

    
1875
/**
1876
 *
1877
 * Creates a description view.
1878
 *
1879
 * @param string $uuid the UUID of the description
1880
 * @param null $descriptive_dataset_uuid the uuid of the data set which defines
1881
 * the display of the description detail page
1882
 *
1883
 * @return object Page object with the fields
1884
 * Page object with the fields
1885
 * - title
1886
 * - content
1887
 */
1888
function cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid = NULL) {
1889
    $description = cdm_ws_get(CDM_WS_PORTAL_DESCRIPTION, $uuid);
1890
    $description_page = new stdClass();
1891
    if (empty($description)) {
1892
      $description_page->title = t('Description does not exist');
1893
      drupal_set_title($description_page->title, PASS_THROUGH); // not necessary if correctly implemented as drupal node
1894
      $description_page->content = "";
1895

    
1896
    } else {
1897
      $description_page->title = $description->titleCache;
1898
      drupal_set_title($description_page->title); // not necessary if correctly implemented as drupal node
1899

    
1900
      // Render the description page.
1901
      $render_array = compose_description_table($description->uuid, $descriptive_dataset_uuid);
1902
      if($render_array['title']){
1903
        $page_title = strip_tags($render_array['title']['#markup']);
1904
        drupal_set_title($page_title);
1905
        unset($render_array['title']);
1906
      }
1907
      $description_page->content = drupal_render($render_array);
1908
    }
1909

    
1910
    return $description_page;
1911
}
1912

    
1913
function cdm_dataportal_description_page_view($uuid, $descriptive_dataset_uuid = NULL) {
1914

    
1915
  cdm_check_valid_portal_page();
1916
  $descriptionpage = cdm_dataportal_description_view($uuid, $descriptive_dataset_uuid);
1917
  if (!empty($descriptionpage)) {
1918
    return cdm_node_show_simulate($descriptionpage->content);
1919
  }
1920
  else {
1921
    return NULL;
1922
  }
1923
}
1924

    
1925
/**
1926
 *
1927
 * Creates a named area view.
1928
 * @param string $uuid the UUID of the specimen
1929
 *  * @return object
1930
 *   An object with two fields:
1931
 *     - title: the page title
1932
 *     - content: the page content
1933
 */
1934

    
1935
function cdm_dataportal_named_area_view($uuid) {
1936
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1937
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1938
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1939
    return null;
1940
  }
1941
  $named_area_page = new stdClass();
1942

    
1943
  $named_area_page->title = $named_area->representation_L10n;
1944

    
1945
  // Render the specimen page.
1946
  $render_array = compose_cdm_named_area_page($uuid);
1947
  $named_area_page->content = drupal_render($render_array);
1948

    
1949
  return $named_area_page;
1950
}
1951

    
1952
function cdm_dataportal_named_area_page_view($uuid) {
1953

    
1954
  cdm_check_valid_portal_page();
1955

    
1956
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1957
  if (!empty($named_area_page)) {
1958
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1959
  }
1960
  else {
1961
    return '';
1962
  }
1963

    
1964

    
1965
}
1966

    
1967
/**
1968
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1969
 *
1970
 * The node page shows the taxon name title and the list of taxon related
1971
 * with such taxon. Name on the tree already in use.
1972
 *
1973
 * @param string $taxon_name_uuid
1974
 *   The uuid of the CDM TaxonName to show a name page for
1975
 * @param string $taxon_to_hide_uuid
1976
 *   A taxon which should not be displayed in the taxon list
1977
 * @param $redirect_to_taxon
1978
 *   Automatically redirect to the related taxon if there is only one
1979
 *   accepted taxon for this name.
1980
 * @param string $highlite_synonym_uuid
1981
 *   Optinal parameter wich takes another taxon uuid, if given the
1982
 *   target taxon pages will show the syonymy tab where the taxon
1983
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1984
 *   in case it is found on this page.
1985
 *
1986
 * @return mixed
1987
 *   The formatted name page as node.
1988
 */
1989
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL, $redirect_to_taxon = false) {
1990

    
1991
  cdm_check_valid_portal_page();
1992

    
1993
  $taxonname_page = cdm_dataportal_name_view(
1994
    is_uuid($taxon_name_uuid) ? $taxon_name_uuid : null,
1995
    is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : null,
1996
    $redirect_to_taxon == 'redirect_to_taxon',
1997
    is_uuid($synonym_uuid) ? $synonym_uuid : null);
1998
  if (!empty($taxonname_page)) {
1999
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
2000
  }
2001
  else {
2002
    return '';
2003
  }
2004
}
2005

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

    
2061
  // Removing the name where we came from.
2062
  foreach ($taxa as $k => &$taxon) {
2063
    if ($taxon->uuid == $taxon_to_hide_uuid) {
2064
      unset($taxa[$k]);
2065
    }
2066
  }
2067
  // Show the taxa list or go to the singular taxon.
2068
  if (sizeof($taxa) == 1 && $redirect_to_taxon) {
2069
    // redirect to the taxon if there is only one.
2070
    $singleTaxon = array_pop($taxa);
2071
    if ($singleTaxon->class != "Taxon") {
2072
      // It is a Synonym -> look for the accepted.
2073
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
2074
      if (!empty($highlite_synonym_uuid)) {
2075
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2076
      }
2077
      else {
2078
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
2079
      }
2080
    }
2081
    else {
2082
      // It is an accepted taxon.
2083
      if (!empty($highlite_synonym_uuid)) {
2084
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
2085
      }
2086
      else {
2087
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
2088
      }
2089
    }
2090
  }
2091
  else {
2092
    // display the name page content
2093
    $taxon_name_page = new stdClass();
2094
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
2095
    $content = array();
2096

    
2097
    RenderHints::pushToRenderStack('name_page');
2098
    RenderHints::setFootnoteListKey('name_page');
2099
    $content['taxon_name'] = markup_to_render_array(render_taxon_or_name($taxon_name), null, '<div class="name-page-name">', '</div>');
2100

    
2101

    
2102
    // name relationships
2103
    $name_relations = cdm_ws_fetch_all(str_replace("$0", $taxon_name->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
2104
    if(count($name_relations) > 0){
2105
      $content['name_relationships'] = compose_name_relationships_list($name_relations, $taxon_name->uuid, null);
2106
    }
2107

    
2108
    // type designations
2109
    $type_designations_render_array = compose_type_designations($taxon_name->uuid);
2110
    $content = array_merge($content, $type_designations_render_array);
2111
    // registrations
2112
    $registrationDTOs= cdm_ws_fetch_all(CDM_WS_REGISTRATION_DTO,  array('nameUuid' => $taxon_name_uuid));
2113
    if(isset($registrationDTOs) && count($registrationDTOs ) > 0 ){
2114
      $content['registrations'][] = markup_to_render_array('<h2>' . t("Registrations") . '</h2>') ;
2115
      foreach ($registrationDTOs as $regDTO){
2116
        $content['registrations'][] = compose_registration_dto_compact($regDTO);
2117
      }
2118
    }
2119

    
2120

    
2121
    // related taxa
2122
    $show_taxa_section = variable_get(CDM_NAME_PAGE_SECTION_TAXA, CDM_NAME_PAGE_SECTION_TAXA_DEFAULT);
2123
    if($show_taxa_section){
2124
      if ($taxa) {
2125
        $content['related_taxa_header'] = markup_to_render_array("<h2>Taxa for this name</h2>");
2126
        $content['related_taxa'] = compose_list_of_taxa($taxa);
2127
      }
2128
      else {
2129
        $content['related_taxa'] = markup_to_render_array('This name is not assigned to a taxon.', null, '<div class="no-taxon-message">', '</div>');
2130
      }
2131
    }
2132

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

    
2135
    $taxon_name_page->content = $content;
2136
    RenderHints::popFromRenderStack();
2137
    RenderHints::clearFootnoteListKey();
2138
    return $taxon_name_page;
2139
  }
2140
}
2141

    
2142

    
2143
/**
2144
 * Returns a registration page as a Drupal node to be rendered by Drupal.
2145
 *
2146
 * @param string  $registration_identifier_encoded
2147
 *   The persistent identifier of the registration urlencoded.
2148
 * @return mixed
2149
 *   The formatted registration page as node.
2150
 */
2151
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
2152

    
2153
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
2154
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
2155
  return cdm_node_show_simulate($registration_page);
2156
}
2157

    
2158
/**
2159
 * @param $registration_identifier_encoded
2160
 * @return array
2161
 *   The drupal render array for the registration view.
2162
 */
2163
function cdm_dataportal_registration_view($registration_identifier_encoded) {
2164

    
2165
  $registration_identifier = urldecode($registration_identifier_encoded);
2166

    
2167
  RenderHints::pushToRenderStack('registration_page');
2168
  RenderHints::setFootnoteListKey('registration_page');
2169

    
2170
  $render_array = array();
2171
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
2172
  if($registration_dto){
2173

    
2174
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
2175
    $render_array = compose_registration_dto_full($registration_dto, true);
2176

    
2177
  } else {
2178
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
2179
    if(isset($status_text->String)) {
2180
      $status_text = strtolower($status_text->String);
2181
      if($status_text == 'preparation' || $status_text == 'curation'){
2182
        $status_text = 'in ' . $status_text;
2183
      }
2184
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
2185
      //$status_message;
2186
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
2187
    } else {
2188
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
2189
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
2190
    }
2191
  }
2192

    
2193
  $render_array = array(
2194
    '#prefix' => '<div id="registration">',
2195
    'registration' => $render_array,
2196
    '#suffix' => '</div>',
2197
  );
2198

    
2199
  RenderHints::popFromRenderStack();
2200
  RenderHints::clearFootnoteListKey();
2201

    
2202
  return $render_array ;
2203
}
2204

    
2205

    
2206
/**
2207
 * Creates a page with the advance search form.
2208
 *
2209
 * NOTE: The advance search form allows searching for taxa.
2210
 */
2211
function cdm_dataportal_view_search_advanced() {
2212
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2213
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2214
}
2215

    
2216
/**
2217
 * Creates a page with the blast search form.
2218
 *
2219
 * NOTE: The advance search form allows searching for specimen in blast DB.
2220
 */
2221
function cdm_dataportal_view_search_blast() {
2222
    drupal_set_title(t('Blast search'), PASS_THROUGH);
2223
    return drupal_get_form('cdm_dataportal_search_blast_form');
2224
}
2225

    
2226
/**
2227
 * Creates a page with the search form for searching by taxon descriptions.
2228
 */
2229
function cdm_dataportal_view_search_taxon_by_description() {
2230
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2231
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2232
}
2233

    
2234
/**
2235
 * Executes the search and generates the result list of taxa.
2236
 */
2237
function cdm_dataportal_view_search_results_taxon() {
2238

    
2239
  $taxonPager = cdm_dataportal_search_taxon_execute();
2240

    
2241
  $showThumbnails = do_showThumbnails();
2242

    
2243
  $setSessionUri = url('cdm_api/setvalue/session', array(
2244
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2245
  ));
2246

    
2247
  drupal_add_js('jQuery(document).ready(function() {
2248

    
2249
      // init
2250
      if(' . $showThumbnails . ' == 1){
2251
          jQuery(\'.media_gallery\').show(20);
2252
      } else {
2253
          jQuery(\'.media_gallery\').hide(20);
2254
      }
2255

    
2256
      // add change handler
2257
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2258
      function(event){
2259
        var state = 0;
2260
        if(jQuery(this).is(\':checked\')){
2261
          jQuery(\'.media_gallery\').show(20);
2262
          state = 1;
2263
        } else {
2264
          jQuery(\'.media_gallery\').hide(20);
2265
        }
2266
        // store state in session variable
2267
        var uri = \'' . $setSessionUri . '\' + state;
2268
        jQuery.get(uri);
2269
      });
2270
  });',
2271
  array('type' => "inline", 'scope' => JS_DEFAULT));
2272

    
2273
  drupal_set_title(t('Search results'), PASS_THROUGH);
2274

    
2275
  return theme('cdm_search_taxa_results', array(
2276
    'pager' => $taxonPager,
2277
    'path' => 'cdm_dataportal/search/results/taxon',
2278
    ));
2279
}
2280

    
2281
/**
2282
 * Executes the blast search and generates the result list of specimen.
2283
 */
2284
function cdm_dataportal_view_search_results_specimen() {
2285

    
2286
    $specimenPager = cdm_dataportal_search_blast_execute();
2287

    
2288
    return theme('cdm_search_specimen_results', array(
2289
        'pager' => $specimenPager,
2290
        'path' => 'cdm_dataportal/search/results/specimen',
2291
    ));
2292
}
2293

    
2294

    
2295
/**
2296
 * Executes the search for registrations and generates the result list..
2297
 */
2298
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2299

    
2300
  switch($mode ){
2301
    case 'taxongraph':
2302
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2303
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2304
      break;
2305
    case 'filter':
2306
    default:
2307
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2308
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2309
  }
2310
  $block->title = null;
2311

    
2312
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2313

    
2314
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2315
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2316
  $render_array = array_merge($render_array, $registrations_pager_array);
2317

    
2318
  return $render_array;
2319
}
2320

    
2321

    
2322
/**
2323
 * Provides the standard image which indicated a loading process
2324
 *
2325
 * @return string
2326
 *  The img html tag
2327
 */
2328
function loading_image_html() {
2329
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2330
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2331
}
2332

    
2333
/**
2334
 * Returns the state of the the showThumbnails flag set in the
2335
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2336
 *
2337
 * @return boolean
2338
 *    returns 1 if the flag is set
2339
 */
2340
function do_showThumbnails() {
2341
  static $showThumbnails = null;
2342

    
2343
  if($showThumbnails == null) {
2344
    $showThumbnails = 0;
2345
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2346
      $showThumbnails = 0;
2347
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2348
      $showThumbnails = is_array($search_gallery_settings)
2349
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2350
        && (
2351
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2352
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2353
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2354
            )
2355
         ? 1 : 0;
2356

    
2357
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2358
    }
2359
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2360
    if (!is_numeric($showThumbnails)) {
2361
      $showThumbnails = 1;
2362
    }
2363
  }
2364

    
2365
  return $showThumbnails;
2366
}
2367

    
2368

    
2369

    
2370
/* ====================== other functions ====================== */
2371
/**
2372
 * Creates a URL to the taxon page specified by the $uuid parameter.
2373
 *
2374
 * The URL will be prepended with a path element to a specific taxon page tab.
2375
 *
2376
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2377
 * be set globally in the administrative settings or individually in the user
2378
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2379
 * the last portal will stay on this last tab.
2380
 *
2381
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2382
 * internal mechanism by a specific value.
2383
 *
2384
 * @param string $uuid
2385
 *   The UUID of the taxon.
2386
 * @param string $page_tab
2387
 *   Overwriting the preset mechanism by defining specific value for the
2388
 *   taxon page tab.
2389
 * @return string
2390
 *   The created URL.
2391
 */
2392
function path_to_taxon($uuid, $page_tab = FALSE) {
2393

    
2394
  $tab = get_default_taxon_tab();
2395
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2396

    
2397
  if (!$uuid) {
2398
    return FALSE;
2399
  }
2400

    
2401
  if ($page_tab) {
2402
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2403
  }
2404
  elseif (!$tab || strtolower($tab) == 'general') {
2405
    $url = 'cdm_dataportal/taxon/' . $uuid;
2406
  }
2407
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2408
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2409
  }
2410
  else {
2411
    $url = 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2412
  }
2413
  return $url;
2414
}
2415

    
2416
function path_to_description($uuid, $descriptive_dataset_uuid = NULL) {
2417

    
2418
    if (!$uuid) {
2419
        return FALSE;
2420
    }
2421
    else {
2422
      return 'cdm_dataportal/description/' . $uuid
2423
        . (is_uuid($descriptive_dataset_uuid) ? '/' . $descriptive_dataset_uuid : '');
2424
    }
2425
}
2426

    
2427
function path_to_specimen($uuid) {
2428

    
2429
    if (!$uuid) {
2430
        return FALSE;
2431
    }
2432
    else {
2433
        return 'cdm_dataportal/occurrence/' . $uuid;
2434
    }
2435
}
2436

    
2437
function path_to_specimen_by_accession_number($accession_number) {
2438

    
2439
    if (!$accession_number) {
2440
        return FALSE;
2441
    }
2442
    else {
2443
        return 'cdm_dataportal/specimen/accession_number/' . $accession_number;
2444
    }
2445
}
2446

    
2447
function path_to_named_area($uuid) {
2448

    
2449
  if (!$uuid) {
2450
    return FALSE;
2451
  }
2452
  else {
2453
    return 'cdm_dataportal/named_area/' . $uuid;
2454
  }
2455
}
2456

    
2457
/**
2458
 * Creates a URL to show a synonmy in the according taxon page.
2459
 *
2460
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2461
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2462
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2463
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2464
 * in the page
2465
 *
2466
 * @param string $synonymUuid
2467
 *    The uuid of the synonym
2468
 * @param string $acceptedUuid
2469
 *    The uuid of the according accepted taxon
2470
 * @return string
2471
 *    The URL to show a synonmy in the according taxon page
2472
 */
2473
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2474
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2475
  return url($acceptedPath, array(
2476
      'query' => array(
2477
        // highlite the synony in the synonymy
2478
        'highlite' => $synonymUuid,
2479
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2480
        // see theme_taxon_page_title()
2481
        'acceptedFor' => $synonymUuid
2482
      ),
2483
      'fragment' => $synonymUuid
2484
  ));
2485

    
2486
}
2487

    
2488
/**
2489
 * Composes the drupal path to the key identified by the uuid.
2490
 *
2491
 * @param string $keyType
2492
 *    the key typer corresponds to the specific class of the CDM
2493
 *    IdentificationKey. Possible values are
2494
 *      -PolytomousKey
2495
 *      -MultimediaKey
2496
 *      - ...
2497
 * @param string $keyUuid
2498
 *   The UUID of the key
2499
 */
2500
function path_to_key($keyType, $keyUuid) {
2501
  if (!$keyUuid || !$keyType) {
2502
    return FALSE;
2503
  }
2504
  $keyType{0} = strtolower($keyType{0});
2505
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2506
}
2507

    
2508
/**
2509
 * Composes the drupal path to the reference identified by the uuid.
2510
 *
2511
 * @param $uuid string String representation of the registration entity uuid.
2512
 *
2513
 * @return string
2514
 *  The drupal path
2515
 *
2516
 */
2517
function path_to_reference($uuid) {
2518
  if (!$uuid) {
2519
    return FALSE;
2520
  }
2521
  return 'cdm_dataportal/reference/' . $uuid;
2522
}
2523

    
2524
/**
2525
 * Composes the drupal path to the reference identified by the uuid.
2526
 *
2527
 * @param string $identifier
2528
 *  The persistent identifier of the registration entity (Registration.identifier).
2529
 * @return string
2530
 *  The drupal path
2531
 */
2532
function path_to_registration($identifier) {
2533

    
2534
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2535
    return $identifier;
2536
  } else {
2537
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2538
  }
2539
}
2540

    
2541
/**
2542
 * Creates the path to a cdm_dataportal taxon name page.
2543
 *
2544
 * @param string $taxon_name_uuid
2545
 *   The uuid as string of the CDM TaxonName to show a name page for
2546
 * @param string $taxon_to_hide_uuid
2547
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2548
 * @param string $highlited_synonym_uuid
2549
 *   Optional parameter which takes another taxon uuid, if given the
2550
 *   target taxon pages will show the synonymy tab where the taxon
2551
 *   referenced by the $highlite_synonym_uuid will be highlighted
2552
 *   in case it is found on this page.
2553
 * @param $redirect_to_taxon
2554
 *   If true, the name page will redirect to the related taxon if there is a single one
2555
 *   for this name only.
2556
 *
2557
 * @return string
2558
 *  URI path element as string
2559
 */
2560
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL, $redirect_to_taxon = false) {
2561
  $res = FALSE;
2562
  if ($name_uuid) {
2563
    $res = 'cdm_dataportal/name/' . $name_uuid .
2564
    '/' . (is_uuid($taxon_to_hide_uuid) ? $taxon_to_hide_uuid : "null") .
2565
    '/' . (is_uuid($highlited_synonym_uuid) ? $highlited_synonym_uuid : "null") .
2566
    '/' . ($redirect_to_taxon || variable_get(CDM_NAME_PAGE_AUTOREDIRECT, 0) ? "redirect_to_taxon" : "");
2567
  }
2568

    
2569
  return $res;
2570
}
2571

    
2572
/**
2573
 * Composes the drupal path to the media entity identified by the uuid.
2574
 *
2575
 * @param string $uuid
2576
 *  The persistent identifier of the entity entity
2577
 * @return string
2578
 *  The drupal path
2579
 */
2580
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2581
  if (!$uuid) {
2582
    return FALSE;
2583
  }
2584
  $out = 'cdm_dataportal/media/' . $uuid;
2585
  if ($representaion_uuid) {
2586
    $out .= '/' . $representaion_uuid;
2587
    if (is_numeric($partId)) {
2588
      $out .= '/' . $partId;
2589
    }
2590
  }
2591
  return $out;
2592
}
2593

    
2594
/**
2595
 * Compares thisRank with thatRank.
2596
 *
2597
 * Returns a negative integer, zero, or a positive integer
2598
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2599
 * e.g:
2600
 * <ul>
2601
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2602
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2603
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2604
 * </ul>
2605
 * <p>
2606
 * This compare logic of the underlying webservice is the
2607
 * <b>inverse logic</b> of the the one implemented in
2608
 * java.lang.Comparable#compareTo(java.lang.Object)
2609
 *
2610
 * @param $thisRankUuid
2611
 * @param $thatRankUuid
2612
 *
2613
 * @return int
2614
 *   A negative integer, zero, or a positive integer
2615
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2616
 */
2617
function rank_compare($thisRankUuid, $thatRankUuid) {
2618
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2619
  return $result->Integer;
2620
}
2621

    
2622
/**
2623
 * Creates a short version of a taxonname.
2624
 *
2625
 * The short name is created by using the taggedTitle field of
2626
 * TaxonNodeDTO instances.
2627
 * If the taggedTitle if empty the fullname will be returned.
2628
 *
2629
 * @param object $taxonNodeDTO
2630
 *   A TaxonNodeDTO object
2631
 *
2632
 * @return string
2633
 */
2634
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2635

    
2636
  $nameStr = '';
2637

    
2638
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2639

    
2640
  // Get all tagged text tokens of the scientific name.
2641
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2642
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2643
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2644
    }
2645
  }
2646
  $nameStr = trim($nameStr);
2647

    
2648
  if ($nameStr) {
2649

    
2650
    // Do not return short names for these.
2651
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2652
      return $nameStr;
2653
    }
2654

    
2655
    /*
2656
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2657
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2658
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2659
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2660
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2661
    */
2662
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2663
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2664
      return $matches[1][0] . "." . $matches[3][0];
2665
    }
2666
    else {
2667
      return $nameStr;
2668
    }
2669
  }
2670
  else {
2671
    return $taxonNodeDTO->titleCache;
2672
  }
2673
}
2674

    
2675
/**
2676
 * Check if a taxon is accepted by the current taxonomic tree.
2677
 *
2678
 * @param mixed $taxon
2679
 *   The Taxon obkect to check.
2680
 *
2681
 * @return bool
2682
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2683
 */
2684
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2685

    
2686
  $defaultTreeUuid = get_current_classification_uuid();
2687

    
2688
  if (isset($taxon->taxonNodes)) {
2689
    $taxonNodes = $taxon->taxonNodes;
2690
  }
2691
  else {
2692
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2693
  }
2694

    
2695
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2696
    foreach ($taxonNodes as $node) {
2697
      if (isset($node->classification)){
2698
        if(is_object($node->classification)) {
2699
          if ($node->classification->uuid == $defaultTreeUuid) {
2700
            return TRUE;
2701
          }
2702
        }
2703
        else {
2704
          if ($node->classification == $defaultTreeUuid) {
2705
            return TRUE;
2706
          }
2707
        }
2708
      }
2709
    }
2710
  }
2711

    
2712
  return FALSE;
2713
}
2714

    
2715
/**
2716
 * Checks is the source has one of the given types.
2717
 *
2718
 * @param object $source
2719
 *   The original source entity
2720
 * @param array $types
2721
 *   An array of element of the OriginalSourceType enumeration
2722
 *   If not set the default will be used which is:
2723
 *    - Lineage
2724
 *    - PrimaryMediaSource
2725
 *    - PrimaryTaxonomicSource
2726
 *    - Unknown
2727
 *    - Other
2728
 * @return boolean
2729
 */
2730
  function _is_original_source_type($source, $types = null) {
2731
    // this is the default
2732
    // maybe this should also be put into the settings
2733
    static $default = array(
2734
      OriginalSourceType::Lineage,
2735
      OriginalSourceType::PrimaryMediaSource,
2736
      OriginalSourceType::PrimaryTaxonomicSource,
2737
      OriginalSourceType::Unknown,
2738
      OriginalSourceType::Other,
2739
      OriginalSourceType::Aggregation
2740
    );
2741

    
2742
    if(!$types){
2743
      $types = $default;
2744
    }
2745
    return isset($source->type) && in_array($source->type, $types);
2746
  }
2747

    
2748
/**
2749
 * Collects all the media from a list of description elements.
2750
 *
2751
 * @param array $descriptionElements
2752
 *   The description elements from which to collect the media.
2753
 *
2754
 * @return array
2755
 *   The output with all the collected media.
2756
 */
2757
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2758

    
2759
  $outArrayOfMedia = array();
2760

    
2761
  // Avoiding a warning box in Drupal for Flora Malesiana.
2762
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2763
    foreach ($descriptionElements as $descriptionElement) {
2764
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2765
        foreach ($descriptionElement->media as $media) {
2766
          if (is_object($media)) {
2767
            $outArrayOfMedia[] = $media;
2768
          }
2769
        }
2770
      }
2771
    }
2772
  }
2773
  return $outArrayOfMedia;
2774
}
2775

    
2776
/**
2777
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2778
 *
2779
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2780
 *
2781
 * @see cdm_fetch_visible_annotations()
2782
 *
2783
 * @param array $cdm_entities
2784
 *   An array of CdmBase instances or a single instance.
2785
 * @param $footnote_list_key_suggestion string
2786
 *    optional parameter. If this parameter is left empty (null, 0, "") the footnote key will be determined be set to
2787
 *    RenderHints::getFootnoteListKey().'-annotations' otherwise the supplied key will be used.
2788
 *
2789
 * @return array of footnote keys
2790
 */
2791
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2792

    
2793
  $footNoteKeys = array();
2794

    
2795
  // Is argument cdmBase an array?
2796
  if (!is_array($cdm_entities)) {
2797
    $cdmBase_array = array();
2798
    $cdmBase_array[] = $cdm_entities;
2799
  }
2800
  else {
2801
    $cdmBase_array = $cdm_entities;
2802
  }
2803

    
2804
  // Getting the key for the footnotemanager.
2805
  if (isset($footnote_list_key_suggestion)) {
2806
    $footnote_list_key = $footnote_list_key_suggestion;
2807
  }
2808
  else {
2809
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2810
  }
2811

    
2812
  // Adding the footnotes keys.
2813
  foreach ($cdmBase_array as $cdmBase_element) {
2814
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2815
    if (is_array($annotations)) {
2816
      foreach ($annotations as $annotation) {
2817
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2818
      }
2819
    }
2820
  }
2821

    
2822
  return $footNoteKeys;
2823
}
2824

    
2825

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

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

    
2869
  if(!array_key_exists('class', $attributes)) {
2870
    $attributes['class'] = array();
2871
  }
2872
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2873
  $dynabox_attributes = drupal_attributes($attributes);
2874

    
2875

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

    
2896

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

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

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

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

    
2959
  cdm_check_valid_portal_page();
2960

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

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

    
2973
}
2974

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

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

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

    
3015
  static $diff_viewer_count = 0;
3016

    
3017
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
3018

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

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

    
3046

    
(10-10/18)