Project

General

Profile

Download (80.5 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_resizable_element($selector, $y_axis_only) {
127

    
128
    _add_jquery_ui();
129
    $options = "";
130
    if($y_axis_only) {
131
      $options = "resize: function(event, ui) {
132
        ui.size.width = ui.originalSize.width;
133
        },
134
        handles: \"s\"";
135

    
136
    }
137
    drupal_add_js("
138
          jQuery(document).ready(function() {
139
             jQuery('" . $selector . "').resizable({". $options ."});
140
          });
141
        ",
142
      array(
143
        'type' => 'inline',
144
        'scope' => 'footer'
145
      )
146
    );
147
  }
148

    
149
  function _add_js_openlayers() {
150

    
151
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
152
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
153

    
154
    if(variable_get('cdm_js_devel_mode', FALSE)){
155
      // develooper mode libs
156
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
157
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
158
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
159
    }
160

    
161
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
162
      array(
163
        'type' => 'file',
164
        'weight' => JS_LIBRARY,
165
        'cache' => TRUE,
166
        'preprocess' => FALSE
167
      )
168
    );
169

    
170
    // see https://github.com/proj4js/proj4js
171
    // http://openlayers.org/dev/examples/using-proj4js.html
172
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
173
      array(
174
        'type' => 'file',
175
        'weight' => JS_LIBRARY,
176
        'cache' => TRUE,
177
      )
178
    );
179

    
180
    // configure the theme
181
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
182
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
183
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
184
        'type' => 'inline',
185
        'weight' => JS_LIBRARY,
186
        'cache' => TRUE,
187
        'preprocess' => FALSE
188
      ));
189

    
190
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
191
      array(
192
        'type' => 'file',
193
        'cache' => TRUE,
194
        'preprocess' => FALSE
195
      )
196
    );
197

    
198
  }
199

    
200
  /**
201
   * @todo Please document this function.
202
   * @see http://drupal.org/node/1354
203
   */
204
  function _add_js_thickbox() {
205
    // ---- jQuery thickbox:
206
    /*
207
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
208
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
209
    */
210
    // drupal_add_js(drupal_get_path('module',
211
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
212
    //
213
    // Add a setting for the path to cdm_dataportal module, used to find the path
214
    // for the loading animation image in thickbox.
215
    drupal_add_js(array(
216
    'cdm_dataportal' => array(
217
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
218
    )
219
    ),
220
    'setting'
221
        );
222
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
223
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
224
  }
225

    
226
  /**
227
   * @todo Please document this function.
228
   * @see http://drupal.org/node/1354
229
   */
230
  function _add_js_lightbox($galleryID) {
231
    /*
232
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
233
    * allow using the "alt" attribute for captions instead of the "title"
234
    * attribute
235
    */
236
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
237
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
238
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
239
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
240
    drupal_add_js('jQuery(document).ready(function() {
241
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
242
          fixedNavigation:  true,
243
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
244
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
245
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
246
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
247
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
248
          adjustToWindow: true
249
        });
250
      });
251
      ', array('type' => 'inline'));
252
  }
253

    
254
  /**
255
   * @todo Please document this function.
256
   * @see http://drupal.org/node/1354
257
   */
258
  function _add_js_footnotes() {
259
    _add_js_domEvent();
260
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
261
  }
262

    
263
  /**
264
   * @todo Please document this function.
265
   * @see http://drupal.org/node/1354
266
   */
267
  function _add_js_cluetip() {
268

    
269
    // TODO replace by
270
    // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
271
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
272
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
273
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
274
    if(variable_get('cdm_js_devel_mode', FALSE)){
275
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
276
    }
277
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
278
    drupal_add_js("jQuery(document).ready(function(){
279
        jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
280
          splitTitle: '|',
281
          showTitle: true,
282
          activation: 'hover',
283
          sicky: true,
284
          arrows: true,
285
          dropShadow: false,
286
          cluetipClass: 'rounded'
287
        });
288
      });",
289
      array(
290
        'type' => 'inline',
291
        'scope' => 'footer'
292
      )
293
    );
294
  }
295

    
296
  /**
297
   * @todo Please document this function.
298
   * @see http://drupal.org/node/1354
299
   */
300
  function _add_js_ahah() {
301

    
302
    _add_js_domEvent(); // requires domEvent.js
303
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
304
  }
305

    
306
/**
307
 * @todo Please document this function.
308
 * @see http://drupal.org/node/1354
309
 */
310
function _add_js_taxonomic_children($jquery_selector) {
311

    
312
  global $base_url;
313

    
314

    
315
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
316
  
317
  drupal_add_js('jQuery(document).ready(function() {
318
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
319
          // hoverClass: "fa-rotate-90",
320
          // activeClass: "fa-rotate-90",
321
          classificationUuid: "' . get_current_classification_uuid() . '",
322
          taxonUuid: "' . get_current_taxon_uuid() . '",
323
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
324
          proxyBaseUri: "' . $base_url . '",
325
          
326
        });
327
      });
328
      ', array('type' => 'inline'));
329
}
330

    
331
  /**
332
   * Adds the external javascript file for domEvent.js.
333
   *
334
   * @see drupal_add_js()
335
   */
336
  function _add_js_domEvent() {
337
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
338
  }
339

    
340
  function _add_jquery_ui()
341
  {
342
    drupal_add_css(drupal_get_path('module',
343
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
344
    drupal_add_js(drupal_get_path('module',
345
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
346
      array(
347
        'type' => 'file',
348
        'weight' => JS_LIBRARY,
349
        'cache' => TRUE,
350
        'preprocess' => FALSE
351
      )
352
    );
353
  }
354

    
355
  /**
356
   * Provides the markup for an font awesome icon.
357
   *
358
   * The icons is created in default size without any extra features.
359
   *
360
   * The available icons are listed here http://fontawesome.io/cheatsheet/
361
   * fontawesome icons have much more features than implemented here in this function,
362
   * for spinning icons, fixed width icons, rotation, etc please checkout the
363
   * examples at http://fontawesome.io/examples/
364
   *
365
   * @parameter $icon_name
366
   *  The name of the icon which starts with 'fa-'
367
   *
368
   * @return String
369
   *    the markup for the icon in an <i> tag
370
   *
371
   */
372
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
373

    
374

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

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

    
380
    drupal_add_html_head_link(
381
      array(
382
        'href' => $font_awesome_css_uri,
383
        'rel' => 'stylesheet'
384
      )
385
    );
386

    
387
    if($icon_name){
388
      if(!isset($attributes['class'])){
389
        $attributes['class'] = array();
390
      }
391
      $attributes['class'][] = 'fa';
392
      $attributes['class'][] = $icon_name;
393

    
394
      return '<i ' . drupal_attributes($attributes) . '></i>';
395
    }
396

    
397
    return '';
398
  }
399

    
400

    
401
  /* ====================== hook implementations ====================== */
402
  /**
403
   * Implements hook_permission().
404
   *
405
   * Valid permissions for this module.
406
   *
407
   * @return array
408
   *   An array of valid permissions for the portfolio module.
409
   */
410
  function cdm_dataportal_permission() {
411
    return array(
412
      'administer cdm_dataportal' => array(
413
        'title' => t('administer cdm_dataportal'),
414
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
415
      ),
416
      'cdm_dataportal view notes' => array(
417
        'title' => t('cdm_dataportal view notes'),
418
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
419
      ),
420
      // TODO Which other permissions are required?
421
      // -> check the WP6 requirements document.
422
    );
423
  }
424

    
425
/**
426
 * Implements hook_menu().
427
 */
428
function cdm_dataportal_menu() {
429
  $items = array();
430

    
431
  // @see settings.php.
432
  cdm_dataportal_menu_admin($items);
433
  cdm_dataportal_menu_help($items);
434

    
435
  $items['cdm_dataportal/names'] = array(
436
    'page callback' => 'cdm_dataportal_view_names',
437
    'access arguments' => array('access content'),
438
    'type' => MENU_CALLBACK,
439
  );
440

    
441
  // Optional callback arguments: page.
442
  $items['cdm_dataportal/taxon'] = array(
443
    'page callback' => 'cdm_dataportal_taxon_page_view',
444
    'access arguments' => array('access content'),
445
    'type' => MENU_CALLBACK,
446
    // Expected callback arguments: uuid.
447
  );
448

    
449
   // Optional callback arguments: page.
450
    //FIXME point to view/page method in this module
451
    $items['cdm_dataportal/specimen'] = array(
452
        'page callback' => 'cdm_dataportal_specimen_page_view',
453
        'access arguments' => array('access content'),
454
        'type' => MENU_CALLBACK,
455
        // Expected callback arguments: uuid.
456
    );
457

    
458
  $items['cdm_dataportal/name'] = array(
459
    'page callback' => 'cdm_dataportal_name_page_view',
460
      /*
461
    'page arguments' => array(
462
       'taxon_name_uuid',
463
       'taxon_to_hide_uuid',
464
       'synonym_uuid' => NULL
465
      ),
466
      */
467
    'access arguments' => array('access content'),
468
    'type' => MENU_CALLBACK,
469
    // Expected callback arguments: uuid.
470
  );
471

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

    
479
  $items['cdm_dataportal/reference/list'] = array(
480
    'page callback' => 'cdm_dataportal_view_reference_list',
481
    'access arguments' => array('access content'),
482
    'type' => MENU_CALLBACK,
483
    // Expected callback arguments: uuid.
484
  );
485

    
486
  $items['cdm_dataportal/media'] = array(
487
    'page callback' => 'cdm_dataportal_view_media',
488
    'access arguments' => array('access content'),
489
    'type' => MENU_CALLBACK,
490
    // Expected callback arguments:
491
    // uuid, mediarepresentation_uuid, part_uuid or part#.
492
  );
493

    
494
  $items['cdm_dataportal/polytomousKey'] = array(
495
    'page callback' => 'cdm_dataportal_view_polytomousKey',
496
    'access arguments' => array('access content'),
497
    'type' => MENU_CALLBACK,
498
    // Expected callback arguments: polytomousKey->uuid.
499
  );
500

    
501
  $items['cdm_dataportal/search'] = array(
502
    'page callback' => 'cdm_dataportal_view_search_advanced',
503
    'access arguments' => array('access content'),
504
    'type' => MENU_CALLBACK,
505
  );
506

    
507
  $items['cdm_dataportal/search/advanced'] = array(
508
    'title' => 'Advanced', // will be passed through t()
509
    'page callback' => 'cdm_dataportal_view_search_advanced',
510
    'access arguments' => array('access content'),
511
    'type' => MENU_DEFAULT_LOCAL_TASK,
512
  );
513

    
514
  $items['cdm_dataportal/search/taxon_by_description'] = array(
515
    'title' => 'By content category', // will be passed through t()
516
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
517
    'access arguments' => array('access content'),
518
    'type' => MENU_LOCAL_TASK,
519
  );
520

    
521
  $items['cdm_dataportal/search/results/taxon'] = array(
522
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
523
    'access arguments' => array('access content'),
524
    'type' => MENU_CALLBACK,
525
  );
526
  /*
527
   $items['cdm/xml2json'] = array(
528
   'page callback' => 'cdm_view_xml2json',
529
   'access arguments' => array('access content'),
530
   'type' => MENU_CALLBACK,
531
   );
532
   */
533

    
534
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
535
  // User configuration of cdm_dataportal.
536
  $items['user/%/cdm_dataportal'] = array(
537
    'title' => 'cdm_dataportal',
538
    'access arguments' => array('access content'),
539
    'page callback' => 'drupal_get_form',
540
    'page arguments' => array('cdm_dataportal_user_form'),
541
    'type' => MENU_LOCAL_TASK,
542
    'weight' => 10,
543
  );
544
  // }
545

    
546
  // 'May not cache' in D5.
547
  $items['cdm_dataportal/name/%'] = array(
548
    // 'page callback' => 'cdm_dataportal_view_name',
549
    'page callback' => 'cdm_dataportal_name_page_view',
550
    'page arguments' => array(2, 3, 4),
551
    'access arguments' => array('access content'),
552
    'type' => MENU_CALLBACK,
553
  );
554

    
555
  // --- Local tasks for Taxon.
556
  // --- tabbed taxon page
557
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
558
    $items['cdm_dataportal/taxon/%'] = array(
559
      'title' => '@tabname',
560
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
561
      'page callback' => 'cdm_dataportal_taxon_page_view',
562
      'access arguments' => array('access content'),
563
      'type' => MENU_CALLBACK,
564
      'weight' => 1,
565
      'page arguments' => array(2, "description")
566
      , // Expected callback arguments: taxon_uuid.
567
    );
568

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

    
580
    $items['cdm_dataportal/taxon/%/description'] = array(
581
      'title' => '@tabname',
582
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
583
      'page callback' => 'cdm_dataportal_taxon_page_view',
584
      'access arguments' => array('access content'),
585
      'type' => MENU_DEFAULT_LOCAL_TASK,
586
      'weight' => 2,
587
      'page arguments' => array(2, "description")
588
      , // Expected callback arguments: taxon_uuid.
589
    );
590

    
591
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
592
      'title' => '@tabname',
593
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy'))),
594
      'page callback' => 'cdm_dataportal_taxon_page_view',
595
      'access arguments' => array('access content'),
596
      'type' => MENU_LOCAL_TASK,
597
      'weight' => 4,
598
      'page arguments' => array(2, "synonymy", 4)
599
      , // Expected callback arguments: taxon_uuid and ...
600
    );
601
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
602
      'title' => '@tabname',
603
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Images'))),
604
      'page callback' => 'cdm_dataportal_taxon_page_view',
605
      'access arguments' => array('access content'),
606
      'type' => MENU_LOCAL_TASK,
607
      'weight' => 5,
608
      'page arguments' => array(2, "images")
609
      , // Expected callback arguments: taxon_uuid.
610
    );
611

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

    
623
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
624
      'title' => '@tabname',
625
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys'))),
626
      'page callback' => 'cdm_dataportal_taxon_page_view',
627
      'access arguments' => array('access content'),
628
      'type' => MENU_LOCAL_TASK,
629
      'weight' => 6,
630
      'page arguments' => array(2, "keys")
631
      , // Expected callback arguments: taxon_uuid.
632
    );
633

    
634
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
635
      'title' => '@tabname',
636
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts'))),
637
        'page callback' => 'cdm_dataportal_taxon_page_view',
638
        'access arguments' => array('access content'),
639
        'type' => MENU_LOCAL_TASK,
640
        'weight' => 6,
641
        'page arguments' => array(2, "experts")
642
    , // Expected callback arguments: taxon_uuid.
643
    );
644

    
645
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
646
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
647
        'access arguments' => array('access taxon autosuggest'),
648
        'page arguments' => array(3,4,5),
649
        'type' => MENU_CALLBACK
650
    );
651
  }
652

    
653
  // --- refresh link for all cdmnode types
654
  foreach (cdm_get_nodetypes() as $type=>$name) {
655
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
656
        'title' => 'Refresh',
657
        'page callback' => 'cdm_dataportal_refresh_node',
658
        'access arguments' => array('administer cdm_dataportal'),
659
        'type' => MENU_LOCAL_TASK,
660
        'weight' => 100,
661
        'page arguments' => array($name, 2)
662
    );
663
  }
664

    
665
  return $items;
666
}
667

    
668
/**
669
 * Implements hook_init().
670
 *
671
 */
672
function cdm_dataportal_init() {
673
  //FIXME To add CSS or JS that should be present on all pages, modules
674
  //      should not implement this hook, but declare these files in their .info file.
675
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
676
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
677
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
678

    
679
  if(variable_get('cdm_debug_mode', FALSE)){
680
    $file = 'temporary://drupal_debug.txt';
681
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
682
  }
683

    
684
  $bibliography_settings = get_bibliography_settings();
685
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
686
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
687
}
688

    
689
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
690

    
691
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
692

    
693
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
694
    // force reloading of all and notify user about this special loading
695
    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: ')
696
        . l('Back to tabbed taxon page', $base_path));
697
    $base_path .= '/all';
698
  } else {
699
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
700
  }
701

    
702
  $parameters['cacheL2_refresh'] ='1';
703

    
704

    
705
  drupal_goto($base_path, array('query' => $parameters));
706
}
707

    
708
/**
709
 * The function generate form for own user cdm dataportal configurations.
710
 */
711
function cdm_dataportal_user_form($form, &$form_state) {
712

    
713
  global $user;
714
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
715

    
716
  $form['taxon_page_tabs'] = array(
717
      '#type' => 'fieldset',
718
      '#tree' => true,
719
      '#title' => t('Taxon page tabs'),
720
  );
721

    
722
  $form['taxon_page_tabs']['user_defined'] = array(
723
    '#type' => 'checkbox',
724
    '#title' => t('Activate user default configuration'),
725
    '#default_value' => variable_get($checkbox_value, 0),
726
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
727
  );
728

    
729
  $form['taxon_page_tabs']['default_tab'] = array(
730
    '#type' => 'select',
731
    '#title' => t('Default tab to display'),
732
    '#default_value' => get_default_taxon_tab(TRUE),
733
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
734
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
735
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
736
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
737
  );
738

    
739

    
740
  if(false){
741
    $form['developer_options'] = array(
742
        '#type' => 'fieldset',
743
        '#tree' => true,
744
        '#title' => t('Developer options'),
745
    );
746

    
747
    $form['developer_options']['show_render_path'] = array(
748
      '#type' => 'checkbox',
749
      '#title' => t('Display the render path for each taxon name.'),
750
      '#default_value' => variable_get($checkbox_value, 0),
751
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
752
        array(
753
            '!link' => l(
754
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
755
            )
756
        ),
757
    );
758
  }
759

    
760
  $form['submit'] = array(
761
    '#type' => 'submit',
762
    '#value' => t('Submit'),
763
  );
764

    
765
  return $form;
766
}
767

    
768
/**
769
 * Form submission handler for user_form().
770
 *
771
 * Submits the user cdm dataportal configurations.
772
 */
773
function cdm_dataportal_user_form_submit($form, &$form_state) {
774
  global $user;
775
  $msg_type = 'status';
776
  $username = $user->name;
777
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
778

    
779
  // FIXME: this is completely wrong, see user_profile_form_submit()
780

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

    
784
    // DEFAULT_TAXON_TAB
785
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
786
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
787
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
788
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
789
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
790
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
791
        '!tab' => $variable[variable_get($variable_to_use, 0)],
792
        '!user' => $username,
793
      ))), $msg_type);
794
    }
795
    else {
796
      drupal_set_message(check_plain(t('The user default tab wont be used for
797
        the next taxon site, check the box if you want to use the user default configuration.')));
798
    }
799

    
800
  }
801
  else {
802
    // Problem with the user id => variables wont be saved.
803
    $msg_type = 'warning';
804
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
805
  }
806
}
807

    
808
/**
809
 * Implements hook_block_info().
810
 */
811
function cdm_dataportal_block_info() {
812

    
813
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
814
    // $block[1]["info"] = t("CDM DataPortal Credits");
815
    $block["2"] = array(
816
        "info" => t("CDM Search Taxa"),
817
        "cache" => DRUPAL_NO_CACHE
818
      );
819
    // $block[3]["info"] = t("CDM Filters");
820
    $block["4"]["info"] = t("CDM Dataportal Print");
821
    $block["keys"]["info"] = t("CDM identification keys");
822
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
823
    $block["classification_breadcrumbs"] =  array(
824
        'info' => t('Classification breadcrumbs'),
825
        'cache' => DRUPAL_CACHE_PER_PAGE
826
      );
827
    $block["taxonomic_children"] =  array(
828
      'info' => t('Taxonomic children'),
829
      'cache' => DRUPAL_CACHE_PER_PAGE
830
    );
831

    
832
    return $block;
833
}
834

    
835
/**
836
 * Implements hook_block_view().
837
 */
838
function cdm_dataportal_block_view($delta) {
839
  // TODO Rename block deltas (e.g. '2') to readable strings.
840
  switch ($delta) {
841
    // case 'delta-1':
842
    // $block['subject'] = t('Credits');
843
    // $block['content'] = theme('cdm_credits');
844
    // return $block;
845
    case '2':
846
      $block['subject'] = t('Search taxa');
847
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
848
      $block['content'] = drupal_render($form);
849

    
850
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
851
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
852
      }
853
      return $block;
854
    case '4':
855
      $block['subject'] = '';
856
      $block['content'] = theme('cdm_print_button');
857
      return $block;
858
    case "keys":
859
      $block['subject'] = t('Identification Keys');
860
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
861
      return $block;
862
    case "fundedByEDIT":
863
      // t('Funded by EDIT');
864
      $text = '<none>';
865
      $block['subject'] = $text;
866
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
867
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
868
        'attributes' => array("target" => "EDIT"),
869
        'absolute' => TRUE,
870
        'html' => TRUE,
871
      ));
872
      return $block;
873
    case 'classification_breadcrumbs':
874
      $taxon_uuid = get_current_taxon_uuid();
875
      $block['subject'] = '<none>';
876
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
877
      return $block;
878
    case 'taxonomic_children':
879
      $taxon_uuid = get_current_taxon_uuid();
880
      $block['subject'] = '<none>';
881
      $block['content'] = compose_taxonomic_children($taxon_uuid);
882
      return $block;
883
  }
884
}
885

    
886
/**
887
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
888
 *
889
 * @return string
890
 *   the taxon uuid or NULL
891
 */
892
function get_current_taxon_uuid()
893
{
894
  static $taxon_uuid;
895

    
896
  if(!isset($taxon_uuid)){
897
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
898
      $taxon_uuid = $_REQUEST['currentTaxon'];
899
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
900
      $taxon_uuid = arg(2);
901
    } else {
902
      $taxon_uuid = null;
903
    }
904
  }
905

    
906
  return $taxon_uuid;
907
}
908

    
909
/**
910
 * Returns the currently classification tree in use.
911
 *
912
 * @return string
913
 *   The uuid of the currently focused classification
914
 */
915
function get_current_classification_uuid() {
916
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
917
    return $_SESSION['cdm']['taxonomictree_uuid'];
918
  }
919
  else {
920
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
921
  }
922
}
923

    
924
/*
925
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
926
 $_SESSION['cdm'] = NULL;
927
 if(is_string($cdm_ws_uri_update)){
928
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
929
 }
930
 }
931

    
932
 function cdm_dataportal_session_validate(){
933
 if(!isset($_SESSION['cdm']['ws_uri'])){
934
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
935
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
936
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
937
 }
938
 }
939
 */
940

    
941
/**
942
 * creates a  selector form for taxonomic trees.
943
 *
944
 * @return array
945
 *  a drupal form array
946
 */
947
function cdm_taxonomictree_selector() {
948
  _add_js_treeselector();
949

    
950
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
951
  return $form;
952
}
953

    
954
/**
955
 * @todo Please document this function.
956
 * @see http://drupal.org/node/1354
957
 *
958
 * @deprecated use compose_classification_selector instead
959
 */
960
function cdm_taxonomictree_selector_form($form, &$form_state) {
961

    
962
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
963
  $form['#action'] = $url;
964

    
965
  $form['var'] = array(
966
    '#weight' => -3,
967
    '#type' => 'hidden',
968
    '#value' => '[cdm][taxonomictree_uuid]',
969
  );
970

    
971
  $destination_array = drupal_get_destination();
972
  $destination = $destination_array['destination'];
973

    
974
  $form['destination'] = array(
975
    '#weight' => -3,
976
    '#type' => 'hidden',
977
    '#value' =>  $destination,
978
  );
979

    
980
  $options = cdm_get_taxontrees_as_options();
981
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
982
  if($taxontree_includes){
983
    $filtered_options = array();
984
    foreach($options as $uuid=>$label){
985
      if(!empty($taxontree_includes[$uuid])){
986
        $filtered_options[$uuid] = $label;
987
      }
988
    }
989
    $options = $filtered_options;
990
  }
991

    
992
  $form['val'] = array(
993
    '#type' => 'select',
994
    '#title' => t('Available classifications'),
995
    '#default_value' => get_current_classification_uuid(),
996
    '#options' => $options,
997
    '#attributes' => array('class' => array('highlite-first-child')),
998
  );
999

    
1000
  return $form;
1001

    
1002
}
1003

    
1004
/**
1005
 *
1006
 * @ingroup compose
1007
 */
1008
function compose_classification_selector() {
1009

    
1010
  $destination_array = drupal_get_destination();
1011
  $destination = $destination_array['destination'];
1012

    
1013
  $options = cdm_get_taxontrees_as_options();
1014
  $items = array();
1015
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1016

    
1017
  $current_classification_uuid = get_current_classification_uuid();
1018

    
1019

    
1020
  foreach($options as $uuid=>$label){
1021
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1022

    
1023
      $class_attributes = '';
1024
      if($current_classification_uuid == $uuid){
1025
        $class_attributes  = array('focused');
1026
      }
1027
      $items[] = array(
1028
        'data' => l($label,
1029
          'cdm_api/setvalue/session',
1030
          array(
1031
            'query' => array(
1032
              'destination' => $destination,
1033
              'val' => $uuid,
1034
              'var' => '[cdm][taxonomictree_uuid]'
1035
            ),
1036
          )
1037
        ),
1038
        'class' => $class_attributes
1039
      );
1040
    }
1041
  }
1042

    
1043
  $render_array = array(
1044
    '#theme' => 'item_list',
1045
    '#type' => 'ul',
1046
    '#items' => $items
1047
  );
1048

    
1049
  return $render_array;
1050
}
1051

    
1052

    
1053
/* UNREACHABLE since action of form directly links to view.
1054
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1055

    
1056
 $_SESSION['cdm']['search'] = $form_values;
1057
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1058
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1059
 //$paramstr = compose_url_prameterstr($form_values);
1060
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1061
 }
1062
 */
1063
/* ====================== menu callback functions ====================== */
1064
/**
1065
 * @todo Please document this function.
1066
 * @see http://drupal.org/node/1354
1067
 */
1068
/*
1069
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1070
  static $comment_node_disabled =  0;
1071
  static $comment_node_read_only =  1;
1072
  static $comment_node_read_write =  2;
1073

    
1074
  if ($form_id == 'node_type_form'
1075
   && isset($form['identity']['type'])
1076
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1077
  ) {
1078
    $form['workflow']['comment'] = array(
1079
      '#type' => 'radios',
1080
      '#title' => t('Default comment setting'),
1081
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1082
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1083
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1084
    );
1085
  }
1086
}
1087
*/
1088

    
1089
/**
1090
 * Displays a list of the known taxonomic names.
1091
 *
1092
 * When the list of taxonomic names is displayed, long lists are split up into
1093
 * multiple pages.
1094
 *
1095
 * TODO: Parameters are still preliminary.
1096
 *
1097
 * @param string $beginsWith
1098
 * @param string $page
1099
 *   Page number to diplay defaults to page 1.
1100
 * @param bool $onlyAccepted
1101
 */
1102
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1103

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

    
1106
  /*
1107
  // FIXME the filter for accepted names will be a form element, thus this
1108
  // widget should be generated via form api preferably as block.
1109
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1110
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1111
  $out .= theme('cdm_listof_taxa', $taxonPager);
1112
  return $out;
1113
  */
1114
}
1115

    
1116
/**
1117
 * @todo Please document this function.
1118
 * @see http://drupal.org/node/1354
1119
 */
1120
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1121

    
1122
  cdm_check_valid_portal_page();
1123

    
1124
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1125
  return theme('cdm_reference_page', array('reference' => $reference));
1126
}
1127

    
1128
/**
1129
 * Creates a view on a all references contained in the portal.
1130
 *
1131
 * This function is used at the path cdm_dataportal/reference/list
1132
 */
1133
function cdm_dataportal_view_reference_list($pageNumber) {
1134
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1135
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1136
}
1137

    
1138
/**
1139
 * @todo Please document this function.
1140
 * @see http://drupal.org/node/1354
1141
 */
1142
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1143

    
1144
  cdm_check_valid_portal_page();
1145

    
1146
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1147
  return theme('cdm_media_page', array(
1148
    'media' => $media,
1149
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1150
    'partId' => $part,
1151
    ));
1152
}
1153

    
1154
/**
1155
 * @todo Please document this function.
1156
 * @see http://drupal.org/node/1354
1157
 */
1158
function _load_taxonBase(&$taxonBase) {
1159
  if (isset($taxonBase->uuid)) {
1160
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1161
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1162
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1163
  }
1164
}
1165

    
1166
/**
1167
 * Loads the media associated to the given taxon from the cdm server.
1168
 * The aggregation settings regarding taxon relathionships and
1169
 * taxonnomic childen are taken into account.
1170
 *
1171
 * The media lists are cached in a static variable.
1172
 *
1173
 * @param Taxon $taxon
1174
 *   A CDM Taxon entitiy
1175
 *
1176
 * @return array
1177
 *   An array of CDM Media entities
1178
 *
1179
 */
1180
function _load_media_for_taxon($taxon) {
1181

    
1182
  static $media = NULL;
1183

    
1184
  if(!isset($media)) {
1185
    $media = array();
1186
  }
1187
  if (!isset($media[$taxon->uuid])) {
1188

    
1189
    // --- GET Images --- //
1190
    $mediaQueryParameters = array(
1191
        "type" => "ImageFile",
1192
    );
1193

    
1194
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1195
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1196
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1197

    
1198
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1199
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1200
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1201
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1202

    
1203
    $ws_endpoint = NULL;
1204
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1205
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1206
    } else {
1207
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1208
    }
1209

    
1210
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1211
        array(
1212
            $taxon->uuid,
1213
        ),
1214
        queryString($mediaQueryParameters)
1215
       );
1216
  }
1217

    
1218
  return $media[$taxon->uuid];
1219
}
1220

    
1221
/**
1222
 *
1223
 * @param Taxon $taxon
1224
 *   A CDM Taxon entitiy
1225
 *
1226
 * @return array
1227
 *   An array of CDM SpecimenOrObservation entities
1228
 *
1229
function _load_occurences_for_taxon($taxon){
1230

    
1231
  static $occurences = NULL;
1232

    
1233
  if(!isset($occurences)) {
1234
    $occurences = array();
1235
  }
1236

    
1237
  if (!isset($occurences[$taxon->uuid])){
1238

    
1239
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1240
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1241
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1242

    
1243
    $by_associatedtaxon_query = http_build_query(array(
1244
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1245
        'relationships' => implode(',', $relationship_choice['direct']),
1246
        'pageSize' => null // all hits in one page
1247
    )
1248
    );
1249

    
1250
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1251
        null,
1252
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1253
    );
1254

    
1255

    
1256
    if(isset($pager->records[0])){
1257
      $occurences[$taxon->uuid] =  $pager->records;
1258
    }
1259
  }
1260
  return $occurences[$taxon->uuid];
1261
}
1262
 */
1263

    
1264
/**
1265
 * Gets a Drupal variable, string or array and returns it.
1266
 *
1267
 * Similar to the variable_get() function of Drupal, except that this function
1268
 * is able to handle arrays correctly. This function is especially useful
1269
 * when dealing with collections of settings form elements (#tree = TRUE).
1270
 *
1271
 * @param string $variableKey
1272
 *   The Unique key of the Drupal variable in the Drupal variables table.
1273
 * @param string $defaultValueString
1274
 *   A string as for example derived from a CONSTANT.
1275
 *
1276
 * @return mixed
1277
 *   usually an array, depending on the nature of the variable.
1278
 *
1279
 * TODO compare with get_array_variable_merged() duplicate functions?
1280
 * @deprecated rather use get_array_variable_merged() since this function
1281
 * used an array as second parameter
1282
 */
1283
function mixed_variable_get($variableKey, $defaultValueString) {
1284
  $systemDefaults = unserialize($defaultValueString);
1285
  $storedSettings = variable_get($variableKey, array());
1286
  if (is_array($storedSettings)) {
1287
    // TODO better use drupal_array_merge_deep() ?
1288
    $settings = array_merge($systemDefaults, $storedSettings);
1289
  }
1290
  else {
1291
    $settings = $systemDefaults;
1292
  }
1293
  return $settings;
1294
}
1295

    
1296
/**
1297
 * Recursive function to convert an object into an array.
1298
 * also subordinate objects will be converted.
1299
 *
1300
 * @param object $object
1301
 * @return the array
1302
 */
1303
function convert_to_array($object) {
1304
  if(is_object($object) || is_array($object)) {
1305
    $array = (array)$object;
1306
    foreach ($array as $key=>$value){
1307
      $array[$key] = convert_to_array($value);
1308
    }
1309
    return $array;
1310
  } else {
1311
    return $object;
1312
  }
1313
}
1314

    
1315
/**
1316
 * Searches the $collection for the cdm entitiy given as $element.
1317
 *
1318
 * The elements are compared by their UUID.
1319
 *
1320
 * @param $element
1321
 *  the CDM entitiy to search for
1322
 * @param $collection
1323
 *  the list of CDM entities to search in
1324
 *
1325
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1326
 *
1327
 */
1328
function contains_cdm_entitiy($element, $collection) {
1329
  $result = FALSE;
1330
  foreach ($collection as $a) {
1331
    if ($a->uuid == $element->uuid) {
1332
      $result = TRUE;
1333
    }
1334
  }
1335
  return $result;
1336
}
1337

    
1338
/**
1339
 * Fiters the array $entity_list of CDM entities by the list
1340
 * of $excludes. Any element contained in the $excludes will be removed
1341
 * from included int the retuned list.
1342
 *
1343
 * If the $entity_list is not an array the $excludes will be returned.
1344
 */
1345
function filter_cdm_entity_list($entity_list, $excludes) {
1346
  if (is_array($entity_list)) {
1347
    $result = $entity_list;
1348
    if ($excludes) {
1349
      foreach ($excludes as $exclude) {
1350
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1351
          $result[] = $exclude;
1352
        }
1353
      }
1354
    }
1355
  }
1356
  else {
1357
    $result = $excludes;
1358
  }
1359
  return $result;
1360
}
1361

    
1362
/**
1363
 * Wraps the given $html string into a render array suitable for drupal_render()
1364
 *
1365
 * @param $html
1366
 *   the html string, see
1367
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1368
 * @param $weight
1369
 *   A positive or negative number (integer or decimal).
1370
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1371
 * @param $prefix
1372
 *   Optional markup for the '#prefix' element of the render array
1373
 * @param $suffix
1374
 *   Optional markup for the '#suffix' element of the render array
1375
 *
1376
 * @return array
1377
 *   A render array
1378
 *
1379
 */
1380
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1381
  $render_array = array(
1382
    '#markup' => $html
1383
      );
1384
  if (is_numeric($weight)) {
1385
    $render_array['#weight'] = $weight;
1386
  }
1387
  if($prefix){
1388
    $render_array['#prefix'] = $prefix;
1389
  }
1390
  if($suffix) {
1391
    $render_array['#suffix'] = $suffix;
1392
  }
1393
  return $render_array;
1394
}
1395

    
1396
/**
1397
 * Loads the subgraph of a given PolytomousKeyNode.
1398
 *
1399
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1400
 * the CDM REST service.
1401
 *
1402
 * @param mixed $polytomousKeyNode
1403
 *   PolytomousKeyNode passed by reference.
1404
 *
1405
 * @return void
1406
 */
1407
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1408

    
1409
  if (!$polytomousKeyNode) {
1410
    return;
1411
  }
1412
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1413
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1414
    return;
1415
  }
1416
  if (!is_uuid($polytomousKeyNode->uuid)) {
1417
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1418
    return;
1419
  }
1420

    
1421
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1422

    
1423
  if (!$polytomousKeyNode) {
1424
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1425
    return;
1426
  }
1427

    
1428
  // Load children.
1429
  foreach ($polytomousKeyNode->children as &$childNode) {
1430
    _load_polytomousKeySubGraph($childNode);
1431
  }
1432

    
1433
  // Load subkey.
1434
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1435

    
1436
  // Load taxon.
1437
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1438
  _load_taxonBase($polytomousKeyNode->taxon);
1439
  return;
1440
}
1441

    
1442
/**
1443
 * @todo Please document this function.
1444
 * @see http://drupal.org/node/1354
1445
 */
1446
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1447

    
1448
  cdm_check_valid_portal_page();
1449

    
1450
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1451

    
1452
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1453
  if (is_array($sourcePager->records)) {
1454
    $polytomousKey->sources = $sourcePager->records;
1455
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1456
  }
1457

    
1458
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1459
  if (is_array($annotationPager->records)) {
1460
    $polytomousKey->annotations = $annotationPager->records;
1461
  }
1462

    
1463
  _load_polytomousKeySubGraph($polytomousKey->root);
1464
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1465
}
1466

    
1467
/**
1468
 * Creates a taxon page view or a chapter of it.
1469
 *
1470
 * The taxon page gives detailed information on a taxon, it shows:
1471
 *  - Taxon name.
1472
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1473
 *    heterotypic and finally followed by misapplied names.
1474
 *    The list is ordered historically.
1475
 *  - All description associated with the taxon.
1476
 *
1477
 * @param string $uuid
1478
 * @param string $chapter
1479
 *   Name of the part to display, valid values are:
1480
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1481
 *
1482
 * @return string
1483
 */
1484
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1485

    
1486
  cdm_check_valid_taxon_page($chapter);
1487
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1488
  // show a warning in case the javascript development mode is anabled
1489
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1490
    drupal_set_message(t('The !url1 is enabled.
1491
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1492
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1493
    )),
1494
    'warning'
1495
        );
1496
  }
1497

    
1498
  // Display the page for the taxon defined by $uuid.
1499
  // set_last_taxon_page_tab(arg(3));
1500
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1501
  if (!empty($taxonpage)) {
1502
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1503
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1504
  }
1505
  else {
1506
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1507
    return '';
1508
  }
1509
}
1510

    
1511
/**
1512
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1513
 * which has two fields, one for the page title and one for the content. Later on in the
1514
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1515
 * function as the function parameters $title and $content.
1516
 *
1517
 * @param string $uuid
1518
 *   the uuid of the taxon to show
1519
 * @param string $chapter
1520
 *   Name of the part to display, valid values are:
1521
 *   'description', 'images', 'synonymy', 'all'.
1522
 *
1523
 * @return taxonpage object with the following fields:
1524
 *   - title : the title of the page
1525
 *   - content: the content of the page
1526
 *
1527
 */
1528
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1529
  // Taxon object.
1530
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1531
  if (empty($taxon)) {
1532
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1533
    return FALSE;
1534
  }
1535
  $taxonpage = new stdClass();
1536

    
1537
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1538
    'taxon' => $taxon
1539
  ));
1540

    
1541
  // Check if the taxon id contained in the currently selected tree.
1542
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1543

    
1544
  if (!$taxon_in_current_classification) {
1545
    $classifications = get_classifications_for_taxon($taxon);
1546
    RenderHints::pushToRenderStack('not_in_current_classification');
1547
    $taxon_name_markup = render_taxon_or_name($taxon);
1548

    
1549
    if (count($classifications) == 0) {
1550
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1551
        array(
1552
        '!taxonname' => $taxon_name_markup,
1553
        )
1554
      ), 'warning');
1555
    }
1556
    else {
1557
      $trees = '';
1558
      foreach ($classifications as $classification) {
1559
        if (isset($classification->titleCache)) {
1560
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1561
        }
1562
      }
1563

    
1564
      drupal_set_message(format_plural(count($trees),
1565
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1566
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1567
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1568
        ) ,
1569
        'warning');
1570
    }
1571
    RenderHints::popFromRenderStack();
1572
  }
1573

    
1574
  // Render the taxon page.
1575
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1576
  $taxonpage->content = drupal_render($render_array);
1577

    
1578
  return $taxonpage;
1579
}
1580

    
1581
/**
1582
 * Creates a specimen page view.
1583
 * @param string $uuid the UUID of the specimen
1584
 * @return array|string
1585
 */
1586
function cdm_dataportal_specimen_page_view($uuid) {
1587

    
1588
    //cdm_check_valid_taxon_page($chapter);
1589
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1590
    // show a warning in case the javascript development mode is anabled
1591
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1592
        drupal_set_message(t('The !url1 is enabled.
1593
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1594
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1595
        )),
1596
            'warning'
1597
        );
1598
    }
1599

    
1600
    // Display the page for the specimen defined by $uuid.
1601
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1602
    if (!empty($specimenpage)) {
1603
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1604
    }
1605
    else {
1606
        return '';
1607
    }
1608
}
1609

    
1610
/**
1611
 *
1612
 * Creates a specimen view.
1613
 * @param string $uuid the UUID of the specimen
1614
 * @return array|string
1615
 */
1616
function cdm_dataportal_specimen_view($uuid) {
1617
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1618
    if (empty($specimen)) {
1619
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1620
        return FALSE;
1621
    }
1622
    $specimenpage = new stdClass();
1623

    
1624
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1625
        'specimen' => $specimen
1626
    ));
1627

    
1628
    // Render the specimen page.
1629
    $render_array = compose_cdm_specimen_page($uuid);
1630
    $specimenpage->content = drupal_render($render_array);
1631

    
1632
    return $specimenpage;
1633
}
1634

    
1635
/**
1636
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1637
 *
1638
 * The node page shows the taxon name title and the list of taxon related
1639
 * with such taxon. Name on the tree already in use.
1640
 *
1641
 * @param UUID $taxon_name_uuid
1642
 *   The uuid of the CDM TaxonNameBase to show a name page for
1643
 * @param UUID $taxon_to_hide_uuid
1644
 *   A taxon which should not be displayed in the taxon list
1645
 * @param UUID $highlite_synonym_uuid
1646
 *   Optinal parameter wich takes another taxon uuid, if given the
1647
 *   target taxon pages will show the syonymy tab where the taxon
1648
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1649
 *   in case it is found on this page.
1650
 *
1651
 * @return mixed
1652
 *   The formatted name page as node.
1653
 */
1654
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1655

    
1656
  cdm_check_valid_portal_page();
1657

    
1658
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1659
  if (!empty($taxonname_page)) {
1660
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1661
  }
1662
  else {
1663
    return '';
1664
  }
1665
}
1666

    
1667
/**
1668
 * View function for a TaxonNameBase page.
1669
 *
1670
 * The name page lists all taxa for which the name specified by the
1671
 * $taxon_name_uuid is being used. I case there is only one name the
1672
 * page automatically redirects ti the according taxon page. Otherwise
1673
 * the list of names is displayed.
1674
 *
1675
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1676
 * list of taxa. This is useful for example when referencing from a taxon
1677
 * to the name page and the referring taxon should not be repeaded in the
1678
 * name page.
1679
 *
1680
 *
1681
 * @param UUID $taxon_name_uuid
1682
 *   The uuid of the CDM TaxonNameBase to show a name page for
1683
 * @param UUID $taxon_to_hide_uuid
1684
 *   A taxon which should not be displayed in the taxon list
1685
 * @param UUID $highlite_synonym_uuid
1686
 *   Optinal parameter wich takes another taxon uuid, if given the
1687
 *   target taxon pages will show the syonymy tab where the taxon
1688
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1689
 *   in case it is found on this page.
1690
 *
1691
 * @return object
1692
 *   An object with two fields:
1693
 *     - title: the page title
1694
 *     - content: the page content
1695
 */
1696
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1697
  // Getting the full taxonname object from the server.
1698
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1699
  if (!$taxon_name) {
1700
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1701
    return FALSE;
1702
  }
1703
  // Searching for all the taxa connected with the taxon name on the tree
1704
  // in use.
1705
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1706
  $request_params = array();
1707
  $request_params['query'] = $name_cache;
1708
  $request_params['tree'] = get_current_classification_uuid();
1709
  $request_params['doTaxa'] = 1;
1710
  $request_params['doSynonyms'] = 1;
1711
  $request_params['doTaxaByCommonNames'] = 0;
1712
  $request_params['matchMode'] = "EXACT";
1713
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1714

    
1715
  // Removing the name where we came from.
1716
  foreach ($taxon_pager->records as $k => &$taxon) {
1717
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1718
      unset($taxon_pager->records[$k]);
1719
    }
1720
  }
1721
  // Show the taxa list or go to the singular taxon.
1722
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1723
    $singleTaxon = array_pop($taxon_pager->records);
1724
    if ($singleTaxon->class != "Taxon") {
1725
      // It is a Synonym -> look for the accepted.
1726
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1727
      if (!empty($highlite_synonym_uuid)) {
1728
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1729
      }
1730
      else {
1731
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1732
      }
1733
    }
1734
    else {
1735
      // It is an accepted taxon.
1736
      if (!empty($highlite_synonym_uuid)) {
1737
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1738
      }
1739
      else {
1740
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1741
      }
1742
    }
1743
  }
1744
  else {// More than one taxa case.
1745
    $taxon_name_page = new stdClass();
1746
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1747
    if ($taxon_pager->records) {
1748
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1749
    }
1750
    else {
1751
      $taxon_name_page->content = 'This name has no taxa';
1752
    }
1753
    return $taxon_name_page;
1754
  }
1755
}
1756

    
1757
/**
1758
 * Creates a page with the advance search form.
1759
 *
1760
 * NOTE: The advance search form allows searching for taxa.
1761
 */
1762
function cdm_dataportal_view_search_advanced() {
1763
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1764
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1765
}
1766

    
1767
/**
1768
 * Creates a page with the search form for searching by taxon descriptions.
1769
 */
1770
function cdm_dataportal_view_search_taxon_by_description() {
1771
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1772
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1773
}
1774

    
1775
/**
1776
 * Executes the search and generates the result list of taxa.
1777
 */
1778
function cdm_dataportal_view_search_results_taxon() {
1779

    
1780
  $taxonPager = cdm_dataportal_search_execute();
1781

    
1782
  $showThumbnails = do_showThumbnails();
1783

    
1784
  $setSessionUri = url('cdm_api/setvalue/session', array(
1785
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1786
  ));
1787

    
1788
  drupal_add_js('jQuery(document).ready(function() {
1789

    
1790
      // init
1791
      if(' . $showThumbnails . ' == 1){
1792
          jQuery(\'.media_gallery\').show(20);
1793
      } else {
1794
          jQuery(\'.media_gallery\').hide(20);
1795
      }
1796

    
1797
      // add change handler
1798
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1799
      function(event){
1800
        var state = 0;
1801
        if(jQuery(this).is(\':checked\')){
1802
          jQuery(\'.media_gallery\').show(20);
1803
          state = 1;
1804
        } else {
1805
          jQuery(\'.media_gallery\').hide(20);
1806
        }
1807
        // store state in session variable
1808
        var uri = \'' . $setSessionUri . '\' + state;
1809
        jQuery.get(uri);
1810
      });
1811
  });',
1812
  array('type' => "inline", 'scope' => JS_DEFAULT));
1813

    
1814
  drupal_set_title(t('Search results'), PASS_THROUGH);
1815

    
1816
  return theme('cdm_search_results', array(
1817
    'pager' => $taxonPager,
1818
    'path' => 'cdm_dataportal/search/results/taxon',
1819
    ));
1820
}
1821

    
1822
/**
1823
 * Provides the standart image wich indicated a loading process
1824
 *
1825
 * @return string
1826
 *  The img html tag
1827
 */
1828
function loading_image_html() {
1829
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1830
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1831
}
1832

    
1833
/**
1834
 * Returns the state of the the showThumbnails flag set in the
1835
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1836
 *
1837
 * @return boolean
1838
 *    returns 1 if the flag is set
1839
 */
1840
function do_showThumbnails() {
1841
  static $showThumbnails = null;
1842

    
1843
  if($showThumbnails == null) {
1844
    $showThumbnails = 0;
1845
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1846
      $showThumbnails = 0;
1847
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1848
      $showThumbnails = is_array($search_gallery_settings)
1849
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1850
        && (
1851
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1852
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1853
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1854
            )
1855
         ? 1 : 0;
1856

    
1857
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1858
    }
1859
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1860
    if (!is_numeric($showThumbnails)) {
1861
      $showThumbnails = 1;
1862
    }
1863
  }
1864

    
1865
  return $showThumbnails;
1866
}
1867

    
1868

    
1869
/* ====================== other functions ====================== */
1870
/**
1871
 * Creates a URL to the taxon page specified by the $uuid parameter.
1872
 *
1873
 * The URL will be prepended with a path element to a specific taxon page tab.
1874
 *
1875
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1876
 * be set globally in the administrative settings or individually in the user
1877
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1878
 * the last portal will stay on this last tab.
1879
 *
1880
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1881
 * internal mechanism by a specific value.
1882
 *
1883
 * @param string $uuid
1884
 *   The UUID of the taxon.
1885
 * @param string $page_tab
1886
 *   Overwriting the preset mechanism by defining specific value for the
1887
 *   taxon page tab.
1888
 *
1889
 * @return string
1890
 *   The created URL.
1891
 */
1892
function path_to_taxon($uuid, $page_tab = FALSE) {
1893

    
1894
  $tab = get_default_taxon_tab();
1895
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1896

    
1897
  if (!$uuid) {
1898
    return FALSE;
1899
  }
1900

    
1901
  if ($page_tab) {
1902
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1903
  }
1904
  elseif (!$tab || strtolower($tab) == 'general') {
1905
    return 'cdm_dataportal/taxon/' . $uuid;
1906
  }
1907
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1908
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1909
  }
1910
  else {
1911
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1912
  }
1913
}
1914

    
1915
function path_to_specimen($uuid) {
1916

    
1917
    if (!$uuid) {
1918
        return FALSE;
1919
    }
1920
    else {
1921
        return 'cdm_dataportal/specimen/' . $uuid;
1922
    }
1923
}
1924

    
1925
/**
1926
 * Creates a URL to show a synonmy in the according taxon page.
1927
 *
1928
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1929
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1930
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1931
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1932
 * in the page
1933
 *
1934
 * @param string $synonymUuid
1935
 *    The uuid of the synonym
1936
 * @param string $acceptedUuid
1937
 *    The uuid of the according accepted taxon
1938
 * @return string
1939
 *    The URL to show a synonmy in the according taxon page
1940
 */
1941
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1942
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1943
  return url($acceptedPath, array(
1944
      'query' => array(
1945
        // highlite the synony in the synonymy
1946
        'highlite' => $synonymUuid,
1947
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1948
        // see theme_taxon_page_title()
1949
        'acceptedFor' => $synonymUuid
1950
      ),
1951
      'fragment' => $synonymUuid
1952
  ));
1953

    
1954
}
1955

    
1956
/**
1957
 * Compses the drupal path to the key identified by the uuid.
1958
 *
1959
 * @param string $keyType
1960
 *    the key typer corresponds to the specific class of the CDM
1961
 *    IdentificationKey. Possible values are
1962
 *      -PolytomousKey
1963
 *      -MultimediaKey
1964
 *      - ...
1965
 * @param UUID $keyUuid
1966
 *   The UUID of the key
1967
 */
1968
function path_to_key($keyType, $keyUuid) {
1969
  if (!$keyUuid || !$keyType) {
1970
    return FALSE;
1971
  }
1972
  $keyType{0} = strtolower($keyType{0});
1973
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1974
}
1975

    
1976
/**
1977
 * @todo Please document this function.
1978
 * @see http://drupal.org/node/1354
1979
 */
1980
function path_to_reference($uuid) {
1981
  if (!$uuid) {
1982
    return FALSE;
1983
  }
1984
  return 'cdm_dataportal/reference/' . $uuid;
1985
}
1986

    
1987
/**
1988
 * Creates the path to a cdm_dataportal taxon name page.
1989
 *
1990
 * @param UUID $taxon_name_uuid
1991
 *   The uuid of the CDM TaxonNameBase to show a name page for
1992
 * @param UUID $taxon_to_hide_uuid
1993
 *   A taxon which should not be displayed in the taxon list
1994
 * @param UUID $highlite_synonym_uuid
1995
 *   Optinal parameter wich takes another taxon uuid, if given the
1996
 *   target taxon pages will show the syonymy tab where the taxon
1997
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1998
 *   in case it is found on this page.
1999
 *
2000
 * @return a URI path element as string
2001
 */
2002
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2003
  $res = FALSE;
2004
  if ($name_uuid) {
2005
    $res = 'cdm_dataportal/name/' . $name_uuid;
2006
  }
2007
  if($taxon_to_hide_uuid){
2008
    $res .= '/' . $taxon_to_hide_uuid;
2009
    if($synonym_uuid){
2010
      $res .= '/' . $synonym_uuid;
2011
    }
2012
  }
2013
  return $res;
2014
}
2015

    
2016
/**
2017
 * @todo Please document this function.
2018
 * @see http://drupal.org/node/1354
2019
 */
2020
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2021
  if (!$uuid) {
2022
    return FALSE;
2023
  }
2024
  $out = 'cdm_dataportal/media/' . $uuid;
2025
  if ($representaion_uuid) {
2026
    $out .= '/' . $representaion_uuid;
2027
    if ($partId !== FALSE) {
2028
      $out .= '/' . $partId;
2029
    }
2030
  }
2031
  return $out;
2032
}
2033

    
2034
/**
2035
 * Compares thisRank with thatRank.
2036
 *
2037
 * Returns a negative integer, zero, or a positive integer
2038
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2039
 * e.g:
2040
 * <ul>
2041
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2042
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2043
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2044
 * </ul>
2045
 * <p>
2046
 * This compare logic of the underlying webservice is the
2047
 * <b>inverse logic</b> of the the one implemented in
2048
 * java.lang.Comparable#compareTo(java.lang.Object)
2049
 *
2050
 * @param $thisRankUuid
2051
 * @param $thatRankUuid
2052
 *
2053
 * @return int
2054
 *   A negative integer, zero, or a positive integer
2055
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2056
 */
2057
function rank_compare($thisRankUuid, $thatRankUuid) {
2058
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2059
  return $result->Integer;
2060
}
2061

    
2062
/**
2063
 * Composes an HTML element class attribute value composed of
2064
 * the shortname of the cdm class and the uuid of the entity.
2065
 * This class attribute should be used whereever an cdm-entity is rendered.
2066
 *
2067
 * These according class selectors in css must be escaped, eg:
2068
 *    .cdm\:TextData
2069
 *
2070
 * @param $cdmEntity
2071
 */
2072
function html_class_attribute_ref($cdmEntity) {
2073

    
2074
  if (is_cdm_entity($cdmEntity)) {
2075
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2076
  }
2077
}
2078

    
2079

    
2080
/**
2081
 * Creates a short taxonname.
2082
 *
2083
 * The short name is created by using the taggedTitle field of
2084
 * NameSTO or NameTO instances.
2085
 * If the taggedTitle if empty the fullname will be returned.
2086
 *
2087
 * @param unknown_type $name
2088
 *   Name or TreeNode.
2089
 *
2090
 * @return string
2091
 */
2092
function cdm_dataportal_shortname_of($name) {
2093
  $nameStr = '';
2094

    
2095
  normalize_tagged_text($name->taggedTitle);
2096

    
2097
  // Get all tagged text tokens of the scientific name.
2098
  foreach ($name->taggedTitle as $tagtxt) {
2099
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2100
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2101
    }
2102
  }
2103
  $nameStr = trim($nameStr);
2104

    
2105
  if ($nameStr) {
2106

    
2107
    // Do not return short names for these.
2108
    if ($name->unplaced || $name->excluded) {
2109
      return $nameStr;
2110
    }
2111

    
2112
    /*
2113
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2114
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2115
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2116
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2117
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2118
    */
2119
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2120
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2121
      return $matches[1][0] . "." . $matches[3][0];
2122
    }
2123
    else {
2124
      return $nameStr;
2125
    }
2126
  }
2127
  else {
2128
    return $name->titleCache;
2129
  }
2130
}
2131

    
2132
/**
2133
 * Check if a taxon is accepted by the current taxonomic tree.
2134
 *
2135
 * @param mixed $taxon
2136
 *   The Taxon obkect to check.
2137
 *
2138
 * @return bool
2139
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2140
 */
2141
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2142

    
2143
  $defaultTreeUuid = get_current_classification_uuid();
2144

    
2145
  if (isset($taxon->taxonNodes)) {
2146
    $taxonNodes = $taxon->taxonNodes;
2147
  }
2148
  else {
2149
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2150
  }
2151

    
2152
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2153
    foreach ($taxonNodes as $node) {
2154
      if (isset($node->classification)){
2155
        if(is_object($node->classification)) {
2156
          if ($node->classification->uuid == $defaultTreeUuid) {
2157
            return TRUE;
2158
          }
2159
        }
2160
        else {
2161
          if ($node->classification == $defaultTreeUuid) {
2162
            return TRUE;
2163
          }
2164
        }
2165
      }
2166
    }
2167
  }
2168

    
2169
  return FALSE;
2170
}
2171

    
2172
/**
2173
 * Checks is the source has one of the given types.
2174
 *
2175
 * @param object $source
2176
 *   The original source entity
2177
 * @param array $types
2178
 *   An array of elementd of the OriginalSourceType enumeration
2179
 *   If not set the default will be used which is:
2180
 *    - Lineage
2181
 *    - PrimaryMediaSource
2182
 *    - PrimaryTaxonomicSource
2183
 *    - Unknown
2184
 *    - Other
2185
 * @return boolean
2186
 */
2187
  function _is_original_source_type($source, $types = null) {
2188
    // this is the default
2189
    // maybe this should also be put into the settings
2190
    static $default = array(
2191
      OriginalSourceType::Lineage,
2192
      OriginalSourceType::PrimaryMediaSource,
2193
      OriginalSourceType::PrimaryTaxonomicSource,
2194
      OriginalSourceType::Unknown,
2195
      OriginalSourceType::Other,
2196
    );
2197

    
2198
    if(!$types){
2199
      $types = $default;
2200
    }
2201
    return isset($source->type) && in_array($source->type, $types);
2202
  }
2203

    
2204
/**
2205
 * @todo Please document this function.
2206
 * @see http://drupal.org/node/1354
2207
 */
2208
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2209
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2210
}
2211

    
2212

    
2213
/**
2214
 * Collects all the media from a list of description elements.
2215
 *
2216
 * @param array $descriptionElements
2217
 *   The description elements from which to collect the media.
2218
 *
2219
 * @return array
2220
 *   The output with all the collected media.
2221
 */
2222
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2223

    
2224
  $outArrayOfMedia = array();
2225

    
2226
  // Avoiding a warning box in Drupal for Flora Malesiana.
2227
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2228
    foreach ($descriptionElements as $descriptionElement) {
2229
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2230
        foreach ($descriptionElement->media as $media) {
2231
          if (is_object($media)) {
2232
            $outArrayOfMedia[] = $media;
2233
          }
2234
        }
2235
      }
2236
    }
2237
  }
2238
  return $outArrayOfMedia;
2239
}
2240

    
2241
/**
2242
 * @todo Please document this function.
2243
 * @see http://drupal.org/node/1354
2244
 *
2245
 * @param array $cdm_entities
2246
 *   An array of CdmBase instances or a single instance.
2247
 * @param string $footnote_list_key_suggestion
2248
 *
2249
 * @return unknown
2250
 */
2251
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2252

    
2253
   static $annotations_types_filter = null;
2254
   if(!$annotations_types_filter) {
2255
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2256
   }
2257

    
2258
  $footNoteKeys = array();
2259

    
2260
  // Is argument cdmBase an array?
2261
  if (!is_array($cdm_entities)) {
2262
    $cdmBase_array = array();
2263
    $cdmBase_array[] = $cdm_entities;
2264
  }
2265
  else {
2266
    $cdmBase_array = $cdm_entities;
2267
  }
2268

    
2269
  // Getting the key for the footnotemanager.
2270
  if (isset($footnote_list_key_suggestion)) {
2271
    $footnote_list_key = $footnote_list_key_suggestion;
2272
  }
2273
  else {
2274
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2275
  }
2276

    
2277
  // Adding the footnotes keys.
2278
  foreach ($cdmBase_array as $cdmBase_element) {
2279
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2280
    if (is_array($annotations)) {
2281
      foreach ($annotations as $annotation) {
2282
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2283
      }
2284
    }
2285
  }
2286

    
2287
  return $footNoteKeys;
2288
}
2289

    
2290

    
2291
/**
2292
 * Creates a CDM Dynabox.
2293
 *
2294
 * @param string $dynabox_id
2295
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2296
 * @param string $label
2297
 *   The clickable text to show.
2298
 * @param string $content_url
2299
 *   The cdm REST service request url wich will deliver the content to be shown
2300
 *   once the dynabox toggles open.
2301
 * @param string $theme
2302
 *   The theme to be used for rendering the cdm REST service response with is
2303
 *   returned from the $content_url.
2304
 * @param string $link_alt_text
2305
 *   The value for the alt attribute of the dynabox link.
2306
 * @param array $enclosingtags
2307
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2308
 *   element itself, $enclosingtags[1] is the tag to be used for the
2309
 *   dynabox_content (optional)
2310
 * @param array $attributes
2311
 * @param $content_element_selector
2312
 *   Optional jQuery selector which can be used to reference a dom element which should
2313
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2314
 *  element will be placed in this container.
2315
 *
2316
 * @param string $open_callback
2317
 *   optional javascript call back function to be triggered after toggling the box to
2318
 *   the open state.
2319
 * @param string $close_callback
2320
 *   optional javascript call back function to be triggered after toggling the box to
2321
 *   the closed state.
2322
 * @return string Returns HTML for a dynabox.
2323
 * Returns HTML for a dynabox.
2324
 */
2325
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2326
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2327
                     $content_element_selector = null,
2328
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2329
  $out = '';
2330

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

    
2334
  if(!array_key_exists('class', $attributes)) {
2335
    $attributes['class'] = array();
2336
  }
2337
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2338
  $dynabox_attributes = drupal_attributes($attributes);
2339

    
2340

    
2341
  _add_js_domEvent(); // requires domEvent.js
2342
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2343
  drupal_add_js("
2344
  jQuery(document).ready(
2345
      function() {
2346
        dynabox('". $dynabox_id ."',
2347
          {
2348
            open_callback: " . $open_callback .",
2349
            close_callback: " . $close_callback .
2350
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2351
          }
2352
        );
2353
      }
2354
   );",
2355
   array(
2356
    'type'=>'inline',
2357
    'scope'=>'footer'
2358
    )
2359
  );
2360

    
2361

    
2362
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2363
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2364
  $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>';
2365
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2366
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2367
  $out .= '    </' . $enclosingtags[1] . '>';
2368
  $out .= '  </' . $enclosingtags[0] . '>';
2369
  $out .= '<!-- dynabox end -->';
2370
  return $out;
2371
}
2372

    
2373
/**
2374
 * Checks whether a feature has any description elements.
2375
 *
2376
 * @param mixed $featureNode
2377
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2378
 *
2379
 * @see _mergeFeatureTreeDescriptions()
2380
 *
2381
 * @return bool
2382
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2383
 *   contains at least one non empty TextData or at least one DescriptionElement
2384
 *   of an other type. A TextData element holding a multilanguageText or a
2385
 *   source reference is considered to be not empty.
2386
 *
2387
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2388
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2389
 *       $feature_block_has_content in compose_feature_block_items_generic
2390
 */
2391
function has_feature_node_description_elements($featureNode) {
2392

    
2393
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2394
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2395
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2396
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2397
          && $descriptionElement->multilanguageText_L10n->text != ''
2398
          || isset($descriptionElement->sources[0])
2399
          || isset($descriptionElement->media[0]) ) {
2400
          return TRUE;
2401
        }
2402
      }
2403
    }
2404
  }
2405
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2406
    foreach ($featureNode->childNodes as $child) {
2407
      if (has_feature_node_description_elements($child)) {
2408
        return TRUE;
2409
      }
2410
    }
2411
  }
2412
  return FALSE;
2413
}
2414

    
2415
/**
2416
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2417
 *
2418
 * @param $chapter
2419
 *   The taxon page chapter or part
2420
 */
2421
function cdm_check_valid_taxon_page($chapter){
2422
  static $taxon_tabs = null;
2423

    
2424
  cdm_check_valid_portal_page();
2425

    
2426
  if($taxon_tabs == null){
2427
    $taxon_tabs = array('all', 'description');
2428
    foreach(get_taxon_tabs_list() as $tab){
2429
      $taxon_tabs[] = strtolower($tab);
2430
    }
2431
  }
2432

    
2433
  if(!in_array($chapter, $taxon_tabs)){
2434
    // oops this is not a valid chapter name
2435
    http_response_code(404); // 404 = Not Found
2436
  }
2437

    
2438
}
2439

    
2440
/**
2441
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2442
 *
2443
 * @param $chapter
2444
 *   The taxon page chapter or part
2445
 */
2446
function cdm_check_valid_portal_page(){
2447
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2448
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2449
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2450
    http_response_code(404); // 404 = Not Found
2451
    exit('HTTP 404');
2452
  }
2453
}
2454

    
2455
/**
2456
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2457
 *
2458
 * @param $text_a
2459
 * @param $text_b
2460
 * @return string
2461
 */
2462
function diff_viewer($text_a, $text_b) {
2463

    
2464
  static $diff_viewer_count = 0;
2465

    
2466
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2467

    
2468
  // http://code.stephenmorley.org/php/diff-implementation/
2469
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2470
  drupal_add_css(drupal_get_path('module',
2471
      'cdm_dataportal') . '/css/diff.css');
2472
  _add_jquery_ui();
2473
  drupal_add_js(
2474
    'jQuery(document).ready( function(){
2475
        jQuery(\'#' . $element_id . '\').accordion({
2476
        collapsible: true,
2477
        active: false,
2478
        fillSpace: true,
2479
        }).children(\'div\').css({ \'height\': \'auto\' });
2480
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2481
     });'
2482
    , array(
2483
    'type' => 'inline',
2484
    'scope' => 'footer'
2485
  ));
2486

    
2487
  $diff = Diff::compare($text_a,
2488
    $text_b);
2489
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2490
    . Diff::toTable($diff, '', '')
2491
    . '</div></div>';
2492
  return $diff_viewer_markup;
2493
}
2494

    
2495

    
(10-10/16)