Project

General

Profile

Download (79 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/pages');
28
  module_load_include('inc', 'cdm_dataportal', 'includes/media');
29
  module_load_include('inc', 'cdm_dataportal', 'includes/maps');
30
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
31
  module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
32
  module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
33

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

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

    
49

    
50
  /* ============================ java script functions ============================= */
51

    
52

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

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

    
74
  /**
75
   */
76
  function drupal_add_js_rowToggle($tableId){
77

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

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

    
91
    $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
92

    
93
    drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
94

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

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

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

    
124
  function _add_js_openlayers() {
125

    
126
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
127
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
128

    
129
    if(variable_get('cdm_js_devel_mode', FALSE)){
130
      // develooper mode libs
131
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
132
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
133
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
134
    }
135

    
136
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
137
      array(
138
        'type' => 'file',
139
        'weight' => JS_LIBRARY,
140
        'cache' => TRUE,
141
        'preprocess' => FALSE
142
      )
143
    );
144

    
145
    // see https://github.com/proj4js/proj4js
146
    // http://openlayers.org/dev/examples/using-proj4js.html
147
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
148
      array(
149
        'type' => 'file',
150
        'weight' => JS_LIBRARY,
151
        'cache' => TRUE,
152
      )
153
    );
154

    
155
    // configure the theme
156
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
157
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
158
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
159
        'type' => 'inline',
160
        'weight' => JS_LIBRARY,
161
        'cache' => TRUE,
162
        'preprocess' => FALSE
163
      ));
164

    
165
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
166
      array(
167
        'type' => 'file',
168
        'cache' => TRUE,
169
        'preprocess' => FALSE
170
      )
171
    );
172

    
173
  }
174

    
175
  /**
176
   * @todo Please document this function.
177
   * @see http://drupal.org/node/1354
178
   */
179
  function _add_js_thickbox() {
180
    // ---- jQuery thickbox:
181
    /*
182
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
183
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
184
    */
185
    // drupal_add_js(drupal_get_path('module',
186
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
187
    //
188
    // Add a setting for the path to cdm_dataportal module, used to find the path
189
    // for the loading animation image in thickbox.
190
    drupal_add_js(array(
191
    'cdm_dataportal' => array(
192
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
193
    )
194
    ),
195
    'setting'
196
        );
197
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
198
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
199
  }
200

    
201
  /**
202
   * @todo Please document this function.
203
   * @see http://drupal.org/node/1354
204
   */
205
  function _add_js_lightbox($galleryID) {
206
    /*
207
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
208
    * allow using the "alt" attribute for captions instead of the "title"
209
    * attribute
210
    */
211
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
212
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
213
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
214
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
215
    drupal_add_js('jQuery(document).ready(function() {
216
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
217
          fixedNavigation:  true,
218
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
219
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
220
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
221
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
222
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
223
          adjustToWindow: true
224
        });
225
      });
226
      ', array('type' => 'inline'));
227
  }
228

    
229
  /**
230
   * @todo Please document this function.
231
   * @see http://drupal.org/node/1354
232
   */
233
  function _add_js_footnotes() {
234
    _add_js_domEvent();
235
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
236
  }
237

    
238
  /**
239
   * @todo Please document this function.
240
   * @see http://drupal.org/node/1354
241
   */
242
  function _add_js_cluetip() {
243

    
244
    // TODO replace by
245
    // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
246
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
247
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
248
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
249
    if(variable_get('cdm_js_devel_mode', FALSE)){
250
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
251
    }
252
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
253
    drupal_add_js("jQuery(document).ready(function(){
254
        jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
255
          splitTitle: '|',
256
          showTitle: true,
257
          activation: 'hover',
258
          sicky: true,
259
          arrows: true,
260
          dropShadow: false,
261
          cluetipClass: 'rounded'
262
        });
263
      });", array('type' => 'inline'));
264
  }
265

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

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

    
276
  /**
277
   * Adds the external javascript file for domEvent.js.
278
   *
279
   * @see drupal_add_js()
280
   */
281
  function _add_js_domEvent() {
282
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
283
  }
284

    
285
  function _add_jquery_ui()
286
  {
287
    drupal_add_css(drupal_get_path('module',
288
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
289
    drupal_add_js(drupal_get_path('module',
290
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
291
      array(
292
        'type' => 'file',
293
        'weight' => JS_LIBRARY,
294
        'cache' => TRUE,
295
        'preprocess' => FALSE
296
      )
297
    );
298
  }
299

    
300
  /**
301
   * Provides the markup for an font awesome icon.
302
   *
303
   * The icons is created in default size without any extra features.
304
   *
305
   * The available icons are listed here http://fontawesome.io/cheatsheet/
306
   * fontawesome icons have much more features than implemented here in this function,
307
   * for spinning icons, fixed width icons, rotation, etc please checkout the
308
   * examples at http://fontawesome.io/examples/
309
   *
310
   * @parameter $icon_name
311
   *  The name of the icon which starts with 'fa-'
312
   *
313
   * @return String
314
   *    the markup for the icon in an <i> tag
315
   *
316
   */
317
  function font_awesome_icon_markup($icon_name, $attributes = array()){
318

    
319

    
320
    //<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
321

    
322
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.2.0/css/font-awesome.min.css';
323
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css";
324

    
325
    drupal_add_html_head_link(
326
      array(
327
        'href' => $font_awesome_css_uri,
328
        'rel' => 'stylesheet'
329
      )
330
    );
331

    
332
    if(!isset($attributes['class'])){
333
      $attributes['class'] = array();
334
    }
335
    $attributes['class'][] = 'fa';
336
    $attributes['class'][] = $icon_name;
337

    
338
    return '<i ' . drupal_attributes($attributes) . '></i>';
339
  }
340

    
341

    
342
  /* ====================== hook implementations ====================== */
343
  /**
344
   * Implements hook_permission().
345
   *
346
   * Valid permissions for this module.
347
   *
348
   * @return array
349
   *   An array of valid permissions for the portfolio module.
350
   */
351
  function cdm_dataportal_permission() {
352
    return array(
353
      'administer cdm_dataportal' => array(
354
        'title' => t('administer cdm_dataportal'),
355
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
356
      ),
357
      'cdm_dataportal view notes' => array(
358
        'title' => t('cdm_dataportal view notes'),
359
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
360
      ),
361
      // TODO Which other permissions are required?
362
      // -> check the WP6 requirements document.
363
    );
364
  }
365

    
366
/**
367
 * Implements hook_menu().
368
 */
369
function cdm_dataportal_menu() {
370
  $items = array();
371

    
372
  // @see settings.php.
373
  cdm_dataportal_menu_admin($items);
374
  cdm_dataportal_menu_help($items);
375

    
376
  $items['cdm_dataportal/names'] = array(
377
    'page callback' => 'cdm_dataportal_view_names',
378
    'access arguments' => array('access content'),
379
    'type' => MENU_CALLBACK,
380
  );
381

    
382
  // Optional callback arguments: page.
383
  $items['cdm_dataportal/taxon'] = array(
384
    'page callback' => 'cdm_dataportal_taxon_page_view',
385
    'access arguments' => array('access content'),
386
    'type' => MENU_CALLBACK,
387
    // Expected callback arguments: uuid.
388
  );
389

    
390
   // Optional callback arguments: page.
391
    //FIXME point to view/page method in this module
392
    $items['cdm_dataportal/specimen'] = array(
393
        'page callback' => 'cdm_dataportal_specimen_page_view',
394
        'access arguments' => array('access content'),
395
        'type' => MENU_CALLBACK,
396
        // Expected callback arguments: uuid.
397
    );
398

    
399
  $items['cdm_dataportal/name'] = array(
400
    'page callback' => 'cdm_dataportal_name_page_view',
401
      /*
402
    'page arguments' => array(
403
       'taxon_name_uuid',
404
       'taxon_to_hide_uuid',
405
       'synonym_uuid' => NULL
406
      ),
407
      */
408
    'access arguments' => array('access content'),
409
    'type' => MENU_CALLBACK,
410
    // Expected callback arguments: uuid.
411
  );
412

    
413
  $items['cdm_dataportal/reference'] = array(
414
    'page callback' => 'cdm_dataportal_view_reference',
415
    'access arguments' => array('access content'),
416
    'type' => MENU_CALLBACK,
417
    // Expected callback arguments: uuid.
418
  );
419

    
420
  $items['cdm_dataportal/reference/list'] = array(
421
    'page callback' => 'cdm_dataportal_view_reference_list',
422
    'access arguments' => array('access content'),
423
    'type' => MENU_CALLBACK,
424
    // Expected callback arguments: uuid.
425
  );
426

    
427
  $items['cdm_dataportal/media'] = array(
428
    'page callback' => 'cdm_dataportal_view_media',
429
    'access arguments' => array('access content'),
430
    'type' => MENU_CALLBACK,
431
    // Expected callback arguments:
432
    // uuid, mediarepresentation_uuid, part_uuid or part#.
433
  );
434

    
435
  $items['cdm_dataportal/polytomousKey'] = array(
436
    'page callback' => 'cdm_dataportal_view_polytomousKey',
437
    'access arguments' => array('access content'),
438
    'type' => MENU_CALLBACK,
439
    // Expected callback arguments: polytomousKey->uuid.
440
  );
441

    
442
  $items['cdm_dataportal/search'] = array(
443
    'page callback' => 'cdm_dataportal_view_search_advanced',
444
    'access arguments' => array('access content'),
445
    'type' => MENU_CALLBACK,
446
  );
447

    
448
  $items['cdm_dataportal/search/advanced'] = array(
449
    'title' => 'Advanced',
450
    'page callback' => 'cdm_dataportal_view_search_advanced',
451
    'access arguments' => array('access content'),
452
    'type' => MENU_DEFAULT_LOCAL_TASK,
453
  );
454

    
455
  $items['cdm_dataportal/search/taxon_by_description'] = array(
456
    'title' => 'By description full text',
457
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
458
    'access arguments' => array('access content'),
459
    'type' => MENU_LOCAL_TASK,
460
  );
461

    
462
  $items['cdm_dataportal/search/results/taxon'] = array(
463
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
464
    'access arguments' => array('access content'),
465
    'type' => MENU_CALLBACK,
466
  );
467
  /*
468
   $items['cdm/xml2json'] = array(
469
   'page callback' => 'cdm_view_xml2json',
470
   'access arguments' => array('access content'),
471
   'type' => MENU_CALLBACK,
472
   );
473
   */
474

    
475
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
476
  // User configuration of cdm_dataportal.
477
  $items['user/%/cdm_dataportal'] = array(
478
    'title' => 'cdm_dataportal',
479
    'access arguments' => array('access content'),
480
    'page callback' => 'drupal_get_form',
481
    'page arguments' => array('cdm_dataportal_user_form'),
482
    'type' => MENU_LOCAL_TASK,
483
    'weight' => 10,
484
  );
485
  // }
486

    
487
  // 'May not cache' in D5.
488
  $items['cdm_dataportal/name/%'] = array(
489
    // 'page callback' => 'cdm_dataportal_view_name',
490
    'page callback' => 'cdm_dataportal_name_page_view',
491
    'page arguments' => array(2, 3, 4),
492
    'access arguments' => array('access content'),
493
    'type' => MENU_CALLBACK,
494
  );
495

    
496
  // --- Local tasks for Taxon.
497
  // --- tabbed taxon page
498
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
499
    $items['cdm_dataportal/taxon/%'] = array(
500
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
501
      'page callback' => 'cdm_dataportal_taxon_page_view',
502
      'access arguments' => array('access content'),
503
      'type' => MENU_CALLBACK,
504
      'weight' => 1,
505
      'page arguments' => array(2, "description")
506
      , // Expected callback arguments: taxon_uuid.
507
    );
508

    
509
    $items['cdm_dataportal/taxon/%/all'] = array(
510
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
511
      'page callback' => 'cdm_dataportal_taxon_page_view',
512
      'access arguments' => array('access content'),
513
      'type' => MENU_CALLBACK,
514
      'weight' => 2,
515
      'page arguments' => array(2, "all")
516
      , // Expected callback arguments: taxon_uuid.
517
    );
518

    
519
    $items['cdm_dataportal/taxon/%/description'] = array(
520
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
521
      'page callback' => 'cdm_dataportal_taxon_page_view',
522
      'access arguments' => array('access content'),
523
      'type' => MENU_DEFAULT_LOCAL_TASK,
524
      'weight' => 2,
525
      'page arguments' => array(2, "description")
526
      , // Expected callback arguments: taxon_uuid.
527
    );
528

    
529
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
530
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
531
      'page callback' => 'cdm_dataportal_taxon_page_view',
532
      'access arguments' => array('access content'),
533
      'type' => MENU_LOCAL_TASK,
534
      'weight' => 4,
535
      'page arguments' => array(2, "synonymy", 4)
536
      , // Expected callback arguments: taxon_uuid and ...
537
    );
538
    $items['cdm_dataportal/taxon/%/images'] = array(
539
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
540
      'page callback' => 'cdm_dataportal_taxon_page_view',
541
      'access arguments' => array('access content'),
542
      'type' => MENU_LOCAL_TASK,
543
      'weight' => 5,
544
      'page arguments' => array(2, "images")
545
      , // Expected callback arguments: taxon_uuid.
546
    );
547

    
548
    $items['cdm_dataportal/taxon/%/specimens'] = array(
549
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
550
      'page callback' => 'cdm_dataportal_taxon_page_view',
551
      'access arguments' => array('access content'),
552
      'type' => MENU_LOCAL_TASK,
553
      'weight' => 6,
554
      'page arguments' => array(2, "specimens")
555
      , // Expected callback arguments: taxon_uuid.
556
    );
557

    
558
    $items['cdm_dataportal/taxon/%/keys'] = array(
559
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
560
      'page callback' => 'cdm_dataportal_taxon_page_view',
561
      'access arguments' => array('access content'),
562
      'type' => MENU_LOCAL_TASK,
563
      'weight' => 6,
564
      'page arguments' => array(2, "keys")
565
      , // Expected callback arguments: taxon_uuid.
566
    );
567

    
568
    $items['cdm_dataportal/taxon/%/experts'] = array(
569
        'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts')),
570
        'page callback' => 'cdm_dataportal_taxon_page_view',
571
        'access arguments' => array('access content'),
572
        'type' => MENU_LOCAL_TASK,
573
        'weight' => 6,
574
        'page arguments' => array(2, "experts")
575
    , // Expected callback arguments: taxon_uuid.
576
    );
577
  }
578

    
579
  // --- refresh link for all cdmnode types
580
  foreach (cdm_get_nodetypes() as $type=>$name) {
581
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
582
        'title' => t('Refresh'),
583
        'page callback' => 'cdm_dataportal_refresh_node',
584
        'access arguments' => array('administer cdm_dataportal'),
585
        'type' => MENU_LOCAL_TASK,
586
        'weight' => 100,
587
        'page arguments' => array($name, 2)
588
    );
589
  }
590

    
591
  return $items;
592
}
593

    
594
/**
595
 * Implements hook_init().
596
 *
597
 */
598
function cdm_dataportal_init() {
599
  //FIXME To add CSS or JS that should be present on all pages, modules
600
  //      should not implement this hook, but declare these files in their .info file.
601
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
602
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
603
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
604

    
605
  if(variable_get('cdm_debug_mode', FALSE)){
606
    $file = 'temporary://drupal_debug.txt';
607
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
608
  }
609

    
610
  $bibliography_settings = get_bibliography_settings();
611
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
612
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
613
}
614

    
615
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
616

    
617
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
618

    
619
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
620
    // force reloading of all and notify user about this special loading
621
    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: ')
622
        . l('Back to tabbed taxon page', $base_path));
623
    $base_path .= '/all';
624
  } else {
625
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
626
  }
627

    
628
  $parameters['cacheL2_refresh'] ='1';
629

    
630

    
631
  drupal_goto($base_path, array('query' => $parameters));
632
}
633

    
634
/**
635
 * The function generate form for own user cdm dataportal configurations.
636
 */
637
function cdm_dataportal_user_form($form, &$form_state) {
638
  global $user;
639
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
640

    
641
  $form['taxon_page_tabs'] = array(
642
      '#type' => 'fieldset',
643
      '#title' => t('Taxon page tabs'),
644
  );
645
  $form['taxon_page_tabs']['check'] = array(
646
    '#type' => 'checkbox',
647
    '#title' => t('Activate user default configuration'),
648
    '#default_value' => variable_get($checkbox_value, 0),
649
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
650
  );
651

    
652
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
653
    '#type' => 'select',
654
    '#title' => t('Default tab to display'),
655
    '#default_value' => get_default_taxon_tab(TRUE),
656
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
657
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
658
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
659
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
660
  );
661

    
662
  $form['submit'] = array(
663
    '#type' => 'submit',
664
    '#value' => t('Submit'),
665
  );
666

    
667
  return $form;
668
}
669

    
670
/**
671
 * Form submission handler for user_form().
672
 *
673
 * Submits the user cdm dataportal configurations.
674
 */
675
function cdm_dataportal_user_form_submit($form, &$form_state) {
676
  global $user;
677
  $msg_type = 'status';
678
  $username = $user->name;
679
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
680

    
681
  // If is the right user the variables are setted.
682
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
683
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
684
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
685
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
686
    if ($form_state['values']['check']) {
687
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
688
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
689
        '!tab' => $variable[variable_get($variable_to_use, 0)],
690
        '!user' => $username,
691
      ))), $msg_type);
692
    }
693
    else {
694
      drupal_set_message(check_plain(t('The user default tab wont be used for
695
        the next taxon site, check the box if you want to use the user default configuration.')));
696
    }
697
    // Problem with the user id => variables wont be saved.
698
  }
699
  else {
700
    $msg_type = 'warning';
701
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
702
  }
703
}
704

    
705
/**
706
 * Implements hook_block_info().
707
 */
708
function cdm_dataportal_block_info() {
709

    
710
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
711
    // $block[1]["info"] = t("CDM DataPortal Credits");
712
    $block["2"] = array(
713
        "info" => t("CDM Search Taxa"),
714
        "cache" => DRUPAL_NO_CACHE
715
      );
716
    // $block[3]["info"] = t("CDM Filters");
717
    $block["4"]["info"] = t("CDM Dataportal Print");
718
    $block["keys"]["info"] = t("CDM identification keys");
719
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
720

    
721
    return $block;
722
}
723

    
724
/**
725
 * Implements hook_block_view().
726
 */
727
function cdm_dataportal_block_view($delta) {
728
  // TODO Rename block deltas (e.g. '2') to readable strings.
729
  switch ($delta) {
730
    // case 'delta-1':
731
    // $block['subject'] = t('Credits');
732
    // $block['content'] = theme('cdm_credits');
733
    // return $block;
734
    case '2':
735
      $block['subject'] = t('Search taxa');
736
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
737
      $block['content'] = drupal_render($form);
738

    
739
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
740
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
741
      }
742
      return $block;
743
    case '4':
744
      $block['subject'] = '';
745
      $block['content'] = theme('cdm_print_button');
746
      return $block;
747
    case "keys":
748
      $block['subject'] = t('Identification Keys');
749
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
750
      return $block;
751
    case "fundedByEDIT":
752
      // t('Funded by EDIT');
753
      $text = '<none>';
754
      $block['subject'] = $text;
755
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
756
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
757
        'attributes' => array("target" => "EDIT"),
758
        'absolute' => TRUE,
759
        'html' => TRUE,
760
      ));
761
      return $block;
762
  }
763
}
764

    
765
/*
766
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
767
 $_SESSION['cdm'] = NULL;
768
 if(is_string($cdm_ws_uri_update)){
769
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
770
 }
771
 }
772

    
773
 function cdm_dataportal_session_validate(){
774
 if(!isset($_SESSION['cdm']['ws_uri'])){
775
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
776
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
777
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
778
 }
779
 }
780
 */
781

    
782
/**
783
 * creates a  selector form for taxonomic trees.
784
 *
785
 * @return a drupal form array
786
 */
787
function cdm_taxonomictree_selector() {
788
  _add_js_treeselector();
789

    
790
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
791
  return $form;
792
}
793

    
794
/**
795
 * @todo Please document this function.
796
 * @see http://drupal.org/node/1354
797
 */
798
function cdm_taxonomictree_selector_form($form, &$form_state) {
799

    
800
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
801
  $form['#action'] = $url;
802

    
803
  $form['var'] = array(
804
    '#weight' => -3,
805
    '#type' => 'hidden',
806
    '#value' => '[cdm][taxonomictree_uuid]',
807
  );
808

    
809
  $destination_array = drupal_get_destination();
810
  $destination = $destination_array['destination'];
811

    
812
  $form['destination'] = array(
813
    '#weight' => -3,
814
    '#type' => 'hidden',
815
    '#value' =>  $destination,
816
  );
817

    
818
  $options = cdm_get_taxontrees_as_options();
819
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
820
  if($taxontree_includes){
821
    $filtered_options = array();
822
    foreach($options as $uuid=>$label){
823
      if(!empty($taxontree_includes[$uuid])){
824
        $filtered_options[$uuid] = $label;
825
      }
826
    }
827
    $options = $filtered_options;
828
  }
829

    
830
  $form['val'] = array(
831
    '#type' => 'select',
832
    '#title' => t('Available classifications'),
833
    '#default_value' => get_current_classification_uuid(),
834
    '#options' => $options,
835
    '#attributes' => array('class' => array('highlite-first-child'))
836
  );
837

    
838
  return $form;
839

    
840
}
841

    
842
/* UNREACHABLE since action of form directly links to view.
843
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
844

    
845
 $_SESSION['cdm']['search'] = $form_values;
846
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
847
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
848
 //$paramstr = compose_url_prameterstr($form_values);
849
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
850
 }
851
 */
852
/* ====================== menu callback functions ====================== */
853
/**
854
 * @todo Please document this function.
855
 * @see http://drupal.org/node/1354
856
 */
857
/*
858
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
859
  static $comment_node_disabled =  0;
860
  static $comment_node_read_only =  1;
861
  static $comment_node_read_write =  2;
862

    
863
  if ($form_id == 'node_type_form'
864
   && isset($form['identity']['type'])
865
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
866
  ) {
867
    $form['workflow']['comment'] = array(
868
      '#type' => 'radios',
869
      '#title' => t('Default comment setting'),
870
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
871
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
872
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
873
    );
874
  }
875
}
876
*/
877

    
878
/**
879
 * Displays a list of the known taxonomic names.
880
 *
881
 * When the list of taxonomic names is displayed, long lists are split up into
882
 * multiple pages.
883
 *
884
 * TODO: Parameters are still preliminary.
885
 *
886
 * @param string $beginsWith
887
 * @param string $page
888
 *   Page number to diplay defaults to page 1.
889
 * @param bool $onlyAccepted
890
 */
891
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
892

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

    
895
  /*
896
  // FIXME the filter for accepted names will be a form element, thus this
897
  // widget should be generated via form api preferably as block.
898
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
899
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
900
  $out .= theme('cdm_listof_taxa', $taxonPager);
901
  return $out;
902
  */
903
}
904

    
905
/**
906
 * @todo Please document this function.
907
 * @see http://drupal.org/node/1354
908
 */
909
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
910

    
911
  cdm_check_valid_portal_page();
912

    
913
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
914
  return theme('cdm_reference_page', array('reference' => $reference));
915
}
916

    
917
/**
918
 * Created a view on a all references contained in the portal.
919
 *
920
 * This function is used at the path cdm_dataportal/reference/list
921
 */
922
function cdm_dataportal_view_reference_list($pageNumber) {
923
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
924
  return theme('cdm_reference_pager', array(
925
    'referencePager' => $referencePager,
926
    'path' => 'cdm_dataportal/reference/list/',
927
    ));
928
}
929

    
930
/**
931
 * @todo Please document this function.
932
 * @see http://drupal.org/node/1354
933
 */
934
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
935

    
936
  cdm_check_valid_portal_page();
937

    
938
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
939
  return theme('cdm_media_page', array(
940
    'media' => $media,
941
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
942
    'partId' => $part,
943
    ));
944
}
945

    
946
/**
947
 * @todo Please document this function.
948
 * @see http://drupal.org/node/1354
949
 */
950
function _load_taxonBase(&$taxonBase) {
951
  if (isset($taxonBase->uuid)) {
952
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
953
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
954
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
955
  }
956
}
957

    
958
/**
959
 * Loads the media associated to the given taxon from the cdm server.
960
 * The aggregation settings regarding taxon relathionships and
961
 * taxonnomic childen are taken into account.
962
 *
963
 * The media lists are cached in a static variable.
964
 *
965
 * @param Taxon $taxon
966
 *   A CDM Taxon entitiy
967
 *
968
 * @return array
969
 *   An array of CDM Media entities
970
 *
971
 */
972
function _load_media_for_taxon($taxon) {
973

    
974
  static $media = NULL;
975

    
976
  if(!isset($media)) {
977
    $media = array();
978
  }
979
  if (!isset($media[$taxon->uuid])) {
980

    
981
    // --- GET Images --- //
982
    $mediaQueryParameters = array(
983
        "type" => "ImageFile",
984
    );
985

    
986
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
987
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
988
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
989

    
990
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
991
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
992
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
993
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
994

    
995
    $ws_endpoint = NULL;
996
    if ( variable_get('cdm_images_include_children', 0) == 0) {
997
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
998
    } else {
999
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1000
    }
1001

    
1002
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1003
        array(
1004
            $taxon->uuid,
1005
        ),
1006
        queryString($mediaQueryParameters)
1007
       );
1008
  }
1009

    
1010
  return $media[$taxon->uuid];
1011
}
1012

    
1013
/**
1014
 *
1015
 * @param Taxon $taxon
1016
 *   A CDM Taxon entitiy
1017
 *
1018
 * @return array
1019
 *   An array of CDM SpecimenOrObservation entities
1020
 *
1021
function _load_occurences_for_taxon($taxon){
1022

    
1023
  static $occurences = NULL;
1024

    
1025
  if(!isset($occurences)) {
1026
    $occurences = array();
1027
  }
1028

    
1029
  if (!isset($occurences[$taxon->uuid])){
1030

    
1031
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1032
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1033
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1034

    
1035
    $by_associatedtaxon_query = http_build_query(array(
1036
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1037
        'relationships' => implode(',', $relationship_choice['direct']),
1038
        'pageSize' => null // all hits in one page
1039
    )
1040
    );
1041

    
1042
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1043
        null,
1044
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1045
    );
1046

    
1047

    
1048
    if(isset($pager->records[0])){
1049
      $occurences[$taxon->uuid] =  $pager->records;
1050
    }
1051
  }
1052
  return $occurences[$taxon->uuid];
1053
}
1054
 */
1055

    
1056
/**
1057
 * Gets a Drupal variable, string or array and returns it.
1058
 *
1059
 * Similar to the variable_get() function of Drupal, except that this function
1060
 * is able to handle arrays correctly. This function is especially useful
1061
 * when dealing with collections of settings form elements (#tree = TRUE).
1062
 *
1063
 * @param string $variableKey
1064
 *   The Unique key of the Drupal variable in the Drupal variables table.
1065
 * @param string $defaultValueString
1066
 *   A string as for example derived from a CONSTANT.
1067
 *
1068
 * @return mixed
1069
 *   usually an array, depending on the nature of the variable.
1070
 *
1071
 * TODO compare with get_array_variable_merged() duplicate functions?
1072
 * @deprecated rather use get_array_variable_merged() since this function
1073
 * used an array as second parameter
1074
 */
1075
function mixed_variable_get($variableKey, $defaultValueString) {
1076
  $systemDefaults = unserialize($defaultValueString);
1077
  $storedSettings = variable_get($variableKey, array());
1078
  if (is_array($storedSettings)) {
1079
    // TODO better use drupal_array_merge_deep() ?
1080
    $settings = array_merge($systemDefaults, $storedSettings);
1081
  }
1082
  else {
1083
    $settings = $systemDefaults;
1084
  }
1085
  return $settings;
1086
}
1087

    
1088
/**
1089
 * Recursive function to convert an object into an array.
1090
 * also subordinate objects will be converted.
1091
 *
1092
 * @param object $object
1093
 * @return the array
1094
 */
1095
function convert_to_array($object) {
1096
  if(is_object($object) || is_array($object)) {
1097
    $array = (array)$object;
1098
    foreach ($array as $key=>$value){
1099
      $array[$key] = convert_to_array($value);
1100
    }
1101
    return $array;
1102
  } else {
1103
    return $object;
1104
  }
1105
}
1106

    
1107
/**
1108
 * Searches the $collection for the cdm entitiy given as $element.
1109
 *
1110
 * The elements are compared by their UUID.
1111
 *
1112
 * @param $element
1113
 *  the CDM entitiy to search for
1114
 * @param $collection
1115
 *  the list of CDM entities to search in
1116
 *
1117
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1118
 *
1119
 */
1120
function contains_cdm_entitiy($element, $collection) {
1121
  $result = FALSE;
1122
  foreach ($collection as $a) {
1123
    if ($a->uuid == $element->uuid) {
1124
      $result = TRUE;
1125
    }
1126
  }
1127
  return $result;
1128
}
1129

    
1130
/**
1131
 * Fiters the array $entity_list of CDM entities by the list
1132
 * of $excludes. Any element contained in the $excludes will be removed
1133
 * from included int the retuned list.
1134
 *
1135
 * If the $entity_list is not an array the $excludes will be returned.
1136
 */
1137
function filter_cdm_entity_list($entity_list, $excludes) {
1138
  if (is_array($entity_list)) {
1139
    $result = $entity_list;
1140
    if ($excludes) {
1141
      foreach ($excludes as $exclude) {
1142
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1143
          $result[] = $exclude;
1144
        }
1145
      }
1146
    }
1147
  }
1148
  else {
1149
    $result = $excludes;
1150
  }
1151
  return $result;
1152
}
1153

    
1154
/**
1155
 * Wraps the given $html string into a render array suitable for drupal_render()
1156
 *
1157
 * @param $html
1158
 *   the html string, see
1159
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1160
 * @param $weight
1161
 *   A positive or negative number (integer or decimal).
1162
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1163
 * @param $prefix
1164
 *   Optional markup for the '#prefix' element of the render array
1165
 * @param $suffix
1166
 *   Optional markup for the '#suffix' element of the render array
1167
 *
1168
 * @return array
1169
 *   A render array
1170
 *
1171
 */
1172
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1173
  $render_array = array(
1174
    '#markup' => $html
1175
      );
1176
  if (is_numeric($weight)) {
1177
    $render_array['#weight'] = $weight;
1178
  }
1179
  if($prefix){
1180
    $render_array['#prefix'] = $prefix;
1181
  }
1182
  if($suffix) {
1183
    $render_array['#suffix'] = $suffix;
1184
  }
1185
  return $render_array;
1186
}
1187

    
1188
/**
1189
 * Loads the subgraph of a given PolytomousKeyNode.
1190
 *
1191
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1192
 * the CDM REST service.
1193
 *
1194
 * @param mixed $polytomousKeyNode
1195
 *   PolytomousKeyNode passed by reference.
1196
 *
1197
 * @return void
1198
 */
1199
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1200

    
1201
  if (!$polytomousKeyNode) {
1202
    return;
1203
  }
1204
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1205
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1206
    return;
1207
  }
1208
  if (!is_uuid($polytomousKeyNode->uuid)) {
1209
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1210
    return;
1211
  }
1212

    
1213
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1214

    
1215
  if (!$polytomousKeyNode) {
1216
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1217
    return;
1218
  }
1219

    
1220
  // Load children.
1221
  foreach ($polytomousKeyNode->children as &$childNode) {
1222
    _load_polytomousKeySubGraph($childNode);
1223
  }
1224

    
1225
  // Load subkey.
1226
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1227

    
1228
  // Load taxon.
1229
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1230
  _load_taxonBase($polytomousKeyNode->taxon);
1231
  return;
1232
}
1233

    
1234
/**
1235
 * @todo Please document this function.
1236
 * @see http://drupal.org/node/1354
1237
 */
1238
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1239

    
1240
  cdm_check_valid_portal_page();
1241

    
1242
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1243

    
1244
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1245
  if (is_array($sourcePager->records)) {
1246
    $polytomousKey->sources = $sourcePager->records;
1247
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1248
  }
1249

    
1250
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1251
  if (is_array($annotationPager->records)) {
1252
    $polytomousKey->annotations = $annotationPager->records;
1253
  }
1254

    
1255
  _load_polytomousKeySubGraph($polytomousKey->root);
1256
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1257
}
1258

    
1259
/**
1260
 * Creates a taxon page view or a chapter of it.
1261
 *
1262
 * The taxon page gives detailed information on a taxon, it shows:
1263
 *  - Taxon name.
1264
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1265
 *    heterotypic and finally followed by misapplied names.
1266
 *    The list is ordered historically.
1267
 *  - All description associated with the taxon.
1268
 *
1269
 * @param string $uuid
1270
 * @param string $chapter
1271
 *   Name of the part to display, valid values are:
1272
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1273
 *
1274
 * @return unknown_type
1275
 */
1276
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1277

    
1278
  cdm_check_valid_taxon_page($chapter);
1279
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1280
  // show a warning in case the javascript development mode is anabled
1281
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1282
    drupal_set_message(t('The !url1 is enabled.
1283
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1284
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1285
    )),
1286
    'warning'
1287
        );
1288
  }
1289

    
1290
  // Display the page for the taxon defined by $uuid.
1291
  // set_last_taxon_page_tab(arg(3));
1292
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1293
  if (!empty($taxonpage)) {
1294
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1295
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1296
  }
1297
  else {
1298
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1299
    return '';
1300
  }
1301
}
1302

    
1303
/**
1304
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1305
 * which has two fields, one for the page title and one for the content. Later on in the
1306
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1307
 * function as the function parameters $title and $content.
1308
 *
1309
 * @param string $uuid
1310
 *   the uuid of the taxon to show
1311
 * @param string $chapter
1312
 *   Name of the part to display, valid values are:
1313
 *   'description', 'images', 'synonymy', 'all'.
1314
 *
1315
 * @return taxonpage object with the following fields:
1316
 *   - title : the title of the page
1317
 *   - content: the content of the page
1318
 *
1319
 */
1320
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1321
  // Taxon object.
1322
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1323
  if (empty($taxon)) {
1324
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1325
    return FALSE;
1326
  }
1327
  $taxonpage = new stdClass();
1328

    
1329
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1330
    'taxon' => $taxon
1331
  ));
1332

    
1333
  // Check if the taxon id contained in the currently selected tree.
1334
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1335

    
1336
  if (!$taxon_in_current_classification) {
1337
    $classifications = get_classifications_for_taxon($taxon);
1338
    if (count($classifications) == 0) {
1339
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.',
1340
        array(
1341
        '!taxonname' => render_taxon_or_name($taxon->name),
1342
        )
1343
      ), 'warning');
1344
    }
1345
    else {
1346
      $trees = '';
1347
      foreach ($classifications as $classification) {
1348
        if (isset($classification->titleCache)) {
1349
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1350
        }
1351
      }
1352

    
1353
      drupal_set_message(format_plural(count($trees),
1354
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1355
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1356
          array('!taxonname' => render_taxon_or_name($taxon), '!trees' => $trees)
1357
        ) ,
1358
        'warning');
1359
    }
1360
  }
1361

    
1362
  // Render the taxon page.
1363
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1364
  $taxonpage->content = drupal_render($render_array);
1365

    
1366
  return $taxonpage;
1367
}
1368

    
1369
/**
1370
 * Creates a specimen page view.
1371
 * @param string $uuid the UUID of the specimen
1372
 * @return array|string
1373
 */
1374
function cdm_dataportal_specimen_page_view($uuid) {
1375

    
1376
    //cdm_check_valid_taxon_page($chapter);
1377
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1378
    // show a warning in case the javascript development mode is anabled
1379
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1380
        drupal_set_message(t('The !url1 is enabled.
1381
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1382
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1383
        )),
1384
            'warning'
1385
        );
1386
    }
1387

    
1388
    // Display the page for the specimen defined by $uuid.
1389
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1390
    if (!empty($specimenpage)) {
1391
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1392
    }
1393
    else {
1394
        return '';
1395
    }
1396
}
1397

    
1398
/**
1399
 *
1400
 * Creates a specimen view.
1401
 * @param string $uuid the UUID of the specimen
1402
 * @return array|string
1403
 */
1404
function cdm_dataportal_specimen_view($uuid) {
1405
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1406
    if (empty($specimen)) {
1407
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1408
        return FALSE;
1409
    }
1410
    $specimenpage = new stdClass();
1411

    
1412
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1413
        'specimen' => $specimen
1414
    ));
1415

    
1416
    // Render the specimen page.
1417
    $render_array = compose_cdm_specimen_page($uuid);
1418
    $specimenpage->content = drupal_render($render_array);
1419

    
1420
    return $specimenpage;
1421
}
1422

    
1423
/**
1424
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1425
 *
1426
 * The node page shows the taxon name title and the list of taxon related
1427
 * with such taxon. Name on the tree already in use.
1428
 *
1429
 * @param UUID $taxon_name_uuid
1430
 *   The uuid of the CDM TaxonNameBase to show a name page for
1431
 * @param UUID $taxon_to_hide_uuid
1432
 *   A taxon which should not be displayed in the taxon list
1433
 * @param UUID $highlite_synonym_uuid
1434
 *   Optinal parameter wich takes another taxon uuid, if given the
1435
 *   target taxon pages will show the syonymy tab where the taxon
1436
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1437
 *   in case it is found on this page.
1438
 *
1439
 * @return mixed
1440
 *   The formatted name page as node.
1441
 */
1442
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1443

    
1444
  cdm_check_valid_portal_page();
1445

    
1446
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1447
  if (!empty($taxonname_page)) {
1448
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1449
  }
1450
  else {
1451
    return '';
1452
  }
1453
}
1454

    
1455
/**
1456
 * View function for a TaxonNameBase page.
1457
 *
1458
 * The name page lists all taxa for which the name specified by the
1459
 * $taxon_name_uuid is being used. I case there is only one name the
1460
 * page automatically redirects ti the according taxon page. Otherwise
1461
 * the list of names is displayed.
1462
 *
1463
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1464
 * list of taxa. This is useful for example when referencing from a taxon
1465
 * to the name page and the referring taxon should not be repeaded in the
1466
 * name page.
1467
 *
1468
 *
1469
 * @param UUID $taxon_name_uuid
1470
 *   The uuid of the CDM TaxonNameBase to show a name page for
1471
 * @param UUID $taxon_to_hide_uuid
1472
 *   A taxon which should not be displayed in the taxon list
1473
 * @param UUID $highlite_synonym_uuid
1474
 *   Optinal parameter wich takes another taxon uuid, if given the
1475
 *   target taxon pages will show the syonymy tab where the taxon
1476
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1477
 *   in case it is found on this page.
1478
 *
1479
 * @return object
1480
 *   An object with two fields:
1481
 *     - title: the page title
1482
 *     - content: the page content
1483
 */
1484
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1485
  // Getting the full taxonname object from the server.
1486
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1487
  if (!$taxon_name) {
1488
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1489
    return FALSE;
1490
  }
1491
  // Searching for all the taxa connected with the taxon name on the tree
1492
  // in use.
1493
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1494
  $request_params = array();
1495
  $request_params['query'] = $name_cache;
1496
  $request_params['tree'] = get_current_classification_uuid();
1497
  $request_params['doTaxa'] = 1;
1498
  $request_params['doSynonyms'] = 1;
1499
  $request_params['doTaxaByCommonNames'] = 0;
1500
  $request_params['matchMode'] = "EXACT";
1501
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1502

    
1503
  // Removing the name where we come from.
1504
  foreach ($taxon_pager->records as $k => &$taxon) {
1505
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1506
      unset($taxon_pager->records[$k]);
1507
    }
1508
  }
1509
  // Show the taxa list or go to the singular taxon.
1510
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1511
    $singleTaxon = array_pop($taxon_pager->records);
1512
    if ($singleTaxon->class != "Taxon") {
1513
      // It is a Synonym -> look for the accepted.
1514
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1515
      if (!empty($highlite_synonym_uuid)) {
1516
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1517
      }
1518
      else {
1519
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1520
      }
1521
    }
1522
    else {
1523
      // It is an accepted taxon.
1524
      if (!empty($highlite_synonym_uuid)) {
1525
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1526
      }
1527
      else {
1528
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1529
      }
1530
    }
1531
  }
1532
  else {// More than one taxa case.
1533
    $taxon_name_page = new stdClass();
1534
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1535
    if ($taxon_pager->records) {
1536
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1537
    }
1538
    else {
1539
      $taxon_name_page->content = 'This name has no taxa';
1540
    }
1541
    return $taxon_name_page;
1542
  }
1543
}
1544

    
1545
/**
1546
 * Creates a page with the advance search form.
1547
 *
1548
 * NOTE: The advance search form allows searching for taxa.
1549
 */
1550
function cdm_dataportal_view_search_advanced() {
1551
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1552
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1553
}
1554

    
1555
/**
1556
 * Creates a page with the search form for searching by taxon descriptions.
1557
 */
1558
function cdm_dataportal_view_search_taxon_by_description() {
1559
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1560
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1561
}
1562

    
1563
/**
1564
 * Executes the search and generates the result list of taxa.
1565
 */
1566
function cdm_dataportal_view_search_results_taxon() {
1567

    
1568
  $taxonPager = cdm_dataportal_search_execute();
1569

    
1570
  $showThumbnails = do_showThumbnails();
1571

    
1572
  $setSessionUri = url('cdm_api/setvalue/session', array(
1573
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1574
  ));
1575

    
1576
  drupal_add_js('jQuery(document).ready(function() {
1577

    
1578
      // init
1579
      if(' . $showThumbnails . ' == 1){
1580
      jQuery(\'.media_gallery\').show(20);
1581
  } else {
1582
      jQuery(\'.media_gallery\').hide(20);
1583
  }
1584
      // add change hander
1585
      jQuery(\'#showThumbnails\').change(
1586
      function(event){
1587
      var state = 0;
1588
      if(jQuery(this).is(\':checked\')){
1589
      jQuery(\'.media_gallery\').show(20);
1590
      state = 1;
1591
  } else {
1592
      jQuery(\'.media_gallery\').hide(20);
1593
  }
1594
      // store state in session variable
1595
      var uri = \'' . $setSessionUri . '\' + state;
1596
      jQuery.get(uri);
1597
  });
1598
  });',
1599
  array('type' => "inline", 'scope' => JS_DEFAULT));
1600

    
1601
  drupal_set_title(t('Search results'), PASS_THROUGH);
1602

    
1603
  return theme('cdm_search_results', array(
1604
    'pager' => $taxonPager,
1605
    'path' => 'cdm_dataportal/search/results/taxon',
1606
    ));
1607
}
1608

    
1609
/**
1610
 * Provides the standart image wich indicated a loading process
1611
 *
1612
 * @return string
1613
 *  The img html tag
1614
 */
1615
function loading_image_html() {
1616
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1617
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1618
}
1619

    
1620
/**
1621
 * Returns the state of the the showThumbnails flag set in the
1622
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1623
 *
1624
 * @return boolean
1625
 *    returns 1 if the flag is set
1626
 */
1627
function do_showThumbnails() {
1628
  static $showThumbnails = null;
1629

    
1630
  if($showThumbnails == null) {
1631
    $showThumbnails = 0;
1632
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1633
      $showThumbnails = 0;
1634
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1635
      $showThumbnails = is_array($search_gallery_settings)
1636
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1637
        && (
1638
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1639
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1640
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1641
            )
1642
         ? 1 : 0;
1643

    
1644
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1645
    }
1646
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1647
    if (!is_numeric($showThumbnails)) {
1648
      $showThumbnails = 1;
1649
    }
1650
  }
1651

    
1652
  return $showThumbnails;
1653
}
1654

    
1655
/**
1656
 * View which transforms XML output from a given webservice endpoint into JSON.
1657
 */
1658
/*
1659
 function cdm_view_xml2json(){
1660
 $file = arg(2);
1661
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1662
 return  xml2json::transformXmlStringToJson($datastr);
1663
 }
1664
 */
1665

    
1666
/* ====================== other functions ====================== */
1667
/**
1668
 * Creates a URL to the taxon page specified by the $uuid parameter.
1669
 *
1670
 * The URL will be prepended with a path element to a specific taxon page tab.
1671
 *
1672
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1673
 * be set globally in the administrative settings or individually in the user
1674
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1675
 * the last portal will stay on this last tab.
1676
 *
1677
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1678
 * internal mechanism by a specific value.
1679
 *
1680
 * @param string $uuid
1681
 *   The UUID of the taxon.
1682
 * @param string $page_tab
1683
 *   Overwriting the preset mechanism by defining specific value for the
1684
 *   taxon page tab.
1685
 *
1686
 * @return string
1687
 *   The created URL.
1688
 */
1689
function path_to_taxon($uuid, $page_tab = FALSE) {
1690

    
1691
  $tab = get_default_taxon_tab();
1692
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1693

    
1694
  if (!$uuid) {
1695
    return FALSE;
1696
  }
1697

    
1698
  if ($page_tab) {
1699
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1700
  }
1701
  elseif (!$tab || strtolower($tab) == 'general') {
1702
    return 'cdm_dataportal/taxon/' . $uuid;
1703
  }
1704
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1705
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1706
  }
1707
  else {
1708
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1709
  }
1710
}
1711

    
1712
function path_to_specimen($uuid) {
1713

    
1714
    if (!$uuid) {
1715
        return FALSE;
1716
    }
1717
    else {
1718
        return 'cdm_dataportal/specimen/' . $uuid;
1719
    }
1720
}
1721

    
1722
/**
1723
 * Creates a URL to show a synonmy in the according taxon page.
1724
 *
1725
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1726
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1727
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1728
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1729
 * in the page
1730
 *
1731
 * @param string $synonymUuid
1732
 *    The uuid of the synonym
1733
 * @param string $acceptedUuid
1734
 *    The uuid of the according accepted taxon
1735
 * @return string
1736
 *    The URL to show a synonmy in the according taxon page
1737
 */
1738
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1739
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1740
  return url($acceptedPath, array(
1741
      'query' => array(
1742
        // highlite the synony in the synonymy
1743
        'highlite' => $synonymUuid,
1744
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1745
        // see theme_taxon_page_title()
1746
        'acceptedFor' => $synonymUuid
1747
      ),
1748
      'fragment' => $synonymUuid
1749
  ));
1750

    
1751
}
1752

    
1753
/**
1754
 * Compses the drupal path to the key identified by the uuid.
1755
 *
1756
 * @param string $keyType
1757
 *    the key typer corresponds to the specific class of the CDM
1758
 *    IdentificationKey. Possible values are
1759
 *      -PolytomousKey
1760
 *      -MultimediaKey
1761
 *      - ...
1762
 * @param UUID $keyUuid
1763
 *   The UUID of the key
1764
 */
1765
function path_to_key($keyType, $keyUuid) {
1766
  if (!$keyUuid || !$keyType) {
1767
    return FALSE;
1768
  }
1769
  $keyType{0} = strtolower($keyType{0});
1770
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1771
}
1772

    
1773
/**
1774
 * @todo Please document this function.
1775
 * @see http://drupal.org/node/1354
1776
 */
1777
function path_to_reference($uuid) {
1778
  if (!$uuid) {
1779
    return FALSE;
1780
  }
1781
  return 'cdm_dataportal/reference/' . $uuid;
1782
}
1783

    
1784
/**
1785
 * Creates the path to a cdm_dataportal taxon name page.
1786
 *
1787
 * @param UUID $taxon_name_uuid
1788
 *   The uuid of the CDM TaxonNameBase to show a name page for
1789
 * @param UUID $taxon_to_hide_uuid
1790
 *   A taxon which should not be displayed in the taxon list
1791
 * @param UUID $highlite_synonym_uuid
1792
 *   Optinal parameter wich takes another taxon uuid, if given the
1793
 *   target taxon pages will show the syonymy tab where the taxon
1794
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1795
 *   in case it is found on this page.
1796
 *
1797
 * @return a URI path element as string
1798
 */
1799
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1800
  $res = FALSE;
1801
  if ($name_uuid) {
1802
    $res = 'cdm_dataportal/name/' . $name_uuid;
1803
  }
1804
  if($taxon_to_hide_uuid){
1805
    $res .= '/' . $taxon_to_hide_uuid;
1806
    if($synonym_uuid){
1807
      $res .= '/' . $synonym_uuid;
1808
    }
1809
  }
1810
  return $res;
1811
}
1812

    
1813
/**
1814
 * @todo Please document this function.
1815
 * @see http://drupal.org/node/1354
1816
 */
1817
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1818
  if (!$uuid) {
1819
    return FALSE;
1820
  }
1821
  $out = 'cdm_dataportal/media/' . $uuid;
1822
  if ($representaion_uuid) {
1823
    $out .= '/' . $representaion_uuid;
1824
    if ($partId !== FALSE) {
1825
      $out .= '/' . $partId;
1826
    }
1827
  }
1828
  return $out;
1829
}
1830

    
1831
/**
1832
 * Compares thisRank with thatRank.
1833
 *
1834
 * Returns a negative integer, zero, or a positive integer
1835
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1836
 * e.g:
1837
 * <ul>
1838
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1839
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1840
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1841
 * </ul>
1842
 * <p>
1843
 * This compare logic of the underlying webservice is the
1844
 * <b>inverse logic</b> of the the one implemented in
1845
 * java.lang.Comparable#compareTo(java.lang.Object)
1846
 *
1847
 * @param $thisRankUuid
1848
 * @param $thatRankUuid
1849
 *
1850
 * @return int
1851
 *   A negative integer, zero, or a positive integer
1852
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1853
 */
1854
function rank_compare($thisRankUuid, $thatRankUuid) {
1855
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1856
  return $result->Integer;
1857
}
1858

    
1859
/**
1860
 * Composes an HTML element class attribute value composed of
1861
 * the shortname of the cdm class and the uuid of the entity.
1862
 * This class attribute should be used whereever an cdm-entity is rendered.
1863
 *
1864
 * These according class selectors in css must be escaped, eg:
1865
 *    .cdm\:TextData
1866
 *
1867
 * @param $cdmEntity
1868
 */
1869
function html_class_attribute_ref($cdmEntity) {
1870

    
1871
  if (is_cdm_entity($cdmEntity)) {
1872
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1873
  }
1874
}
1875

    
1876

    
1877
/**
1878
 * Creates a short taxonname.
1879
 *
1880
 * The short name is created by using the taggedTitle field of
1881
 * NameSTO or NameTO instances.
1882
 * If the taggedTitle if empty the fullname will be returned.
1883
 *
1884
 * @param unknown_type $name
1885
 *   Name or TreeNode.
1886
 *
1887
 * @return string
1888
 */
1889
function cdm_dataportal_shortname_of($name) {
1890
  $nameStr = '';
1891

    
1892
  normalize_tagged_text($name->taggedTitle);
1893

    
1894
  // Get all tagged text tokens of the scientific name.
1895
  foreach ($name->taggedTitle as $tagtxt) {
1896
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1897
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1898
    }
1899
  }
1900
  $nameStr = trim($nameStr);
1901

    
1902
  if ($nameStr) {
1903

    
1904
    // Do not return short names for these.
1905
    if ($name->unplaced || $name->excluded) {
1906
      return $nameStr;
1907
    }
1908

    
1909
    /*
1910
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1911
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1912
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1913
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1914
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1915
    */
1916
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1917
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1918
      return $matches[1][0] . "." . $matches[3][0];
1919
    }
1920
    else {
1921
      return $nameStr;
1922
    }
1923
  }
1924
  else {
1925
    return $name->titleCache;
1926
  }
1927
}
1928

    
1929
/**
1930
 * Check if a taxon is accepted by the current taxonomic tree.
1931
 *
1932
 * @param mixed $taxon
1933
 *   The Taxon obkect to check.
1934
 *
1935
 * @return bool
1936
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1937
 */
1938
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1939

    
1940
  $defaultTreeUuid = get_current_classification_uuid();
1941

    
1942
  if (isset($taxon->taxonNodes)) {
1943
    $taxonNodes = $taxon->taxonNodes;
1944
  }
1945
  else {
1946
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1947
  }
1948

    
1949
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1950
    foreach ($taxonNodes as $node) {
1951
      if (isset($node->classification)){
1952
        if(is_object($node->classification)) {
1953
          if ($node->classification->uuid == $defaultTreeUuid) {
1954
            return TRUE;
1955
          }
1956
        }
1957
        else {
1958
          if ($node->classification == $defaultTreeUuid) {
1959
            return TRUE;
1960
          }
1961
        }
1962
      }
1963
    }
1964
  }
1965

    
1966
  return FALSE;
1967
}
1968

    
1969
/**
1970
 * Checks is the source has one of the given types.
1971
 *
1972
 * @param object $source
1973
 *   The original source entity
1974
 * @param array $types
1975
 *   An array of elementd of the OriginalSourceType enumeration
1976
 *   If not set the default will be used which is:
1977
 *    - Lineage
1978
 *    - PrimaryMediaSource
1979
 *    - PrimaryTaxonomicSource
1980
 *    - Unknown
1981
 *    - Other
1982
 * @return boolean
1983
 */
1984
  function _is_original_source_type($source, $types = null) {
1985
    // this is the default
1986
    // maybe this should also be put into the settings
1987
    static $default = array(
1988
      OriginalSourceType::Lineage,
1989
      OriginalSourceType::PrimaryMediaSource,
1990
      OriginalSourceType::PrimaryTaxonomicSource,
1991
      OriginalSourceType::Unknown,
1992
      OriginalSourceType::Other,
1993
    );
1994

    
1995
    if(!$types){
1996
      $types = $default;
1997
    }
1998
    return isset($source->type) && in_array($source->type, $types);
1999
  }
2000

    
2001
/**
2002
 * @todo Please document this function.
2003
 * @see http://drupal.org/node/1354
2004
 */
2005
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2006
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2007
}
2008

    
2009
/**
2010
 * Gets the metadata info such as title or artist of a media file.
2011
 *
2012
 * The function tries at first to get all the info from the file metadata
2013
 * and if it is not avaible look at the media file info stored at the database.
2014
 *
2015
 * @param mixed $media
2016
 *   The media file object for which to get the metadata.
2017
 *
2018
 * @return array
2019
 *   The array with the available specified metadata info.
2020
 * TODO rename to read_media_metadata() and move to *.module.
2021
 */
2022
function cdm_read_media_metadata($media) {
2023

    
2024
  $metadata_caption = array(
2025
    'title' => '',// Media_metadata and media.
2026
    'artist' => '',// Media_metadata and media.
2027
    'rights',// Media_metadata and media.
2028
    'location',// Media_metadata.
2029
    'filename' => '',// Media.
2030
    'mediacreated' => '',// Media.
2031
    'description' => '',
2032
  );// Media.
2033

    
2034
  // Getting the media metadata.
2035
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
2036
  $media_metadata_aux = (array) $media_metadata;
2037

    
2038
  // Filename.
2039
  if (!empty($media->representations[0]->parts[0]->uri)) {
2040
    $fileUri = $media->representations[0]->parts[0]->uri;
2041
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
2042
    $metadata_caption['filename'] = $filename;
2043
  }
2044
  else {
2045
    $metadata_caption['filename'] = '';
2046
  }
2047

    
2048
  // Title.
2049
  if (!empty($media_metadata->ObjectName)) {
2050
    $metadata_caption['title'] = $media_metadata->ObjectName;
2051
  }
2052
  elseif (!empty($media_metadata_aux['Object Name'])) {
2053
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
2054
  }
2055
  elseif (!empty($media->title_L10n)) {
2056
    $metadata_caption['title'] = $media->title_L10n;
2057
  }
2058
  elseif (!empty($media->titleCache)) {
2059
    $metadata_caption['title'] = $media->titleCache;
2060
  }
2061

    
2062
  // Append description to title.
2063
  if (!empty($media->description_L10n)) {
2064
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
2065
  }
2066

    
2067
  // Artist.
2068
  if (!empty($media_metadata->Artist)) {
2069
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
2070
  }
2071
  elseif (!empty($media->artist->titleCache)) {
2072
    $metadata_caption['artist'] = $media->artist->titleCache;
2073
  }
2074

    
2075
  // Copyright.
2076
  $metadata_caption['rights'] = array(
2077
    'copyright' => array('agentNames' => array()),
2078
    'license' => array(
2079
      'agentNames' => array(),
2080
      'types' => array(),
2081
      'abbreviatedTexts' => array(),
2082
      'uris' => array(),
2083
    ),
2084
  );
2085
  if (!empty($media_metadata->Copyright)) {
2086
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
2087
  }
2088
  elseif (isset($media->rights) && is_array($media->rights)) {
2089
    foreach ($media->rights as $right) {
2090
      if(isset($right->term)){
2091
        switch ($right->type->uuid) {
2092
          case UUID_RIGHTS_LICENCE:
2093
            $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
2094
            $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
2095
            $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
2096
            $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
2097
            break;
2098
          case UUID_RIGHTS_COPYRIGHT:
2099
            $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
2100
            break;
2101
        }
2102
      }
2103
    }
2104
  }
2105
  else {
2106
    $metadata_caption['rights']['agentNames'][] = '';
2107
  }
2108

    
2109
  // Filling the description (though there is no description in the db???).
2110
  // $metadata_caption['description'] = $media->description_L10n;
2111

    
2112
  // Location.
2113
  $metadata_caption['location'] = array();
2114
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
2115
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
2116
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
2117
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
2118

    
2119
  /*
2120
   // Creation date.
2121
   if($media_metadata["Modify Date"])
2122
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
2123
   else
2124
   $metadata_caption['mediacreated'] = $media->created;
2125
   */
2126

    
2127
  // Returned value.
2128
  return $metadata_caption;
2129
}
2130

    
2131
/**
2132
 * Collects all the media from a list of description elements.
2133
 *
2134
 * @param array $descriptionElements
2135
 *   The description elements from which to collect the media.
2136
 *
2137
 * @return array
2138
 *   The output with all the collected media.
2139
 */
2140
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2141

    
2142
  $outArrayOfMedia = array();
2143

    
2144
  // Avoiding a warning box in Drupal for Flora Malesiana.
2145
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2146
    foreach ($descriptionElements as $descriptionElement) {
2147
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2148
        foreach ($descriptionElement->media as $media) {
2149
          if (is_object($media)) {
2150
            $outArrayOfMedia[] = $media;
2151
          }
2152
        }
2153
      }
2154
    }
2155
  }
2156
  return $outArrayOfMedia;
2157
}
2158

    
2159
/**
2160
 * @todo Please document this function.
2161
 * @see http://drupal.org/node/1354
2162
 *
2163
 * @param array $cdm_entities
2164
 *   An array of CdmBase instances or a single instance.
2165
 * @param string $footnote_list_key_suggestion
2166
 *
2167
 * @return unknown
2168
 */
2169
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2170

    
2171
   static $annotations_types_filter = null;
2172
   if(!$annotations_types_filter) {
2173
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2174
   }
2175

    
2176
  $footNoteKeys = array();
2177

    
2178
  // Is argument cdmBase an array?
2179
  if (!is_array($cdm_entities)) {
2180
    $cdmBase_array = array();
2181
    $cdmBase_array[] = $cdm_entities;
2182
  }
2183
  else {
2184
    $cdmBase_array = $cdm_entities;
2185
  }
2186

    
2187
  // Getting the key for the footnotemanager.
2188
  if (isset($footnote_list_key_suggestion)) {
2189
    $footnote_list_key = $footnote_list_key_suggestion;
2190
  }
2191
  else {
2192
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2193
  }
2194

    
2195
  // Adding the footnotes keys.
2196
  foreach ($cdmBase_array as $cdmBase_element) {
2197
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2198
    if (is_array($annotations)) {
2199
      foreach ($annotations as $annotation) {
2200
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2201
      }
2202
    }
2203
  }
2204

    
2205
  return $footNoteKeys;
2206
}
2207

    
2208

    
2209
/**
2210
 * Creates a CDM Dynabox.
2211
 *
2212
 * @param string $dynabox_id
2213
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2214
 * @param string $label
2215
 *   The clickable text to show.
2216
 * @param string $content_url
2217
 *   The cdm REST service request url wich will deliver the content to be shown
2218
 *   once the dynabox toggles open.
2219
 * @param string $theme
2220
 *   The theme to be used for rendering the cdm REST service response with is
2221
 *   returned from the $content_url.
2222
 * @param string $link_alt_text
2223
 *   The value for the alt attribute of the dynabox link.
2224
 * @param array $enclosingtags
2225
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2226
 *   element itself, $enclosingtags[1] is the tag to be used for the
2227
 *   dynabox_content (optional)
2228
 * @param array $attributes
2229
 * @param $content_element_selector
2230
 *   Optional jQuery selector which can be used to reference a dom element which should
2231
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2232
 *  element will be placed in this container.
2233
 *
2234
 * @param string $open_callback
2235
 *   optional javascript call back function to be triggered after toggling the box to
2236
 *   the open state.
2237
 * @param string $close_callback
2238
 *   optional javascript call back function to be triggered after toggling the box to
2239
 *   the closed state.
2240
 * @return string Returns HTML for a dynabox.
2241
 * Returns HTML for a dynabox.
2242
 */
2243
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2244
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2245
                     $content_element_selector = null,
2246
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2247
  $out = '';
2248

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

    
2252
  if(!array_key_exists('class', $attributes)) {
2253
    $attributes['class'] = array();
2254
  }
2255
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2256
  $dynabox_attributes = drupal_attributes($attributes);
2257

    
2258

    
2259
  _add_js_domEvent(); // requires domEvent.js
2260
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2261
  drupal_add_js("
2262
  jQuery(document).ready(
2263
      function() {
2264
        dynabox('". $dynabox_id ."',
2265
          {
2266
            open_callback: " . $open_callback .",
2267
            close_callback: " . $close_callback .
2268
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2269
          }
2270
        );
2271
      }
2272
   );",
2273
   array(
2274
    'type'=>'inline',
2275
    'scope'=>'footer'
2276
    )
2277
  );
2278

    
2279

    
2280
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2281
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2282
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2283
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2284
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2285
  $out .= '    </' . $enclosingtags[1] . '>';
2286
  $out .= '  </' . $enclosingtags[0] . '>';
2287
  $out .= '<!-- dynabox end -->';
2288
  return $out;
2289
}
2290

    
2291
/**
2292
 * Checks whether a feature has any description elements.
2293
 *
2294
 * @param mixed $featureNode
2295
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2296
 *
2297
 * @see _mergeFeatureTreeDescriptions()
2298
 *
2299
 * @return bool
2300
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2301
 *   contains at least one non empty TextData or at least one DescriptionElement
2302
 *   of an other type. A TextData element holding a multilanguageText or a
2303
 *   source reference is considered to be not empty.
2304
 *
2305
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2306
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2307
 *       $feature_block_has_content in compose_description_elements_other_features
2308
 */
2309
function has_feature_node_description_elements($featureNode) {
2310

    
2311
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2312
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2313
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2314
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2315
          && $descriptionElement->multilanguageText_L10n->text != ''
2316
          || isset($descriptionElement->sources[0])
2317
          || isset($descriptionElement->media[0]) ) {
2318
          return TRUE;
2319
        }
2320
      }
2321
    }
2322
  }
2323
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2324
    foreach ($featureNode->childNodes as $child) {
2325
      if (has_feature_node_description_elements($child)) {
2326
        return TRUE;
2327
      }
2328
    }
2329
  }
2330
  return FALSE;
2331
}
2332

    
2333
/**
2334
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2335
 *
2336
 * @param $chapter
2337
 *   The taxon page chapter or part
2338
 */
2339
function cdm_check_valid_taxon_page($chapter){
2340
  static $taxon_tabs = null;
2341

    
2342
  cdm_check_valid_portal_page();
2343

    
2344
  if($taxon_tabs == null){
2345
    $taxon_tabs = array('all', 'description');
2346
    foreach(get_taxon_tabs_list() as $tab){
2347
      $taxon_tabs[] = strtolower($tab);
2348
    }
2349
  }
2350

    
2351
  if(!in_array($chapter, $taxon_tabs)){
2352
    // oops this is not a valid chapter name
2353
    http_send_status(404); // 404 = Not Found
2354
  }
2355

    
2356
}
2357

    
2358
/**
2359
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2360
 *
2361
 * @param $chapter
2362
 *   The taxon page chapter or part
2363
 */
2364
function cdm_check_valid_portal_page(){
2365
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2366
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2367
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2368
    http_send_status(404); // 404 = Not Found
2369
    exit('HTTP 404');
2370
  }
2371
}
2372

    
2373
/**
2374
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2375
 *
2376
 * @param $text_a
2377
 * @param $text_b
2378
 * @return string
2379
 */
2380
function diff_viewer($text_a, $text_b) {
2381

    
2382
  static $diff_viewer_count = 0;
2383

    
2384
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2385

    
2386
  // http://code.stephenmorley.org/php/diff-implementation/
2387
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2388
  drupal_add_css(drupal_get_path('module',
2389
      'cdm_dataportal') . '/css/diff.css');
2390
  _add_jquery_ui();
2391
  drupal_add_js(
2392
    'jQuery(document).ready( function(){
2393
        jQuery(\'#' . $element_id . '\').accordion({
2394
        collapsible: true,
2395
        active: false,
2396
        fillSpace: true,
2397
        }).children(\'div\').css({ \'height\': \'auto\' });
2398
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2399
     });'
2400
    , array(
2401
    'type' => 'inline',
2402
    'scope' => 'footer'
2403
  ));
2404

    
2405
  $diff = Diff::compare($text_a,
2406
    $text_b);
2407
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2408
    . Diff::toTable($diff, '', '')
2409
    . '</div></div>';
2410
  return $diff_viewer_markup;
2411
}
2412

    
2413

    
(9-9/15)