Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

    
126
  function _add_js_openlayers() {
127

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

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

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

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

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

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

    
175
  }
176

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

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

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

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

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

    
273
  /**
274
   * @todo Please document this function.
275
   * @see http://drupal.org/node/1354
276
   */
277
  function _add_js_ahah() {
278

    
279
    _add_js_domEvent(); // requires domEvent.js
280
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
281
  }
282

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

    
289
  global $base_url;
290

    
291

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

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

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

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

    
351

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

    
354
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.5.0/css/font-awesome.min.css';
355
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css";
356

    
357
    drupal_add_html_head_link(
358
      array(
359
        'href' => $font_awesome_css_uri,
360
        'rel' => 'stylesheet'
361
      )
362
    );
363

    
364
    if($icon_name){
365
      if(!isset($attributes['class'])){
366
        $attributes['class'] = array();
367
      }
368
      $attributes['class'][] = 'fa';
369
      $attributes['class'][] = $icon_name;
370

    
371
      return '<i ' . drupal_attributes($attributes) . '></i>';
372
    }
373

    
374
    return '';
375
  }
376

    
377

    
378
  /* ====================== hook implementations ====================== */
379
  /**
380
   * Implements hook_permission().
381
   *
382
   * Valid permissions for this module.
383
   *
384
   * @return array
385
   *   An array of valid permissions for the portfolio module.
386
   */
387
  function cdm_dataportal_permission() {
388
    return array(
389
      'administer cdm_dataportal' => array(
390
        'title' => t('administer cdm_dataportal'),
391
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
392
      ),
393
      'cdm_dataportal view notes' => array(
394
        'title' => t('cdm_dataportal view notes'),
395
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
396
      ),
397
      // TODO Which other permissions are required?
398
      // -> check the WP6 requirements document.
399
    );
400
  }
401

    
402
/**
403
 * Implements hook_menu().
404
 */
405
function cdm_dataportal_menu() {
406
  $items = array();
407

    
408
  // @see settings.php.
409
  cdm_dataportal_menu_admin($items);
410
  cdm_dataportal_menu_help($items);
411

    
412
  $items['cdm_dataportal/names'] = array(
413
    'page callback' => 'cdm_dataportal_view_names',
414
    'access arguments' => array('access content'),
415
    'type' => MENU_CALLBACK,
416
  );
417

    
418
  // Optional callback arguments: page.
419
  $items['cdm_dataportal/taxon'] = array(
420
    'page callback' => 'cdm_dataportal_taxon_page_view',
421
    'access arguments' => array('access content'),
422
    'type' => MENU_CALLBACK,
423
    // Expected callback arguments: uuid.
424
  );
425

    
426
   // Optional callback arguments: page.
427
    //FIXME point to view/page method in this module
428
    $items['cdm_dataportal/specimen'] = array(
429
        'page callback' => 'cdm_dataportal_specimen_page_view',
430
        'access arguments' => array('access content'),
431
        'type' => MENU_CALLBACK,
432
        // Expected callback arguments: uuid.
433
    );
434

    
435
  $items['cdm_dataportal/name'] = array(
436
    'page callback' => 'cdm_dataportal_name_page_view',
437
      /*
438
    'page arguments' => array(
439
       'taxon_name_uuid',
440
       'taxon_to_hide_uuid',
441
       'synonym_uuid' => NULL
442
      ),
443
      */
444
    'access arguments' => array('access content'),
445
    'type' => MENU_CALLBACK,
446
    // Expected callback arguments: uuid.
447
  );
448

    
449
  $items['cdm_dataportal/reference'] = array(
450
    'page callback' => 'cdm_dataportal_view_reference',
451
    'access arguments' => array('access content'),
452
    'type' => MENU_CALLBACK,
453
    // Expected callback arguments: uuid.
454
  );
455

    
456
  $items['cdm_dataportal/reference/list'] = array(
457
    'page callback' => 'cdm_dataportal_view_reference_list',
458
    'access arguments' => array('access content'),
459
    'type' => MENU_CALLBACK,
460
    // Expected callback arguments: uuid.
461
  );
462

    
463
  $items['cdm_dataportal/media'] = array(
464
    'page callback' => 'cdm_dataportal_view_media',
465
    'access arguments' => array('access content'),
466
    'type' => MENU_CALLBACK,
467
    // Expected callback arguments:
468
    // uuid, mediarepresentation_uuid, part_uuid or part#.
469
  );
470

    
471
  $items['cdm_dataportal/polytomousKey'] = array(
472
    'page callback' => 'cdm_dataportal_view_polytomousKey',
473
    'access arguments' => array('access content'),
474
    'type' => MENU_CALLBACK,
475
    // Expected callback arguments: polytomousKey->uuid.
476
  );
477

    
478
  $items['cdm_dataportal/search'] = array(
479
    'page callback' => 'cdm_dataportal_view_search_advanced',
480
    'access arguments' => array('access content'),
481
    'type' => MENU_CALLBACK,
482
  );
483

    
484
  $items['cdm_dataportal/search/advanced'] = array(
485
    'title' => 'Advanced', // will be passed through t()
486
    'page callback' => 'cdm_dataportal_view_search_advanced',
487
    'access arguments' => array('access content'),
488
    'type' => MENU_DEFAULT_LOCAL_TASK,
489
  );
490

    
491
  $items['cdm_dataportal/search/taxon_by_description'] = array(
492
    'title' => 'By factual data', // will be passed through t()
493
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
494
    'access arguments' => array('access content'),
495
    'type' => MENU_LOCAL_TASK,
496
  );
497

    
498
  $items['cdm_dataportal/search/results/taxon'] = array(
499
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
500
    'access arguments' => array('access content'),
501
    'type' => MENU_CALLBACK,
502
  );
503
  /*
504
   $items['cdm/xml2json'] = array(
505
   'page callback' => 'cdm_view_xml2json',
506
   'access arguments' => array('access content'),
507
   'type' => MENU_CALLBACK,
508
   );
509
   */
510

    
511
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
512
  // User configuration of cdm_dataportal.
513
  $items['user/%/cdm_dataportal'] = array(
514
    'title' => 'cdm_dataportal',
515
    'access arguments' => array('access content'),
516
    'page callback' => 'drupal_get_form',
517
    'page arguments' => array('cdm_dataportal_user_form'),
518
    'type' => MENU_LOCAL_TASK,
519
    'weight' => 10,
520
  );
521
  // }
522

    
523
  // 'May not cache' in D5.
524
  $items['cdm_dataportal/name/%'] = array(
525
    // 'page callback' => 'cdm_dataportal_view_name',
526
    'page callback' => 'cdm_dataportal_name_page_view',
527
    'page arguments' => array(2, 3, 4),
528
    'access arguments' => array('access content'),
529
    'type' => MENU_CALLBACK,
530
  );
531

    
532
  // --- Local tasks for Taxon.
533
  // --- tabbed taxon page
534
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
535
    $items['cdm_dataportal/taxon/%'] = array(
536
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
537
      'page callback' => 'cdm_dataportal_taxon_page_view',
538
      'access arguments' => array('access content'),
539
      'type' => MENU_CALLBACK,
540
      'weight' => 1,
541
      'page arguments' => array(2, "description")
542
      , // Expected callback arguments: taxon_uuid.
543
    );
544

    
545
    $items['cdm_dataportal/taxon/%/all'] = array(
546
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
547
      'page callback' => 'cdm_dataportal_taxon_page_view',
548
      'access arguments' => array('access content'),
549
      'type' => MENU_CALLBACK,
550
      'weight' => 2,
551
      'page arguments' => array(2, "all")
552
      , // Expected callback arguments: taxon_uuid.
553
    );
554

    
555
    $items['cdm_dataportal/taxon/%/description'] = array(
556
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
557
      'page callback' => 'cdm_dataportal_taxon_page_view',
558
      'access arguments' => array('access content'),
559
      'type' => MENU_DEFAULT_LOCAL_TASK,
560
      'weight' => 2,
561
      'page arguments' => array(2, "description")
562
      , // Expected callback arguments: taxon_uuid.
563
    );
564

    
565
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
566
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
567
      'page callback' => 'cdm_dataportal_taxon_page_view',
568
      'access arguments' => array('access content'),
569
      'type' => MENU_LOCAL_TASK,
570
      'weight' => 4,
571
      'page arguments' => array(2, "synonymy", 4)
572
      , // Expected callback arguments: taxon_uuid and ...
573
    );
574
    $items['cdm_dataportal/taxon/%/images'] = array(
575
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
576
      'page callback' => 'cdm_dataportal_taxon_page_view',
577
      'access arguments' => array('access content'),
578
      'type' => MENU_LOCAL_TASK,
579
      'weight' => 5,
580
      'page arguments' => array(2, "images")
581
      , // Expected callback arguments: taxon_uuid.
582
    );
583

    
584
    $items['cdm_dataportal/taxon/%/specimens'] = array(
585
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
586
      'page callback' => 'cdm_dataportal_taxon_page_view',
587
      'access arguments' => array('access content'),
588
      'type' => MENU_LOCAL_TASK,
589
      'weight' => 6,
590
      'page arguments' => array(2, "specimens")
591
      , // Expected callback arguments: taxon_uuid.
592
    );
593

    
594
    $items['cdm_dataportal/taxon/%/keys'] = array(
595
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
596
      'page callback' => 'cdm_dataportal_taxon_page_view',
597
      'access arguments' => array('access content'),
598
      'type' => MENU_LOCAL_TASK,
599
      'weight' => 6,
600
      'page arguments' => array(2, "keys")
601
      , // Expected callback arguments: taxon_uuid.
602
    );
603

    
604
    $items['cdm_dataportal/taxon/%/experts'] = array(
605
        'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts')),
606
        'page callback' => 'cdm_dataportal_taxon_page_view',
607
        'access arguments' => array('access content'),
608
        'type' => MENU_LOCAL_TASK,
609
        'weight' => 6,
610
        'page arguments' => array(2, "experts")
611
    , // Expected callback arguments: taxon_uuid.
612
    );
613
  }
614

    
615
  // --- refresh link for all cdmnode types
616
  foreach (cdm_get_nodetypes() as $type=>$name) {
617
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
618
        'title' => t('Refresh'),
619
        'page callback' => 'cdm_dataportal_refresh_node',
620
        'access arguments' => array('administer cdm_dataportal'),
621
        'type' => MENU_LOCAL_TASK,
622
        'weight' => 100,
623
        'page arguments' => array($name, 2)
624
    );
625
  }
626

    
627
  return $items;
628
}
629

    
630
/**
631
 * Implements hook_init().
632
 *
633
 */
634
function cdm_dataportal_init() {
635
  //FIXME To add CSS or JS that should be present on all pages, modules
636
  //      should not implement this hook, but declare these files in their .info file.
637
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
638
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
639
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
640

    
641
  if(variable_get('cdm_debug_mode', FALSE)){
642
    $file = 'temporary://drupal_debug.txt';
643
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
644
  }
645

    
646
  $bibliography_settings = get_bibliography_settings();
647
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
648
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
649
}
650

    
651
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
652

    
653
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
654

    
655
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
656
    // force reloading of all and notify user about this special loading
657
    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: ')
658
        . l('Back to tabbed taxon page', $base_path));
659
    $base_path .= '/all';
660
  } else {
661
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
662
  }
663

    
664
  $parameters['cacheL2_refresh'] ='1';
665

    
666

    
667
  drupal_goto($base_path, array('query' => $parameters));
668
}
669

    
670
/**
671
 * The function generate form for own user cdm dataportal configurations.
672
 */
673
function cdm_dataportal_user_form($form, &$form_state) {
674

    
675
  global $user;
676
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
677

    
678
  $form['taxon_page_tabs'] = array(
679
      '#type' => 'fieldset',
680
      '#tree' => true,
681
      '#title' => t('Taxon page tabs'),
682
  );
683

    
684
  $form['taxon_page_tabs']['user_defined'] = array(
685
    '#type' => 'checkbox',
686
    '#title' => t('Activate user default configuration'),
687
    '#default_value' => variable_get($checkbox_value, 0),
688
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
689
  );
690

    
691
  $form['taxon_page_tabs']['default_tab'] = array(
692
    '#type' => 'select',
693
    '#title' => t('Default tab to display'),
694
    '#default_value' => get_default_taxon_tab(TRUE),
695
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
696
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
697
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
698
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
699
  );
700

    
701

    
702
  if(false){
703
    $form['developer_options'] = array(
704
        '#type' => 'fieldset',
705
        '#tree' => true,
706
        '#title' => t('Developer options'),
707
    );
708

    
709
    $form['developer_options']['show_render_path'] = array(
710
      '#type' => 'checkbox',
711
      '#title' => t('Display the render path for each taxon name.'),
712
      '#default_value' => variable_get($checkbox_value, 0),
713
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
714
        array(
715
            '!link' => l(
716
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
717
            )
718
        ),
719
    );
720
  }
721

    
722
  $form['submit'] = array(
723
    '#type' => 'submit',
724
    '#value' => t('Submit'),
725
  );
726

    
727
  return $form;
728
}
729

    
730
/**
731
 * Form submission handler for user_form().
732
 *
733
 * Submits the user cdm dataportal configurations.
734
 */
735
function cdm_dataportal_user_form_submit($form, &$form_state) {
736
  global $user;
737
  $msg_type = 'status';
738
  $username = $user->name;
739
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
740

    
741
  // FIXME: this is completely wrong, see user_profile_form_submit()
742

    
743
  // it is only possible to change own user settings
744
  if (arg(0) == 'user' && is_numeric(arg(1)) && $user->uid == arg(1)) {
745

    
746
    // DEFAULT_TAXON_TAB
747
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
748
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
749
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
750
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
751
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
752
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
753
        '!tab' => $variable[variable_get($variable_to_use, 0)],
754
        '!user' => $username,
755
      ))), $msg_type);
756
    }
757
    else {
758
      drupal_set_message(check_plain(t('The user default tab wont be used for
759
        the next taxon site, check the box if you want to use the user default configuration.')));
760
    }
761

    
762
  }
763
  else {
764
    // Problem with the user id => variables wont be saved.
765
    $msg_type = 'warning';
766
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
767
  }
768
}
769

    
770
/**
771
 * Implements hook_block_info().
772
 */
773
function cdm_dataportal_block_info() {
774

    
775
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
776
    // $block[1]["info"] = t("CDM DataPortal Credits");
777
    $block["2"] = array(
778
        "info" => t("CDM Search Taxa"),
779
        "cache" => DRUPAL_NO_CACHE
780
      );
781
    // $block[3]["info"] = t("CDM Filters");
782
    $block["4"]["info"] = t("CDM Dataportal Print");
783
    $block["keys"]["info"] = t("CDM identification keys");
784
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
785
    $block["classification_breadcrumbs"] =  array(
786
        'info' => t('Classification breadcrumbs'),
787
        'cache' => DRUPAL_CACHE_PER_PAGE
788
      );
789

    
790
    return $block;
791
}
792

    
793
/**
794
 * Implements hook_block_view().
795
 */
796
function cdm_dataportal_block_view($delta) {
797
  // TODO Rename block deltas (e.g. '2') to readable strings.
798
  switch ($delta) {
799
    // case 'delta-1':
800
    // $block['subject'] = t('Credits');
801
    // $block['content'] = theme('cdm_credits');
802
    // return $block;
803
    case '2':
804
      $block['subject'] = t('Search taxa');
805
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
806
      $block['content'] = drupal_render($form);
807

    
808
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
809
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
810
      }
811
      return $block;
812
    case '4':
813
      $block['subject'] = '';
814
      $block['content'] = theme('cdm_print_button');
815
      return $block;
816
    case "keys":
817
      $block['subject'] = t('Identification Keys');
818
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
819
      return $block;
820
    case "fundedByEDIT":
821
      // t('Funded by EDIT');
822
      $text = '<none>';
823
      $block['subject'] = $text;
824
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
825
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
826
        'attributes' => array("target" => "EDIT"),
827
        'absolute' => TRUE,
828
        'html' => TRUE,
829
      ));
830
      return $block;
831
    case 'classification_breadcrumbs':
832
      $taxon_uuid = get_current_taxon_uuid();
833
      $block['subject'] = '<none>';
834
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
835
      return $block;
836
    
837
  }
838
}
839

    
840
/**
841
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
842
 *
843
 * @return string
844
 *   the taxon uuid or NULL
845
 */
846
function get_current_taxon_uuid()
847
{
848
  static $taxon_uuid;
849

    
850
  if(!isset($taxon_uuid)){
851
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
852
      $taxon_uuid = $_REQUEST['currentTaxon'];
853
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
854
      $taxon_uuid = arg(2);
855
    } else {
856
      $taxon_uuid = null;
857
    }
858
  }
859

    
860
  return $taxon_uuid;
861
}
862

    
863
/**
864
 * Returns the currently classification tree in use.
865
 *
866
 * @return string
867
 *   The uuid of the currently focused classification
868
 */
869
function get_current_classification_uuid() {
870
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
871
    return $_SESSION['cdm']['taxonomictree_uuid'];
872
  }
873
  else {
874
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
875
  }
876
}
877

    
878
/*
879
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
880
 $_SESSION['cdm'] = NULL;
881
 if(is_string($cdm_ws_uri_update)){
882
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
883
 }
884
 }
885

    
886
 function cdm_dataportal_session_validate(){
887
 if(!isset($_SESSION['cdm']['ws_uri'])){
888
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
889
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
890
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
891
 }
892
 }
893
 */
894

    
895
/**
896
 * creates a  selector form for taxonomic trees.
897
 *
898
 * @return array
899
 *  a drupal form array
900
 */
901
function cdm_taxonomictree_selector() {
902
  _add_js_treeselector();
903

    
904
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
905
  return $form;
906
}
907

    
908
/**
909
 * @todo Please document this function.
910
 * @see http://drupal.org/node/1354
911
 *
912
 * @deprecated use compose_classification_selector instead
913
 */
914
function cdm_taxonomictree_selector_form($form, &$form_state) {
915

    
916
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
917
  $form['#action'] = $url;
918

    
919
  $form['var'] = array(
920
    '#weight' => -3,
921
    '#type' => 'hidden',
922
    '#value' => '[cdm][taxonomictree_uuid]',
923
  );
924

    
925
  $destination_array = drupal_get_destination();
926
  $destination = $destination_array['destination'];
927

    
928
  $form['destination'] = array(
929
    '#weight' => -3,
930
    '#type' => 'hidden',
931
    '#value' =>  $destination,
932
  );
933

    
934
  $options = cdm_get_taxontrees_as_options();
935
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
936
  if($taxontree_includes){
937
    $filtered_options = array();
938
    foreach($options as $uuid=>$label){
939
      if(!empty($taxontree_includes[$uuid])){
940
        $filtered_options[$uuid] = $label;
941
      }
942
    }
943
    $options = $filtered_options;
944
  }
945

    
946
  $form['val'] = array(
947
    '#type' => 'select',
948
    '#title' => t('Available classifications'),
949
    '#default_value' => get_current_classification_uuid(),
950
    '#options' => $options,
951
    '#attributes' => array('class' => array('highlite-first-child')),
952
  );
953

    
954
  return $form;
955

    
956
}
957

    
958
/**
959
 *
960
 * @ingroup compose
961
 */
962
function compose_classification_selector() {
963

    
964
  $destination_array = drupal_get_destination();
965
  $destination = $destination_array['destination'];
966

    
967
  $options = cdm_get_taxontrees_as_options();
968
  $items = array();
969
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
970

    
971
  $current_classification_uuid = get_current_classification_uuid();
972

    
973

    
974
  foreach($options as $uuid=>$label){
975
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
976

    
977
      $class_attributes = '';
978
      if($current_classification_uuid == $uuid){
979
        $class_attributes  = array('focused');
980
      }
981
      $items[] = array(
982
        'data' => l($label,
983
          'cdm_api/setvalue/session',
984
          array(
985
            'query' => array(
986
              'destination' => $destination,
987
              'val' => $uuid,
988
              'var' => '[cdm][taxonomictree_uuid]'
989
            ),
990
          )
991
        ),
992
        'class' => $class_attributes
993
      );
994
    }
995
  }
996

    
997
  $render_array = array(
998
    '#theme' => 'item_list',
999
    '#type' => 'ul',
1000
    '#items' => $items
1001
  );
1002

    
1003
  return $render_array;
1004
}
1005

    
1006

    
1007
/* UNREACHABLE since action of form directly links to view.
1008
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1009

    
1010
 $_SESSION['cdm']['search'] = $form_values;
1011
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1012
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1013
 //$paramstr = compose_url_prameterstr($form_values);
1014
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1015
 }
1016
 */
1017
/* ====================== menu callback functions ====================== */
1018
/**
1019
 * @todo Please document this function.
1020
 * @see http://drupal.org/node/1354
1021
 */
1022
/*
1023
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1024
  static $comment_node_disabled =  0;
1025
  static $comment_node_read_only =  1;
1026
  static $comment_node_read_write =  2;
1027

    
1028
  if ($form_id == 'node_type_form'
1029
   && isset($form['identity']['type'])
1030
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1031
  ) {
1032
    $form['workflow']['comment'] = array(
1033
      '#type' => 'radios',
1034
      '#title' => t('Default comment setting'),
1035
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1036
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1037
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1038
    );
1039
  }
1040
}
1041
*/
1042

    
1043
/**
1044
 * Displays a list of the known taxonomic names.
1045
 *
1046
 * When the list of taxonomic names is displayed, long lists are split up into
1047
 * multiple pages.
1048
 *
1049
 * TODO: Parameters are still preliminary.
1050
 *
1051
 * @param string $beginsWith
1052
 * @param string $page
1053
 *   Page number to diplay defaults to page 1.
1054
 * @param bool $onlyAccepted
1055
 */
1056
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1057

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

    
1060
  /*
1061
  // FIXME the filter for accepted names will be a form element, thus this
1062
  // widget should be generated via form api preferably as block.
1063
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1064
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1065
  $out .= theme('cdm_listof_taxa', $taxonPager);
1066
  return $out;
1067
  */
1068
}
1069

    
1070
/**
1071
 * @todo Please document this function.
1072
 * @see http://drupal.org/node/1354
1073
 */
1074
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1075

    
1076
  cdm_check_valid_portal_page();
1077

    
1078
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1079
  return theme('cdm_reference_page', array('reference' => $reference));
1080
}
1081

    
1082
/**
1083
 * Creates a view on a all references contained in the portal.
1084
 *
1085
 * This function is used at the path cdm_dataportal/reference/list
1086
 */
1087
function cdm_dataportal_view_reference_list($pageNumber) {
1088
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1089
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1090
}
1091

    
1092
/**
1093
 * @todo Please document this function.
1094
 * @see http://drupal.org/node/1354
1095
 */
1096
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1097

    
1098
  cdm_check_valid_portal_page();
1099

    
1100
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1101
  return theme('cdm_media_page', array(
1102
    'media' => $media,
1103
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1104
    'partId' => $part,
1105
    ));
1106
}
1107

    
1108
/**
1109
 * @todo Please document this function.
1110
 * @see http://drupal.org/node/1354
1111
 */
1112
function _load_taxonBase(&$taxonBase) {
1113
  if (isset($taxonBase->uuid)) {
1114
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1115
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1116
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1117
  }
1118
}
1119

    
1120
/**
1121
 * Loads the media associated to the given taxon from the cdm server.
1122
 * The aggregation settings regarding taxon relathionships and
1123
 * taxonnomic childen are taken into account.
1124
 *
1125
 * The media lists are cached in a static variable.
1126
 *
1127
 * @param Taxon $taxon
1128
 *   A CDM Taxon entitiy
1129
 *
1130
 * @return array
1131
 *   An array of CDM Media entities
1132
 *
1133
 */
1134
function _load_media_for_taxon($taxon) {
1135

    
1136
  static $media = NULL;
1137

    
1138
  if(!isset($media)) {
1139
    $media = array();
1140
  }
1141
  if (!isset($media[$taxon->uuid])) {
1142

    
1143
    // --- GET Images --- //
1144
    $mediaQueryParameters = array(
1145
        "type" => "ImageFile",
1146
    );
1147

    
1148
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1149
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1150
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1151

    
1152
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1153
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1154
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1155
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1156

    
1157
    $ws_endpoint = NULL;
1158
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1159
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1160
    } else {
1161
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1162
    }
1163

    
1164
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1165
        array(
1166
            $taxon->uuid,
1167
        ),
1168
        queryString($mediaQueryParameters)
1169
       );
1170
  }
1171

    
1172
  return $media[$taxon->uuid];
1173
}
1174

    
1175
/**
1176
 *
1177
 * @param Taxon $taxon
1178
 *   A CDM Taxon entitiy
1179
 *
1180
 * @return array
1181
 *   An array of CDM SpecimenOrObservation entities
1182
 *
1183
function _load_occurences_for_taxon($taxon){
1184

    
1185
  static $occurences = NULL;
1186

    
1187
  if(!isset($occurences)) {
1188
    $occurences = array();
1189
  }
1190

    
1191
  if (!isset($occurences[$taxon->uuid])){
1192

    
1193
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1194
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1195
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1196

    
1197
    $by_associatedtaxon_query = http_build_query(array(
1198
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1199
        'relationships' => implode(',', $relationship_choice['direct']),
1200
        'pageSize' => null // all hits in one page
1201
    )
1202
    );
1203

    
1204
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1205
        null,
1206
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1207
    );
1208

    
1209

    
1210
    if(isset($pager->records[0])){
1211
      $occurences[$taxon->uuid] =  $pager->records;
1212
    }
1213
  }
1214
  return $occurences[$taxon->uuid];
1215
}
1216
 */
1217

    
1218
/**
1219
 * Gets a Drupal variable, string or array and returns it.
1220
 *
1221
 * Similar to the variable_get() function of Drupal, except that this function
1222
 * is able to handle arrays correctly. This function is especially useful
1223
 * when dealing with collections of settings form elements (#tree = TRUE).
1224
 *
1225
 * @param string $variableKey
1226
 *   The Unique key of the Drupal variable in the Drupal variables table.
1227
 * @param string $defaultValueString
1228
 *   A string as for example derived from a CONSTANT.
1229
 *
1230
 * @return mixed
1231
 *   usually an array, depending on the nature of the variable.
1232
 *
1233
 * TODO compare with get_array_variable_merged() duplicate functions?
1234
 * @deprecated rather use get_array_variable_merged() since this function
1235
 * used an array as second parameter
1236
 */
1237
function mixed_variable_get($variableKey, $defaultValueString) {
1238
  $systemDefaults = unserialize($defaultValueString);
1239
  $storedSettings = variable_get($variableKey, array());
1240
  if (is_array($storedSettings)) {
1241
    // TODO better use drupal_array_merge_deep() ?
1242
    $settings = array_merge($systemDefaults, $storedSettings);
1243
  }
1244
  else {
1245
    $settings = $systemDefaults;
1246
  }
1247
  return $settings;
1248
}
1249

    
1250
/**
1251
 * Recursive function to convert an object into an array.
1252
 * also subordinate objects will be converted.
1253
 *
1254
 * @param object $object
1255
 * @return the array
1256
 */
1257
function convert_to_array($object) {
1258
  if(is_object($object) || is_array($object)) {
1259
    $array = (array)$object;
1260
    foreach ($array as $key=>$value){
1261
      $array[$key] = convert_to_array($value);
1262
    }
1263
    return $array;
1264
  } else {
1265
    return $object;
1266
  }
1267
}
1268

    
1269
/**
1270
 * Searches the $collection for the cdm entitiy given as $element.
1271
 *
1272
 * The elements are compared by their UUID.
1273
 *
1274
 * @param $element
1275
 *  the CDM entitiy to search for
1276
 * @param $collection
1277
 *  the list of CDM entities to search in
1278
 *
1279
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1280
 *
1281
 */
1282
function contains_cdm_entitiy($element, $collection) {
1283
  $result = FALSE;
1284
  foreach ($collection as $a) {
1285
    if ($a->uuid == $element->uuid) {
1286
      $result = TRUE;
1287
    }
1288
  }
1289
  return $result;
1290
}
1291

    
1292
/**
1293
 * Fiters the array $entity_list of CDM entities by the list
1294
 * of $excludes. Any element contained in the $excludes will be removed
1295
 * from included int the retuned list.
1296
 *
1297
 * If the $entity_list is not an array the $excludes will be returned.
1298
 */
1299
function filter_cdm_entity_list($entity_list, $excludes) {
1300
  if (is_array($entity_list)) {
1301
    $result = $entity_list;
1302
    if ($excludes) {
1303
      foreach ($excludes as $exclude) {
1304
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1305
          $result[] = $exclude;
1306
        }
1307
      }
1308
    }
1309
  }
1310
  else {
1311
    $result = $excludes;
1312
  }
1313
  return $result;
1314
}
1315

    
1316
/**
1317
 * Wraps the given $html string into a render array suitable for drupal_render()
1318
 *
1319
 * @param $html
1320
 *   the html string, see
1321
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1322
 * @param $weight
1323
 *   A positive or negative number (integer or decimal).
1324
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1325
 * @param $prefix
1326
 *   Optional markup for the '#prefix' element of the render array
1327
 * @param $suffix
1328
 *   Optional markup for the '#suffix' element of the render array
1329
 *
1330
 * @return array
1331
 *   A render array
1332
 *
1333
 */
1334
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1335
  $render_array = array(
1336
    '#markup' => $html
1337
      );
1338
  if (is_numeric($weight)) {
1339
    $render_array['#weight'] = $weight;
1340
  }
1341
  if($prefix){
1342
    $render_array['#prefix'] = $prefix;
1343
  }
1344
  if($suffix) {
1345
    $render_array['#suffix'] = $suffix;
1346
  }
1347
  return $render_array;
1348
}
1349

    
1350
/**
1351
 * Loads the subgraph of a given PolytomousKeyNode.
1352
 *
1353
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1354
 * the CDM REST service.
1355
 *
1356
 * @param mixed $polytomousKeyNode
1357
 *   PolytomousKeyNode passed by reference.
1358
 *
1359
 * @return void
1360
 */
1361
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1362

    
1363
  if (!$polytomousKeyNode) {
1364
    return;
1365
  }
1366
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1367
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1368
    return;
1369
  }
1370
  if (!is_uuid($polytomousKeyNode->uuid)) {
1371
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1372
    return;
1373
  }
1374

    
1375
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1376

    
1377
  if (!$polytomousKeyNode) {
1378
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1379
    return;
1380
  }
1381

    
1382
  // Load children.
1383
  foreach ($polytomousKeyNode->children as &$childNode) {
1384
    _load_polytomousKeySubGraph($childNode);
1385
  }
1386

    
1387
  // Load subkey.
1388
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1389

    
1390
  // Load taxon.
1391
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1392
  _load_taxonBase($polytomousKeyNode->taxon);
1393
  return;
1394
}
1395

    
1396
/**
1397
 * @todo Please document this function.
1398
 * @see http://drupal.org/node/1354
1399
 */
1400
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1401

    
1402
  cdm_check_valid_portal_page();
1403

    
1404
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1405

    
1406
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1407
  if (is_array($sourcePager->records)) {
1408
    $polytomousKey->sources = $sourcePager->records;
1409
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1410
  }
1411

    
1412
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1413
  if (is_array($annotationPager->records)) {
1414
    $polytomousKey->annotations = $annotationPager->records;
1415
  }
1416

    
1417
  _load_polytomousKeySubGraph($polytomousKey->root);
1418
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1419
}
1420

    
1421
/**
1422
 * Creates a taxon page view or a chapter of it.
1423
 *
1424
 * The taxon page gives detailed information on a taxon, it shows:
1425
 *  - Taxon name.
1426
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1427
 *    heterotypic and finally followed by misapplied names.
1428
 *    The list is ordered historically.
1429
 *  - All description associated with the taxon.
1430
 *
1431
 * @param string $uuid
1432
 * @param string $chapter
1433
 *   Name of the part to display, valid values are:
1434
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1435
 *
1436
 * @return unknown_type
1437
 */
1438
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1439

    
1440
  cdm_check_valid_taxon_page($chapter);
1441
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1442
  // show a warning in case the javascript development mode is anabled
1443
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1444
    drupal_set_message(t('The !url1 is enabled.
1445
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1446
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1447
    )),
1448
    'warning'
1449
        );
1450
  }
1451

    
1452
  // Display the page for the taxon defined by $uuid.
1453
  // set_last_taxon_page_tab(arg(3));
1454
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1455
  if (!empty($taxonpage)) {
1456
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1457
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1458
  }
1459
  else {
1460
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1461
    return '';
1462
  }
1463
}
1464

    
1465
/**
1466
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1467
 * which has two fields, one for the page title and one for the content. Later on in the
1468
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1469
 * function as the function parameters $title and $content.
1470
 *
1471
 * @param string $uuid
1472
 *   the uuid of the taxon to show
1473
 * @param string $chapter
1474
 *   Name of the part to display, valid values are:
1475
 *   'description', 'images', 'synonymy', 'all'.
1476
 *
1477
 * @return taxonpage object with the following fields:
1478
 *   - title : the title of the page
1479
 *   - content: the content of the page
1480
 *
1481
 */
1482
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1483
  // Taxon object.
1484
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1485
  if (empty($taxon)) {
1486
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1487
    return FALSE;
1488
  }
1489
  $taxonpage = new stdClass();
1490

    
1491
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1492
    'taxon' => $taxon
1493
  ));
1494

    
1495
  // Check if the taxon id contained in the currently selected tree.
1496
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1497

    
1498
  if (!$taxon_in_current_classification) {
1499
    $classifications = get_classifications_for_taxon($taxon);
1500
    RenderHints::pushToRenderStack('not_in_current_classification');
1501
    $taxon_name_markup = render_taxon_or_name($taxon);
1502

    
1503
    if (count($classifications) == 0) {
1504
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1505
        array(
1506
        '!taxonname' => $taxon_name_markup,
1507
        )
1508
      ), 'warning');
1509
    }
1510
    else {
1511
      $trees = '';
1512
      foreach ($classifications as $classification) {
1513
        if (isset($classification->titleCache)) {
1514
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1515
        }
1516
      }
1517

    
1518
      drupal_set_message(format_plural(count($trees),
1519
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1520
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1521
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1522
        ) ,
1523
        'warning');
1524
    }
1525
    RenderHints::popFromRenderStack();
1526
  }
1527

    
1528
  // Render the taxon page.
1529
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1530
  $taxonpage->content = drupal_render($render_array);
1531

    
1532
  return $taxonpage;
1533
}
1534

    
1535
/**
1536
 * Creates a specimen page view.
1537
 * @param string $uuid the UUID of the specimen
1538
 * @return array|string
1539
 */
1540
function cdm_dataportal_specimen_page_view($uuid) {
1541

    
1542
    //cdm_check_valid_taxon_page($chapter);
1543
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1544
    // show a warning in case the javascript development mode is anabled
1545
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1546
        drupal_set_message(t('The !url1 is enabled.
1547
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1548
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1549
        )),
1550
            'warning'
1551
        );
1552
    }
1553

    
1554
    // Display the page for the specimen defined by $uuid.
1555
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1556
    if (!empty($specimenpage)) {
1557
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1558
    }
1559
    else {
1560
        return '';
1561
    }
1562
}
1563

    
1564
/**
1565
 *
1566
 * Creates a specimen view.
1567
 * @param string $uuid the UUID of the specimen
1568
 * @return array|string
1569
 */
1570
function cdm_dataportal_specimen_view($uuid) {
1571
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1572
    if (empty($specimen)) {
1573
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1574
        return FALSE;
1575
    }
1576
    $specimenpage = new stdClass();
1577

    
1578
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1579
        'specimen' => $specimen
1580
    ));
1581

    
1582
    // Render the specimen page.
1583
    $render_array = compose_cdm_specimen_page($uuid);
1584
    $specimenpage->content = drupal_render($render_array);
1585

    
1586
    return $specimenpage;
1587
}
1588

    
1589
/**
1590
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1591
 *
1592
 * The node page shows the taxon name title and the list of taxon related
1593
 * with such taxon. Name on the tree already in use.
1594
 *
1595
 * @param UUID $taxon_name_uuid
1596
 *   The uuid of the CDM TaxonNameBase to show a name page for
1597
 * @param UUID $taxon_to_hide_uuid
1598
 *   A taxon which should not be displayed in the taxon list
1599
 * @param UUID $highlite_synonym_uuid
1600
 *   Optinal parameter wich takes another taxon uuid, if given the
1601
 *   target taxon pages will show the syonymy tab where the taxon
1602
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1603
 *   in case it is found on this page.
1604
 *
1605
 * @return mixed
1606
 *   The formatted name page as node.
1607
 */
1608
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1609

    
1610
  cdm_check_valid_portal_page();
1611

    
1612
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1613
  if (!empty($taxonname_page)) {
1614
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1615
  }
1616
  else {
1617
    return '';
1618
  }
1619
}
1620

    
1621
/**
1622
 * View function for a TaxonNameBase page.
1623
 *
1624
 * The name page lists all taxa for which the name specified by the
1625
 * $taxon_name_uuid is being used. I case there is only one name the
1626
 * page automatically redirects ti the according taxon page. Otherwise
1627
 * the list of names is displayed.
1628
 *
1629
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1630
 * list of taxa. This is useful for example when referencing from a taxon
1631
 * to the name page and the referring taxon should not be repeaded in the
1632
 * name page.
1633
 *
1634
 *
1635
 * @param UUID $taxon_name_uuid
1636
 *   The uuid of the CDM TaxonNameBase to show a name page for
1637
 * @param UUID $taxon_to_hide_uuid
1638
 *   A taxon which should not be displayed in the taxon list
1639
 * @param UUID $highlite_synonym_uuid
1640
 *   Optinal parameter wich takes another taxon uuid, if given the
1641
 *   target taxon pages will show the syonymy tab where the taxon
1642
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1643
 *   in case it is found on this page.
1644
 *
1645
 * @return object
1646
 *   An object with two fields:
1647
 *     - title: the page title
1648
 *     - content: the page content
1649
 */
1650
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1651
  // Getting the full taxonname object from the server.
1652
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1653
  if (!$taxon_name) {
1654
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1655
    return FALSE;
1656
  }
1657
  // Searching for all the taxa connected with the taxon name on the tree
1658
  // in use.
1659
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1660
  $request_params = array();
1661
  $request_params['query'] = $name_cache;
1662
  $request_params['tree'] = get_current_classification_uuid();
1663
  $request_params['doTaxa'] = 1;
1664
  $request_params['doSynonyms'] = 1;
1665
  $request_params['doTaxaByCommonNames'] = 0;
1666
  $request_params['matchMode'] = "EXACT";
1667
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1668

    
1669
  // Removing the name where we came from.
1670
  foreach ($taxon_pager->records as $k => &$taxon) {
1671
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1672
      unset($taxon_pager->records[$k]);
1673
    }
1674
  }
1675
  // Show the taxa list or go to the singular taxon.
1676
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1677
    $singleTaxon = array_pop($taxon_pager->records);
1678
    if ($singleTaxon->class != "Taxon") {
1679
      // It is a Synonym -> look for the accepted.
1680
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1681
      if (!empty($highlite_synonym_uuid)) {
1682
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1683
      }
1684
      else {
1685
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1686
      }
1687
    }
1688
    else {
1689
      // It is an accepted taxon.
1690
      if (!empty($highlite_synonym_uuid)) {
1691
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1692
      }
1693
      else {
1694
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1695
      }
1696
    }
1697
  }
1698
  else {// More than one taxa case.
1699
    $taxon_name_page = new stdClass();
1700
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1701
    if ($taxon_pager->records) {
1702
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1703
    }
1704
    else {
1705
      $taxon_name_page->content = 'This name has no taxa';
1706
    }
1707
    return $taxon_name_page;
1708
  }
1709
}
1710

    
1711
/**
1712
 * Creates a page with the advance search form.
1713
 *
1714
 * NOTE: The advance search form allows searching for taxa.
1715
 */
1716
function cdm_dataportal_view_search_advanced() {
1717
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1718
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1719
}
1720

    
1721
/**
1722
 * Creates a page with the search form for searching by taxon descriptions.
1723
 */
1724
function cdm_dataportal_view_search_taxon_by_description() {
1725
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1726
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1727
}
1728

    
1729
/**
1730
 * Executes the search and generates the result list of taxa.
1731
 */
1732
function cdm_dataportal_view_search_results_taxon() {
1733

    
1734
  $taxonPager = cdm_dataportal_search_execute();
1735

    
1736
  $showThumbnails = do_showThumbnails();
1737

    
1738
  $setSessionUri = url('cdm_api/setvalue/session', array(
1739
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1740
  ));
1741

    
1742
  drupal_add_js('jQuery(document).ready(function() {
1743

    
1744
      // init
1745
      if(' . $showThumbnails . ' == 1){
1746
          jQuery(\'.media_gallery\').show(20);
1747
      } else {
1748
          jQuery(\'.media_gallery\').hide(20);
1749
      }
1750

    
1751
      // add change handler
1752
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1753
      function(event){
1754
        var state = 0;
1755
        if(jQuery(this).is(\':checked\')){
1756
          jQuery(\'.media_gallery\').show(20);
1757
          state = 1;
1758
        } else {
1759
          jQuery(\'.media_gallery\').hide(20);
1760
        }
1761
        // store state in session variable
1762
        var uri = \'' . $setSessionUri . '\' + state;
1763
        jQuery.get(uri);
1764
      });
1765
  });',
1766
  array('type' => "inline", 'scope' => JS_DEFAULT));
1767

    
1768
  drupal_set_title(t('Search results'), PASS_THROUGH);
1769

    
1770
  return theme('cdm_search_results', array(
1771
    'pager' => $taxonPager,
1772
    'path' => 'cdm_dataportal/search/results/taxon',
1773
    ));
1774
}
1775

    
1776
/**
1777
 * Provides the standart image wich indicated a loading process
1778
 *
1779
 * @return string
1780
 *  The img html tag
1781
 */
1782
function loading_image_html() {
1783
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1784
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1785
}
1786

    
1787
/**
1788
 * Returns the state of the the showThumbnails flag set in the
1789
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1790
 *
1791
 * @return boolean
1792
 *    returns 1 if the flag is set
1793
 */
1794
function do_showThumbnails() {
1795
  static $showThumbnails = null;
1796

    
1797
  if($showThumbnails == null) {
1798
    $showThumbnails = 0;
1799
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1800
      $showThumbnails = 0;
1801
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1802
      $showThumbnails = is_array($search_gallery_settings)
1803
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1804
        && (
1805
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1806
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1807
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1808
            )
1809
         ? 1 : 0;
1810

    
1811
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1812
    }
1813
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1814
    if (!is_numeric($showThumbnails)) {
1815
      $showThumbnails = 1;
1816
    }
1817
  }
1818

    
1819
  return $showThumbnails;
1820
}
1821

    
1822

    
1823
/* ====================== other functions ====================== */
1824
/**
1825
 * Creates a URL to the taxon page specified by the $uuid parameter.
1826
 *
1827
 * The URL will be prepended with a path element to a specific taxon page tab.
1828
 *
1829
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1830
 * be set globally in the administrative settings or individually in the user
1831
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1832
 * the last portal will stay on this last tab.
1833
 *
1834
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1835
 * internal mechanism by a specific value.
1836
 *
1837
 * @param string $uuid
1838
 *   The UUID of the taxon.
1839
 * @param string $page_tab
1840
 *   Overwriting the preset mechanism by defining specific value for the
1841
 *   taxon page tab.
1842
 *
1843
 * @return string
1844
 *   The created URL.
1845
 */
1846
function path_to_taxon($uuid, $page_tab = FALSE) {
1847

    
1848
  $tab = get_default_taxon_tab();
1849
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1850

    
1851
  if (!$uuid) {
1852
    return FALSE;
1853
  }
1854

    
1855
  if ($page_tab) {
1856
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1857
  }
1858
  elseif (!$tab || strtolower($tab) == 'general') {
1859
    return 'cdm_dataportal/taxon/' . $uuid;
1860
  }
1861
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1862
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1863
  }
1864
  else {
1865
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1866
  }
1867
}
1868

    
1869
function path_to_specimen($uuid) {
1870

    
1871
    if (!$uuid) {
1872
        return FALSE;
1873
    }
1874
    else {
1875
        return 'cdm_dataportal/specimen/' . $uuid;
1876
    }
1877
}
1878

    
1879
/**
1880
 * Creates a URL to show a synonmy in the according taxon page.
1881
 *
1882
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1883
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1884
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1885
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1886
 * in the page
1887
 *
1888
 * @param string $synonymUuid
1889
 *    The uuid of the synonym
1890
 * @param string $acceptedUuid
1891
 *    The uuid of the according accepted taxon
1892
 * @return string
1893
 *    The URL to show a synonmy in the according taxon page
1894
 */
1895
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1896
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1897
  return url($acceptedPath, array(
1898
      'query' => array(
1899
        // highlite the synony in the synonymy
1900
        'highlite' => $synonymUuid,
1901
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1902
        // see theme_taxon_page_title()
1903
        'acceptedFor' => $synonymUuid
1904
      ),
1905
      'fragment' => $synonymUuid
1906
  ));
1907

    
1908
}
1909

    
1910
/**
1911
 * Compses the drupal path to the key identified by the uuid.
1912
 *
1913
 * @param string $keyType
1914
 *    the key typer corresponds to the specific class of the CDM
1915
 *    IdentificationKey. Possible values are
1916
 *      -PolytomousKey
1917
 *      -MultimediaKey
1918
 *      - ...
1919
 * @param UUID $keyUuid
1920
 *   The UUID of the key
1921
 */
1922
function path_to_key($keyType, $keyUuid) {
1923
  if (!$keyUuid || !$keyType) {
1924
    return FALSE;
1925
  }
1926
  $keyType{0} = strtolower($keyType{0});
1927
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1928
}
1929

    
1930
/**
1931
 * @todo Please document this function.
1932
 * @see http://drupal.org/node/1354
1933
 */
1934
function path_to_reference($uuid) {
1935
  if (!$uuid) {
1936
    return FALSE;
1937
  }
1938
  return 'cdm_dataportal/reference/' . $uuid;
1939
}
1940

    
1941
/**
1942
 * Creates the path to a cdm_dataportal taxon name page.
1943
 *
1944
 * @param UUID $taxon_name_uuid
1945
 *   The uuid of the CDM TaxonNameBase to show a name page for
1946
 * @param UUID $taxon_to_hide_uuid
1947
 *   A taxon which should not be displayed in the taxon list
1948
 * @param UUID $highlite_synonym_uuid
1949
 *   Optinal parameter wich takes another taxon uuid, if given the
1950
 *   target taxon pages will show the syonymy tab where the taxon
1951
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1952
 *   in case it is found on this page.
1953
 *
1954
 * @return a URI path element as string
1955
 */
1956
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1957
  $res = FALSE;
1958
  if ($name_uuid) {
1959
    $res = 'cdm_dataportal/name/' . $name_uuid;
1960
  }
1961
  if($taxon_to_hide_uuid){
1962
    $res .= '/' . $taxon_to_hide_uuid;
1963
    if($synonym_uuid){
1964
      $res .= '/' . $synonym_uuid;
1965
    }
1966
  }
1967
  return $res;
1968
}
1969

    
1970
/**
1971
 * @todo Please document this function.
1972
 * @see http://drupal.org/node/1354
1973
 */
1974
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1975
  if (!$uuid) {
1976
    return FALSE;
1977
  }
1978
  $out = 'cdm_dataportal/media/' . $uuid;
1979
  if ($representaion_uuid) {
1980
    $out .= '/' . $representaion_uuid;
1981
    if ($partId !== FALSE) {
1982
      $out .= '/' . $partId;
1983
    }
1984
  }
1985
  return $out;
1986
}
1987

    
1988
/**
1989
 * Compares thisRank with thatRank.
1990
 *
1991
 * Returns a negative integer, zero, or a positive integer
1992
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1993
 * e.g:
1994
 * <ul>
1995
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1996
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1997
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1998
 * </ul>
1999
 * <p>
2000
 * This compare logic of the underlying webservice is the
2001
 * <b>inverse logic</b> of the the one implemented in
2002
 * java.lang.Comparable#compareTo(java.lang.Object)
2003
 *
2004
 * @param $thisRankUuid
2005
 * @param $thatRankUuid
2006
 *
2007
 * @return int
2008
 *   A negative integer, zero, or a positive integer
2009
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2010
 */
2011
function rank_compare($thisRankUuid, $thatRankUuid) {
2012
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2013
  return $result->Integer;
2014
}
2015

    
2016
/**
2017
 * Composes an HTML element class attribute value composed of
2018
 * the shortname of the cdm class and the uuid of the entity.
2019
 * This class attribute should be used whereever an cdm-entity is rendered.
2020
 *
2021
 * These according class selectors in css must be escaped, eg:
2022
 *    .cdm\:TextData
2023
 *
2024
 * @param $cdmEntity
2025
 */
2026
function html_class_attribute_ref($cdmEntity) {
2027

    
2028
  if (is_cdm_entity($cdmEntity)) {
2029
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2030
  }
2031
}
2032

    
2033

    
2034
/**
2035
 * Creates a short taxonname.
2036
 *
2037
 * The short name is created by using the taggedTitle field of
2038
 * NameSTO or NameTO instances.
2039
 * If the taggedTitle if empty the fullname will be returned.
2040
 *
2041
 * @param unknown_type $name
2042
 *   Name or TreeNode.
2043
 *
2044
 * @return string
2045
 */
2046
function cdm_dataportal_shortname_of($name) {
2047
  $nameStr = '';
2048

    
2049
  normalize_tagged_text($name->taggedTitle);
2050

    
2051
  // Get all tagged text tokens of the scientific name.
2052
  foreach ($name->taggedTitle as $tagtxt) {
2053
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2054
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2055
    }
2056
  }
2057
  $nameStr = trim($nameStr);
2058

    
2059
  if ($nameStr) {
2060

    
2061
    // Do not return short names for these.
2062
    if ($name->unplaced || $name->excluded) {
2063
      return $nameStr;
2064
    }
2065

    
2066
    /*
2067
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2068
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2069
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2070
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2071
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2072
    */
2073
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2074
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2075
      return $matches[1][0] . "." . $matches[3][0];
2076
    }
2077
    else {
2078
      return $nameStr;
2079
    }
2080
  }
2081
  else {
2082
    return $name->titleCache;
2083
  }
2084
}
2085

    
2086
/**
2087
 * Check if a taxon is accepted by the current taxonomic tree.
2088
 *
2089
 * @param mixed $taxon
2090
 *   The Taxon obkect to check.
2091
 *
2092
 * @return bool
2093
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2094
 */
2095
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2096

    
2097
  $defaultTreeUuid = get_current_classification_uuid();
2098

    
2099
  if (isset($taxon->taxonNodes)) {
2100
    $taxonNodes = $taxon->taxonNodes;
2101
  }
2102
  else {
2103
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2104
  }
2105

    
2106
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2107
    foreach ($taxonNodes as $node) {
2108
      if (isset($node->classification)){
2109
        if(is_object($node->classification)) {
2110
          if ($node->classification->uuid == $defaultTreeUuid) {
2111
            return TRUE;
2112
          }
2113
        }
2114
        else {
2115
          if ($node->classification == $defaultTreeUuid) {
2116
            return TRUE;
2117
          }
2118
        }
2119
      }
2120
    }
2121
  }
2122

    
2123
  return FALSE;
2124
}
2125

    
2126
/**
2127
 * Checks is the source has one of the given types.
2128
 *
2129
 * @param object $source
2130
 *   The original source entity
2131
 * @param array $types
2132
 *   An array of elementd of the OriginalSourceType enumeration
2133
 *   If not set the default will be used which is:
2134
 *    - Lineage
2135
 *    - PrimaryMediaSource
2136
 *    - PrimaryTaxonomicSource
2137
 *    - Unknown
2138
 *    - Other
2139
 * @return boolean
2140
 */
2141
  function _is_original_source_type($source, $types = null) {
2142
    // this is the default
2143
    // maybe this should also be put into the settings
2144
    static $default = array(
2145
      OriginalSourceType::Lineage,
2146
      OriginalSourceType::PrimaryMediaSource,
2147
      OriginalSourceType::PrimaryTaxonomicSource,
2148
      OriginalSourceType::Unknown,
2149
      OriginalSourceType::Other,
2150
    );
2151

    
2152
    if(!$types){
2153
      $types = $default;
2154
    }
2155
    return isset($source->type) && in_array($source->type, $types);
2156
  }
2157

    
2158
/**
2159
 * @todo Please document this function.
2160
 * @see http://drupal.org/node/1354
2161
 */
2162
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2163
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2164
}
2165

    
2166

    
2167
/**
2168
 * Collects all the media from a list of description elements.
2169
 *
2170
 * @param array $descriptionElements
2171
 *   The description elements from which to collect the media.
2172
 *
2173
 * @return array
2174
 *   The output with all the collected media.
2175
 */
2176
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2177

    
2178
  $outArrayOfMedia = array();
2179

    
2180
  // Avoiding a warning box in Drupal for Flora Malesiana.
2181
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2182
    foreach ($descriptionElements as $descriptionElement) {
2183
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2184
        foreach ($descriptionElement->media as $media) {
2185
          if (is_object($media)) {
2186
            $outArrayOfMedia[] = $media;
2187
          }
2188
        }
2189
      }
2190
    }
2191
  }
2192
  return $outArrayOfMedia;
2193
}
2194

    
2195
/**
2196
 * @todo Please document this function.
2197
 * @see http://drupal.org/node/1354
2198
 *
2199
 * @param array $cdm_entities
2200
 *   An array of CdmBase instances or a single instance.
2201
 * @param string $footnote_list_key_suggestion
2202
 *
2203
 * @return unknown
2204
 */
2205
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2206

    
2207
   static $annotations_types_filter = null;
2208
   if(!$annotations_types_filter) {
2209
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2210
   }
2211

    
2212
  $footNoteKeys = array();
2213

    
2214
  // Is argument cdmBase an array?
2215
  if (!is_array($cdm_entities)) {
2216
    $cdmBase_array = array();
2217
    $cdmBase_array[] = $cdm_entities;
2218
  }
2219
  else {
2220
    $cdmBase_array = $cdm_entities;
2221
  }
2222

    
2223
  // Getting the key for the footnotemanager.
2224
  if (isset($footnote_list_key_suggestion)) {
2225
    $footnote_list_key = $footnote_list_key_suggestion;
2226
  }
2227
  else {
2228
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2229
  }
2230

    
2231
  // Adding the footnotes keys.
2232
  foreach ($cdmBase_array as $cdmBase_element) {
2233
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2234
    if (is_array($annotations)) {
2235
      foreach ($annotations as $annotation) {
2236
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2237
      }
2238
    }
2239
  }
2240

    
2241
  return $footNoteKeys;
2242
}
2243

    
2244

    
2245
/**
2246
 * Creates a CDM Dynabox.
2247
 *
2248
 * @param string $dynabox_id
2249
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2250
 * @param string $label
2251
 *   The clickable text to show.
2252
 * @param string $content_url
2253
 *   The cdm REST service request url wich will deliver the content to be shown
2254
 *   once the dynabox toggles open.
2255
 * @param string $theme
2256
 *   The theme to be used for rendering the cdm REST service response with is
2257
 *   returned from the $content_url.
2258
 * @param string $link_alt_text
2259
 *   The value for the alt attribute of the dynabox link.
2260
 * @param array $enclosingtags
2261
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2262
 *   element itself, $enclosingtags[1] is the tag to be used for the
2263
 *   dynabox_content (optional)
2264
 * @param array $attributes
2265
 * @param $content_element_selector
2266
 *   Optional jQuery selector which can be used to reference a dom element which should
2267
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2268
 *  element will be placed in this container.
2269
 *
2270
 * @param string $open_callback
2271
 *   optional javascript call back function to be triggered after toggling the box to
2272
 *   the open state.
2273
 * @param string $close_callback
2274
 *   optional javascript call back function to be triggered after toggling the box to
2275
 *   the closed state.
2276
 * @return string Returns HTML for a dynabox.
2277
 * Returns HTML for a dynabox.
2278
 */
2279
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2280
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2281
                     $content_element_selector = null,
2282
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2283
  $out = '';
2284

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

    
2288
  if(!array_key_exists('class', $attributes)) {
2289
    $attributes['class'] = array();
2290
  }
2291
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2292
  $dynabox_attributes = drupal_attributes($attributes);
2293

    
2294

    
2295
  _add_js_domEvent(); // requires domEvent.js
2296
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2297
  drupal_add_js("
2298
  jQuery(document).ready(
2299
      function() {
2300
        dynabox('". $dynabox_id ."',
2301
          {
2302
            open_callback: " . $open_callback .",
2303
            close_callback: " . $close_callback .
2304
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2305
          }
2306
        );
2307
      }
2308
   );",
2309
   array(
2310
    'type'=>'inline',
2311
    'scope'=>'footer'
2312
    )
2313
  );
2314

    
2315

    
2316
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2317
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2318
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2319
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2320
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2321
  $out .= '    </' . $enclosingtags[1] . '>';
2322
  $out .= '  </' . $enclosingtags[0] . '>';
2323
  $out .= '<!-- dynabox end -->';
2324
  return $out;
2325
}
2326

    
2327
/**
2328
 * Checks whether a feature has any description elements.
2329
 *
2330
 * @param mixed $featureNode
2331
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2332
 *
2333
 * @see _mergeFeatureTreeDescriptions()
2334
 *
2335
 * @return bool
2336
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2337
 *   contains at least one non empty TextData or at least one DescriptionElement
2338
 *   of an other type. A TextData element holding a multilanguageText or a
2339
 *   source reference is considered to be not empty.
2340
 *
2341
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2342
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2343
 *       $feature_block_has_content in compose_feature_block_items_generic
2344
 */
2345
function has_feature_node_description_elements($featureNode) {
2346

    
2347
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2348
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2349
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2350
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2351
          && $descriptionElement->multilanguageText_L10n->text != ''
2352
          || isset($descriptionElement->sources[0])
2353
          || isset($descriptionElement->media[0]) ) {
2354
          return TRUE;
2355
        }
2356
      }
2357
    }
2358
  }
2359
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2360
    foreach ($featureNode->childNodes as $child) {
2361
      if (has_feature_node_description_elements($child)) {
2362
        return TRUE;
2363
      }
2364
    }
2365
  }
2366
  return FALSE;
2367
}
2368

    
2369
/**
2370
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2371
 *
2372
 * @param $chapter
2373
 *   The taxon page chapter or part
2374
 */
2375
function cdm_check_valid_taxon_page($chapter){
2376
  static $taxon_tabs = null;
2377

    
2378
  cdm_check_valid_portal_page();
2379

    
2380
  if($taxon_tabs == null){
2381
    $taxon_tabs = array('all', 'description');
2382
    foreach(get_taxon_tabs_list() as $tab){
2383
      $taxon_tabs[] = strtolower($tab);
2384
    }
2385
  }
2386

    
2387
  if(!in_array($chapter, $taxon_tabs)){
2388
    // oops this is not a valid chapter name
2389
    http_response_code(404); // 404 = Not Found
2390
  }
2391

    
2392
}
2393

    
2394
/**
2395
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2396
 *
2397
 * @param $chapter
2398
 *   The taxon page chapter or part
2399
 */
2400
function cdm_check_valid_portal_page(){
2401
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2402
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2403
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2404
    http_response_code(404); // 404 = Not Found
2405
    exit('HTTP 404');
2406
  }
2407
}
2408

    
2409
/**
2410
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2411
 *
2412
 * @param $text_a
2413
 * @param $text_b
2414
 * @return string
2415
 */
2416
function diff_viewer($text_a, $text_b) {
2417

    
2418
  static $diff_viewer_count = 0;
2419

    
2420
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2421

    
2422
  // http://code.stephenmorley.org/php/diff-implementation/
2423
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2424
  drupal_add_css(drupal_get_path('module',
2425
      'cdm_dataportal') . '/css/diff.css');
2426
  _add_jquery_ui();
2427
  drupal_add_js(
2428
    'jQuery(document).ready( function(){
2429
        jQuery(\'#' . $element_id . '\').accordion({
2430
        collapsible: true,
2431
        active: false,
2432
        fillSpace: true,
2433
        }).children(\'div\').css({ \'height\': \'auto\' });
2434
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2435
     });'
2436
    , array(
2437
    'type' => 'inline',
2438
    'scope' => 'footer'
2439
  ));
2440

    
2441
  $diff = Diff::compare($text_a,
2442
    $text_b);
2443
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2444
    . Diff::toTable($diff, '', '')
2445
    . '</div></div>';
2446
  return $diff_viewer_markup;
2447
}
2448

    
2449

    
(10-10/16)