Project

General

Profile

Download (81.2 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
        'group' => JS_LIBRARY,
165
        'weight' => 0,
166
        'cache' => TRUE,
167
        'preprocess' => FALSE
168
      )
169
    );
170

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

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

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

    
201
  }
202

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

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

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

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

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

    
299
  /**
300
   * @todo Please document this function.
301
   * @see http://drupal.org/node/1354
302
   */
303
  function _add_js_ahah() {
304

    
305
    _add_js_domEvent(); // requires domEvent.js
306
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
307
  }
308

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

    
315
  global $base_url;
316

    
317

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

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

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

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

    
377

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

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

    
383
    drupal_add_html_head_link(
384
      array(
385
        'href' => $font_awesome_css_uri,
386
        'rel' => 'stylesheet'
387
      )
388
    );
389

    
390
    if($icon_name){
391
      if(!isset($attributes['class'])){
392
        $attributes['class'] = array();
393
      }
394
      $attributes['class'][] = 'fa';
395
      $attributes['class'][] = $icon_name;
396

    
397
      return '<i ' . drupal_attributes($attributes) . '></i>';
398
    }
399

    
400
    return '';
401
  }
402

    
403

    
404
  /* ====================== hook implementations ====================== */
405
  /**
406
   * Implements hook_permission().
407
   *
408
   * Valid permissions for this module.
409
   *
410
   * @return array
411
   *   An array of valid permissions for the cdm_dataportal module.
412
   */
413
  function cdm_dataportal_permission() {
414
    return array(
415
      'administer cdm_dataportal' => array(
416
        'title' => t('Administer CDM DataPortal settings'),
417
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
418
      ),
419
      'access cdm content' => array(
420
        'title' => t('Access CDM content'),
421
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
422
      ),
423
    );
424
  }
425

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
666
  return $items;
667
}
668

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

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

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

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

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

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

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

    
705

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

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

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

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

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

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

    
740

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

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

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

    
766
  return $form;
767
}
768

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

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

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

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

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

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

    
814
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
815
    // $block[1]["info"] = t("CDM DataPortal Credits");
816
    $block["2"] = array(
817
        "info" => t("CDM - Search Taxa"),
818
        "cache" => DRUPAL_NO_CACHE
819
      );
820
    // $block[3]["info"] = t("CDM Filters");
821
    $block["4"]["info"] = t("CDM  - Dataportal Print");
822
    $block["keys"]["info"] = t("CDM - Identification keys");
823
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
824
    $block["classification_breadcrumbs"] =  array(
825
        'info' => t('CDM - Classification breadcrumbs'),
826
        'cache' => DRUPAL_CACHE_PER_PAGE
827
      );
828
    $block["taxonomic_children"] =  array(
829
      'info' => t('CDM - Taxonomic children'),
830
      'cache' => DRUPAL_CACHE_PER_PAGE
831
    );
832
    $block["back_to_search_results"] =  array(
833
      'title' => '<none>',
834
      'info' => t('CDM - Back to search Results'),
835
      'cache' => DRUPAL_CACHE_PER_PAGE,
836
      'visibility' => BLOCK_VISIBILITY_LISTED,
837
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
838
    );
839

    
840
    return $block;
841
}
842

    
843
/**
844
 * Implements hook_block_view().
845
 */
846
function cdm_dataportal_block_view($delta) {
847
  // TODO Rename block deltas (e.g. '2') to readable strings.
848
  switch ($delta) {
849
    // case 'delta-1':
850
    // $block['subject'] = t('Credits');
851
    // $block['content'] = theme('cdm_credits');
852
    // return $block;
853
    case '2':
854
      $block['subject'] = t('Search taxa');
855
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
856
      $block['content'] = drupal_render($form);
857

    
858
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
859
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
860
      }
861
      return $block;
862
    case '4':
863
      $block['subject'] = '';
864
      $block['content'] = theme('cdm_print_button');
865
      return $block;
866
    case "keys":
867
      $block['subject'] = t('Identification Keys');
868
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
869
      return $block;
870
    case "fundedByEDIT":
871
      // t('Funded by EDIT');
872
      $text = '<none>';
873
      $block['subject'] = $text;
874
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
875
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
876
        'attributes' => array("target" => "EDIT"),
877
        'absolute' => TRUE,
878
        'html' => TRUE,
879
      ));
880
      return $block;
881
    case 'classification_breadcrumbs':
882
      $taxon_uuid = get_current_taxon_uuid();
883
      $block['subject'] = '<none>';
884
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
885
      return $block;
886
    case 'taxonomic_children':
887
      $taxon_uuid = get_current_taxon_uuid();
888
      $block['subject'] = '<none>';
889
      $block['content'] = compose_taxonomic_children($taxon_uuid);
890
      return $block;
891
    case 'back_to_search_results':
892
      $block['subject'] = '<none>';
893
      if (isset($_SESSION['cdm']['search'])) {
894
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
895
      }
896
      return $block;
897
    default:
898
      return null;
899
  }
900
}
901

    
902
/**
903
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
904
 *
905
 * @return string
906
 *   the taxon uuid or NULL
907
 */
908
function get_current_taxon_uuid()
909
{
910
  static $taxon_uuid;
911

    
912
  if(!isset($taxon_uuid)){
913
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
914
      $taxon_uuid = $_REQUEST['currentTaxon'];
915
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
916
      $taxon_uuid = arg(2);
917
    } else {
918
      $taxon_uuid = null;
919
    }
920
  }
921

    
922
  return $taxon_uuid;
923
}
924

    
925
/**
926
 * Returns the currently classification tree in use.
927
 *
928
 * @return string
929
 *   The uuid of the currently focused classification
930
 */
931
function get_current_classification_uuid() {
932
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
933
    return $_SESSION['cdm']['taxonomictree_uuid'];
934
  }
935
  else {
936
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
937
  }
938
}
939

    
940
/*
941
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
942
 $_SESSION['cdm'] = NULL;
943
 if(is_string($cdm_ws_uri_update)){
944
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
945
 }
946
 }
947

    
948
 function cdm_dataportal_session_validate(){
949
 if(!isset($_SESSION['cdm']['ws_uri'])){
950
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
951
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
952
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
953
 }
954
 }
955
 */
956

    
957
/**
958
 * creates a  selector form for taxonomic trees.
959
 *
960
 * @return array
961
 *  a drupal form array
962
 */
963
function cdm_taxonomictree_selector() {
964
  _add_js_treeselector();
965

    
966
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
967
  return $form;
968
}
969

    
970
/**
971
 * @todo Please document this function.
972
 * @see http://drupal.org/node/1354
973
 *
974
 * @deprecated use compose_classification_selector instead
975
 */
976
function cdm_taxonomictree_selector_form($form, &$form_state) {
977

    
978
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
979
  $form['#action'] = $url;
980

    
981
  $form['var'] = array(
982
    '#weight' => -3,
983
    '#type' => 'hidden',
984
    '#value' => '[cdm][taxonomictree_uuid]',
985
  );
986

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

    
990
  $form['destination'] = array(
991
    '#weight' => -3,
992
    '#type' => 'hidden',
993
    '#value' =>  $destination,
994
  );
995

    
996
  $options = cdm_get_taxontrees_as_options();
997
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
998
  if($taxontree_includes){
999
    $filtered_options = array();
1000
    foreach($options as $uuid=>$label){
1001
      if(!empty($taxontree_includes[$uuid])){
1002
        $filtered_options[$uuid] = $label;
1003
      }
1004
    }
1005
    $options = $filtered_options;
1006
  }
1007

    
1008
  $form['val'] = array(
1009
    '#type' => 'select',
1010
    '#title' => t('Available classifications'),
1011
    '#default_value' => get_current_classification_uuid(),
1012
    '#options' => $options,
1013
    '#attributes' => array('class' => array('highlite-first-child')),
1014
  );
1015

    
1016
  return $form;
1017

    
1018
}
1019

    
1020
/**
1021
 *
1022
 * @ingroup compose
1023
 */
1024
function compose_classification_selector() {
1025

    
1026
  $destination_array = drupal_get_destination();
1027
  $destination = $destination_array['destination'];
1028

    
1029
  $options = cdm_get_taxontrees_as_options();
1030
  $items = array();
1031
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1032

    
1033
  $current_classification_uuid = get_current_classification_uuid();
1034

    
1035

    
1036
  foreach($options as $uuid=>$label){
1037
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1038

    
1039
      $class_attributes = '';
1040
      if($current_classification_uuid == $uuid){
1041
        $class_attributes  = array('focused');
1042
      }
1043
      $items[] = array(
1044
        'data' => l($label,
1045
          'cdm_api/setvalue/session',
1046
          array(
1047
            'query' => array(
1048
              'destination' => $destination,
1049
              'val' => $uuid,
1050
              'var' => '[cdm][taxonomictree_uuid]'
1051
            ),
1052
          )
1053
        ),
1054
        'class' => $class_attributes
1055
      );
1056
    }
1057
  }
1058

    
1059
  $render_array = array(
1060
    '#theme' => 'item_list',
1061
    '#type' => 'ul',
1062
    '#items' => $items
1063
  );
1064

    
1065
  return $render_array;
1066
}
1067

    
1068

    
1069
/* UNREACHABLE since action of form directly links to view.
1070
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1071

    
1072
 $_SESSION['cdm']['search'] = $form_values;
1073
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1074
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1075
 //$paramstr = compose_url_prameterstr($form_values);
1076
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1077
 }
1078
 */
1079
/* ====================== menu callback functions ====================== */
1080
/**
1081
 * @todo Please document this function.
1082
 * @see http://drupal.org/node/1354
1083
 */
1084
/*
1085
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1086
  static $comment_node_disabled =  0;
1087
  static $comment_node_read_only =  1;
1088
  static $comment_node_read_write =  2;
1089

    
1090
  if ($form_id == 'node_type_form'
1091
   && isset($form['identity']['type'])
1092
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1093
  ) {
1094
    $form['workflow']['comment'] = array(
1095
      '#type' => 'radios',
1096
      '#title' => t('Default comment setting'),
1097
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1098
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1099
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1100
    );
1101
  }
1102
}
1103
*/
1104

    
1105
/**
1106
 * Displays a list of the known taxonomic names.
1107
 *
1108
 * When the list of taxonomic names is displayed, long lists are split up into
1109
 * multiple pages.
1110
 *
1111
 * TODO: Parameters are still preliminary.
1112
 *
1113
 * @param string $beginsWith
1114
 * @param string $page
1115
 *   Page number to diplay defaults to page 1.
1116
 * @param bool $onlyAccepted
1117
 */
1118
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1119

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

    
1122
  /*
1123
  // FIXME the filter for accepted names will be a form element, thus this
1124
  // widget should be generated via form api preferably as block.
1125
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1126
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1127
  $out .= theme('cdm_listof_taxa', $taxonPager);
1128
  return $out;
1129
  */
1130
}
1131

    
1132
/**
1133
 * @todo Please document this function.
1134
 * @see http://drupal.org/node/1354
1135
 */
1136
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1137

    
1138
  cdm_check_valid_portal_page();
1139

    
1140
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1141
  return theme('cdm_reference_page', array('reference' => $reference));
1142
}
1143

    
1144
/**
1145
 * Creates a view on a all references contained in the portal.
1146
 *
1147
 * This function is used at the path cdm_dataportal/reference/list
1148
 */
1149
function cdm_dataportal_view_reference_list($pageNumber) {
1150
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1151
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1152
}
1153

    
1154
/**
1155
 * @todo Please document this function.
1156
 * @see http://drupal.org/node/1354
1157
 */
1158
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1159

    
1160
  cdm_check_valid_portal_page();
1161

    
1162
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1163
  return theme('cdm_media_page', array(
1164
    'media' => $media,
1165
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1166
    'partId' => $part,
1167
    ));
1168
}
1169

    
1170
/**
1171
 * @todo Please document this function.
1172
 * @see http://drupal.org/node/1354
1173
 */
1174
function _load_taxonBase(&$taxonBase) {
1175
  if (isset($taxonBase->uuid)) {
1176
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1177
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1178
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1179
  }
1180
}
1181

    
1182
/**
1183
 * Loads the media associated to the given taxon from the cdm server.
1184
 * The aggregation settings regarding taxon relathionships and
1185
 * taxonnomic childen are taken into account.
1186
 *
1187
 * The media lists are cached in a static variable.
1188
 *
1189
 * @param Taxon $taxon
1190
 *   A CDM Taxon entitiy
1191
 *
1192
 * @return array
1193
 *   An array of CDM Media entities
1194
 *
1195
 */
1196
function _load_media_for_taxon($taxon) {
1197

    
1198
  static $media = NULL;
1199

    
1200
  if(!isset($media)) {
1201
    $media = array();
1202
  }
1203
  if (!isset($media[$taxon->uuid])) {
1204

    
1205
    // --- GET Images --- //
1206
    $mediaQueryParameters = array(
1207
        "type" => "ImageFile",
1208
    );
1209

    
1210
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1211
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1212
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1213

    
1214
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1215
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1216
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1217
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1218

    
1219
    $ws_endpoint = NULL;
1220
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1221
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1222
    } else {
1223
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1224
    }
1225

    
1226
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1227
        array(
1228
            $taxon->uuid,
1229
        ),
1230
        queryString($mediaQueryParameters)
1231
       );
1232
  }
1233

    
1234
  return $media[$taxon->uuid];
1235
}
1236

    
1237
/**
1238
 *
1239
 * @param Taxon $taxon
1240
 *   A CDM Taxon entitiy
1241
 *
1242
 * @return array
1243
 *   An array of CDM SpecimenOrObservation entities
1244
 *
1245
function _load_occurences_for_taxon($taxon){
1246

    
1247
  static $occurences = NULL;
1248

    
1249
  if(!isset($occurences)) {
1250
    $occurences = array();
1251
  }
1252

    
1253
  if (!isset($occurences[$taxon->uuid])){
1254

    
1255
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1256
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1257
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1258

    
1259
    $by_associatedtaxon_query = http_build_query(array(
1260
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1261
        'relationships' => implode(',', $relationship_choice['direct']),
1262
        'pageSize' => null // all hits in one page
1263
    )
1264
    );
1265

    
1266
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1267
        null,
1268
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1269
    );
1270

    
1271

    
1272
    if(isset($pager->records[0])){
1273
      $occurences[$taxon->uuid] =  $pager->records;
1274
    }
1275
  }
1276
  return $occurences[$taxon->uuid];
1277
}
1278
 */
1279

    
1280
/**
1281
 * Gets a Drupal variable, string or array and returns it.
1282
 *
1283
 * Similar to the variable_get() function of Drupal, except that this function
1284
 * is able to handle arrays correctly. This function is especially useful
1285
 * when dealing with collections of settings form elements (#tree = TRUE).
1286
 *
1287
 * @param string $variableKey
1288
 *   The Unique key of the Drupal variable in the Drupal variables table.
1289
 * @param string $defaultValueString
1290
 *   A string as for example derived from a CONSTANT.
1291
 *
1292
 * @return mixed
1293
 *   usually an array, depending on the nature of the variable.
1294
 *
1295
 * TODO compare with get_array_variable_merged() duplicate functions?
1296
 * @deprecated rather use get_array_variable_merged() since this function
1297
 * used an array as second parameter
1298
 */
1299
function mixed_variable_get($variableKey, $defaultValueString) {
1300
  $systemDefaults = unserialize($defaultValueString);
1301
  $storedSettings = variable_get($variableKey, array());
1302
  if (is_array($storedSettings)) {
1303
    // TODO better use drupal_array_merge_deep() ?
1304
    $settings = array_merge($systemDefaults, $storedSettings);
1305
  }
1306
  else {
1307
    $settings = $systemDefaults;
1308
  }
1309
  return $settings;
1310
}
1311

    
1312
/**
1313
 * Recursive function to convert an object into an array.
1314
 * also subordinate objects will be converted.
1315
 *
1316
 * @param object $object
1317
 * @return the array
1318
 */
1319
function convert_to_array($object) {
1320
  if(is_object($object) || is_array($object)) {
1321
    $array = (array)$object;
1322
    foreach ($array as $key=>$value){
1323
      $array[$key] = convert_to_array($value);
1324
    }
1325
    return $array;
1326
  } else {
1327
    return $object;
1328
  }
1329
}
1330

    
1331
/**
1332
 * Searches the $collection for the cdm entitiy given as $element.
1333
 *
1334
 * The elements are compared by their UUID.
1335
 *
1336
 * @param $element
1337
 *  the CDM entitiy to search for
1338
 * @param $collection
1339
 *  the list of CDM entities to search in
1340
 *
1341
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1342
 *
1343
 */
1344
function contains_cdm_entitiy($element, $collection) {
1345
  $result = FALSE;
1346
  foreach ($collection as $a) {
1347
    if ($a->uuid == $element->uuid) {
1348
      $result = TRUE;
1349
    }
1350
  }
1351
  return $result;
1352
}
1353

    
1354
/**
1355
 * Fiters the array $entity_list of CDM entities by the list
1356
 * of $excludes. Any element contained in the $excludes will be removed
1357
 * from included int the retuned list.
1358
 *
1359
 * If the $entity_list is not an array the $excludes will be returned.
1360
 */
1361
function filter_cdm_entity_list($entity_list, $excludes) {
1362
  if (is_array($entity_list)) {
1363
    $result = $entity_list;
1364
    if ($excludes) {
1365
      foreach ($excludes as $exclude) {
1366
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1367
          $result[] = $exclude;
1368
        }
1369
      }
1370
    }
1371
  }
1372
  else {
1373
    $result = $excludes;
1374
  }
1375
  return $result;
1376
}
1377

    
1378
/**
1379
 * Wraps the given $html string into a render array suitable for drupal_render()
1380
 *
1381
 * @param $html
1382
 *   the html string, see
1383
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1384
 * @param $weight
1385
 *   A positive or negative number (integer or decimal).
1386
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1387
 * @param $prefix
1388
 *   Optional markup for the '#prefix' element of the render array
1389
 * @param $suffix
1390
 *   Optional markup for the '#suffix' element of the render array
1391
 *
1392
 * @return array
1393
 *   A render array
1394
 *
1395
 */
1396
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1397
  $render_array = array(
1398
    '#markup' => $html
1399
      );
1400
  if (is_numeric($weight)) {
1401
    $render_array['#weight'] = $weight;
1402
  }
1403
  if($prefix){
1404
    $render_array['#prefix'] = $prefix;
1405
  }
1406
  if($suffix) {
1407
    $render_array['#suffix'] = $suffix;
1408
  }
1409
  return $render_array;
1410
}
1411

    
1412
/**
1413
 * Loads the subgraph of a given PolytomousKeyNode.
1414
 *
1415
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1416
 * the CDM REST service.
1417
 *
1418
 * @param mixed $polytomousKeyNode
1419
 *   PolytomousKeyNode passed by reference.
1420
 *
1421
 * @return void
1422
 */
1423
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1424

    
1425
  if (!$polytomousKeyNode) {
1426
    return;
1427
  }
1428
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1429
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1430
    return;
1431
  }
1432
  if (!is_uuid($polytomousKeyNode->uuid)) {
1433
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1434
    return;
1435
  }
1436

    
1437
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1438

    
1439
  if (!$polytomousKeyNode) {
1440
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1441
    return;
1442
  }
1443

    
1444
  // Load children.
1445
  foreach ($polytomousKeyNode->children as &$childNode) {
1446
    _load_polytomousKeySubGraph($childNode);
1447
  }
1448

    
1449
  // Load subkey.
1450
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1451

    
1452
  // Load taxon.
1453
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1454
  _load_taxonBase($polytomousKeyNode->taxon);
1455
  return;
1456
}
1457

    
1458
/**
1459
 * @todo Please document this function.
1460
 * @see http://drupal.org/node/1354
1461
 */
1462
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1463

    
1464
  cdm_check_valid_portal_page();
1465

    
1466
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1467

    
1468
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1469
  if (is_array($sourcePager->records)) {
1470
    $polytomousKey->sources = $sourcePager->records;
1471
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1472
  }
1473

    
1474
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1475
  if (is_array($annotationPager->records)) {
1476
    $polytomousKey->annotations = $annotationPager->records;
1477
  }
1478

    
1479
  _load_polytomousKeySubGraph($polytomousKey->root);
1480
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1481
}
1482

    
1483
/**
1484
 * Creates a taxon page view or a chapter of it.
1485
 *
1486
 * The taxon page gives detailed information on a taxon, it shows:
1487
 *  - Taxon name.
1488
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1489
 *    heterotypic and finally followed by misapplied names.
1490
 *    The list is ordered historically.
1491
 *  - All description associated with the taxon.
1492
 *
1493
 * @param string $uuid
1494
 * @param string $chapter
1495
 *   Name of the part to display, valid values are:
1496
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1497
 *
1498
 * @return string
1499
 */
1500
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1501

    
1502
  cdm_check_valid_taxon_page($chapter);
1503
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1504
  // show a warning in case the javascript development mode is anabled
1505
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1506
    drupal_set_message(t('The !url1 is enabled.
1507
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1508
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1509
    )),
1510
    'warning'
1511
        );
1512
  }
1513

    
1514
  // Display the page for the taxon defined by $uuid.
1515
  // set_last_taxon_page_tab(arg(3));
1516
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1517
  if (!empty($taxonpage)) {
1518
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1519
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1520
  }
1521
  else {
1522
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1523
    return '';
1524
  }
1525
}
1526

    
1527
/**
1528
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1529
 * which has two fields, one for the page title and one for the content. Later on in the
1530
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1531
 * function as the function parameters $title and $content.
1532
 *
1533
 * @param string $uuid
1534
 *   the uuid of the taxon to show
1535
 * @param string $chapter
1536
 *   Name of the part to display, valid values are:
1537
 *   'description', 'images', 'synonymy', 'all'.
1538
 *
1539
 * @return object with the following fields:
1540
 *   - title : the title of the page
1541
 *   - content: the content of the page
1542
 *
1543
 */
1544
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1545
  // Taxon object.
1546
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1547
  if (empty($taxon)) {
1548
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1549
    return FALSE;
1550
  }
1551
  $taxonpage = new stdClass();
1552

    
1553
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1554
    'taxon' => $taxon
1555
  ));
1556

    
1557
  // Check if the taxon id contained in the currently selected tree.
1558
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1559

    
1560
  if (!$taxon_in_current_classification) {
1561
    $classifications = get_classifications_for_taxon($taxon);
1562
    RenderHints::pushToRenderStack('not_in_current_classification');
1563
    $taxon_name_markup = render_taxon_or_name($taxon);
1564

    
1565
    if (count($classifications) == 0) {
1566
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1567
        array(
1568
        '!taxonname' => $taxon_name_markup,
1569
        )
1570
      ), 'warning');
1571
    }
1572
    else {
1573
      $trees = '';
1574
      foreach ($classifications as $classification) {
1575
        if (isset($classification->titleCache)) {
1576
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1577
        }
1578
      }
1579

    
1580
      drupal_set_message(format_plural(count($trees),
1581
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1582
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1583
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1584
        ) ,
1585
        'warning');
1586
    }
1587
    RenderHints::popFromRenderStack();
1588
  }
1589

    
1590
  // Render the taxon page.
1591
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1592
  $taxonpage->content = drupal_render($render_array);
1593

    
1594
  return $taxonpage;
1595
}
1596

    
1597
/**
1598
 * Creates a specimen page view.
1599
 * @param string $uuid the UUID of the specimen
1600
 * @return array|string
1601
 */
1602
function cdm_dataportal_specimen_page_view($uuid) {
1603

    
1604
    //cdm_check_valid_taxon_page($chapter);
1605
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1606
    // show a warning in case the javascript development mode is anabled
1607
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1608
        drupal_set_message(t('The !url1 is enabled.
1609
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1610
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1611
        )),
1612
            'warning'
1613
        );
1614
    }
1615

    
1616
    // Display the page for the specimen defined by $uuid.
1617
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1618
    if (!empty($specimenpage)) {
1619
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1620
    }
1621
    else {
1622
        return '';
1623
    }
1624
}
1625

    
1626
/**
1627
 *
1628
 * Creates a specimen view.
1629
 * @param string $uuid the UUID of the specimen
1630
 * @return array|string
1631
 */
1632
function cdm_dataportal_specimen_view($uuid) {
1633
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1634
    if (empty($specimen)) {
1635
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1636
        return FALSE;
1637
    }
1638
    $specimenpage = new stdClass();
1639

    
1640
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1641
        'specimen' => $specimen
1642
    ));
1643

    
1644
    // Render the specimen page.
1645
    $render_array = compose_cdm_specimen_page($uuid);
1646
    $specimenpage->content = drupal_render($render_array);
1647

    
1648
    return $specimenpage;
1649
}
1650

    
1651
/**
1652
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1653
 *
1654
 * The node page shows the taxon name title and the list of taxon related
1655
 * with such taxon. Name on the tree already in use.
1656
 *
1657
 * @param UUID $taxon_name_uuid
1658
 *   The uuid of the CDM TaxonNameBase to show a name page for
1659
 * @param UUID $taxon_to_hide_uuid
1660
 *   A taxon which should not be displayed in the taxon list
1661
 * @param UUID $highlite_synonym_uuid
1662
 *   Optinal parameter wich takes another taxon uuid, if given the
1663
 *   target taxon pages will show the syonymy tab where the taxon
1664
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1665
 *   in case it is found on this page.
1666
 *
1667
 * @return mixed
1668
 *   The formatted name page as node.
1669
 */
1670
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1671

    
1672
  cdm_check_valid_portal_page();
1673

    
1674
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1675
  if (!empty($taxonname_page)) {
1676
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1677
  }
1678
  else {
1679
    return '';
1680
  }
1681
}
1682

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

    
1731
  // Removing the name where we came from.
1732
  foreach ($taxon_pager->records as $k => &$taxon) {
1733
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1734
      unset($taxon_pager->records[$k]);
1735
    }
1736
  }
1737
  // Show the taxa list or go to the singular taxon.
1738
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1739
    $singleTaxon = array_pop($taxon_pager->records);
1740
    if ($singleTaxon->class != "Taxon") {
1741
      // It is a Synonym -> look for the accepted.
1742
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1743
      if (!empty($highlite_synonym_uuid)) {
1744
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1745
      }
1746
      else {
1747
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1748
      }
1749
    }
1750
    else {
1751
      // It is an accepted taxon.
1752
      if (!empty($highlite_synonym_uuid)) {
1753
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1754
      }
1755
      else {
1756
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1757
      }
1758
    }
1759
  }
1760
  else {// More than one taxa case.
1761
    $taxon_name_page = new stdClass();
1762
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1763
    if ($taxon_pager->records) {
1764
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1765
    }
1766
    else {
1767
      $taxon_name_page->content = 'This name has no taxa';
1768
    }
1769
    return $taxon_name_page;
1770
  }
1771
}
1772

    
1773
/**
1774
 * Creates a page with the advance search form.
1775
 *
1776
 * NOTE: The advance search form allows searching for taxa.
1777
 */
1778
function cdm_dataportal_view_search_advanced() {
1779
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1780
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1781
}
1782

    
1783
/**
1784
 * Creates a page with the search form for searching by taxon descriptions.
1785
 */
1786
function cdm_dataportal_view_search_taxon_by_description() {
1787
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1788
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1789
}
1790

    
1791
/**
1792
 * Executes the search and generates the result list of taxa.
1793
 */
1794
function cdm_dataportal_view_search_results_taxon() {
1795

    
1796
  $taxonPager = cdm_dataportal_search_execute();
1797

    
1798
  $showThumbnails = do_showThumbnails();
1799

    
1800
  $setSessionUri = url('cdm_api/setvalue/session', array(
1801
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1802
  ));
1803

    
1804
  drupal_add_js('jQuery(document).ready(function() {
1805

    
1806
      // init
1807
      if(' . $showThumbnails . ' == 1){
1808
          jQuery(\'.media_gallery\').show(20);
1809
      } else {
1810
          jQuery(\'.media_gallery\').hide(20);
1811
      }
1812

    
1813
      // add change handler
1814
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1815
      function(event){
1816
        var state = 0;
1817
        if(jQuery(this).is(\':checked\')){
1818
          jQuery(\'.media_gallery\').show(20);
1819
          state = 1;
1820
        } else {
1821
          jQuery(\'.media_gallery\').hide(20);
1822
        }
1823
        // store state in session variable
1824
        var uri = \'' . $setSessionUri . '\' + state;
1825
        jQuery.get(uri);
1826
      });
1827
  });',
1828
  array('type' => "inline", 'scope' => JS_DEFAULT));
1829

    
1830
  drupal_set_title(t('Search results'), PASS_THROUGH);
1831

    
1832
  return theme('cdm_search_results', array(
1833
    'pager' => $taxonPager,
1834
    'path' => 'cdm_dataportal/search/results/taxon',
1835
    ));
1836
}
1837

    
1838
/**
1839
 * Provides the standart image wich indicated a loading process
1840
 *
1841
 * @return string
1842
 *  The img html tag
1843
 */
1844
function loading_image_html() {
1845
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1846
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1847
}
1848

    
1849
/**
1850
 * Returns the state of the the showThumbnails flag set in the
1851
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1852
 *
1853
 * @return boolean
1854
 *    returns 1 if the flag is set
1855
 */
1856
function do_showThumbnails() {
1857
  static $showThumbnails = null;
1858

    
1859
  if($showThumbnails == null) {
1860
    $showThumbnails = 0;
1861
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1862
      $showThumbnails = 0;
1863
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1864
      $showThumbnails = is_array($search_gallery_settings)
1865
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1866
        && (
1867
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1868
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1869
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1870
            )
1871
         ? 1 : 0;
1872

    
1873
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1874
    }
1875
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1876
    if (!is_numeric($showThumbnails)) {
1877
      $showThumbnails = 1;
1878
    }
1879
  }
1880

    
1881
  return $showThumbnails;
1882
}
1883

    
1884

    
1885
/* ====================== other functions ====================== */
1886
/**
1887
 * Creates a URL to the taxon page specified by the $uuid parameter.
1888
 *
1889
 * The URL will be prepended with a path element to a specific taxon page tab.
1890
 *
1891
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1892
 * be set globally in the administrative settings or individually in the user
1893
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1894
 * the last portal will stay on this last tab.
1895
 *
1896
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1897
 * internal mechanism by a specific value.
1898
 *
1899
 * @param string $uuid
1900
 *   The UUID of the taxon.
1901
 * @param string $page_tab
1902
 *   Overwriting the preset mechanism by defining specific value for the
1903
 *   taxon page tab.
1904
 *
1905
 * @return string
1906
 *   The created URL.
1907
 */
1908
function path_to_taxon($uuid, $page_tab = FALSE) {
1909

    
1910
  $tab = get_default_taxon_tab();
1911
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1912

    
1913
  if (!$uuid) {
1914
    return FALSE;
1915
  }
1916

    
1917
  if ($page_tab) {
1918
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1919
  }
1920
  elseif (!$tab || strtolower($tab) == 'general') {
1921
    return 'cdm_dataportal/taxon/' . $uuid;
1922
  }
1923
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1924
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1925
  }
1926
  else {
1927
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1928
  }
1929
}
1930

    
1931
function path_to_specimen($uuid) {
1932

    
1933
    if (!$uuid) {
1934
        return FALSE;
1935
    }
1936
    else {
1937
        return 'cdm_dataportal/specimen/' . $uuid;
1938
    }
1939
}
1940

    
1941
/**
1942
 * Creates a URL to show a synonmy in the according taxon page.
1943
 *
1944
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1945
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1946
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1947
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1948
 * in the page
1949
 *
1950
 * @param string $synonymUuid
1951
 *    The uuid of the synonym
1952
 * @param string $acceptedUuid
1953
 *    The uuid of the according accepted taxon
1954
 * @return string
1955
 *    The URL to show a synonmy in the according taxon page
1956
 */
1957
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1958
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1959
  return url($acceptedPath, array(
1960
      'query' => array(
1961
        // highlite the synony in the synonymy
1962
        'highlite' => $synonymUuid,
1963
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1964
        // see theme_taxon_page_title()
1965
        'acceptedFor' => $synonymUuid
1966
      ),
1967
      'fragment' => $synonymUuid
1968
  ));
1969

    
1970
}
1971

    
1972
/**
1973
 * Compses the drupal path to the key identified by the uuid.
1974
 *
1975
 * @param string $keyType
1976
 *    the key typer corresponds to the specific class of the CDM
1977
 *    IdentificationKey. Possible values are
1978
 *      -PolytomousKey
1979
 *      -MultimediaKey
1980
 *      - ...
1981
 * @param UUID $keyUuid
1982
 *   The UUID of the key
1983
 */
1984
function path_to_key($keyType, $keyUuid) {
1985
  if (!$keyUuid || !$keyType) {
1986
    return FALSE;
1987
  }
1988
  $keyType{0} = strtolower($keyType{0});
1989
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1990
}
1991

    
1992
/**
1993
 * @todo Please document this function.
1994
 * @see http://drupal.org/node/1354
1995
 */
1996
function path_to_reference($uuid) {
1997
  if (!$uuid) {
1998
    return FALSE;
1999
  }
2000
  return 'cdm_dataportal/reference/' . $uuid;
2001
}
2002

    
2003
/**
2004
 * Creates the path to a cdm_dataportal taxon name page.
2005
 *
2006
 * @param UUID $taxon_name_uuid
2007
 *   The uuid of the CDM TaxonNameBase to show a name page for
2008
 * @param UUID $taxon_to_hide_uuid
2009
 *   A taxon which should not be displayed in the taxon list
2010
 * @param UUID $highlite_synonym_uuid
2011
 *   Optinal parameter wich takes another taxon uuid, if given the
2012
 *   target taxon pages will show the syonymy tab where the taxon
2013
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
2014
 *   in case it is found on this page.
2015
 *
2016
 * @return a URI path element as string
2017
 */
2018
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2019
  $res = FALSE;
2020
  if ($name_uuid) {
2021
    $res = 'cdm_dataportal/name/' . $name_uuid;
2022
  }
2023
  if($taxon_to_hide_uuid){
2024
    $res .= '/' . $taxon_to_hide_uuid;
2025
    if($synonym_uuid){
2026
      $res .= '/' . $synonym_uuid;
2027
    }
2028
  }
2029
  return $res;
2030
}
2031

    
2032
/**
2033
 * @todo Please document this function.
2034
 * @see http://drupal.org/node/1354
2035
 */
2036
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2037
  if (!$uuid) {
2038
    return FALSE;
2039
  }
2040
  $out = 'cdm_dataportal/media/' . $uuid;
2041
  if ($representaion_uuid) {
2042
    $out .= '/' . $representaion_uuid;
2043
    if ($partId !== FALSE) {
2044
      $out .= '/' . $partId;
2045
    }
2046
  }
2047
  return $out;
2048
}
2049

    
2050
/**
2051
 * Compares thisRank with thatRank.
2052
 *
2053
 * Returns a negative integer, zero, or a positive integer
2054
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2055
 * e.g:
2056
 * <ul>
2057
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2058
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2059
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2060
 * </ul>
2061
 * <p>
2062
 * This compare logic of the underlying webservice is the
2063
 * <b>inverse logic</b> of the the one implemented in
2064
 * java.lang.Comparable#compareTo(java.lang.Object)
2065
 *
2066
 * @param $thisRankUuid
2067
 * @param $thatRankUuid
2068
 *
2069
 * @return int
2070
 *   A negative integer, zero, or a positive integer
2071
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2072
 */
2073
function rank_compare($thisRankUuid, $thatRankUuid) {
2074
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2075
  return $result->Integer;
2076
}
2077

    
2078
/**
2079
 * Composes an HTML element class attribute value composed of
2080
 * the shortname of the cdm class and the uuid of the entity.
2081
 * This class attribute should be used whereever an cdm-entity is rendered.
2082
 *
2083
 * These according class selectors in css must be escaped, eg:
2084
 *    .cdm\:TextData
2085
 *
2086
 * @param $cdmEntity
2087
 */
2088
function html_class_attribute_ref($cdmEntity) {
2089

    
2090
  if (is_cdm_entity($cdmEntity)) {
2091
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2092
  }
2093
}
2094

    
2095

    
2096
/**
2097
 * Creates a short version of a taxonname.
2098
 *
2099
 * The short name is created by using the taggedTitle field of
2100
 * TaxonNodeDTO instances.
2101
 * If the taggedTitle if empty the fullname will be returned.
2102
 *
2103
 * @param object $taxonNodeDTO
2104
 *   A TaxonNodeDTO object
2105
 *
2106
 * @return string
2107
 */
2108
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2109

    
2110
  $nameStr = '';
2111

    
2112
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2113

    
2114
  // Get all tagged text tokens of the scientific name.
2115
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2116
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2117
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2118
    }
2119
  }
2120
  $nameStr = trim($nameStr);
2121

    
2122
  if ($nameStr) {
2123

    
2124
    // Do not return short names for these.
2125
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2126
      return $nameStr;
2127
    }
2128

    
2129
    /*
2130
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2131
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2132
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2133
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2134
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2135
    */
2136
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2137
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2138
      return $matches[1][0] . "." . $matches[3][0];
2139
    }
2140
    else {
2141
      return $nameStr;
2142
    }
2143
  }
2144
  else {
2145
    return $taxonNodeDTO->titleCache;
2146
  }
2147
}
2148

    
2149
/**
2150
 * Check if a taxon is accepted by the current taxonomic tree.
2151
 *
2152
 * @param mixed $taxon
2153
 *   The Taxon obkect to check.
2154
 *
2155
 * @return bool
2156
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2157
 */
2158
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2159

    
2160
  $defaultTreeUuid = get_current_classification_uuid();
2161

    
2162
  if (isset($taxon->taxonNodes)) {
2163
    $taxonNodes = $taxon->taxonNodes;
2164
  }
2165
  else {
2166
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2167
  }
2168

    
2169
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2170
    foreach ($taxonNodes as $node) {
2171
      if (isset($node->classification)){
2172
        if(is_object($node->classification)) {
2173
          if ($node->classification->uuid == $defaultTreeUuid) {
2174
            return TRUE;
2175
          }
2176
        }
2177
        else {
2178
          if ($node->classification == $defaultTreeUuid) {
2179
            return TRUE;
2180
          }
2181
        }
2182
      }
2183
    }
2184
  }
2185

    
2186
  return FALSE;
2187
}
2188

    
2189
/**
2190
 * Checks is the source has one of the given types.
2191
 *
2192
 * @param object $source
2193
 *   The original source entity
2194
 * @param array $types
2195
 *   An array of elementd of the OriginalSourceType enumeration
2196
 *   If not set the default will be used which is:
2197
 *    - Lineage
2198
 *    - PrimaryMediaSource
2199
 *    - PrimaryTaxonomicSource
2200
 *    - Unknown
2201
 *    - Other
2202
 * @return boolean
2203
 */
2204
  function _is_original_source_type($source, $types = null) {
2205
    // this is the default
2206
    // maybe this should also be put into the settings
2207
    static $default = array(
2208
      OriginalSourceType::Lineage,
2209
      OriginalSourceType::PrimaryMediaSource,
2210
      OriginalSourceType::PrimaryTaxonomicSource,
2211
      OriginalSourceType::Unknown,
2212
      OriginalSourceType::Other,
2213
    );
2214

    
2215
    if(!$types){
2216
      $types = $default;
2217
    }
2218
    return isset($source->type) && in_array($source->type, $types);
2219
  }
2220

    
2221
/**
2222
 * @todo Please document this function.
2223
 * @see http://drupal.org/node/1354
2224
 */
2225
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2226
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2227
}
2228

    
2229

    
2230
/**
2231
 * Collects all the media from a list of description elements.
2232
 *
2233
 * @param array $descriptionElements
2234
 *   The description elements from which to collect the media.
2235
 *
2236
 * @return array
2237
 *   The output with all the collected media.
2238
 */
2239
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2240

    
2241
  $outArrayOfMedia = array();
2242

    
2243
  // Avoiding a warning box in Drupal for Flora Malesiana.
2244
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2245
    foreach ($descriptionElements as $descriptionElement) {
2246
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2247
        foreach ($descriptionElement->media as $media) {
2248
          if (is_object($media)) {
2249
            $outArrayOfMedia[] = $media;
2250
          }
2251
        }
2252
      }
2253
    }
2254
  }
2255
  return $outArrayOfMedia;
2256
}
2257

    
2258
/**
2259
 * @todo Please document this function.
2260
 * @see http://drupal.org/node/1354
2261
 *
2262
 * @param array $cdm_entities
2263
 *   An array of CdmBase instances or a single instance.
2264
 * @param string $footnote_list_key_suggestion
2265
 *
2266
 * @return unknown
2267
 */
2268
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2269

    
2270
   static $annotations_types_filter = null;
2271
   if(!$annotations_types_filter) {
2272
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2273
   }
2274

    
2275
  $footNoteKeys = array();
2276

    
2277
  // Is argument cdmBase an array?
2278
  if (!is_array($cdm_entities)) {
2279
    $cdmBase_array = array();
2280
    $cdmBase_array[] = $cdm_entities;
2281
  }
2282
  else {
2283
    $cdmBase_array = $cdm_entities;
2284
  }
2285

    
2286
  // Getting the key for the footnotemanager.
2287
  if (isset($footnote_list_key_suggestion)) {
2288
    $footnote_list_key = $footnote_list_key_suggestion;
2289
  }
2290
  else {
2291
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2292
  }
2293

    
2294
  // Adding the footnotes keys.
2295
  foreach ($cdmBase_array as $cdmBase_element) {
2296
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2297
    if (is_array($annotations)) {
2298
      foreach ($annotations as $annotation) {
2299
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2300
      }
2301
    }
2302
  }
2303

    
2304
  return $footNoteKeys;
2305
}
2306

    
2307

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

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

    
2351
  if(!array_key_exists('class', $attributes)) {
2352
    $attributes['class'] = array();
2353
  }
2354
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2355
  $dynabox_attributes = drupal_attributes($attributes);
2356

    
2357

    
2358
  _add_js_domEvent(); // requires domEvent.js
2359
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2360
  drupal_add_js("
2361
  jQuery(document).ready(
2362
      function() {
2363
        dynabox('". $dynabox_id ."',
2364
          {
2365
            open_callback: " . $open_callback .",
2366
            close_callback: " . $close_callback .
2367
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2368
          }
2369
        );
2370
      }
2371
   );",
2372
   array(
2373
    'type'=>'inline',
2374
    'scope'=>'footer'
2375
    )
2376
  );
2377

    
2378

    
2379
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2380
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2381
  $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>';
2382
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2383
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2384
  $out .= '    </' . $enclosingtags[1] . '>';
2385
  $out .= '  </' . $enclosingtags[0] . '>';
2386
  $out .= '<!-- dynabox end -->';
2387
  return $out;
2388
}
2389

    
2390
/**
2391
 * Checks whether a feature has any description elements.
2392
 *
2393
 * @param mixed $featureNode
2394
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2395
 *
2396
 * @see _mergeFeatureTreeDescriptions()
2397
 *
2398
 * @return bool
2399
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2400
 *   contains at least one non empty TextData or at least one DescriptionElement
2401
 *   of an other type. A TextData element holding a multilanguageText or a
2402
 *   source reference is considered to be not empty.
2403
 *
2404
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2405
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2406
 *       $feature_block_has_content in compose_feature_block_items_generic
2407
 */
2408
function has_feature_node_description_elements($featureNode) {
2409

    
2410
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2411
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2412
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2413
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2414
          && $descriptionElement->multilanguageText_L10n->text != ''
2415
          || isset($descriptionElement->sources[0])
2416
          || isset($descriptionElement->media[0]) ) {
2417
          return TRUE;
2418
        }
2419
      }
2420
    }
2421
  }
2422
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2423
    foreach ($featureNode->childNodes as $child) {
2424
      if (has_feature_node_description_elements($child)) {
2425
        return TRUE;
2426
      }
2427
    }
2428
  }
2429
  return FALSE;
2430
}
2431

    
2432
/**
2433
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2434
 *
2435
 * @param $chapter
2436
 *   The taxon page chapter or part
2437
 */
2438
function cdm_check_valid_taxon_page($chapter){
2439
  static $taxon_tabs = null;
2440

    
2441
  cdm_check_valid_portal_page();
2442

    
2443
  if($taxon_tabs == null){
2444
    $taxon_tabs = array('all', 'description');
2445
    foreach(get_taxon_tabs_list() as $tab){
2446
      $taxon_tabs[] = strtolower($tab);
2447
    }
2448
  }
2449

    
2450
  if(!in_array($chapter, $taxon_tabs)){
2451
    // oops this is not a valid chapter name
2452
    http_response_code(404); // 404 = Not Found
2453
  }
2454

    
2455
}
2456

    
2457
/**
2458
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2459
 *
2460
 * @param $chapter
2461
 *   The taxon page chapter or part
2462
 */
2463
function cdm_check_valid_portal_page(){
2464
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2465
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2466
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2467
    http_response_code(404); // 404 = Not Found
2468
    exit('HTTP 404');
2469
  }
2470
}
2471

    
2472
/**
2473
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2474
 *
2475
 * @param $text_a
2476
 * @param $text_b
2477
 * @return string
2478
 */
2479
function diff_viewer($text_a, $text_b) {
2480

    
2481
  static $diff_viewer_count = 0;
2482

    
2483
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2484

    
2485
  // http://code.stephenmorley.org/php/diff-implementation/
2486
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2487
  drupal_add_css(drupal_get_path('module',
2488
      'cdm_dataportal') . '/css/diff.css');
2489
  _add_jquery_ui();
2490
  drupal_add_js(
2491
    'jQuery(document).ready( function(){
2492
        jQuery(\'#' . $element_id . '\').accordion({
2493
        collapsible: true,
2494
        active: false,
2495
        fillSpace: true,
2496
        }).children(\'div\').css({ \'height\': \'auto\' });
2497
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2498
     });'
2499
    , array(
2500
    'type' => 'inline',
2501
    'scope' => 'footer'
2502
  ));
2503

    
2504
  $diff = Diff::compare($text_a,
2505
    $text_b);
2506
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2507
    . Diff::toTable($diff, '', '')
2508
    . '</div></div>';
2509
  return $diff_viewer_markup;
2510
}
2511

    
2512

    
(10-10/16)