Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

    
126
  function _add_js_openlayers() {
127

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

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

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

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

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

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

    
175
  }
176

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

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

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

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

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

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

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

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

    
289
  global $base_url;
290

    
291

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

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

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

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

    
351

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

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

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

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

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

    
374
    return '';
375
  }
376

    
377

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
589
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
590
      'title' => '@tabname',
591
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens'))),
592
      'page callback' => 'cdm_dataportal_taxon_page_view',
593
      'access arguments' => array('access content'),
594
      'type' => MENU_LOCAL_TASK,
595
      'weight' => 6,
596
      'page arguments' => array(2, "specimens")
597
      , // Expected callback arguments: taxon_uuid.
598
    );
599

    
600
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
601
      'title' => '@tabname',
602
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys'))),
603
      'page callback' => 'cdm_dataportal_taxon_page_view',
604
      'access arguments' => array('access content'),
605
      'type' => MENU_LOCAL_TASK,
606
      'weight' => 6,
607
      'page arguments' => array(2, "keys")
608
      , // Expected callback arguments: taxon_uuid.
609
    );
610

    
611
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
612
      'title' => '@tabname',
613
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts'))),
614
        'page callback' => 'cdm_dataportal_taxon_page_view',
615
        'access arguments' => array('access content'),
616
        'type' => MENU_LOCAL_TASK,
617
        'weight' => 6,
618
        'page arguments' => array(2, "experts")
619
    , // Expected callback arguments: taxon_uuid.
620
    );
621

    
622
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
623
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
624
        'access arguments' => array('access taxon autosuggest'),
625
        'page arguments' => array(3,4,5),
626
        'type' => MENU_CALLBACK
627
    );
628
  }
629

    
630
  // --- refresh link for all cdmnode types
631
  foreach (cdm_get_nodetypes() as $type=>$name) {
632
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
633
        'title' => 'Refresh',
634
        'page callback' => 'cdm_dataportal_refresh_node',
635
        'access arguments' => array('administer cdm_dataportal'),
636
        'type' => MENU_LOCAL_TASK,
637
        'weight' => 100,
638
        'page arguments' => array($name, 2)
639
    );
640
  }
641

    
642
  return $items;
643
}
644

    
645
/**
646
 * Implements hook_init().
647
 *
648
 */
649
function cdm_dataportal_init() {
650
  //FIXME To add CSS or JS that should be present on all pages, modules
651
  //      should not implement this hook, but declare these files in their .info file.
652
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
653
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
654
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
655

    
656
  if(variable_get('cdm_debug_mode', FALSE)){
657
    $file = 'temporary://drupal_debug.txt';
658
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
659
  }
660

    
661
  $bibliography_settings = get_bibliography_settings();
662
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
663
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
664
}
665

    
666
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
667

    
668
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
669

    
670
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
671
    // force reloading of all and notify user about this special loading
672
    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: ')
673
        . l('Back to tabbed taxon page', $base_path));
674
    $base_path .= '/all';
675
  } else {
676
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
677
  }
678

    
679
  $parameters['cacheL2_refresh'] ='1';
680

    
681

    
682
  drupal_goto($base_path, array('query' => $parameters));
683
}
684

    
685
/**
686
 * The function generate form for own user cdm dataportal configurations.
687
 */
688
function cdm_dataportal_user_form($form, &$form_state) {
689

    
690
  global $user;
691
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
692

    
693
  $form['taxon_page_tabs'] = array(
694
      '#type' => 'fieldset',
695
      '#tree' => true,
696
      '#title' => t('Taxon page tabs'),
697
  );
698

    
699
  $form['taxon_page_tabs']['user_defined'] = array(
700
    '#type' => 'checkbox',
701
    '#title' => t('Activate user default configuration'),
702
    '#default_value' => variable_get($checkbox_value, 0),
703
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
704
  );
705

    
706
  $form['taxon_page_tabs']['default_tab'] = array(
707
    '#type' => 'select',
708
    '#title' => t('Default tab to display'),
709
    '#default_value' => get_default_taxon_tab(TRUE),
710
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
711
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
712
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
713
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
714
  );
715

    
716

    
717
  if(false){
718
    $form['developer_options'] = array(
719
        '#type' => 'fieldset',
720
        '#tree' => true,
721
        '#title' => t('Developer options'),
722
    );
723

    
724
    $form['developer_options']['show_render_path'] = array(
725
      '#type' => 'checkbox',
726
      '#title' => t('Display the render path for each taxon name.'),
727
      '#default_value' => variable_get($checkbox_value, 0),
728
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
729
        array(
730
            '!link' => l(
731
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
732
            )
733
        ),
734
    );
735
  }
736

    
737
  $form['submit'] = array(
738
    '#type' => 'submit',
739
    '#value' => t('Submit'),
740
  );
741

    
742
  return $form;
743
}
744

    
745
/**
746
 * Form submission handler for user_form().
747
 *
748
 * Submits the user cdm dataportal configurations.
749
 */
750
function cdm_dataportal_user_form_submit($form, &$form_state) {
751
  global $user;
752
  $msg_type = 'status';
753
  $username = $user->name;
754
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
755

    
756
  // FIXME: this is completely wrong, see user_profile_form_submit()
757

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

    
761
    // DEFAULT_TAXON_TAB
762
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
763
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
764
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
765
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
766
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
767
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
768
        '!tab' => $variable[variable_get($variable_to_use, 0)],
769
        '!user' => $username,
770
      ))), $msg_type);
771
    }
772
    else {
773
      drupal_set_message(check_plain(t('The user default tab wont be used for
774
        the next taxon site, check the box if you want to use the user default configuration.')));
775
    }
776

    
777
  }
778
  else {
779
    // Problem with the user id => variables wont be saved.
780
    $msg_type = 'warning';
781
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
782
  }
783
}
784

    
785
/**
786
 * Implements hook_block_info().
787
 */
788
function cdm_dataportal_block_info() {
789

    
790
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
791
    // $block[1]["info"] = t("CDM DataPortal Credits");
792
    $block["2"] = array(
793
        "info" => t("CDM Search Taxa"),
794
        "cache" => DRUPAL_NO_CACHE
795
      );
796
    // $block[3]["info"] = t("CDM Filters");
797
    $block["4"]["info"] = t("CDM Dataportal Print");
798
    $block["keys"]["info"] = t("CDM identification keys");
799
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
800
    $block["classification_breadcrumbs"] =  array(
801
        'info' => t('Classification breadcrumbs'),
802
        'cache' => DRUPAL_CACHE_PER_PAGE
803
      );
804
    $block["taxonomic_children"] =  array(
805
      'info' => t('Taxonomic children'),
806
      'cache' => DRUPAL_CACHE_PER_PAGE
807
    );
808

    
809
    return $block;
810
}
811

    
812
/**
813
 * Implements hook_block_view().
814
 */
815
function cdm_dataportal_block_view($delta) {
816
  // TODO Rename block deltas (e.g. '2') to readable strings.
817
  switch ($delta) {
818
    // case 'delta-1':
819
    // $block['subject'] = t('Credits');
820
    // $block['content'] = theme('cdm_credits');
821
    // return $block;
822
    case '2':
823
      $block['subject'] = t('Search taxa');
824
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
825
      $block['content'] = drupal_render($form);
826

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

    
863
/**
864
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
865
 *
866
 * @return string
867
 *   the taxon uuid or NULL
868
 */
869
function get_current_taxon_uuid()
870
{
871
  static $taxon_uuid;
872

    
873
  if(!isset($taxon_uuid)){
874
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
875
      $taxon_uuid = $_REQUEST['currentTaxon'];
876
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
877
      $taxon_uuid = arg(2);
878
    } else {
879
      $taxon_uuid = null;
880
    }
881
  }
882

    
883
  return $taxon_uuid;
884
}
885

    
886
/**
887
 * Returns the currently classification tree in use.
888
 *
889
 * @return string
890
 *   The uuid of the currently focused classification
891
 */
892
function get_current_classification_uuid() {
893
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
894
    return $_SESSION['cdm']['taxonomictree_uuid'];
895
  }
896
  else {
897
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
898
  }
899
}
900

    
901
/*
902
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
903
 $_SESSION['cdm'] = NULL;
904
 if(is_string($cdm_ws_uri_update)){
905
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
906
 }
907
 }
908

    
909
 function cdm_dataportal_session_validate(){
910
 if(!isset($_SESSION['cdm']['ws_uri'])){
911
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
912
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
913
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
914
 }
915
 }
916
 */
917

    
918
/**
919
 * creates a  selector form for taxonomic trees.
920
 *
921
 * @return array
922
 *  a drupal form array
923
 */
924
function cdm_taxonomictree_selector() {
925
  _add_js_treeselector();
926

    
927
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
928
  return $form;
929
}
930

    
931
/**
932
 * @todo Please document this function.
933
 * @see http://drupal.org/node/1354
934
 *
935
 * @deprecated use compose_classification_selector instead
936
 */
937
function cdm_taxonomictree_selector_form($form, &$form_state) {
938

    
939
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
940
  $form['#action'] = $url;
941

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

    
948
  $destination_array = drupal_get_destination();
949
  $destination = $destination_array['destination'];
950

    
951
  $form['destination'] = array(
952
    '#weight' => -3,
953
    '#type' => 'hidden',
954
    '#value' =>  $destination,
955
  );
956

    
957
  $options = cdm_get_taxontrees_as_options();
958
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
959
  if($taxontree_includes){
960
    $filtered_options = array();
961
    foreach($options as $uuid=>$label){
962
      if(!empty($taxontree_includes[$uuid])){
963
        $filtered_options[$uuid] = $label;
964
      }
965
    }
966
    $options = $filtered_options;
967
  }
968

    
969
  $form['val'] = array(
970
    '#type' => 'select',
971
    '#title' => t('Available classifications'),
972
    '#default_value' => get_current_classification_uuid(),
973
    '#options' => $options,
974
    '#attributes' => array('class' => array('highlite-first-child')),
975
  );
976

    
977
  return $form;
978

    
979
}
980

    
981
/**
982
 *
983
 * @ingroup compose
984
 */
985
function compose_classification_selector() {
986

    
987
  $destination_array = drupal_get_destination();
988
  $destination = $destination_array['destination'];
989

    
990
  $options = cdm_get_taxontrees_as_options();
991
  $items = array();
992
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
993

    
994
  $current_classification_uuid = get_current_classification_uuid();
995

    
996

    
997
  foreach($options as $uuid=>$label){
998
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
999

    
1000
      $class_attributes = '';
1001
      if($current_classification_uuid == $uuid){
1002
        $class_attributes  = array('focused');
1003
      }
1004
      $items[] = array(
1005
        'data' => l($label,
1006
          'cdm_api/setvalue/session',
1007
          array(
1008
            'query' => array(
1009
              'destination' => $destination,
1010
              'val' => $uuid,
1011
              'var' => '[cdm][taxonomictree_uuid]'
1012
            ),
1013
          )
1014
        ),
1015
        'class' => $class_attributes
1016
      );
1017
    }
1018
  }
1019

    
1020
  $render_array = array(
1021
    '#theme' => 'item_list',
1022
    '#type' => 'ul',
1023
    '#items' => $items
1024
  );
1025

    
1026
  return $render_array;
1027
}
1028

    
1029

    
1030
/* UNREACHABLE since action of form directly links to view.
1031
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1032

    
1033
 $_SESSION['cdm']['search'] = $form_values;
1034
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1035
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1036
 //$paramstr = compose_url_prameterstr($form_values);
1037
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1038
 }
1039
 */
1040
/* ====================== menu callback functions ====================== */
1041
/**
1042
 * @todo Please document this function.
1043
 * @see http://drupal.org/node/1354
1044
 */
1045
/*
1046
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1047
  static $comment_node_disabled =  0;
1048
  static $comment_node_read_only =  1;
1049
  static $comment_node_read_write =  2;
1050

    
1051
  if ($form_id == 'node_type_form'
1052
   && isset($form['identity']['type'])
1053
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1054
  ) {
1055
    $form['workflow']['comment'] = array(
1056
      '#type' => 'radios',
1057
      '#title' => t('Default comment setting'),
1058
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1059
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1060
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1061
    );
1062
  }
1063
}
1064
*/
1065

    
1066
/**
1067
 * Displays a list of the known taxonomic names.
1068
 *
1069
 * When the list of taxonomic names is displayed, long lists are split up into
1070
 * multiple pages.
1071
 *
1072
 * TODO: Parameters are still preliminary.
1073
 *
1074
 * @param string $beginsWith
1075
 * @param string $page
1076
 *   Page number to diplay defaults to page 1.
1077
 * @param bool $onlyAccepted
1078
 */
1079
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1080

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

    
1083
  /*
1084
  // FIXME the filter for accepted names will be a form element, thus this
1085
  // widget should be generated via form api preferably as block.
1086
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1087
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1088
  $out .= theme('cdm_listof_taxa', $taxonPager);
1089
  return $out;
1090
  */
1091
}
1092

    
1093
/**
1094
 * @todo Please document this function.
1095
 * @see http://drupal.org/node/1354
1096
 */
1097
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1098

    
1099
  cdm_check_valid_portal_page();
1100

    
1101
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1102
  return theme('cdm_reference_page', array('reference' => $reference));
1103
}
1104

    
1105
/**
1106
 * Creates a view on a all references contained in the portal.
1107
 *
1108
 * This function is used at the path cdm_dataportal/reference/list
1109
 */
1110
function cdm_dataportal_view_reference_list($pageNumber) {
1111
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1112
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1113
}
1114

    
1115
/**
1116
 * @todo Please document this function.
1117
 * @see http://drupal.org/node/1354
1118
 */
1119
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1120

    
1121
  cdm_check_valid_portal_page();
1122

    
1123
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1124
  return theme('cdm_media_page', array(
1125
    'media' => $media,
1126
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1127
    'partId' => $part,
1128
    ));
1129
}
1130

    
1131
/**
1132
 * @todo Please document this function.
1133
 * @see http://drupal.org/node/1354
1134
 */
1135
function _load_taxonBase(&$taxonBase) {
1136
  if (isset($taxonBase->uuid)) {
1137
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1138
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1139
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1140
  }
1141
}
1142

    
1143
/**
1144
 * Loads the media associated to the given taxon from the cdm server.
1145
 * The aggregation settings regarding taxon relathionships and
1146
 * taxonnomic childen are taken into account.
1147
 *
1148
 * The media lists are cached in a static variable.
1149
 *
1150
 * @param Taxon $taxon
1151
 *   A CDM Taxon entitiy
1152
 *
1153
 * @return array
1154
 *   An array of CDM Media entities
1155
 *
1156
 */
1157
function _load_media_for_taxon($taxon) {
1158

    
1159
  static $media = NULL;
1160

    
1161
  if(!isset($media)) {
1162
    $media = array();
1163
  }
1164
  if (!isset($media[$taxon->uuid])) {
1165

    
1166
    // --- GET Images --- //
1167
    $mediaQueryParameters = array(
1168
        "type" => "ImageFile",
1169
    );
1170

    
1171
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1172
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1173
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1174

    
1175
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1176
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1177
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1178
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1179

    
1180
    $ws_endpoint = NULL;
1181
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1182
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1183
    } else {
1184
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1185
    }
1186

    
1187
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1188
        array(
1189
            $taxon->uuid,
1190
        ),
1191
        queryString($mediaQueryParameters)
1192
       );
1193
  }
1194

    
1195
  return $media[$taxon->uuid];
1196
}
1197

    
1198
/**
1199
 *
1200
 * @param Taxon $taxon
1201
 *   A CDM Taxon entitiy
1202
 *
1203
 * @return array
1204
 *   An array of CDM SpecimenOrObservation entities
1205
 *
1206
function _load_occurences_for_taxon($taxon){
1207

    
1208
  static $occurences = NULL;
1209

    
1210
  if(!isset($occurences)) {
1211
    $occurences = array();
1212
  }
1213

    
1214
  if (!isset($occurences[$taxon->uuid])){
1215

    
1216
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1217
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1218
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1219

    
1220
    $by_associatedtaxon_query = http_build_query(array(
1221
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1222
        'relationships' => implode(',', $relationship_choice['direct']),
1223
        'pageSize' => null // all hits in one page
1224
    )
1225
    );
1226

    
1227
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1228
        null,
1229
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1230
    );
1231

    
1232

    
1233
    if(isset($pager->records[0])){
1234
      $occurences[$taxon->uuid] =  $pager->records;
1235
    }
1236
  }
1237
  return $occurences[$taxon->uuid];
1238
}
1239
 */
1240

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

    
1273
/**
1274
 * Recursive function to convert an object into an array.
1275
 * also subordinate objects will be converted.
1276
 *
1277
 * @param object $object
1278
 * @return the array
1279
 */
1280
function convert_to_array($object) {
1281
  if(is_object($object) || is_array($object)) {
1282
    $array = (array)$object;
1283
    foreach ($array as $key=>$value){
1284
      $array[$key] = convert_to_array($value);
1285
    }
1286
    return $array;
1287
  } else {
1288
    return $object;
1289
  }
1290
}
1291

    
1292
/**
1293
 * Searches the $collection for the cdm entitiy given as $element.
1294
 *
1295
 * The elements are compared by their UUID.
1296
 *
1297
 * @param $element
1298
 *  the CDM entitiy to search for
1299
 * @param $collection
1300
 *  the list of CDM entities to search in
1301
 *
1302
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1303
 *
1304
 */
1305
function contains_cdm_entitiy($element, $collection) {
1306
  $result = FALSE;
1307
  foreach ($collection as $a) {
1308
    if ($a->uuid == $element->uuid) {
1309
      $result = TRUE;
1310
    }
1311
  }
1312
  return $result;
1313
}
1314

    
1315
/**
1316
 * Fiters the array $entity_list of CDM entities by the list
1317
 * of $excludes. Any element contained in the $excludes will be removed
1318
 * from included int the retuned list.
1319
 *
1320
 * If the $entity_list is not an array the $excludes will be returned.
1321
 */
1322
function filter_cdm_entity_list($entity_list, $excludes) {
1323
  if (is_array($entity_list)) {
1324
    $result = $entity_list;
1325
    if ($excludes) {
1326
      foreach ($excludes as $exclude) {
1327
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1328
          $result[] = $exclude;
1329
        }
1330
      }
1331
    }
1332
  }
1333
  else {
1334
    $result = $excludes;
1335
  }
1336
  return $result;
1337
}
1338

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

    
1373
/**
1374
 * Loads the subgraph of a given PolytomousKeyNode.
1375
 *
1376
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1377
 * the CDM REST service.
1378
 *
1379
 * @param mixed $polytomousKeyNode
1380
 *   PolytomousKeyNode passed by reference.
1381
 *
1382
 * @return void
1383
 */
1384
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1385

    
1386
  if (!$polytomousKeyNode) {
1387
    return;
1388
  }
1389
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1390
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1391
    return;
1392
  }
1393
  if (!is_uuid($polytomousKeyNode->uuid)) {
1394
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1395
    return;
1396
  }
1397

    
1398
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1399

    
1400
  if (!$polytomousKeyNode) {
1401
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1402
    return;
1403
  }
1404

    
1405
  // Load children.
1406
  foreach ($polytomousKeyNode->children as &$childNode) {
1407
    _load_polytomousKeySubGraph($childNode);
1408
  }
1409

    
1410
  // Load subkey.
1411
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1412

    
1413
  // Load taxon.
1414
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1415
  _load_taxonBase($polytomousKeyNode->taxon);
1416
  return;
1417
}
1418

    
1419
/**
1420
 * @todo Please document this function.
1421
 * @see http://drupal.org/node/1354
1422
 */
1423
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1424

    
1425
  cdm_check_valid_portal_page();
1426

    
1427
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1428

    
1429
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1430
  if (is_array($sourcePager->records)) {
1431
    $polytomousKey->sources = $sourcePager->records;
1432
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1433
  }
1434

    
1435
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1436
  if (is_array($annotationPager->records)) {
1437
    $polytomousKey->annotations = $annotationPager->records;
1438
  }
1439

    
1440
  _load_polytomousKeySubGraph($polytomousKey->root);
1441
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1442
}
1443

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

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

    
1475
  // Display the page for the taxon defined by $uuid.
1476
  // set_last_taxon_page_tab(arg(3));
1477
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1478
  if (!empty($taxonpage)) {
1479
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1480
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1481
  }
1482
  else {
1483
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1484
    return '';
1485
  }
1486
}
1487

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

    
1514
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1515
    'taxon' => $taxon
1516
  ));
1517

    
1518
  // Check if the taxon id contained in the currently selected tree.
1519
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1520

    
1521
  if (!$taxon_in_current_classification) {
1522
    $classifications = get_classifications_for_taxon($taxon);
1523
    RenderHints::pushToRenderStack('not_in_current_classification');
1524
    $taxon_name_markup = render_taxon_or_name($taxon);
1525

    
1526
    if (count($classifications) == 0) {
1527
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1528
        array(
1529
        '!taxonname' => $taxon_name_markup,
1530
        )
1531
      ), 'warning');
1532
    }
1533
    else {
1534
      $trees = '';
1535
      foreach ($classifications as $classification) {
1536
        if (isset($classification->titleCache)) {
1537
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1538
        }
1539
      }
1540

    
1541
      drupal_set_message(format_plural(count($trees),
1542
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1543
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1544
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1545
        ) ,
1546
        'warning');
1547
    }
1548
    RenderHints::popFromRenderStack();
1549
  }
1550

    
1551
  // Render the taxon page.
1552
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1553
  $taxonpage->content = drupal_render($render_array);
1554

    
1555
  return $taxonpage;
1556
}
1557

    
1558
/**
1559
 * Creates a specimen page view.
1560
 * @param string $uuid the UUID of the specimen
1561
 * @return array|string
1562
 */
1563
function cdm_dataportal_specimen_page_view($uuid) {
1564

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

    
1577
    // Display the page for the specimen defined by $uuid.
1578
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1579
    if (!empty($specimenpage)) {
1580
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1581
    }
1582
    else {
1583
        return '';
1584
    }
1585
}
1586

    
1587
/**
1588
 *
1589
 * Creates a specimen view.
1590
 * @param string $uuid the UUID of the specimen
1591
 * @return array|string
1592
 */
1593
function cdm_dataportal_specimen_view($uuid) {
1594
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1595
    if (empty($specimen)) {
1596
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1597
        return FALSE;
1598
    }
1599
    $specimenpage = new stdClass();
1600

    
1601
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1602
        'specimen' => $specimen
1603
    ));
1604

    
1605
    // Render the specimen page.
1606
    $render_array = compose_cdm_specimen_page($uuid);
1607
    $specimenpage->content = drupal_render($render_array);
1608

    
1609
    return $specimenpage;
1610
}
1611

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

    
1633
  cdm_check_valid_portal_page();
1634

    
1635
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1636
  if (!empty($taxonname_page)) {
1637
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1638
  }
1639
  else {
1640
    return '';
1641
  }
1642
}
1643

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

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

    
1734
/**
1735
 * Creates a page with the advance search form.
1736
 *
1737
 * NOTE: The advance search form allows searching for taxa.
1738
 */
1739
function cdm_dataportal_view_search_advanced() {
1740
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1741
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1742
}
1743

    
1744
/**
1745
 * Creates a page with the search form for searching by taxon descriptions.
1746
 */
1747
function cdm_dataportal_view_search_taxon_by_description() {
1748
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1749
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1750
}
1751

    
1752
/**
1753
 * Executes the search and generates the result list of taxa.
1754
 */
1755
function cdm_dataportal_view_search_results_taxon() {
1756

    
1757
  $taxonPager = cdm_dataportal_search_execute();
1758

    
1759
  $showThumbnails = do_showThumbnails();
1760

    
1761
  $setSessionUri = url('cdm_api/setvalue/session', array(
1762
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1763
  ));
1764

    
1765
  drupal_add_js('jQuery(document).ready(function() {
1766

    
1767
      // init
1768
      if(' . $showThumbnails . ' == 1){
1769
          jQuery(\'.media_gallery\').show(20);
1770
      } else {
1771
          jQuery(\'.media_gallery\').hide(20);
1772
      }
1773

    
1774
      // add change handler
1775
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1776
      function(event){
1777
        var state = 0;
1778
        if(jQuery(this).is(\':checked\')){
1779
          jQuery(\'.media_gallery\').show(20);
1780
          state = 1;
1781
        } else {
1782
          jQuery(\'.media_gallery\').hide(20);
1783
        }
1784
        // store state in session variable
1785
        var uri = \'' . $setSessionUri . '\' + state;
1786
        jQuery.get(uri);
1787
      });
1788
  });',
1789
  array('type' => "inline", 'scope' => JS_DEFAULT));
1790

    
1791
  drupal_set_title(t('Search results'), PASS_THROUGH);
1792

    
1793
  return theme('cdm_search_results', array(
1794
    'pager' => $taxonPager,
1795
    'path' => 'cdm_dataportal/search/results/taxon',
1796
    ));
1797
}
1798

    
1799
/**
1800
 * Provides the standart image wich indicated a loading process
1801
 *
1802
 * @return string
1803
 *  The img html tag
1804
 */
1805
function loading_image_html() {
1806
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1807
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1808
}
1809

    
1810
/**
1811
 * Returns the state of the the showThumbnails flag set in the
1812
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1813
 *
1814
 * @return boolean
1815
 *    returns 1 if the flag is set
1816
 */
1817
function do_showThumbnails() {
1818
  static $showThumbnails = null;
1819

    
1820
  if($showThumbnails == null) {
1821
    $showThumbnails = 0;
1822
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1823
      $showThumbnails = 0;
1824
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1825
      $showThumbnails = is_array($search_gallery_settings)
1826
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1827
        && (
1828
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1829
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1830
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1831
            )
1832
         ? 1 : 0;
1833

    
1834
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1835
    }
1836
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1837
    if (!is_numeric($showThumbnails)) {
1838
      $showThumbnails = 1;
1839
    }
1840
  }
1841

    
1842
  return $showThumbnails;
1843
}
1844

    
1845

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

    
1871
  $tab = get_default_taxon_tab();
1872
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1873

    
1874
  if (!$uuid) {
1875
    return FALSE;
1876
  }
1877

    
1878
  if ($page_tab) {
1879
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1880
  }
1881
  elseif (!$tab || strtolower($tab) == 'general') {
1882
    return 'cdm_dataportal/taxon/' . $uuid;
1883
  }
1884
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1885
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1886
  }
1887
  else {
1888
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1889
  }
1890
}
1891

    
1892
function path_to_specimen($uuid) {
1893

    
1894
    if (!$uuid) {
1895
        return FALSE;
1896
    }
1897
    else {
1898
        return 'cdm_dataportal/specimen/' . $uuid;
1899
    }
1900
}
1901

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

    
1931
}
1932

    
1933
/**
1934
 * Compses the drupal path to the key identified by the uuid.
1935
 *
1936
 * @param string $keyType
1937
 *    the key typer corresponds to the specific class of the CDM
1938
 *    IdentificationKey. Possible values are
1939
 *      -PolytomousKey
1940
 *      -MultimediaKey
1941
 *      - ...
1942
 * @param UUID $keyUuid
1943
 *   The UUID of the key
1944
 */
1945
function path_to_key($keyType, $keyUuid) {
1946
  if (!$keyUuid || !$keyType) {
1947
    return FALSE;
1948
  }
1949
  $keyType{0} = strtolower($keyType{0});
1950
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1951
}
1952

    
1953
/**
1954
 * @todo Please document this function.
1955
 * @see http://drupal.org/node/1354
1956
 */
1957
function path_to_reference($uuid) {
1958
  if (!$uuid) {
1959
    return FALSE;
1960
  }
1961
  return 'cdm_dataportal/reference/' . $uuid;
1962
}
1963

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

    
1993
/**
1994
 * @todo Please document this function.
1995
 * @see http://drupal.org/node/1354
1996
 */
1997
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1998
  if (!$uuid) {
1999
    return FALSE;
2000
  }
2001
  $out = 'cdm_dataportal/media/' . $uuid;
2002
  if ($representaion_uuid) {
2003
    $out .= '/' . $representaion_uuid;
2004
    if ($partId !== FALSE) {
2005
      $out .= '/' . $partId;
2006
    }
2007
  }
2008
  return $out;
2009
}
2010

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

    
2039
/**
2040
 * Composes an HTML element class attribute value composed of
2041
 * the shortname of the cdm class and the uuid of the entity.
2042
 * This class attribute should be used whereever an cdm-entity is rendered.
2043
 *
2044
 * These according class selectors in css must be escaped, eg:
2045
 *    .cdm\:TextData
2046
 *
2047
 * @param $cdmEntity
2048
 */
2049
function html_class_attribute_ref($cdmEntity) {
2050

    
2051
  if (is_cdm_entity($cdmEntity)) {
2052
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2053
  }
2054
}
2055

    
2056

    
2057
/**
2058
 * Creates a short taxonname.
2059
 *
2060
 * The short name is created by using the taggedTitle field of
2061
 * NameSTO or NameTO instances.
2062
 * If the taggedTitle if empty the fullname will be returned.
2063
 *
2064
 * @param unknown_type $name
2065
 *   Name or TreeNode.
2066
 *
2067
 * @return string
2068
 */
2069
function cdm_dataportal_shortname_of($name) {
2070
  $nameStr = '';
2071

    
2072
  normalize_tagged_text($name->taggedTitle);
2073

    
2074
  // Get all tagged text tokens of the scientific name.
2075
  foreach ($name->taggedTitle as $tagtxt) {
2076
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2077
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2078
    }
2079
  }
2080
  $nameStr = trim($nameStr);
2081

    
2082
  if ($nameStr) {
2083

    
2084
    // Do not return short names for these.
2085
    if ($name->unplaced || $name->excluded) {
2086
      return $nameStr;
2087
    }
2088

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

    
2109
/**
2110
 * Check if a taxon is accepted by the current taxonomic tree.
2111
 *
2112
 * @param mixed $taxon
2113
 *   The Taxon obkect to check.
2114
 *
2115
 * @return bool
2116
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2117
 */
2118
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2119

    
2120
  $defaultTreeUuid = get_current_classification_uuid();
2121

    
2122
  if (isset($taxon->taxonNodes)) {
2123
    $taxonNodes = $taxon->taxonNodes;
2124
  }
2125
  else {
2126
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2127
  }
2128

    
2129
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2130
    foreach ($taxonNodes as $node) {
2131
      if (isset($node->classification)){
2132
        if(is_object($node->classification)) {
2133
          if ($node->classification->uuid == $defaultTreeUuid) {
2134
            return TRUE;
2135
          }
2136
        }
2137
        else {
2138
          if ($node->classification == $defaultTreeUuid) {
2139
            return TRUE;
2140
          }
2141
        }
2142
      }
2143
    }
2144
  }
2145

    
2146
  return FALSE;
2147
}
2148

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

    
2175
    if(!$types){
2176
      $types = $default;
2177
    }
2178
    return isset($source->type) && in_array($source->type, $types);
2179
  }
2180

    
2181
/**
2182
 * @todo Please document this function.
2183
 * @see http://drupal.org/node/1354
2184
 */
2185
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2186
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2187
}
2188

    
2189

    
2190
/**
2191
 * Collects all the media from a list of description elements.
2192
 *
2193
 * @param array $descriptionElements
2194
 *   The description elements from which to collect the media.
2195
 *
2196
 * @return array
2197
 *   The output with all the collected media.
2198
 */
2199
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2200

    
2201
  $outArrayOfMedia = array();
2202

    
2203
  // Avoiding a warning box in Drupal for Flora Malesiana.
2204
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2205
    foreach ($descriptionElements as $descriptionElement) {
2206
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2207
        foreach ($descriptionElement->media as $media) {
2208
          if (is_object($media)) {
2209
            $outArrayOfMedia[] = $media;
2210
          }
2211
        }
2212
      }
2213
    }
2214
  }
2215
  return $outArrayOfMedia;
2216
}
2217

    
2218
/**
2219
 * @todo Please document this function.
2220
 * @see http://drupal.org/node/1354
2221
 *
2222
 * @param array $cdm_entities
2223
 *   An array of CdmBase instances or a single instance.
2224
 * @param string $footnote_list_key_suggestion
2225
 *
2226
 * @return unknown
2227
 */
2228
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2229

    
2230
   static $annotations_types_filter = null;
2231
   if(!$annotations_types_filter) {
2232
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2233
   }
2234

    
2235
  $footNoteKeys = array();
2236

    
2237
  // Is argument cdmBase an array?
2238
  if (!is_array($cdm_entities)) {
2239
    $cdmBase_array = array();
2240
    $cdmBase_array[] = $cdm_entities;
2241
  }
2242
  else {
2243
    $cdmBase_array = $cdm_entities;
2244
  }
2245

    
2246
  // Getting the key for the footnotemanager.
2247
  if (isset($footnote_list_key_suggestion)) {
2248
    $footnote_list_key = $footnote_list_key_suggestion;
2249
  }
2250
  else {
2251
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2252
  }
2253

    
2254
  // Adding the footnotes keys.
2255
  foreach ($cdmBase_array as $cdmBase_element) {
2256
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2257
    if (is_array($annotations)) {
2258
      foreach ($annotations as $annotation) {
2259
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2260
      }
2261
    }
2262
  }
2263

    
2264
  return $footNoteKeys;
2265
}
2266

    
2267

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

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

    
2311
  if(!array_key_exists('class', $attributes)) {
2312
    $attributes['class'] = array();
2313
  }
2314
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2315
  $dynabox_attributes = drupal_attributes($attributes);
2316

    
2317

    
2318
  _add_js_domEvent(); // requires domEvent.js
2319
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2320
  drupal_add_js("
2321
  jQuery(document).ready(
2322
      function() {
2323
        dynabox('". $dynabox_id ."',
2324
          {
2325
            open_callback: " . $open_callback .",
2326
            close_callback: " . $close_callback .
2327
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2328
          }
2329
        );
2330
      }
2331
   );",
2332
   array(
2333
    'type'=>'inline',
2334
    'scope'=>'footer'
2335
    )
2336
  );
2337

    
2338

    
2339
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2340
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2341
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t('@link-alt-text', array('@link-alt-text' => $link_alt_text)) . '">' . $label . '</a>';
2342
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2343
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2344
  $out .= '    </' . $enclosingtags[1] . '>';
2345
  $out .= '  </' . $enclosingtags[0] . '>';
2346
  $out .= '<!-- dynabox end -->';
2347
  return $out;
2348
}
2349

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

    
2370
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2371
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2372
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2373
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2374
          && $descriptionElement->multilanguageText_L10n->text != ''
2375
          || isset($descriptionElement->sources[0])
2376
          || isset($descriptionElement->media[0]) ) {
2377
          return TRUE;
2378
        }
2379
      }
2380
    }
2381
  }
2382
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2383
    foreach ($featureNode->childNodes as $child) {
2384
      if (has_feature_node_description_elements($child)) {
2385
        return TRUE;
2386
      }
2387
    }
2388
  }
2389
  return FALSE;
2390
}
2391

    
2392
/**
2393
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2394
 *
2395
 * @param $chapter
2396
 *   The taxon page chapter or part
2397
 */
2398
function cdm_check_valid_taxon_page($chapter){
2399
  static $taxon_tabs = null;
2400

    
2401
  cdm_check_valid_portal_page();
2402

    
2403
  if($taxon_tabs == null){
2404
    $taxon_tabs = array('all', 'description');
2405
    foreach(get_taxon_tabs_list() as $tab){
2406
      $taxon_tabs[] = strtolower($tab);
2407
    }
2408
  }
2409

    
2410
  if(!in_array($chapter, $taxon_tabs)){
2411
    // oops this is not a valid chapter name
2412
    http_response_code(404); // 404 = Not Found
2413
  }
2414

    
2415
}
2416

    
2417
/**
2418
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2419
 *
2420
 * @param $chapter
2421
 *   The taxon page chapter or part
2422
 */
2423
function cdm_check_valid_portal_page(){
2424
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2425
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2426
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2427
    http_response_code(404); // 404 = Not Found
2428
    exit('HTTP 404');
2429
  }
2430
}
2431

    
2432
/**
2433
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2434
 *
2435
 * @param $text_a
2436
 * @param $text_b
2437
 * @return string
2438
 */
2439
function diff_viewer($text_a, $text_b) {
2440

    
2441
  static $diff_viewer_count = 0;
2442

    
2443
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2444

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

    
2464
  $diff = Diff::compare($text_a,
2465
    $text_b);
2466
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2467
    . Diff::toTable($diff, '', '')
2468
    . '</div></div>';
2469
  return $diff_viewer_markup;
2470
}
2471

    
2472

    
(10-10/16)