Project

General

Profile

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

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

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

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

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

    
49

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

    
52

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

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

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

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

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

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

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

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

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

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

    
124
  function _add_js_openlayers() {
125

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

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

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

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

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

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

    
173
  }
174

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

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

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

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

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

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

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

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

    
285
  /**
286
   * Provides the markup for an font awesome icon.
287
   *
288
   * The icons is created in default size without any extra features.
289
   *
290
   * The available icons are listed here http://fontawesome.io/cheatsheet/
291
   * fontawesome icons have much more features than implemented here in this function,
292
   * for spinning icons, fixed width icons, rotation, etc please checkout the
293
   * examples at http://fontawesome.io/examples/
294
   *
295
   * @parameter $icon_name
296
   *  The name of the icon which starts with 'fa-'
297
   *
298
   * @return String
299
   *    the markup for the icon in an <i> tag
300
   *
301
   */
302
  function font_awesome_icon_markup($icon_name, $attributes = array()){
303

    
304

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

    
307
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.2.0/css/font-awesome.min.css';
308
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css";
309

    
310
    drupal_add_html_head_link(
311
      array(
312
        'href' => $font_awesome_css_uri,
313
        'rel' => 'stylesheet'
314
      )
315
    );
316

    
317
    if(!isset($attributes['class'])){
318
      $attributes['class'] = array();
319
    }
320
    $attributes['class'][] = 'fa';
321
    $attributes['class'][] = $icon_name;
322

    
323
    return '<i ' . drupal_attributes($attributes) . '></i>';
324
  }
325

    
326

    
327
  /* ====================== hook implementations ====================== */
328
  /**
329
   * Implements hook_permission().
330
   *
331
   * Valid permissions for this module.
332
   *
333
   * @return array
334
   *   An array of valid permissions for the portfolio module.
335
   */
336
  function cdm_dataportal_permission() {
337
    return array(
338
      'administer cdm_dataportal' => array(
339
        'title' => t('administer cdm_dataportal'),
340
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
341
      ),
342
      'cdm_dataportal view notes' => array(
343
        'title' => t('cdm_dataportal view notes'),
344
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
345
      ),
346
      // TODO Which other permissions are required?
347
      // -> check the WP6 requirements document.
348
    );
349
  }
350

    
351
/**
352
 * Implements hook_menu().
353
 */
354
function cdm_dataportal_menu() {
355
  $items = array();
356

    
357
  // @see settings.php.
358
  cdm_dataportal_menu_admin($items);
359
  cdm_dataportal_menu_help($items);
360

    
361
  $items['cdm_dataportal/names'] = array(
362
    'page callback' => 'cdm_dataportal_view_names',
363
    'access arguments' => array('access content'),
364
    'type' => MENU_CALLBACK,
365
  );
366

    
367
  // Optional callback arguments: page.
368
  $items['cdm_dataportal/taxon'] = array(
369
    'page callback' => 'cdm_dataportal_taxon_page_view',
370
    'access arguments' => array('access content'),
371
    'type' => MENU_CALLBACK,
372
    // Expected callback arguments: uuid.
373
  );
374

    
375
   // Optional callback arguments: page.
376
    //FIXME point to view/page method in this module
377
    $items['cdm_dataportal/specimen'] = array(
378
        'page callback' => 'cdm_dataportal_specimen_page_view',
379
        'access arguments' => array('access content'),
380
        'type' => MENU_CALLBACK,
381
        // Expected callback arguments: uuid.
382
    );
383

    
384
  $items['cdm_dataportal/name'] = array(
385
    'page callback' => 'cdm_dataportal_name_page_view',
386
      /*
387
    'page arguments' => array(
388
       'taxon_name_uuid',
389
       'taxon_to_hide_uuid',
390
       'synonym_uuid' => NULL
391
      ),
392
      */
393
    'access arguments' => array('access content'),
394
    'type' => MENU_CALLBACK,
395
    // Expected callback arguments: uuid.
396
  );
397

    
398
  $items['cdm_dataportal/reference'] = array(
399
    'page callback' => 'cdm_dataportal_view_reference',
400
    'access arguments' => array('access content'),
401
    'type' => MENU_CALLBACK,
402
    // Expected callback arguments: uuid.
403
  );
404

    
405
  $items['cdm_dataportal/reference/list'] = array(
406
    'page callback' => 'cdm_dataportal_view_reference_list',
407
    'access arguments' => array('access content'),
408
    'type' => MENU_CALLBACK,
409
    // Expected callback arguments: uuid.
410
  );
411

    
412
  $items['cdm_dataportal/media'] = array(
413
    'page callback' => 'cdm_dataportal_view_media',
414
    'access arguments' => array('access content'),
415
    'type' => MENU_CALLBACK,
416
    // Expected callback arguments:
417
    // uuid, mediarepresentation_uuid, part_uuid or part#.
418
  );
419

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

    
427
  $items['cdm_dataportal/search'] = array(
428
    'page callback' => 'cdm_dataportal_view_search_advanced',
429
    'access arguments' => array('access content'),
430
    'type' => MENU_CALLBACK,
431
  );
432

    
433
  $items['cdm_dataportal/search/advanced'] = array(
434
    'title' => 'Advanced',
435
    'page callback' => 'cdm_dataportal_view_search_advanced',
436
    'access arguments' => array('access content'),
437
    'type' => MENU_DEFAULT_LOCAL_TASK,
438
  );
439

    
440
  $items['cdm_dataportal/search/taxon_by_description'] = array(
441
    'title' => 'By description full text',
442
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
443
    'access arguments' => array('access content'),
444
    'type' => MENU_LOCAL_TASK,
445
  );
446

    
447
  $items['cdm_dataportal/search/results/taxon'] = array(
448
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
449
    'access arguments' => array('access content'),
450
    'type' => MENU_CALLBACK,
451
  );
452
  /*
453
   $items['cdm/xml2json'] = array(
454
   'page callback' => 'cdm_view_xml2json',
455
   'access arguments' => array('access content'),
456
   'type' => MENU_CALLBACK,
457
   );
458
   */
459

    
460
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
461
  // User configuration of cdm_dataportal.
462
  $items['user/%/cdm_dataportal'] = array(
463
    'title' => 'cdm_dataportal',
464
    'access arguments' => array('access content'),
465
    'page callback' => 'drupal_get_form',
466
    'page arguments' => array('cdm_dataportal_user_form'),
467
    'type' => MENU_LOCAL_TASK,
468
    'weight' => 10,
469
  );
470
  // }
471

    
472
  // 'May not cache' in D5.
473
  $items['cdm_dataportal/name/%'] = array(
474
    // 'page callback' => 'cdm_dataportal_view_name',
475
    'page callback' => 'cdm_dataportal_name_page_view',
476
    'page arguments' => array(2, 3, 4),
477
    'access arguments' => array('access content'),
478
    'type' => MENU_CALLBACK,
479
  );
480

    
481
  // --- Local tasks for Taxon.
482
  // --- tabbed taxon page
483
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
484
    $items['cdm_dataportal/taxon/%'] = array(
485
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
486
      'page callback' => 'cdm_dataportal_taxon_page_view',
487
      'access arguments' => array('access content'),
488
      'type' => MENU_CALLBACK,
489
      'weight' => 1,
490
      'page arguments' => array(2, "description")
491
      , // Expected callback arguments: name_uuid.
492
    );
493

    
494
    $items['cdm_dataportal/taxon/%/all'] = array(
495
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
496
      'page callback' => 'cdm_dataportal_taxon_page_view',
497
      'access arguments' => array('access content'),
498
      'type' => MENU_CALLBACK,
499
      'weight' => 2,
500
      'page arguments' => array(2, "all")
501
      , // Expected callback arguments: name_uuid.
502
    );
503

    
504
    $items['cdm_dataportal/taxon/%/description'] = array(
505
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
506
      'page callback' => 'cdm_dataportal_taxon_page_view',
507
      'access arguments' => array('access content'),
508
      'type' => MENU_DEFAULT_LOCAL_TASK,
509
      'weight' => 2,
510
      'page arguments' => array(2, "description")
511
      , // Expected callback arguments: name_uuid.
512
    );
513

    
514
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
515
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
516
      'page callback' => 'cdm_dataportal_taxon_page_view',
517
      'access arguments' => array('access content'),
518
      'type' => MENU_LOCAL_TASK,
519
      'weight' => 4,
520
      'page arguments' => array(2, "synonymy", 4)
521
      , // Expected callback arguments: name_uuid.
522
    );
523
    $items['cdm_dataportal/taxon/%/images'] = array(
524
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
525
      'page callback' => 'cdm_dataportal_taxon_page_view',
526
      'access arguments' => array('access content'),
527
      'type' => MENU_LOCAL_TASK,
528
      'weight' => 5,
529
      'page arguments' => array(2, "images")
530
      , // Expected callback arguments: name_uuid.
531
    );
532

    
533
    $items['cdm_dataportal/taxon/%/specimens'] = array(
534
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
535
      'page callback' => 'cdm_dataportal_taxon_page_view',
536
      'access arguments' => array('access content'),
537
      'type' => MENU_LOCAL_TASK,
538
      'weight' => 6,
539
      'page arguments' => array(2, "specimens")
540
      , // Expected callback arguments: name_uuid.
541
    );
542

    
543
    $items['cdm_dataportal/taxon/%/keys'] = array(
544
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
545
      'page callback' => 'cdm_dataportal_taxon_page_view',
546
      'access arguments' => array('access content'),
547
      'type' => MENU_LOCAL_TASK,
548
      'weight' => 6,
549
      'page arguments' => array(2, "keys")
550
      , // Expected callback arguments: name_uuid.
551
    );
552
  }
553

    
554
  // --- refresh link for all cdmnode types
555
  foreach (cdm_get_nodetypes() as $type=>$name) {
556
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
557
        'title' => t('Refresh'),
558
        'page callback' => 'cdm_dataportal_refresh_node',
559
        'access arguments' => array('administer cdm_dataportal'),
560
        'type' => MENU_LOCAL_TASK,
561
        'weight' => 100,
562
        'page arguments' => array($name, 2)
563
    );
564
  }
565

    
566
  return $items;
567
}
568

    
569
/**
570
 * Implements hook_init().
571
 *
572
 */
573
function cdm_dataportal_init() {
574
  //FIXME To add CSS or JS that should be present on all pages, modules
575
  //      should not implement this hook, but declare these files in their .info file.
576
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
577
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
578
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
579

    
580
  if(variable_get('cdm_debug_mode', FALSE)){
581
    $file = 'temporary://drupal_debug.txt';
582
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
583
  }
584

    
585
  $bibliography_settings = get_bibliography_settings();
586
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
587
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
588
}
589

    
590
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
591

    
592
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
593

    
594
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
595
    // force reloading of all and notify user about this special loading
596
    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: ')
597
        . l('Back to tabbed taxon page', $base_path));
598
    $base_path .= '/all';
599
  } else {
600
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
601
  }
602

    
603
  $parameters['cacheL2_refresh'] ='1';
604

    
605

    
606
  drupal_goto($base_path, array('query' => $parameters));
607
}
608

    
609
/**
610
 * The function generate form for own user cdm dataportal configurations.
611
 */
612
function cdm_dataportal_user_form($form, &$form_state) {
613
  global $user;
614
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
615

    
616
  $form['taxon_page_tabs'] = array(
617
      '#type' => 'fieldset',
618
      '#title' => t('Taxon page tabs'),
619
  );
620
  $form['taxon_page_tabs']['check'] = array(
621
    '#type' => 'checkbox',
622
    '#title' => t('Activate user default configuration'),
623
    '#default_value' => variable_get($checkbox_value, 0),
624
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
625
  );
626

    
627
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
628
    '#type' => 'select',
629
    '#title' => t('Default tab to display'),
630
    '#default_value' => get_default_taxon_tab(TRUE),
631
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
632
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
633
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
634
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
635
  );
636

    
637
  $form['submit'] = array(
638
    '#type' => 'submit',
639
    '#value' => t('Submit'),
640
  );
641

    
642
  return $form;
643
}
644

    
645
/**
646
 * Form submission handler for user_form().
647
 *
648
 * Submits the user cdm dataportal configurations.
649
 */
650
function cdm_dataportal_user_form_submit($form, &$form_state) {
651
  global $user;
652
  $msg_type = 'status';
653
  $username = $user->name;
654
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
655

    
656
  // If is the right user the variables are setted.
657
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
658
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
659
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
660
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
661
    if ($form_state['values']['check']) {
662
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
663
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
664
        '!tab' => $variable[variable_get($variable_to_use, 0)],
665
        '!user' => $username,
666
      ))), $msg_type);
667
    }
668
    else {
669
      drupal_set_message(check_plain(t('The user default tab wont be used for
670
        the next taxon site, check the box if you want to use the user default configuration.')));
671
    }
672
    // Problem with the user id => variables wont be saved.
673
  }
674
  else {
675
    $msg_type = 'warning';
676
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
677
  }
678
}
679

    
680
/**
681
 * Implements hook_block_info().
682
 */
683
function cdm_dataportal_block_info() {
684

    
685
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
686
    // $block[1]["info"] = t("CDM DataPortal Credits");
687
    $block["2"] = array(
688
        "info" => t("CDM Search Taxa"),
689
        "cache" => DRUPAL_NO_CACHE
690
      );
691
    // $block[3]["info"] = t("CDM Filters");
692
    $block["4"]["info"] = t("CDM Dataportal Print");
693
    $block["keys"]["info"] = t("CDM identification keys");
694
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
695

    
696
    return $block;
697
}
698

    
699
/**
700
 * Implements hook_block_view().
701
 */
702
function cdm_dataportal_block_view($delta) {
703
  // TODO Rename block deltas (e.g. '2') to readable strings.
704
  switch ($delta) {
705
    // case 'delta-1':
706
    // $block['subject'] = t('Credits');
707
    // $block['content'] = theme('cdm_credits');
708
    // return $block;
709
    case '2':
710
      $block['subject'] = t('Search taxa');
711
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
712
      $block['content'] = drupal_render($form);
713

    
714
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
715
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
716
      }
717
      return $block;
718
    case '4':
719
      $block['subject'] = '';
720
      $block['content'] = theme('cdm_print_button');
721
      return $block;
722
    case "keys":
723
      $block['subject'] = t('Identification Keys');
724
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
725
      return $block;
726
    case "fundedByEDIT":
727
      // t('Funded by EDIT');
728
      $text = '<none>';
729
      $block['subject'] = $text;
730
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
731
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
732
        'attributes' => array("target" => "EDIT"),
733
        'absolute' => TRUE,
734
        'html' => TRUE,
735
      ));
736
      return $block;
737
  }
738
}
739

    
740
/*
741
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
742
 $_SESSION['cdm'] = NULL;
743
 if(is_string($cdm_ws_uri_update)){
744
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
745
 }
746
 }
747

    
748
 function cdm_dataportal_session_validate(){
749
 if(!isset($_SESSION['cdm']['ws_uri'])){
750
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
751
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
752
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
753
 }
754
 }
755
 */
756

    
757
/**
758
 * creates a  selector form for taxonomic trees.
759
 *
760
 * @return a drupal form array
761
 */
762
function cdm_taxonomictree_selector() {
763
  _add_js_treeselector();
764

    
765
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
766
  return $form;
767
}
768

    
769
/**
770
 * @todo Please document this function.
771
 * @see http://drupal.org/node/1354
772
 */
773
function cdm_taxonomictree_selector_form($form, &$form_state) {
774

    
775
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
776
  $form['#action'] = $url;
777

    
778
  $form['var'] = array(
779
    '#weight' => -3,
780
    '#type' => 'hidden',
781
    '#value' => '[cdm][taxonomictree_uuid]',
782
  );
783

    
784
  $destination_array = drupal_get_destination();
785
  $destination = $destination_array['destination'];
786

    
787
  $form['destination'] = array(
788
    '#weight' => -3,
789
    '#type' => 'hidden',
790
    '#value' =>  $destination,
791
  );
792

    
793
  $options = cdm_get_taxontrees_as_options();
794
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
795
  if($taxontree_includes){
796
    $filtered_options = array();
797
    foreach($options as $uuid=>$label){
798
      if(!empty($taxontree_includes[$uuid])){
799
        $filtered_options[$uuid] = $label;
800
      }
801
    }
802
    $options = $filtered_options;
803
  }
804

    
805
  $form['val'] = array(
806
    '#type' => 'select',
807
    '#title' => t('Available classifications'),
808
    '#default_value' => get_taxonomictree_uuid_selected(),
809
    '#options' => $options,
810
    '#attributes' => array('class' => array('highlite-first-child'))
811
  );
812

    
813
  return $form;
814

    
815
}
816

    
817
/* UNREACHABLE since action of form directly links to view.
818
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
819

    
820
 $_SESSION['cdm']['search'] = $form_values;
821
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
822
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
823
 //$paramstr = compose_url_prameterstr($form_values);
824
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
825
 }
826
 */
827
/* ====================== menu callback functions ====================== */
828
/**
829
 * @todo Please document this function.
830
 * @see http://drupal.org/node/1354
831
 */
832
/*
833
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
834
  static $comment_node_disabled =  0;
835
  static $comment_node_read_only =  1;
836
  static $comment_node_read_write =  2;
837

    
838
  if ($form_id == 'node_type_form'
839
   && isset($form['identity']['type'])
840
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
841
  ) {
842
    $form['workflow']['comment'] = array(
843
      '#type' => 'radios',
844
      '#title' => t('Default comment setting'),
845
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
846
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
847
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
848
    );
849
  }
850
}
851
*/
852

    
853
/**
854
 * Displays a list of the known taxonomic names.
855
 *
856
 * When the list of taxonomic names is displayed, long lists are split up into
857
 * multiple pages.
858
 *
859
 * TODO: Parameters are still preliminary.
860
 *
861
 * @param string $beginsWith
862
 * @param string $page
863
 *   Page number to diplay defaults to page 1.
864
 * @param bool $onlyAccepted
865
 */
866
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
867

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

    
870
  /*
871
  // FIXME the filter for accepted names will be a form element, thus this
872
  // widget should be generated via form api preferably as block.
873
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
874
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
875
  $out .= theme('cdm_listof_taxa', $taxonPager);
876
  return $out;
877
  */
878
}
879

    
880
/**
881
 * @todo Please document this function.
882
 * @see http://drupal.org/node/1354
883
 */
884
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
885

    
886
  cdm_check_valid_portal_page();
887

    
888
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
889
  return theme('cdm_reference_page', array('reference' => $reference));
890
}
891

    
892
/**
893
 * Created a view on a all references contained in the portal.
894
 *
895
 * This function is used at the path cdm_dataportal/reference/list
896
 */
897
function cdm_dataportal_view_reference_list($pageNumber) {
898
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
899
  return theme('cdm_reference_pager', array(
900
    'referencePager' => $referencePager,
901
    'path' => 'cdm_dataportal/reference/list/',
902
    ));
903
}
904

    
905
/**
906
 * @todo Please document this function.
907
 * @see http://drupal.org/node/1354
908
 */
909
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
910

    
911
  cdm_check_valid_portal_page();
912

    
913
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
914
  return theme('cdm_media_page', array(
915
    'media' => $media,
916
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
917
    'partId' => $part,
918
    ));
919
}
920

    
921
/**
922
 * @todo Please document this function.
923
 * @see http://drupal.org/node/1354
924
 */
925
function _load_taxonBase(&$taxonBase) {
926
  if (isset($taxonBase->uuid)) {
927
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
928
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
929
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
930
  }
931
}
932

    
933
/**
934
 * Loads the media associated to the given taxon from the cdm server.
935
 * The aggregation settings regarding taxon relathionships and
936
 * taxonnomic childen are taken into account.
937
 *
938
 * The media lists are cached in a static variable.
939
 *
940
 * @param Taxon $taxon
941
 *   A CDM Taxon entitiy
942
 *
943
 * @return array
944
 *   An array of CDM Media entities
945
 *
946
 */
947
function _load_media_for_taxon($taxon) {
948

    
949
  static $media = NULL;
950

    
951
  if(!isset($media)) {
952
    $media = array();
953
  }
954
  if (!isset($media[$taxon->uuid])) {
955

    
956
    // --- GET Images --- //
957
    $mediaQueryParameters = array(
958
        "type" => "ImageFile",
959
    );
960

    
961
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
962
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
963
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
964

    
965
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
966
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
967
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
968
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
969

    
970
    $ws_endpoint = NULL;
971
    if ( variable_get('cdm_images_include_children', 0) == 0) {
972
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
973
    } else {
974
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
975
    }
976

    
977
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
978
        array(
979
            $taxon->uuid,
980
        ),
981
        queryString($mediaQueryParameters)
982
       );
983
  }
984

    
985
  return $media[$taxon->uuid];
986
}
987

    
988
/**
989
 *
990
 * @param Taxon $taxon
991
 *   A CDM Taxon entitiy
992
 *
993
 * @return array
994
 *   An array of CDM SpecimenOrObservation entities
995
 *
996
function _load_occurences_for_taxon($taxon){
997

    
998
  static $occurences = NULL;
999

    
1000
  if(!isset($occurences)) {
1001
    $occurences = array();
1002
  }
1003

    
1004
  if (!isset($occurences[$taxon->uuid])){
1005

    
1006
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1007
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1008
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1009

    
1010
    $by_associatedtaxon_query = http_build_query(array(
1011
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1012
        'relationships' => implode(',', $relationship_choice['direct']),
1013
        'pageSize' => null // all hits in one page
1014
    )
1015
    );
1016

    
1017
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1018
        null,
1019
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1020
    );
1021

    
1022

    
1023
    if(isset($pager->records[0])){
1024
      $occurences[$taxon->uuid] =  $pager->records;
1025
    }
1026
  }
1027
  return $occurences[$taxon->uuid];
1028
}
1029
 */
1030

    
1031
/**
1032
 * Gets a Drupal variable, string or array and returns it.
1033
 *
1034
 * Similar to the variable_get() function of Drupal, except that this function
1035
 * is able to handle arrays correctly. This function is especially useful
1036
 * when dealing with collections of settings form elements (#tree = TRUE).
1037
 *
1038
 * @param string $variableKey
1039
 *   The Unique key of the Drupal variable in the Drupal variables table.
1040
 * @param string $defaultValueString
1041
 *   A string as for example derived from a CONSTANT.
1042
 *
1043
 * @return mixed
1044
 *   usually an array, depending on the nature of the variable.
1045
 *
1046
 * TODO compare with get_array_variable_merged() duplicate functions?
1047
 * @deprecated rather use get_array_variable_merged() since this function
1048
 * used an array as second parameter
1049
 */
1050
function mixed_variable_get($variableKey, $defaultValueString) {
1051
  $systemDefaults = unserialize($defaultValueString);
1052
  $storedSettings = variable_get($variableKey, array());
1053
  if (is_array($storedSettings)) {
1054
    // TODO better use drupal_array_merge_deep() ?
1055
    $settings = array_merge($systemDefaults, $storedSettings);
1056
  }
1057
  else {
1058
    $settings = $systemDefaults;
1059
  }
1060
  return $settings;
1061
}
1062

    
1063
/**
1064
 * Recursive function to convert an object into an array.
1065
 * also subordinate objects will be converted.
1066
 *
1067
 * @param object $object
1068
 * @return the array
1069
 */
1070
function convert_to_array($object) {
1071
  if(is_object($object) || is_array($object)) {
1072
    $array = (array)$object;
1073
    foreach ($array as $key=>$value){
1074
      $array[$key] = convert_to_array($value);
1075
    }
1076
    return $array;
1077
  } else {
1078
    return $object;
1079
  }
1080
}
1081

    
1082
/**
1083
 * Searches the $collection for the cdm entitiy given as $element.
1084
 *
1085
 * The elements are compared by their UUID.
1086
 *
1087
 * @param $element
1088
 *  the CDM entitiy to search for
1089
 * @param $collection
1090
 *  the list of CDM entities to search in
1091
 *
1092
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1093
 *
1094
 */
1095
function contains_cdm_entitiy($element, $collection) {
1096
  $result = FALSE;
1097
  foreach ($collection as $a) {
1098
    if ($a->uuid == $element->uuid) {
1099
      $result = TRUE;
1100
    }
1101
  }
1102
  return $result;
1103
}
1104

    
1105
/**
1106
 * Fiters the array $entity_list of CDM entities by the list
1107
 * of $excludes. Any element contained in the $excludes will be removed
1108
 * from included int the retuned list.
1109
 *
1110
 * If the $entity_list is not an array the $excludes will be returned.
1111
 */
1112
function filter_cdm_entity_list($entity_list, $excludes) {
1113
  if (is_array($entity_list)) {
1114
    $result = $entity_list;
1115
    if ($excludes) {
1116
      foreach ($excludes as $exclude) {
1117
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1118
          $result[] = $exclude;
1119
        }
1120
      }
1121
    }
1122
  }
1123
  else {
1124
    $result = $excludes;
1125
  }
1126
  return $result;
1127
}
1128

    
1129
/**
1130
 * Wraps the given $html string into a render array suitable for drupal_render()
1131
 *
1132
 * @param $html
1133
 *   the html string, see
1134
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1135
 * @param $weight
1136
 *   A positive or negative number (integer or decimal).
1137
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1138
 * @param $prefix
1139
 *   Optional markup for the '#prefix' element of the render array
1140
 * @param $suffix
1141
 *   Optional markup for the '#suffix' element of the render array
1142
 *
1143
 * @return array
1144
 *   A render array
1145
 *
1146
 */
1147
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1148
  $render_array = array(
1149
    '#markup' => $html
1150
      );
1151
  if (is_numeric($weight)) {
1152
    $render_array['#weight'] = $weight;
1153
  }
1154
  if($prefix){
1155
    $render_array['#prefix'] = $prefix;
1156
  }
1157
  if($suffix) {
1158
    $render_array['#suffix'] = $suffix;
1159
  }
1160
  return $render_array;
1161
}
1162

    
1163
/**
1164
 * Loads the subgraph of a given PolytomousKeyNode.
1165
 *
1166
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1167
 * the CDM REST service.
1168
 *
1169
 * @param mixed $polytomousKeyNode
1170
 *   PolytomousKeyNode passed by reference.
1171
 *
1172
 * @return void
1173
 */
1174
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1175

    
1176
  if (!$polytomousKeyNode) {
1177
    return;
1178
  }
1179
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1180
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1181
    return;
1182
  }
1183
  if (!is_uuid($polytomousKeyNode->uuid)) {
1184
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1185
    return;
1186
  }
1187

    
1188
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1189

    
1190
  if (!$polytomousKeyNode) {
1191
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1192
    return;
1193
  }
1194

    
1195
  // Load children.
1196
  foreach ($polytomousKeyNode->children as &$childNode) {
1197
    _load_polytomousKeySubGraph($childNode);
1198
  }
1199

    
1200
  // Load subkey.
1201
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1202

    
1203
  // Load taxon.
1204
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1205
  _load_taxonBase($polytomousKeyNode->taxon);
1206
  return;
1207
}
1208

    
1209
/**
1210
 * @todo Please document this function.
1211
 * @see http://drupal.org/node/1354
1212
 */
1213
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1214

    
1215
  cdm_check_valid_portal_page();
1216

    
1217
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1218

    
1219
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1220
  if (is_array($sourcePager->records)) {
1221
    $polytomousKey->sources = $sourcePager->records;
1222
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1223
  }
1224

    
1225
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1226
  if (is_array($annotationPager->records)) {
1227
    $polytomousKey->annotations = $annotationPager->records;
1228
  }
1229

    
1230
  _load_polytomousKeySubGraph($polytomousKey->root);
1231
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1232
}
1233

    
1234
/**
1235
 * Creates a taxon page view or a chapter of it.
1236
 *
1237
 * The taxon page gives detailed information on a taxon, it shows:
1238
 *  - Taxon name.
1239
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1240
 *    heterotypic and finally followed by misapplied names.
1241
 *    The list is ordered historically.
1242
 *  - All description associated with the taxon.
1243
 *
1244
 * @param string $uuid
1245
 * @param string $chapter
1246
 *   Name of the part to display, valid values are:
1247
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1248
 *
1249
 * @return unknown_type
1250
 */
1251
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1252

    
1253
  cdm_check_valid_taxon_page($chapter);
1254
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1255
  // show a warning in case the javascript development mode is anabled
1256
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1257
    drupal_set_message(t('The !url1 is enabled.
1258
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1259
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1260
    )),
1261
    'warning'
1262
        );
1263
  }
1264

    
1265
  // Display the page for the taxon defined by $uuid.
1266
  // set_last_taxon_page_tab(arg(3));
1267
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1268
  if (!empty($taxonpage)) {
1269
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1270
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1271
  }
1272
  else {
1273
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1274
    return '';
1275
  }
1276
}
1277

    
1278
/**
1279
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1280
 * which has two fields, one for the page title and one for the content. Later on in the
1281
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1282
 * function as the function parameters $title and $content.
1283
 *
1284
 * @param string $uuid
1285
 *   the uuid of the taxon to show
1286
 * @param string $chapter
1287
 *   Name of the part to display, valid values are:
1288
 *   'description', 'images', 'synonymy', 'all'.
1289
 *
1290
 * @return taxonpage object with the following fields:
1291
 *   - title : the title of the page
1292
 *   - content: the content of the page
1293
 *
1294
 */
1295
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1296
  // Taxon object.
1297
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1298
  if (empty($taxon)) {
1299
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1300
    return FALSE;
1301
  }
1302
  $taxonpage = new stdClass();
1303

    
1304
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1305
    'taxon' => $taxon
1306
  ));
1307

    
1308
  // Check if the taxon id contained in the currently selected tree.
1309
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1310

    
1311
  if (!$taxon_in_current_tree) {
1312
    $classifications = get_classifications_for_taxon($taxon);
1313
    if (count($classifications) == 0) {
1314
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1315
        '!taxonname' => render_taxon_or_name($taxon->name),
1316
      ))), 'warning');
1317
    }
1318
    else {
1319
      $trees = '';
1320
      foreach ($classifications as $classification) {
1321
        if (isset($classification->titleCache)) {
1322
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1323
        }
1324
      }
1325

    
1326
      drupal_set_message(format_plural(count($trees),
1327
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1328
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1329
          array('!taxonname' => render_taxon_or_name($taxon), '!trees' => $trees)) , 'warning');
1330
    }
1331
  }
1332

    
1333
  // Render the taxon page.
1334
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1335
  $taxonpage->content = drupal_render($render_array);
1336

    
1337
  return $taxonpage;
1338
}
1339

    
1340
/**
1341
 * Creates a specimen page view.
1342
 * @param string $uuid the UUID of the specimen
1343
 * @return array|string
1344
 */
1345
function cdm_dataportal_specimen_page_view($uuid) {
1346

    
1347
    //cdm_check_valid_taxon_page($chapter);
1348
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1349
    // show a warning in case the javascript development mode is anabled
1350
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1351
        drupal_set_message(t('The !url1 is enabled.
1352
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1353
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1354
        )),
1355
            'warning'
1356
        );
1357
    }
1358

    
1359
    // Display the page for the specimen defined by $uuid.
1360
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1361
    if (!empty($specimenpage)) {
1362
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1363
    }
1364
    else {
1365
        return '';
1366
    }
1367
}
1368

    
1369
/**
1370
 *
1371
 * Creates a specimen view.
1372
 * @param string $uuid the UUID of the specimen
1373
 * @return array|string
1374
 */
1375
function cdm_dataportal_specimen_view($uuid) {
1376
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1377
    if (empty($specimen)) {
1378
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1379
        return FALSE;
1380
    }
1381
    $specimenpage = new stdClass();
1382

    
1383
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1384
        'specimen' => $specimen
1385
    ));
1386

    
1387
    // Render the specimen page.
1388
    $render_array = compose_cdm_specimen_page($uuid);
1389
    $specimenpage->content = drupal_render($render_array);
1390

    
1391
    return $specimenpage;
1392
}
1393

    
1394
/**
1395
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1396
 *
1397
 * The node page shows the taxon name title and the list of taxon related
1398
 * with such taxon. Name on the tree already in use.
1399
 *
1400
 * @param UUID $taxon_name_uuid
1401
 *   The uuid of the CDM TaxonNameBase to show a name page for
1402
 * @param UUID $taxon_to_hide_uuid
1403
 *   A taxon which should not be displayed in the taxon list
1404
 * @param UUID $highlite_synonym_uuid
1405
 *   Optinal parameter wich takes another taxon uuid, if given the
1406
 *   target taxon pages will show the syonymy tab where the taxon
1407
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1408
 *   in case it is found on this page.
1409
 *
1410
 * @return mixed
1411
 *   The formatted name page as node.
1412
 */
1413
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1414

    
1415
  cdm_check_valid_portal_page();
1416

    
1417
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1418
  if (!empty($taxonname_page)) {
1419
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1420
  }
1421
  else {
1422
    return '';
1423
  }
1424
}
1425

    
1426
/**
1427
 * View function for a TaxonNameBase page.
1428
 *
1429
 * The name page lists all taxa for which the name specified by the
1430
 * $taxon_name_uuid is being used. I case there is only one name the
1431
 * page automatically redirects ti the according taxon page. Otherwise
1432
 * the list of names is displayed.
1433
 *
1434
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1435
 * list of taxa. This is useful for example when referencing from a taxon
1436
 * to the name page and the referring taxon should not be repeaded in the
1437
 * name page.
1438
 *
1439
 *
1440
 * @param UUID $taxon_name_uuid
1441
 *   The uuid of the CDM TaxonNameBase to show a name page for
1442
 * @param UUID $taxon_to_hide_uuid
1443
 *   A taxon which should not be displayed in the taxon list
1444
 * @param UUID $highlite_synonym_uuid
1445
 *   Optinal parameter wich takes another taxon uuid, if given the
1446
 *   target taxon pages will show the syonymy tab where the taxon
1447
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1448
 *   in case it is found on this page.
1449
 *
1450
 * @return object
1451
 *   An object with two fields:
1452
 *     - title: the page title
1453
 *     - content: the page content
1454
 */
1455
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1456
  // Getting the full taxonname object from the server.
1457
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1458
  if (!$taxon_name) {
1459
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1460
    return FALSE;
1461
  }
1462
  // Searching for all the taxa connected with the taxon name on the tree
1463
  // in use.
1464
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1465
  $request_params = array();
1466
  $request_params['query'] = $name_cache;
1467
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1468
  $request_params['doTaxa'] = 1;
1469
  $request_params['doSynonyms'] = 1;
1470
  $request_params['doTaxaByCommonNames'] = 0;
1471
  $request_params['matchMode'] = "EXACT";
1472
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1473

    
1474
  // Removing the name where we come from.
1475
  foreach ($taxon_pager->records as $k => &$taxon) {
1476
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1477
      unset($taxon_pager->records[$k]);
1478
    }
1479
  }
1480
  // Show the taxa list or go to the singular taxon.
1481
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1482
    $singleTaxon = array_pop($taxon_pager->records);
1483
    if ($singleTaxon->class != "Taxon") {
1484
      // It is a Synonym -> look for the accepted.
1485
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1486
      if (!empty($highlite_synonym_uuid)) {
1487
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1488
      }
1489
      else {
1490
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1491
      }
1492
    }
1493
    else {
1494
      // It is an accepted taxon.
1495
      if (!empty($highlite_synonym_uuid)) {
1496
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1497
      }
1498
      else {
1499
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1500
      }
1501
    }
1502
  }
1503
  else {// More than one taxa case.
1504
    $taxon_name_page = new stdClass();
1505
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1506
    if ($taxon_pager->records) {
1507
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1508
    }
1509
    else {
1510
      $taxon_name_page->content = 'This name has no taxa';
1511
    }
1512
    return $taxon_name_page;
1513
  }
1514
}
1515

    
1516
/**
1517
 * Creates a page with the advance search form.
1518
 *
1519
 * NOTE: The advance search form allows searching for taxa.
1520
 */
1521
function cdm_dataportal_view_search_advanced() {
1522
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1523
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1524
}
1525

    
1526
/**
1527
 * Creates a page with the search form for searching by taxon descriptions.
1528
 */
1529
function cdm_dataportal_view_search_taxon_by_description() {
1530
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1531
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1532
}
1533

    
1534
/**
1535
 * Executes the search and generates the result list of taxa.
1536
 */
1537
function cdm_dataportal_view_search_results_taxon() {
1538

    
1539
  $taxonPager = cdm_dataportal_search_execute();
1540

    
1541
  $showThumbnails = do_showThumbnails();
1542

    
1543
  $setSessionUri = url('cdm_api/setvalue/session', array(
1544
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1545
  ));
1546

    
1547
  drupal_add_js('jQuery(document).ready(function() {
1548

    
1549
      // init
1550
      if(' . $showThumbnails . ' == 1){
1551
      jQuery(\'.media_gallery\').show(20);
1552
  } else {
1553
      jQuery(\'.media_gallery\').hide(20);
1554
  }
1555
      // add change hander
1556
      jQuery(\'#showThumbnails\').change(
1557
      function(event){
1558
      var state = 0;
1559
      if(jQuery(this).is(\':checked\')){
1560
      jQuery(\'.media_gallery\').show(20);
1561
      state = 1;
1562
  } else {
1563
      jQuery(\'.media_gallery\').hide(20);
1564
  }
1565
      // store state in session variable
1566
      var uri = \'' . $setSessionUri . '\' + state;
1567
      jQuery.get(uri);
1568
  });
1569
  });',
1570
  array('type' => "inline", 'scope' => JS_DEFAULT));
1571

    
1572
  drupal_set_title(t('Search results'), PASS_THROUGH);
1573

    
1574
  return theme('cdm_search_results', array(
1575
    'pager' => $taxonPager,
1576
    'path' => 'cdm_dataportal/search/results/taxon',
1577
    ));
1578
}
1579

    
1580
/**
1581
 * Provides the standart image wich indicated a loading process
1582
 *
1583
 * @return string
1584
 *  The img html tag
1585
 */
1586
function loading_image_html() {
1587
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1588
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1589
}
1590

    
1591
/**
1592
 * Returns the state of the the showThumbnails flag set in the
1593
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1594
 *
1595
 * @return boolean
1596
 *    returns 1 if the flag is set
1597
 */
1598
function do_showThumbnails() {
1599
  static $showThumbnails = null;
1600

    
1601
  if($showThumbnails == null) {
1602
    $showThumbnails = 0;
1603
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1604
      $showThumbnails = 0;
1605
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1606
      $showThumbnails = is_array($search_gallery_settings)
1607
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1608
        && (
1609
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1610
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1611
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1612
            )
1613
         ? 1 : 0;
1614

    
1615
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1616
    }
1617
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1618
    if (!is_numeric($showThumbnails)) {
1619
      $showThumbnails = 1;
1620
    }
1621
  }
1622

    
1623
  return $showThumbnails;
1624
}
1625

    
1626
/**
1627
 * View which transforms XML output from a given webservice endpoint into JSON.
1628
 */
1629
/*
1630
 function cdm_view_xml2json(){
1631
 $file = arg(2);
1632
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1633
 return  xml2json::transformXmlStringToJson($datastr);
1634
 }
1635
 */
1636

    
1637
/* ====================== other functions ====================== */
1638
/**
1639
 * Creates a URL to the taxon page specified by the $uuid parameter.
1640
 *
1641
 * The URL will be prepended with a path element to a specific taxon page tab.
1642
 *
1643
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1644
 * be set globally in the administrative settings or individually in the user
1645
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1646
 * the last portal will stay on this last tab.
1647
 *
1648
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1649
 * internal mechanism by a specific value.
1650
 *
1651
 * @param string $uuid
1652
 *   The UUID of the taxon.
1653
 * @param string $page_tab
1654
 *   Overwriting the preset mechanism by defining specific value for the
1655
 *   taxon page tab.
1656
 *
1657
 * @return string
1658
 *   The created URL.
1659
 */
1660
function path_to_taxon($uuid, $page_tab = FALSE) {
1661

    
1662
  $tab = get_default_taxon_tab();
1663
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1664

    
1665
  if (!$uuid) {
1666
    return FALSE;
1667
  }
1668

    
1669
  if ($page_tab) {
1670
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1671
  }
1672
  elseif (!$tab || strtolower($tab) == 'general') {
1673
    return 'cdm_dataportal/taxon/' . $uuid;
1674
  }
1675
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1676
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1677
  }
1678
  else {
1679
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1680
  }
1681
}
1682

    
1683
function path_to_specimen($uuid) {
1684

    
1685
    if (!$uuid) {
1686
        return FALSE;
1687
    }
1688
    else {
1689
        return 'cdm_dataportal/specimen/' . $uuid;
1690
    }
1691
}
1692

    
1693
/**
1694
 * Creates a URL to show a synonmy in the according taxon page.
1695
 *
1696
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1697
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1698
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1699
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1700
 * in the page
1701
 *
1702
 * @param string $synonymUuid
1703
 *    The uuid of the synonym
1704
 * @param string $acceptedUuid
1705
 *    The uuid of the according accepted taxon
1706
 * @return string
1707
 *    The URL to show a synonmy in the according taxon page
1708
 */
1709
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1710
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1711
  return url($acceptedPath, array(
1712
      'query' => array(
1713
        // highlite the synony in the synonymy
1714
        'highlite' => $synonymUuid,
1715
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1716
        // see theme_taxon_page_title()
1717
        'acceptedFor' => $synonymUuid
1718
      ),
1719
      'fragment' => $synonymUuid
1720
  ));
1721

    
1722
}
1723

    
1724
/**
1725
 * Compses the drupal path to the key identified by the uuid.
1726
 *
1727
 * @param string $keyType
1728
 *    the key typer corresponds to the specific class of the CDM
1729
 *    IdentificationKey. Possible values are
1730
 *      -PolytomousKey
1731
 *      -MultimediaKey
1732
 *      - ...
1733
 * @param UUID $keyUuid
1734
 *   The UUID of the key
1735
 */
1736
function path_to_key($keyType, $keyUuid) {
1737
  if (!$keyUuid || !$keyType) {
1738
    return FALSE;
1739
  }
1740
  $keyType{0} = strtolower($keyType{0});
1741
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1742
}
1743

    
1744
/**
1745
 * @todo Please document this function.
1746
 * @see http://drupal.org/node/1354
1747
 */
1748
function path_to_reference($uuid) {
1749
  if (!$uuid) {
1750
    return FALSE;
1751
  }
1752
  return 'cdm_dataportal/reference/' . $uuid;
1753
}
1754

    
1755
/**
1756
 * Creates the path to a cdm_dataportal taxon name page.
1757
 *
1758
 * @param UUID $taxon_name_uuid
1759
 *   The uuid of the CDM TaxonNameBase to show a name page for
1760
 * @param UUID $taxon_to_hide_uuid
1761
 *   A taxon which should not be displayed in the taxon list
1762
 * @param UUID $highlite_synonym_uuid
1763
 *   Optinal parameter wich takes another taxon uuid, if given the
1764
 *   target taxon pages will show the syonymy tab where the taxon
1765
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1766
 *   in case it is found on this page.
1767
 *
1768
 * @return a URI path element as string
1769
 */
1770
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1771
  $res = FALSE;
1772
  if ($name_uuid) {
1773
    $res = 'cdm_dataportal/name/' . $name_uuid;
1774
  }
1775
  if($taxon_to_hide_uuid){
1776
    $res .= '/' . $taxon_to_hide_uuid;
1777
    if($synonym_uuid){
1778
      $res .= '/' . $synonym_uuid;
1779
    }
1780
  }
1781
  return $res;
1782
}
1783

    
1784
/**
1785
 * @todo Please document this function.
1786
 * @see http://drupal.org/node/1354
1787
 */
1788
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1789
  if (!$uuid) {
1790
    return FALSE;
1791
  }
1792
  $out = 'cdm_dataportal/media/' . $uuid;
1793
  if ($representaion_uuid) {
1794
    $out .= '/' . $representaion_uuid;
1795
    if ($partId !== FALSE) {
1796
      $out .= '/' . $partId;
1797
    }
1798
  }
1799
  return $out;
1800
}
1801

    
1802
/**
1803
 * Compares thisRank with thatRank.
1804
 *
1805
 * Returns a negative integer, zero, or a positive integer
1806
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1807
 * e.g:
1808
 * <ul>
1809
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1810
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1811
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1812
 * </ul>
1813
 * <p>
1814
 * This compare logic of the underlying webservice is the
1815
 * <b>inverse logic</b> of the the one implemented in
1816
 * java.lang.Comparable#compareTo(java.lang.Object)
1817
 *
1818
 * @param $thisRankUuid
1819
 * @param $thatRankUuid
1820
 *
1821
 * @return int
1822
 *   A negative integer, zero, or a positive integer
1823
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1824
 */
1825
function rank_compare($thisRankUuid, $thatRankUuid) {
1826
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1827
  return $result->Integer;
1828
}
1829

    
1830
/**
1831
 * Composes an HTML element class attribute value composed of
1832
 * the shortname of the cdm class and the uuid of the entity.
1833
 * This class attribute should be used whereever an cdm-entity is rendered.
1834
 *
1835
 * These according class selectors in css must be escaped, eg:
1836
 *    .cdm\:TextData
1837
 *
1838
 * @param $cdmEntity
1839
 */
1840
function html_class_attribute_ref($cdmEntity) {
1841

    
1842
  if (is_cdm_entity($cdmEntity)) {
1843
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1844
  }
1845
}
1846

    
1847
/**
1848
 * Preprocess the taggedTitle arrays.
1849
 *
1850
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
1851
 * into tag type "name"
1852
 *
1853
 * Step 2: Two taggedTexts which have the same type and which have
1854
 * a separator between them are merged together.
1855
 *
1856
 * @param array $taggedTextList
1857
 *    An array of TaggedText objects
1858
 */
1859
function normalize_tagged_title(&$taggedTextList) {
1860

    
1861
  if (is_array($taggedTextList)) {
1862

    
1863
    // First pass: rename.
1864
    for ($i = 0; $i < count($taggedTextList); $i++) {
1865

    
1866
      if ($taggedTextList[$i]->type == "hybridSign") {
1867
        $taggedTextList[$i]->type = "name";
1868
      }
1869
    }
1870

    
1871
    // Second pass: resolve separators.
1872
    $taggedNameListNew = array();
1873
    for ($i = 0; $i < count($taggedTextList); $i++) {
1874

    
1875
      if ($i + 1 < count($taggedTextList) && $taggedTextList[$i + 1]->type == "separator") {
1876
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1877
          $taggedName = clone $taggedTextList[$i];
1878
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1879
          $taggedNameListNew[] = $taggedName;
1880
          ++$i;
1881
          ++$i;
1882
        }
1883
      }
1884
      else {
1885
        $taggedNameListNew[] = $taggedTextList[$i];
1886
      }
1887
    }
1888
    $taggedTextList = $taggedNameListNew;
1889
  }
1890
}
1891

    
1892
function split_secref_from_tagged_title(&$taggedTextList) {
1893

    
1894
  $secref_tt = array();
1895
  if (is_array($taggedTextList)) {
1896
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
1897
      if ($taggedTextList[$i + 1]->type == "secReference" && $taggedTextList[$i]->type == "separator"){
1898
        $secref_tt[0] = $taggedTextList[$i];
1899
        $secref_tt[1] = $taggedTextList[$i + 1];
1900
        unset($taggedTextList[$i]);
1901
        unset($taggedTextList[$i + 1]);
1902
      }
1903
    }
1904
  }
1905
  return $secref_tt;
1906
}
1907
/**
1908
 * Creates a short taxonname.
1909
 *
1910
 * The short name is created by using the taggename field of
1911
 * NameSTO or NameTO instances.
1912
 * If the taggename if empty the fullname will be returned.
1913
 *
1914
 * @param unknown_type $name
1915
 *   Name or TreeNode.
1916
 *
1917
 * @return string
1918
 */
1919
function cdm_dataportal_shortname_of($name) {
1920
  $nameStr = '';
1921

    
1922
  normalize_tagged_title($name->taggedTitle);
1923

    
1924
  // Get all tagged text tokens of the scientific name.
1925
  foreach ($name->taggedTitle as $tagtxt) {
1926
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1927
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1928
    }
1929
  }
1930
  $nameStr = trim($nameStr);
1931

    
1932
  if ($nameStr) {
1933

    
1934
    // Do not return short names for these.
1935
    if ($name->unplaced || $name->excluded) {
1936
      return $nameStr;
1937
    }
1938

    
1939
    /*
1940
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1941
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1942
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1943
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1944
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1945
    */
1946
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1947
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1948
      return $matches[1][0] . "." . $matches[3][0];
1949
    }
1950
    else {
1951
      return $nameStr;
1952
    }
1953
  }
1954
  else {
1955
    return $name->titleCache;
1956
  }
1957
}
1958

    
1959
/**
1960
 * Check if a taxon is accepted by the current taxonomic tree.
1961
 *
1962
 * @param mixed $taxon
1963
 *   The Taxon obkect to check.
1964
 *
1965
 * @return bool
1966
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1967
 */
1968
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1969

    
1970
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1971

    
1972
  if (isset($taxon->taxonNodes)) {
1973
    $taxonNodes = $taxon->taxonNodes;
1974
  }
1975
  else {
1976
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1977
  }
1978

    
1979
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1980
    foreach ($taxonNodes as $node) {
1981
      if (isset($node->classification)){
1982
        if(is_object($node->classification)) {
1983
          if ($node->classification->uuid == $defaultTreeUuid) {
1984
            return TRUE;
1985
          }
1986
        }
1987
        else {
1988
          if ($node->classification == $defaultTreeUuid) {
1989
            return TRUE;
1990
          }
1991
        }
1992
      }
1993
    }
1994
  }
1995

    
1996
  return FALSE;
1997
}
1998

    
1999
/**
2000
 * Checks is the source has one of the given types.
2001
 *
2002
 * @param object $source
2003
 *   The original source entity
2004
 * @param array $types
2005
 *   An array of elementd of the OriginalSourceType enumeration
2006
 *   If not set the default will be used which is:
2007
 *    - Lineage
2008
 *    - PrimaryMediaSource
2009
 *    - PrimaryTaxonomicSource
2010
 *    - Unknown
2011
 *    - Other
2012
 * @return boolean
2013
 */
2014
  function _is_original_source_type($source, $types = null) {
2015
    // this is the default
2016
    // maybe this should also be put into the settings
2017
    static $default = array(
2018
      OriginalSourceType::Lineage,
2019
      OriginalSourceType::PrimaryMediaSource,
2020
      OriginalSourceType::PrimaryTaxonomicSource,
2021
      OriginalSourceType::Unknown,
2022
      OriginalSourceType::Other,
2023
    );
2024

    
2025
    if(!$types){
2026
      $types = $default;
2027
    }
2028
    return isset($source->type) && in_array($source->type, $types);
2029
  }
2030

    
2031
/**
2032
 * @todo Please document this function.
2033
 * @see http://drupal.org/node/1354
2034
 */
2035
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2036
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2037
}
2038

    
2039
/**
2040
 * Gets the metadata info such as title or artist of a media file.
2041
 *
2042
 * The function tries at first to get all the info from the file metadata
2043
 * and if it is not avaible look at the media file info stored at the database.
2044
 *
2045
 * @param mixed $media
2046
 *   The media file object for which to get the metadata.
2047
 *
2048
 * @return array
2049
 *   The array with the available specified metadata info.
2050
 * TODO rename to read_media_metadata() and move to *.module.
2051
 */
2052
function cdm_read_media_metadata($media) {
2053

    
2054
  $metadata_caption = array(
2055
    'title' => '',// Media_metadata and media.
2056
    'artist' => '',// Media_metadata and media.
2057
    'rights',// Media_metadata and media.
2058
    'location',// Media_metadata.
2059
    'filename' => '',// Media.
2060
    'mediacreated' => '',// Media.
2061
    'description' => '',
2062
  );// Media.
2063

    
2064
  // Getting the media metadata.
2065
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
2066
  $media_metadata_aux = (array) $media_metadata;
2067

    
2068
  // Filename.
2069
  if (!empty($media->representations[0]->parts[0]->uri)) {
2070
    $fileUri = $media->representations[0]->parts[0]->uri;
2071
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
2072
    $metadata_caption['filename'] = $filename;
2073
  }
2074
  else {
2075
    $metadata_caption['filename'] = '';
2076
  }
2077

    
2078
  // Title.
2079
  if (!empty($media_metadata->ObjectName)) {
2080
    $metadata_caption['title'] = $media_metadata->ObjectName;
2081
  }
2082
  elseif (!empty($media_metadata_aux['Object Name'])) {
2083
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
2084
  }
2085
  elseif (!empty($media->title_L10n)) {
2086
    $metadata_caption['title'] = $media->title_L10n;
2087
  }
2088
  elseif (!empty($media->titleCache)) {
2089
    $metadata_caption['title'] = $media->titleCache;
2090
  }
2091

    
2092
  // Append description to title.
2093
  if (!empty($media->description_L10n)) {
2094
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
2095
  }
2096

    
2097
  // Artist.
2098
  if (!empty($media_metadata->Artist)) {
2099
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
2100
  }
2101
  elseif (!empty($media->artist->titleCache)) {
2102
    $metadata_caption['artist'] = $media->artist->titleCache;
2103
  }
2104

    
2105
  // Copyright.
2106
  $metadata_caption['rights'] = array(
2107
    'copyright' => array('agentNames' => array()),
2108
    'license' => array(
2109
      'agentNames' => array(),
2110
      'types' => array(),
2111
      'abbreviatedTexts' => array(),
2112
      'uris' => array(),
2113
    ),
2114
  );
2115
  if (!empty($media_metadata->Copyright)) {
2116
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
2117
  }
2118
  elseif (isset($media->rights) && is_array($media->rights)) {
2119
    foreach ($media->rights as $right) {
2120
      if(isset($right->term)){
2121
        switch ($right->type->uuid) {
2122
          case UUID_RIGHTS_LICENCE:
2123
            $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
2124
            $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
2125
            $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
2126
            $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
2127
            break;
2128
          case UUID_RIGHTS_COPYRIGHT:
2129
            $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
2130
            break;
2131
        }
2132
      }
2133
    }
2134
  }
2135
  else {
2136
    $metadata_caption['rights']['agentNames'][] = '';
2137
  }
2138

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

    
2142
  // Location.
2143
  $metadata_caption['location'] = array();
2144
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
2145
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
2146
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
2147
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
2148

    
2149
  /*
2150
   // Creation date.
2151
   if($media_metadata["Modify Date"])
2152
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
2153
   else
2154
   $metadata_caption['mediacreated'] = $media->created;
2155
   */
2156

    
2157
  // Returned value.
2158
  return $metadata_caption;
2159
}
2160

    
2161
/**
2162
 * Collects all the media from a list of description elements.
2163
 *
2164
 * @param array $descriptionElements
2165
 *   The description elements from which to collect the media.
2166
 *
2167
 * @return array
2168
 *   The output with all the collected media.
2169
 */
2170
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2171

    
2172
  $outArrayOfMedia = array();
2173

    
2174
  // Avoiding a warning box in Drupal for Flora Malesiana.
2175
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2176
    foreach ($descriptionElements as $descriptionElement) {
2177
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2178
        foreach ($descriptionElement->media as $media) {
2179
          if (is_object($media)) {
2180
            $outArrayOfMedia[] = $media;
2181
          }
2182
        }
2183
      }
2184
    }
2185
  }
2186
  return $outArrayOfMedia;
2187
}
2188

    
2189
/**
2190
 * @todo Please document this function.
2191
 * @see http://drupal.org/node/1354
2192
 *
2193
 * @param array $cdm_entities
2194
 *   An array of CdmBase instances or a single instance.
2195
 * @param string $footnote_list_key_suggestion
2196
 *
2197
 * @return unknown
2198
 */
2199
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2200

    
2201
   static $annotations_types_filter = null;
2202
   if(!$annotations_types_filter) {
2203
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2204
   }
2205

    
2206
  $footNoteKeys = array();
2207

    
2208
  // Is argument cdmBase an array?
2209
  if (!is_array($cdm_entities)) {
2210
    $cdmBase_array = array();
2211
    $cdmBase_array[] = $cdm_entities;
2212
  }
2213
  else {
2214
    $cdmBase_array = $cdm_entities;
2215
  }
2216

    
2217
  // Getting the key for the footnotemanager.
2218
  if (isset($footnote_list_key_suggestion)) {
2219
    $footnote_list_key = $footnote_list_key_suggestion;
2220
  }
2221
  else {
2222
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2223
  }
2224

    
2225
  // Adding the footnotes keys.
2226
  foreach ($cdmBase_array as $cdmBase_element) {
2227
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2228
    if (is_array($annotations)) {
2229
      foreach ($annotations as $annotation) {
2230
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2231
      }
2232
    }
2233
  }
2234

    
2235
  return $footNoteKeys;
2236
}
2237

    
2238
// @WA Comment: should this not be a theme function?
2239
/**
2240
 *  Creates a CDM Dynabox.
2241
 * @param string $dynabox_id
2242
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice.
2243
 * @param string $label
2244
 *   The clickable text to show.
2245
 * @param string $content_url
2246
 *   The cdm REST service request url wich will deliver the content to be shown
2247
 *   once the dynabox toggles open.
2248
 * @param string $theme
2249
 *   The theme to be used for rendering the cdm REST service response with is
2250
 *   returned from the $content_url.
2251
 * @param string $link_alt_text
2252
 *   The value for the alt attribute of the dynabox link.
2253
 * @param array $enclosingtags
2254
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2255
 *   element itself, $enclosingtags[1] is the tag to be used for the
2256
 *   dynabox_content (optional)
2257
 * @param string $open_callback
2258
 *   optional javascript call back function to be triggered after toggling the box to
2259
 *   the open state.
2260
 * @param string $close_callback
2261
 *   optional javascript call back function to be triggered after toggling the box to
2262
 *   the closed state.
2263
 *
2264
 * @return string
2265
 *   Returns HTML for a dynabox.
2266
 */
2267
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $attributes = array(), $open_callback = 'function(){}', $close_callback = 'function(){}') {
2268
  $out = '';
2269

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

    
2273
  if(!array_key_exists('class', $attributes)) {
2274
    $attributes['class'] = array();
2275
  }
2276
  $attributes['class'][] = 'dynabox-' . $dynabox_id;
2277
  $dynabox_attributes = drupal_attributes($attributes);
2278

    
2279

    
2280
  _add_js_domEvent(); // requires domEvent.js
2281
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2282
  drupal_add_js("
2283
  jQuery(document).ready(
2284
      function() {
2285
        dynabox('". $dynabox_id ."',
2286
          {
2287
            open_callback: " . $open_callback .",
2288
            close_callback: " . $close_callback ."
2289
          }
2290
        );
2291
      }
2292
   );",
2293
   array(
2294
    'type'=>'inline',
2295
    'scope'=>'footer'
2296
    )
2297
  );
2298

    
2299

    
2300
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2301
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2302
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2303
  // TODO stop using the title attribute, the label href now contains the same url!
2304
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '">';
2305
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2306
  $out .= '</' . $enclosingtags[1] . '>';
2307
  $out .= '</' . $enclosingtags[0] . '>';
2308
  $out .= '<!-- dynabox end -->';
2309
  return $out;
2310
}
2311

    
2312
/**
2313
 * Checks whether a feature has any description elements.
2314
 *
2315
 * @param mixed $featureNode
2316
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2317
 *
2318
 * @see _mergeFeatureTreeDescriptions()
2319
 *
2320
 * @return bool
2321
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2322
 *   contains at least one non empty TextData or at least one DescriptionElement
2323
 *   of an other type. A TextData element holding a multilanguageText or a
2324
 *   source reference is considered to be not empty.
2325
 *
2326
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2327
 *       see $block_content_is_not_empty in compose_cdm_feature_nodes() and
2328
 *       $feature_block_has_content in compose_cdm_descriptionElements
2329
 */
2330
function has_feature_node_description_elements($featureNode) {
2331

    
2332
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2333
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2334
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2335
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2336
          && $descriptionElement->multilanguageText_L10n->text != ''
2337
          || isset($descriptionElement->sources[0])
2338
          || isset($descriptionElement->media[0]) ) {
2339
          return TRUE;
2340
        }
2341
      }
2342
    }
2343
  }
2344
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2345
    foreach ($featureNode->childNodes as $child) {
2346
      if (has_feature_node_description_elements($child)) {
2347
        return TRUE;
2348
      }
2349
    }
2350
  }
2351
  return FALSE;
2352
}
2353

    
2354
/**
2355
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2356
 *
2357
 * @param $chapter
2358
 *   The taxon page chapter or part
2359
 */
2360
function cdm_check_valid_taxon_page($chapter){
2361
  static $taxon_tabs = null;
2362

    
2363
  cdm_check_valid_portal_page();
2364

    
2365
  if($taxon_tabs == null){
2366
    $taxon_tabs = array('all', 'description');
2367
    foreach(get_taxon_tabs_list() as $tab){
2368
      $taxon_tabs[] = strtolower($tab);
2369
    }
2370
  }
2371

    
2372
  if(!in_array($chapter, $taxon_tabs)){
2373
    // oops this is not a valid chapter name
2374
    http_send_status(404); // 404 = Not Found
2375
  }
2376

    
2377
}
2378

    
2379
/**
2380
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2381
 *
2382
 * @param $chapter
2383
 *   The taxon page chapter or part
2384
 */
2385
function cdm_check_valid_portal_page(){
2386
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2387
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2388
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2389
    http_send_status(404); // 404 = Not Found
2390
    exit('HTTP 404');
2391
  }
2392
}
2393

    
2394
/**
2395
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2396
 *
2397
 * @param $text_a
2398
 * @param $text_b
2399
 * @return string
2400
 */
2401
function diff_viewer($text_a, $text_b) {
2402

    
2403
  static $diff_viewer_count = 0;
2404

    
2405
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2406

    
2407
  // http://code.stephenmorley.org/php/diff-implementation/
2408
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2409
  drupal_add_css(drupal_get_path('module',
2410
      'cdm_dataportal') . '/css/diff.css');
2411
  drupal_add_css(drupal_get_path('module',
2412
      'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
2413
  drupal_add_js(drupal_get_path('module',
2414
      'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
2415
    array(
2416
      'type' => 'file',
2417
      'weight' => JS_LIBRARY,
2418
      'cache' => TRUE,
2419
      'preprocess' => FALSE
2420
    )
2421
  );
2422
  drupal_add_js(
2423
    'jQuery(document).ready( function(){
2424
        jQuery(\'#' . $element_id . '\').accordion({
2425
        collapsible: true,
2426
        active: false,
2427
        fillSpace: true,
2428
        }).children(\'div\').css({ \'height\': \'auto\' });
2429
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2430
     });'
2431
    , array(
2432
    'type' => 'inline',
2433
    'scope' => 'footer'
2434
  ));
2435

    
2436
  $diff = Diff::compare($text_a,
2437
    $text_b);
2438
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2439
    . Diff::toTable($diff, '', '')
2440
    . '</div></div>';
2441
  return $diff_viewer_markup;
2442
}
2443

    
(8-8/14)