Project

General

Profile

Download (79.3 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').'/fonts/font-awesome-4.6.3/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
    $items['cdm_dataportal/taxon/autosuggest'] = array(
615
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
616
        'access arguments' => array('access taxon autosuggest'),
617
        'type' => MENU_CALLBACK
618
    );
619
  }
620

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

    
633
  return $items;
634
}
635

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

    
647
  if(variable_get('cdm_debug_mode', FALSE)){
648
    $file = 'temporary://drupal_debug.txt';
649
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
650
  }
651

    
652
  $bibliography_settings = get_bibliography_settings();
653
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
654
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
655
}
656

    
657
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
658

    
659
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
660

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

    
670
  $parameters['cacheL2_refresh'] ='1';
671

    
672

    
673
  drupal_goto($base_path, array('query' => $parameters));
674
}
675

    
676
/**
677
 * The function generate form for own user cdm dataportal configurations.
678
 */
679
function cdm_dataportal_user_form($form, &$form_state) {
680

    
681
  global $user;
682
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
683

    
684
  $form['taxon_page_tabs'] = array(
685
      '#type' => 'fieldset',
686
      '#tree' => true,
687
      '#title' => t('Taxon page tabs'),
688
  );
689

    
690
  $form['taxon_page_tabs']['user_defined'] = array(
691
    '#type' => 'checkbox',
692
    '#title' => t('Activate user default configuration'),
693
    '#default_value' => variable_get($checkbox_value, 0),
694
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
695
  );
696

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

    
707

    
708
  if(false){
709
    $form['developer_options'] = array(
710
        '#type' => 'fieldset',
711
        '#tree' => true,
712
        '#title' => t('Developer options'),
713
    );
714

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

    
728
  $form['submit'] = array(
729
    '#type' => 'submit',
730
    '#value' => t('Submit'),
731
  );
732

    
733
  return $form;
734
}
735

    
736
/**
737
 * Form submission handler for user_form().
738
 *
739
 * Submits the user cdm dataportal configurations.
740
 */
741
function cdm_dataportal_user_form_submit($form, &$form_state) {
742
  global $user;
743
  $msg_type = 'status';
744
  $username = $user->name;
745
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
746

    
747
  // FIXME: this is completely wrong, see user_profile_form_submit()
748

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

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

    
768
  }
769
  else {
770
    // Problem with the user id => variables wont be saved.
771
    $msg_type = 'warning';
772
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
773
  }
774
}
775

    
776
/**
777
 * Implements hook_block_info().
778
 */
779
function cdm_dataportal_block_info() {
780

    
781
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
782
    // $block[1]["info"] = t("CDM DataPortal Credits");
783
    $block["2"] = array(
784
        "info" => t("CDM Search Taxa"),
785
        "cache" => DRUPAL_NO_CACHE
786
      );
787
    // $block[3]["info"] = t("CDM Filters");
788
    $block["4"]["info"] = t("CDM Dataportal Print");
789
    $block["keys"]["info"] = t("CDM identification keys");
790
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
791
    $block["classification_breadcrumbs"] =  array(
792
        'info' => t('Classification breadcrumbs'),
793
        'cache' => DRUPAL_CACHE_PER_PAGE
794
      );
795
    $block["taxonomic_children"] =  array(
796
      'info' => t('Taxonomic children'),
797
      'cache' => DRUPAL_CACHE_PER_PAGE
798
    );
799

    
800
    return $block;
801
}
802

    
803
/**
804
 * Implements hook_block_view().
805
 */
806
function cdm_dataportal_block_view($delta) {
807
  // TODO Rename block deltas (e.g. '2') to readable strings.
808
  switch ($delta) {
809
    // case 'delta-1':
810
    // $block['subject'] = t('Credits');
811
    // $block['content'] = theme('cdm_credits');
812
    // return $block;
813
    case '2':
814
      $block['subject'] = t('Search taxa');
815
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
816
      $block['content'] = drupal_render($form);
817

    
818
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
819
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
820
      }
821
      return $block;
822
    case '4':
823
      $block['subject'] = '';
824
      $block['content'] = theme('cdm_print_button');
825
      return $block;
826
    case "keys":
827
      $block['subject'] = t('Identification Keys');
828
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
829
      return $block;
830
    case "fundedByEDIT":
831
      // t('Funded by EDIT');
832
      $text = '<none>';
833
      $block['subject'] = $text;
834
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
835
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
836
        'attributes' => array("target" => "EDIT"),
837
        'absolute' => TRUE,
838
        'html' => TRUE,
839
      ));
840
      return $block;
841
    case 'classification_breadcrumbs':
842
      $taxon_uuid = get_current_taxon_uuid();
843
      $block['subject'] = '<none>';
844
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
845
      return $block;
846
    case 'taxonomic_children':
847
      $taxon_uuid = get_current_taxon_uuid();
848
      $block['subject'] = '<none>';
849
      $block['content'] = compose_taxonomic_children($taxon_uuid);
850
      return $block;
851
  }
852
}
853

    
854
/**
855
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
856
 *
857
 * @return string
858
 *   the taxon uuid or NULL
859
 */
860
function get_current_taxon_uuid()
861
{
862
  static $taxon_uuid;
863

    
864
  if(!isset($taxon_uuid)){
865
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
866
      $taxon_uuid = $_REQUEST['currentTaxon'];
867
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
868
      $taxon_uuid = arg(2);
869
    } else {
870
      $taxon_uuid = null;
871
    }
872
  }
873

    
874
  return $taxon_uuid;
875
}
876

    
877
/**
878
 * Returns the currently classification tree in use.
879
 *
880
 * @return string
881
 *   The uuid of the currently focused classification
882
 */
883
function get_current_classification_uuid() {
884
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
885
    return $_SESSION['cdm']['taxonomictree_uuid'];
886
  }
887
  else {
888
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
889
  }
890
}
891

    
892
/*
893
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
894
 $_SESSION['cdm'] = NULL;
895
 if(is_string($cdm_ws_uri_update)){
896
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
897
 }
898
 }
899

    
900
 function cdm_dataportal_session_validate(){
901
 if(!isset($_SESSION['cdm']['ws_uri'])){
902
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
903
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
904
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
905
 }
906
 }
907
 */
908

    
909
/**
910
 * creates a  selector form for taxonomic trees.
911
 *
912
 * @return array
913
 *  a drupal form array
914
 */
915
function cdm_taxonomictree_selector() {
916
  _add_js_treeselector();
917

    
918
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
919
  return $form;
920
}
921

    
922
/**
923
 * @todo Please document this function.
924
 * @see http://drupal.org/node/1354
925
 *
926
 * @deprecated use compose_classification_selector instead
927
 */
928
function cdm_taxonomictree_selector_form($form, &$form_state) {
929

    
930
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
931
  $form['#action'] = $url;
932

    
933
  $form['var'] = array(
934
    '#weight' => -3,
935
    '#type' => 'hidden',
936
    '#value' => '[cdm][taxonomictree_uuid]',
937
  );
938

    
939
  $destination_array = drupal_get_destination();
940
  $destination = $destination_array['destination'];
941

    
942
  $form['destination'] = array(
943
    '#weight' => -3,
944
    '#type' => 'hidden',
945
    '#value' =>  $destination,
946
  );
947

    
948
  $options = cdm_get_taxontrees_as_options();
949
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
950
  if($taxontree_includes){
951
    $filtered_options = array();
952
    foreach($options as $uuid=>$label){
953
      if(!empty($taxontree_includes[$uuid])){
954
        $filtered_options[$uuid] = $label;
955
      }
956
    }
957
    $options = $filtered_options;
958
  }
959

    
960
  $form['val'] = array(
961
    '#type' => 'select',
962
    '#title' => t('Available classifications'),
963
    '#default_value' => get_current_classification_uuid(),
964
    '#options' => $options,
965
    '#attributes' => array('class' => array('highlite-first-child')),
966
  );
967

    
968
  return $form;
969

    
970
}
971

    
972
/**
973
 *
974
 * @ingroup compose
975
 */
976
function compose_classification_selector() {
977

    
978
  $destination_array = drupal_get_destination();
979
  $destination = $destination_array['destination'];
980

    
981
  $options = cdm_get_taxontrees_as_options();
982
  $items = array();
983
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
984

    
985
  $current_classification_uuid = get_current_classification_uuid();
986

    
987

    
988
  foreach($options as $uuid=>$label){
989
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
990

    
991
      $class_attributes = '';
992
      if($current_classification_uuid == $uuid){
993
        $class_attributes  = array('focused');
994
      }
995
      $items[] = array(
996
        'data' => l($label,
997
          'cdm_api/setvalue/session',
998
          array(
999
            'query' => array(
1000
              'destination' => $destination,
1001
              'val' => $uuid,
1002
              'var' => '[cdm][taxonomictree_uuid]'
1003
            ),
1004
          )
1005
        ),
1006
        'class' => $class_attributes
1007
      );
1008
    }
1009
  }
1010

    
1011
  $render_array = array(
1012
    '#theme' => 'item_list',
1013
    '#type' => 'ul',
1014
    '#items' => $items
1015
  );
1016

    
1017
  return $render_array;
1018
}
1019

    
1020

    
1021
/* UNREACHABLE since action of form directly links to view.
1022
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1023

    
1024
 $_SESSION['cdm']['search'] = $form_values;
1025
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1026
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1027
 //$paramstr = compose_url_prameterstr($form_values);
1028
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1029
 }
1030
 */
1031
/* ====================== menu callback functions ====================== */
1032
/**
1033
 * @todo Please document this function.
1034
 * @see http://drupal.org/node/1354
1035
 */
1036
/*
1037
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1038
  static $comment_node_disabled =  0;
1039
  static $comment_node_read_only =  1;
1040
  static $comment_node_read_write =  2;
1041

    
1042
  if ($form_id == 'node_type_form'
1043
   && isset($form['identity']['type'])
1044
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1045
  ) {
1046
    $form['workflow']['comment'] = array(
1047
      '#type' => 'radios',
1048
      '#title' => t('Default comment setting'),
1049
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1050
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1051
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1052
    );
1053
  }
1054
}
1055
*/
1056

    
1057
/**
1058
 * Displays a list of the known taxonomic names.
1059
 *
1060
 * When the list of taxonomic names is displayed, long lists are split up into
1061
 * multiple pages.
1062
 *
1063
 * TODO: Parameters are still preliminary.
1064
 *
1065
 * @param string $beginsWith
1066
 * @param string $page
1067
 *   Page number to diplay defaults to page 1.
1068
 * @param bool $onlyAccepted
1069
 */
1070
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1071

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

    
1074
  /*
1075
  // FIXME the filter for accepted names will be a form element, thus this
1076
  // widget should be generated via form api preferably as block.
1077
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1078
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1079
  $out .= theme('cdm_listof_taxa', $taxonPager);
1080
  return $out;
1081
  */
1082
}
1083

    
1084
/**
1085
 * @todo Please document this function.
1086
 * @see http://drupal.org/node/1354
1087
 */
1088
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1089

    
1090
  cdm_check_valid_portal_page();
1091

    
1092
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1093
  return theme('cdm_reference_page', array('reference' => $reference));
1094
}
1095

    
1096
/**
1097
 * Creates a view on a all references contained in the portal.
1098
 *
1099
 * This function is used at the path cdm_dataportal/reference/list
1100
 */
1101
function cdm_dataportal_view_reference_list($pageNumber) {
1102
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1103
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1104
}
1105

    
1106
/**
1107
 * @todo Please document this function.
1108
 * @see http://drupal.org/node/1354
1109
 */
1110
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1111

    
1112
  cdm_check_valid_portal_page();
1113

    
1114
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1115
  return theme('cdm_media_page', array(
1116
    'media' => $media,
1117
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1118
    'partId' => $part,
1119
    ));
1120
}
1121

    
1122
/**
1123
 * @todo Please document this function.
1124
 * @see http://drupal.org/node/1354
1125
 */
1126
function _load_taxonBase(&$taxonBase) {
1127
  if (isset($taxonBase->uuid)) {
1128
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1129
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1130
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1131
  }
1132
}
1133

    
1134
/**
1135
 * Loads the media associated to the given taxon from the cdm server.
1136
 * The aggregation settings regarding taxon relathionships and
1137
 * taxonnomic childen are taken into account.
1138
 *
1139
 * The media lists are cached in a static variable.
1140
 *
1141
 * @param Taxon $taxon
1142
 *   A CDM Taxon entitiy
1143
 *
1144
 * @return array
1145
 *   An array of CDM Media entities
1146
 *
1147
 */
1148
function _load_media_for_taxon($taxon) {
1149

    
1150
  static $media = NULL;
1151

    
1152
  if(!isset($media)) {
1153
    $media = array();
1154
  }
1155
  if (!isset($media[$taxon->uuid])) {
1156

    
1157
    // --- GET Images --- //
1158
    $mediaQueryParameters = array(
1159
        "type" => "ImageFile",
1160
    );
1161

    
1162
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1163
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1164
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1165

    
1166
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1167
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1168
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1169
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1170

    
1171
    $ws_endpoint = NULL;
1172
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1173
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1174
    } else {
1175
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1176
    }
1177

    
1178
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1179
        array(
1180
            $taxon->uuid,
1181
        ),
1182
        queryString($mediaQueryParameters)
1183
       );
1184
  }
1185

    
1186
  return $media[$taxon->uuid];
1187
}
1188

    
1189
/**
1190
 *
1191
 * @param Taxon $taxon
1192
 *   A CDM Taxon entitiy
1193
 *
1194
 * @return array
1195
 *   An array of CDM SpecimenOrObservation entities
1196
 *
1197
function _load_occurences_for_taxon($taxon){
1198

    
1199
  static $occurences = NULL;
1200

    
1201
  if(!isset($occurences)) {
1202
    $occurences = array();
1203
  }
1204

    
1205
  if (!isset($occurences[$taxon->uuid])){
1206

    
1207
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1208
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1209
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1210

    
1211
    $by_associatedtaxon_query = http_build_query(array(
1212
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1213
        'relationships' => implode(',', $relationship_choice['direct']),
1214
        'pageSize' => null // all hits in one page
1215
    )
1216
    );
1217

    
1218
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1219
        null,
1220
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1221
    );
1222

    
1223

    
1224
    if(isset($pager->records[0])){
1225
      $occurences[$taxon->uuid] =  $pager->records;
1226
    }
1227
  }
1228
  return $occurences[$taxon->uuid];
1229
}
1230
 */
1231

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

    
1264
/**
1265
 * Recursive function to convert an object into an array.
1266
 * also subordinate objects will be converted.
1267
 *
1268
 * @param object $object
1269
 * @return the array
1270
 */
1271
function convert_to_array($object) {
1272
  if(is_object($object) || is_array($object)) {
1273
    $array = (array)$object;
1274
    foreach ($array as $key=>$value){
1275
      $array[$key] = convert_to_array($value);
1276
    }
1277
    return $array;
1278
  } else {
1279
    return $object;
1280
  }
1281
}
1282

    
1283
/**
1284
 * Searches the $collection for the cdm entitiy given as $element.
1285
 *
1286
 * The elements are compared by their UUID.
1287
 *
1288
 * @param $element
1289
 *  the CDM entitiy to search for
1290
 * @param $collection
1291
 *  the list of CDM entities to search in
1292
 *
1293
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1294
 *
1295
 */
1296
function contains_cdm_entitiy($element, $collection) {
1297
  $result = FALSE;
1298
  foreach ($collection as $a) {
1299
    if ($a->uuid == $element->uuid) {
1300
      $result = TRUE;
1301
    }
1302
  }
1303
  return $result;
1304
}
1305

    
1306
/**
1307
 * Fiters the array $entity_list of CDM entities by the list
1308
 * of $excludes. Any element contained in the $excludes will be removed
1309
 * from included int the retuned list.
1310
 *
1311
 * If the $entity_list is not an array the $excludes will be returned.
1312
 */
1313
function filter_cdm_entity_list($entity_list, $excludes) {
1314
  if (is_array($entity_list)) {
1315
    $result = $entity_list;
1316
    if ($excludes) {
1317
      foreach ($excludes as $exclude) {
1318
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1319
          $result[] = $exclude;
1320
        }
1321
      }
1322
    }
1323
  }
1324
  else {
1325
    $result = $excludes;
1326
  }
1327
  return $result;
1328
}
1329

    
1330
/**
1331
 * Wraps the given $html string into a render array suitable for drupal_render()
1332
 *
1333
 * @param $html
1334
 *   the html string, see
1335
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1336
 * @param $weight
1337
 *   A positive or negative number (integer or decimal).
1338
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1339
 * @param $prefix
1340
 *   Optional markup for the '#prefix' element of the render array
1341
 * @param $suffix
1342
 *   Optional markup for the '#suffix' element of the render array
1343
 *
1344
 * @return array
1345
 *   A render array
1346
 *
1347
 */
1348
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1349
  $render_array = array(
1350
    '#markup' => $html
1351
      );
1352
  if (is_numeric($weight)) {
1353
    $render_array['#weight'] = $weight;
1354
  }
1355
  if($prefix){
1356
    $render_array['#prefix'] = $prefix;
1357
  }
1358
  if($suffix) {
1359
    $render_array['#suffix'] = $suffix;
1360
  }
1361
  return $render_array;
1362
}
1363

    
1364
/**
1365
 * Loads the subgraph of a given PolytomousKeyNode.
1366
 *
1367
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1368
 * the CDM REST service.
1369
 *
1370
 * @param mixed $polytomousKeyNode
1371
 *   PolytomousKeyNode passed by reference.
1372
 *
1373
 * @return void
1374
 */
1375
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1376

    
1377
  if (!$polytomousKeyNode) {
1378
    return;
1379
  }
1380
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1381
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1382
    return;
1383
  }
1384
  if (!is_uuid($polytomousKeyNode->uuid)) {
1385
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1386
    return;
1387
  }
1388

    
1389
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1390

    
1391
  if (!$polytomousKeyNode) {
1392
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1393
    return;
1394
  }
1395

    
1396
  // Load children.
1397
  foreach ($polytomousKeyNode->children as &$childNode) {
1398
    _load_polytomousKeySubGraph($childNode);
1399
  }
1400

    
1401
  // Load subkey.
1402
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1403

    
1404
  // Load taxon.
1405
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1406
  _load_taxonBase($polytomousKeyNode->taxon);
1407
  return;
1408
}
1409

    
1410
/**
1411
 * @todo Please document this function.
1412
 * @see http://drupal.org/node/1354
1413
 */
1414
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1415

    
1416
  cdm_check_valid_portal_page();
1417

    
1418
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1419

    
1420
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1421
  if (is_array($sourcePager->records)) {
1422
    $polytomousKey->sources = $sourcePager->records;
1423
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1424
  }
1425

    
1426
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1427
  if (is_array($annotationPager->records)) {
1428
    $polytomousKey->annotations = $annotationPager->records;
1429
  }
1430

    
1431
  _load_polytomousKeySubGraph($polytomousKey->root);
1432
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1433
}
1434

    
1435
/**
1436
 * Creates a taxon page view or a chapter of it.
1437
 *
1438
 * The taxon page gives detailed information on a taxon, it shows:
1439
 *  - Taxon name.
1440
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1441
 *    heterotypic and finally followed by misapplied names.
1442
 *    The list is ordered historically.
1443
 *  - All description associated with the taxon.
1444
 *
1445
 * @param string $uuid
1446
 * @param string $chapter
1447
 *   Name of the part to display, valid values are:
1448
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1449
 *
1450
 * @return unknown_type
1451
 */
1452
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1453

    
1454
  cdm_check_valid_taxon_page($chapter);
1455
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1456
  // show a warning in case the javascript development mode is anabled
1457
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1458
    drupal_set_message(t('The !url1 is enabled.
1459
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1460
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1461
    )),
1462
    'warning'
1463
        );
1464
  }
1465

    
1466
  // Display the page for the taxon defined by $uuid.
1467
  // set_last_taxon_page_tab(arg(3));
1468
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1469
  if (!empty($taxonpage)) {
1470
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1471
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1472
  }
1473
  else {
1474
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1475
    return '';
1476
  }
1477
}
1478

    
1479
/**
1480
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1481
 * which has two fields, one for the page title and one for the content. Later on in the
1482
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1483
 * function as the function parameters $title and $content.
1484
 *
1485
 * @param string $uuid
1486
 *   the uuid of the taxon to show
1487
 * @param string $chapter
1488
 *   Name of the part to display, valid values are:
1489
 *   'description', 'images', 'synonymy', 'all'.
1490
 *
1491
 * @return taxonpage object with the following fields:
1492
 *   - title : the title of the page
1493
 *   - content: the content of the page
1494
 *
1495
 */
1496
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1497
  // Taxon object.
1498
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1499
  if (empty($taxon)) {
1500
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1501
    return FALSE;
1502
  }
1503
  $taxonpage = new stdClass();
1504

    
1505
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1506
    'taxon' => $taxon
1507
  ));
1508

    
1509
  // Check if the taxon id contained in the currently selected tree.
1510
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1511

    
1512
  if (!$taxon_in_current_classification) {
1513
    $classifications = get_classifications_for_taxon($taxon);
1514
    RenderHints::pushToRenderStack('not_in_current_classification');
1515
    $taxon_name_markup = render_taxon_or_name($taxon);
1516

    
1517
    if (count($classifications) == 0) {
1518
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1519
        array(
1520
        '!taxonname' => $taxon_name_markup,
1521
        )
1522
      ), 'warning');
1523
    }
1524
    else {
1525
      $trees = '';
1526
      foreach ($classifications as $classification) {
1527
        if (isset($classification->titleCache)) {
1528
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1529
        }
1530
      }
1531

    
1532
      drupal_set_message(format_plural(count($trees),
1533
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1534
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1535
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1536
        ) ,
1537
        'warning');
1538
    }
1539
    RenderHints::popFromRenderStack();
1540
  }
1541

    
1542
  // Render the taxon page.
1543
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1544
  $taxonpage->content = drupal_render($render_array);
1545

    
1546
  return $taxonpage;
1547
}
1548

    
1549
/**
1550
 * Creates a specimen page view.
1551
 * @param string $uuid the UUID of the specimen
1552
 * @return array|string
1553
 */
1554
function cdm_dataportal_specimen_page_view($uuid) {
1555

    
1556
    //cdm_check_valid_taxon_page($chapter);
1557
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1558
    // show a warning in case the javascript development mode is anabled
1559
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1560
        drupal_set_message(t('The !url1 is enabled.
1561
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1562
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1563
        )),
1564
            'warning'
1565
        );
1566
    }
1567

    
1568
    // Display the page for the specimen defined by $uuid.
1569
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1570
    if (!empty($specimenpage)) {
1571
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1572
    }
1573
    else {
1574
        return '';
1575
    }
1576
}
1577

    
1578
/**
1579
 *
1580
 * Creates a specimen view.
1581
 * @param string $uuid the UUID of the specimen
1582
 * @return array|string
1583
 */
1584
function cdm_dataportal_specimen_view($uuid) {
1585
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1586
    if (empty($specimen)) {
1587
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1588
        return FALSE;
1589
    }
1590
    $specimenpage = new stdClass();
1591

    
1592
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1593
        'specimen' => $specimen
1594
    ));
1595

    
1596
    // Render the specimen page.
1597
    $render_array = compose_cdm_specimen_page($uuid);
1598
    $specimenpage->content = drupal_render($render_array);
1599

    
1600
    return $specimenpage;
1601
}
1602

    
1603
/**
1604
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1605
 *
1606
 * The node page shows the taxon name title and the list of taxon related
1607
 * with such taxon. Name on the tree already in use.
1608
 *
1609
 * @param UUID $taxon_name_uuid
1610
 *   The uuid of the CDM TaxonNameBase to show a name page for
1611
 * @param UUID $taxon_to_hide_uuid
1612
 *   A taxon which should not be displayed in the taxon list
1613
 * @param UUID $highlite_synonym_uuid
1614
 *   Optinal parameter wich takes another taxon uuid, if given the
1615
 *   target taxon pages will show the syonymy tab where the taxon
1616
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1617
 *   in case it is found on this page.
1618
 *
1619
 * @return mixed
1620
 *   The formatted name page as node.
1621
 */
1622
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1623

    
1624
  cdm_check_valid_portal_page();
1625

    
1626
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1627
  if (!empty($taxonname_page)) {
1628
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1629
  }
1630
  else {
1631
    return '';
1632
  }
1633
}
1634

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

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

    
1725
/**
1726
 * Creates a page with the advance search form.
1727
 *
1728
 * NOTE: The advance search form allows searching for taxa.
1729
 */
1730
function cdm_dataportal_view_search_advanced() {
1731
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1732
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1733
}
1734

    
1735
/**
1736
 * Creates a page with the search form for searching by taxon descriptions.
1737
 */
1738
function cdm_dataportal_view_search_taxon_by_description() {
1739
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1740
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1741
}
1742

    
1743
/**
1744
 * Executes the search and generates the result list of taxa.
1745
 */
1746
function cdm_dataportal_view_search_results_taxon() {
1747

    
1748
  $taxonPager = cdm_dataportal_search_execute();
1749

    
1750
  $showThumbnails = do_showThumbnails();
1751

    
1752
  $setSessionUri = url('cdm_api/setvalue/session', array(
1753
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1754
  ));
1755

    
1756
  drupal_add_js('jQuery(document).ready(function() {
1757

    
1758
      // init
1759
      if(' . $showThumbnails . ' == 1){
1760
          jQuery(\'.media_gallery\').show(20);
1761
      } else {
1762
          jQuery(\'.media_gallery\').hide(20);
1763
      }
1764

    
1765
      // add change handler
1766
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1767
      function(event){
1768
        var state = 0;
1769
        if(jQuery(this).is(\':checked\')){
1770
          jQuery(\'.media_gallery\').show(20);
1771
          state = 1;
1772
        } else {
1773
          jQuery(\'.media_gallery\').hide(20);
1774
        }
1775
        // store state in session variable
1776
        var uri = \'' . $setSessionUri . '\' + state;
1777
        jQuery.get(uri);
1778
      });
1779
  });',
1780
  array('type' => "inline", 'scope' => JS_DEFAULT));
1781

    
1782
  drupal_set_title(t('Search results'), PASS_THROUGH);
1783

    
1784
  return theme('cdm_search_results', array(
1785
    'pager' => $taxonPager,
1786
    'path' => 'cdm_dataportal/search/results/taxon',
1787
    ));
1788
}
1789

    
1790
/**
1791
 * Provides the standart image wich indicated a loading process
1792
 *
1793
 * @return string
1794
 *  The img html tag
1795
 */
1796
function loading_image_html() {
1797
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1798
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1799
}
1800

    
1801
/**
1802
 * Returns the state of the the showThumbnails flag set in the
1803
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1804
 *
1805
 * @return boolean
1806
 *    returns 1 if the flag is set
1807
 */
1808
function do_showThumbnails() {
1809
  static $showThumbnails = null;
1810

    
1811
  if($showThumbnails == null) {
1812
    $showThumbnails = 0;
1813
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1814
      $showThumbnails = 0;
1815
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1816
      $showThumbnails = is_array($search_gallery_settings)
1817
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1818
        && (
1819
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1820
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1821
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1822
            )
1823
         ? 1 : 0;
1824

    
1825
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1826
    }
1827
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1828
    if (!is_numeric($showThumbnails)) {
1829
      $showThumbnails = 1;
1830
    }
1831
  }
1832

    
1833
  return $showThumbnails;
1834
}
1835

    
1836

    
1837
/* ====================== other functions ====================== */
1838
/**
1839
 * Creates a URL to the taxon page specified by the $uuid parameter.
1840
 *
1841
 * The URL will be prepended with a path element to a specific taxon page tab.
1842
 *
1843
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1844
 * be set globally in the administrative settings or individually in the user
1845
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1846
 * the last portal will stay on this last tab.
1847
 *
1848
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1849
 * internal mechanism by a specific value.
1850
 *
1851
 * @param string $uuid
1852
 *   The UUID of the taxon.
1853
 * @param string $page_tab
1854
 *   Overwriting the preset mechanism by defining specific value for the
1855
 *   taxon page tab.
1856
 *
1857
 * @return string
1858
 *   The created URL.
1859
 */
1860
function path_to_taxon($uuid, $page_tab = FALSE) {
1861

    
1862
  $tab = get_default_taxon_tab();
1863
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1864

    
1865
  if (!$uuid) {
1866
    return FALSE;
1867
  }
1868

    
1869
  if ($page_tab) {
1870
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1871
  }
1872
  elseif (!$tab || strtolower($tab) == 'general') {
1873
    return 'cdm_dataportal/taxon/' . $uuid;
1874
  }
1875
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1876
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1877
  }
1878
  else {
1879
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1880
  }
1881
}
1882

    
1883
function path_to_specimen($uuid) {
1884

    
1885
    if (!$uuid) {
1886
        return FALSE;
1887
    }
1888
    else {
1889
        return 'cdm_dataportal/specimen/' . $uuid;
1890
    }
1891
}
1892

    
1893
/**
1894
 * Creates a URL to show a synonmy in the according taxon page.
1895
 *
1896
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1897
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1898
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1899
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1900
 * in the page
1901
 *
1902
 * @param string $synonymUuid
1903
 *    The uuid of the synonym
1904
 * @param string $acceptedUuid
1905
 *    The uuid of the according accepted taxon
1906
 * @return string
1907
 *    The URL to show a synonmy in the according taxon page
1908
 */
1909
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1910
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1911
  return url($acceptedPath, array(
1912
      'query' => array(
1913
        // highlite the synony in the synonymy
1914
        'highlite' => $synonymUuid,
1915
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1916
        // see theme_taxon_page_title()
1917
        'acceptedFor' => $synonymUuid
1918
      ),
1919
      'fragment' => $synonymUuid
1920
  ));
1921

    
1922
}
1923

    
1924
/**
1925
 * Compses the drupal path to the key identified by the uuid.
1926
 *
1927
 * @param string $keyType
1928
 *    the key typer corresponds to the specific class of the CDM
1929
 *    IdentificationKey. Possible values are
1930
 *      -PolytomousKey
1931
 *      -MultimediaKey
1932
 *      - ...
1933
 * @param UUID $keyUuid
1934
 *   The UUID of the key
1935
 */
1936
function path_to_key($keyType, $keyUuid) {
1937
  if (!$keyUuid || !$keyType) {
1938
    return FALSE;
1939
  }
1940
  $keyType{0} = strtolower($keyType{0});
1941
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1942
}
1943

    
1944
/**
1945
 * @todo Please document this function.
1946
 * @see http://drupal.org/node/1354
1947
 */
1948
function path_to_reference($uuid) {
1949
  if (!$uuid) {
1950
    return FALSE;
1951
  }
1952
  return 'cdm_dataportal/reference/' . $uuid;
1953
}
1954

    
1955
/**
1956
 * Creates the path to a cdm_dataportal taxon name page.
1957
 *
1958
 * @param UUID $taxon_name_uuid
1959
 *   The uuid of the CDM TaxonNameBase to show a name page for
1960
 * @param UUID $taxon_to_hide_uuid
1961
 *   A taxon which should not be displayed in the taxon list
1962
 * @param UUID $highlite_synonym_uuid
1963
 *   Optinal parameter wich takes another taxon uuid, if given the
1964
 *   target taxon pages will show the syonymy tab where the taxon
1965
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1966
 *   in case it is found on this page.
1967
 *
1968
 * @return a URI path element as string
1969
 */
1970
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1971
  $res = FALSE;
1972
  if ($name_uuid) {
1973
    $res = 'cdm_dataportal/name/' . $name_uuid;
1974
  }
1975
  if($taxon_to_hide_uuid){
1976
    $res .= '/' . $taxon_to_hide_uuid;
1977
    if($synonym_uuid){
1978
      $res .= '/' . $synonym_uuid;
1979
    }
1980
  }
1981
  return $res;
1982
}
1983

    
1984
/**
1985
 * @todo Please document this function.
1986
 * @see http://drupal.org/node/1354
1987
 */
1988
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1989
  if (!$uuid) {
1990
    return FALSE;
1991
  }
1992
  $out = 'cdm_dataportal/media/' . $uuid;
1993
  if ($representaion_uuid) {
1994
    $out .= '/' . $representaion_uuid;
1995
    if ($partId !== FALSE) {
1996
      $out .= '/' . $partId;
1997
    }
1998
  }
1999
  return $out;
2000
}
2001

    
2002
/**
2003
 * Compares thisRank with thatRank.
2004
 *
2005
 * Returns a negative integer, zero, or a positive integer
2006
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2007
 * e.g:
2008
 * <ul>
2009
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2010
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2011
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2012
 * </ul>
2013
 * <p>
2014
 * This compare logic of the underlying webservice is the
2015
 * <b>inverse logic</b> of the the one implemented in
2016
 * java.lang.Comparable#compareTo(java.lang.Object)
2017
 *
2018
 * @param $thisRankUuid
2019
 * @param $thatRankUuid
2020
 *
2021
 * @return int
2022
 *   A negative integer, zero, or a positive integer
2023
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2024
 */
2025
function rank_compare($thisRankUuid, $thatRankUuid) {
2026
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2027
  return $result->Integer;
2028
}
2029

    
2030
/**
2031
 * Composes an HTML element class attribute value composed of
2032
 * the shortname of the cdm class and the uuid of the entity.
2033
 * This class attribute should be used whereever an cdm-entity is rendered.
2034
 *
2035
 * These according class selectors in css must be escaped, eg:
2036
 *    .cdm\:TextData
2037
 *
2038
 * @param $cdmEntity
2039
 */
2040
function html_class_attribute_ref($cdmEntity) {
2041

    
2042
  if (is_cdm_entity($cdmEntity)) {
2043
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2044
  }
2045
}
2046

    
2047

    
2048
/**
2049
 * Creates a short taxonname.
2050
 *
2051
 * The short name is created by using the taggedTitle field of
2052
 * NameSTO or NameTO instances.
2053
 * If the taggedTitle if empty the fullname will be returned.
2054
 *
2055
 * @param unknown_type $name
2056
 *   Name or TreeNode.
2057
 *
2058
 * @return string
2059
 */
2060
function cdm_dataportal_shortname_of($name) {
2061
  $nameStr = '';
2062

    
2063
  normalize_tagged_text($name->taggedTitle);
2064

    
2065
  // Get all tagged text tokens of the scientific name.
2066
  foreach ($name->taggedTitle as $tagtxt) {
2067
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2068
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2069
    }
2070
  }
2071
  $nameStr = trim($nameStr);
2072

    
2073
  if ($nameStr) {
2074

    
2075
    // Do not return short names for these.
2076
    if ($name->unplaced || $name->excluded) {
2077
      return $nameStr;
2078
    }
2079

    
2080
    /*
2081
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2082
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2083
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2084
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2085
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2086
    */
2087
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2088
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2089
      return $matches[1][0] . "." . $matches[3][0];
2090
    }
2091
    else {
2092
      return $nameStr;
2093
    }
2094
  }
2095
  else {
2096
    return $name->titleCache;
2097
  }
2098
}
2099

    
2100
/**
2101
 * Check if a taxon is accepted by the current taxonomic tree.
2102
 *
2103
 * @param mixed $taxon
2104
 *   The Taxon obkect to check.
2105
 *
2106
 * @return bool
2107
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2108
 */
2109
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2110

    
2111
  $defaultTreeUuid = get_current_classification_uuid();
2112

    
2113
  if (isset($taxon->taxonNodes)) {
2114
    $taxonNodes = $taxon->taxonNodes;
2115
  }
2116
  else {
2117
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2118
  }
2119

    
2120
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2121
    foreach ($taxonNodes as $node) {
2122
      if (isset($node->classification)){
2123
        if(is_object($node->classification)) {
2124
          if ($node->classification->uuid == $defaultTreeUuid) {
2125
            return TRUE;
2126
          }
2127
        }
2128
        else {
2129
          if ($node->classification == $defaultTreeUuid) {
2130
            return TRUE;
2131
          }
2132
        }
2133
      }
2134
    }
2135
  }
2136

    
2137
  return FALSE;
2138
}
2139

    
2140
/**
2141
 * Checks is the source has one of the given types.
2142
 *
2143
 * @param object $source
2144
 *   The original source entity
2145
 * @param array $types
2146
 *   An array of elementd of the OriginalSourceType enumeration
2147
 *   If not set the default will be used which is:
2148
 *    - Lineage
2149
 *    - PrimaryMediaSource
2150
 *    - PrimaryTaxonomicSource
2151
 *    - Unknown
2152
 *    - Other
2153
 * @return boolean
2154
 */
2155
  function _is_original_source_type($source, $types = null) {
2156
    // this is the default
2157
    // maybe this should also be put into the settings
2158
    static $default = array(
2159
      OriginalSourceType::Lineage,
2160
      OriginalSourceType::PrimaryMediaSource,
2161
      OriginalSourceType::PrimaryTaxonomicSource,
2162
      OriginalSourceType::Unknown,
2163
      OriginalSourceType::Other,
2164
    );
2165

    
2166
    if(!$types){
2167
      $types = $default;
2168
    }
2169
    return isset($source->type) && in_array($source->type, $types);
2170
  }
2171

    
2172
/**
2173
 * @todo Please document this function.
2174
 * @see http://drupal.org/node/1354
2175
 */
2176
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2177
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2178
}
2179

    
2180

    
2181
/**
2182
 * Collects all the media from a list of description elements.
2183
 *
2184
 * @param array $descriptionElements
2185
 *   The description elements from which to collect the media.
2186
 *
2187
 * @return array
2188
 *   The output with all the collected media.
2189
 */
2190
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2191

    
2192
  $outArrayOfMedia = array();
2193

    
2194
  // Avoiding a warning box in Drupal for Flora Malesiana.
2195
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2196
    foreach ($descriptionElements as $descriptionElement) {
2197
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2198
        foreach ($descriptionElement->media as $media) {
2199
          if (is_object($media)) {
2200
            $outArrayOfMedia[] = $media;
2201
          }
2202
        }
2203
      }
2204
    }
2205
  }
2206
  return $outArrayOfMedia;
2207
}
2208

    
2209
/**
2210
 * @todo Please document this function.
2211
 * @see http://drupal.org/node/1354
2212
 *
2213
 * @param array $cdm_entities
2214
 *   An array of CdmBase instances or a single instance.
2215
 * @param string $footnote_list_key_suggestion
2216
 *
2217
 * @return unknown
2218
 */
2219
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2220

    
2221
   static $annotations_types_filter = null;
2222
   if(!$annotations_types_filter) {
2223
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2224
   }
2225

    
2226
  $footNoteKeys = array();
2227

    
2228
  // Is argument cdmBase an array?
2229
  if (!is_array($cdm_entities)) {
2230
    $cdmBase_array = array();
2231
    $cdmBase_array[] = $cdm_entities;
2232
  }
2233
  else {
2234
    $cdmBase_array = $cdm_entities;
2235
  }
2236

    
2237
  // Getting the key for the footnotemanager.
2238
  if (isset($footnote_list_key_suggestion)) {
2239
    $footnote_list_key = $footnote_list_key_suggestion;
2240
  }
2241
  else {
2242
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2243
  }
2244

    
2245
  // Adding the footnotes keys.
2246
  foreach ($cdmBase_array as $cdmBase_element) {
2247
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2248
    if (is_array($annotations)) {
2249
      foreach ($annotations as $annotation) {
2250
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2251
      }
2252
    }
2253
  }
2254

    
2255
  return $footNoteKeys;
2256
}
2257

    
2258

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

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

    
2302
  if(!array_key_exists('class', $attributes)) {
2303
    $attributes['class'] = array();
2304
  }
2305
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2306
  $dynabox_attributes = drupal_attributes($attributes);
2307

    
2308

    
2309
  _add_js_domEvent(); // requires domEvent.js
2310
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2311
  drupal_add_js("
2312
  jQuery(document).ready(
2313
      function() {
2314
        dynabox('". $dynabox_id ."',
2315
          {
2316
            open_callback: " . $open_callback .",
2317
            close_callback: " . $close_callback .
2318
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2319
          }
2320
        );
2321
      }
2322
   );",
2323
   array(
2324
    'type'=>'inline',
2325
    'scope'=>'footer'
2326
    )
2327
  );
2328

    
2329

    
2330
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2331
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2332
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2333
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2334
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2335
  $out .= '    </' . $enclosingtags[1] . '>';
2336
  $out .= '  </' . $enclosingtags[0] . '>';
2337
  $out .= '<!-- dynabox end -->';
2338
  return $out;
2339
}
2340

    
2341
/**
2342
 * Checks whether a feature has any description elements.
2343
 *
2344
 * @param mixed $featureNode
2345
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2346
 *
2347
 * @see _mergeFeatureTreeDescriptions()
2348
 *
2349
 * @return bool
2350
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2351
 *   contains at least one non empty TextData or at least one DescriptionElement
2352
 *   of an other type. A TextData element holding a multilanguageText or a
2353
 *   source reference is considered to be not empty.
2354
 *
2355
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2356
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2357
 *       $feature_block_has_content in compose_feature_block_items_generic
2358
 */
2359
function has_feature_node_description_elements($featureNode) {
2360

    
2361
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2362
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2363
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2364
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2365
          && $descriptionElement->multilanguageText_L10n->text != ''
2366
          || isset($descriptionElement->sources[0])
2367
          || isset($descriptionElement->media[0]) ) {
2368
          return TRUE;
2369
        }
2370
      }
2371
    }
2372
  }
2373
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2374
    foreach ($featureNode->childNodes as $child) {
2375
      if (has_feature_node_description_elements($child)) {
2376
        return TRUE;
2377
      }
2378
    }
2379
  }
2380
  return FALSE;
2381
}
2382

    
2383
/**
2384
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2385
 *
2386
 * @param $chapter
2387
 *   The taxon page chapter or part
2388
 */
2389
function cdm_check_valid_taxon_page($chapter){
2390
  static $taxon_tabs = null;
2391

    
2392
  cdm_check_valid_portal_page();
2393

    
2394
  if($taxon_tabs == null){
2395
    $taxon_tabs = array('all', 'description');
2396
    foreach(get_taxon_tabs_list() as $tab){
2397
      $taxon_tabs[] = strtolower($tab);
2398
    }
2399
  }
2400

    
2401
  if(!in_array($chapter, $taxon_tabs)){
2402
    // oops this is not a valid chapter name
2403
    http_response_code(404); // 404 = Not Found
2404
  }
2405

    
2406
}
2407

    
2408
/**
2409
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2410
 *
2411
 * @param $chapter
2412
 *   The taxon page chapter or part
2413
 */
2414
function cdm_check_valid_portal_page(){
2415
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2416
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2417
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2418
    http_response_code(404); // 404 = Not Found
2419
    exit('HTTP 404');
2420
  }
2421
}
2422

    
2423
/**
2424
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2425
 *
2426
 * @param $text_a
2427
 * @param $text_b
2428
 * @return string
2429
 */
2430
function diff_viewer($text_a, $text_b) {
2431

    
2432
  static $diff_viewer_count = 0;
2433

    
2434
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2435

    
2436
  // http://code.stephenmorley.org/php/diff-implementation/
2437
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2438
  drupal_add_css(drupal_get_path('module',
2439
      'cdm_dataportal') . '/css/diff.css');
2440
  _add_jquery_ui();
2441
  drupal_add_js(
2442
    'jQuery(document).ready( function(){
2443
        jQuery(\'#' . $element_id . '\').accordion({
2444
        collapsible: true,
2445
        active: false,
2446
        fillSpace: true,
2447
        }).children(\'div\').css({ \'height\': \'auto\' });
2448
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2449
     });'
2450
    , array(
2451
    'type' => 'inline',
2452
    'scope' => 'footer'
2453
  ));
2454

    
2455
  $diff = Diff::compare($text_a,
2456
    $text_b);
2457
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2458
    . Diff::toTable($diff, '', '')
2459
    . '</div></div>';
2460
  return $diff_viewer_markup;
2461
}
2462

    
2463

    
(10-10/16)