Project

General

Profile

Download (81.6 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_ahah() {
271

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

    
276
/**
277
 * @todo Please document this function.
278
 * @see http://drupal.org/node/1354
279
 */
280
function _add_js_taxonomic_children($jquery_selector) {
281

    
282
  global $base_url;
283

    
284

    
285
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
286
  
287
  drupal_add_js('jQuery(document).ready(function() {
288
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
289
          // hoverClass: "fa-rotate-90",
290
          // activeClass: "fa-rotate-90",
291
          classificationUuid: "' . get_current_classification_uuid() . '",
292
          taxonUuid: "' . get_current_taxon_uuid() . '",
293
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
294
          proxyBaseUri: "' . $base_url . '",
295
          
296
        });
297
      });
298
      ', array('type' => 'inline'));
299
}
300

    
301
  /**
302
   * Adds the external javascript file for domEvent.js.
303
   *
304
   * @see drupal_add_js()
305
   */
306
  function _add_js_domEvent() {
307
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
308
  }
309

    
310
  function _add_jquery_ui()
311
  {
312
    drupal_add_css(drupal_get_path('module',
313
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
314
    drupal_add_js(drupal_get_path('module',
315
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
316
      array(
317
        'type' => 'file',
318
        'weight' => JS_LIBRARY,
319
        'cache' => TRUE,
320
        'preprocess' => FALSE
321
      )
322
    );
323
  }
324

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

    
344

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

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

    
350
    drupal_add_html_head_link(
351
      array(
352
        'href' => $font_awesome_css_uri,
353
        'rel' => 'stylesheet'
354
      )
355
    );
356

    
357
    if($icon_name){
358
      if(!isset($attributes['class'])){
359
        $attributes['class'] = array();
360
      }
361
      $attributes['class'][] = 'fa';
362
      $attributes['class'][] = $icon_name;
363

    
364
      return '<i ' . drupal_attributes($attributes) . '></i>';
365
    }
366

    
367
    return '';
368
  }
369

    
370

    
371
  /* ====================== hook implementations ====================== */
372
  /**
373
   * Implements hook_permission().
374
   *
375
   * Valid permissions for this module.
376
   *
377
   * @return array
378
   *   An array of valid permissions for the cdm_dataportal module.
379
   */
380
  function cdm_dataportal_permission() {
381
    return array(
382
      'administer cdm_dataportal' => array(
383
        'title' => t('Administer CDM DataPortal settings'),
384
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
385
      ),
386
      'access cdm content' => array(
387
        'title' => t('Access CDM content'),
388
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
389
      ),
390
    );
391
  }
392

    
393
/**
394
 * Implements hook_menu().
395
 */
396
function cdm_dataportal_menu() {
397
  $items = array();
398

    
399
  // @see settings.php.
400
  cdm_dataportal_menu_admin($items);
401
  cdm_dataportal_menu_help($items);
402

    
403
  $items['cdm_dataportal/names'] = array(
404
    'page callback' => 'cdm_dataportal_view_names',
405
    'access arguments' => array('access cdm content'),
406
    'type' => MENU_CALLBACK,
407
  );
408

    
409
  // Optional callback arguments: page.
410
  $items['cdm_dataportal/taxon'] = array(
411
    'page callback' => 'cdm_dataportal_taxon_page_view',
412
    'access arguments' => array('access cdm content'),
413
    'type' => MENU_CALLBACK,
414
    // Expected callback arguments: uuid.
415
  );
416

    
417
  $items['cdm_dataportal/specimen'] = array(
418
      'page callback' => 'cdm_dataportal_specimen_page_view',
419
      'access arguments' => array('access cdm content'),
420
      'type' => MENU_CALLBACK,
421
      // Expected callback arguments: uuid.
422
  );
423

    
424
  $items['cdm_dataportal/named_area'] = array(
425
    'page callback' => 'cdm_dataportal_named_area_page_view',
426
    'access arguments' => array('access cdm content'),
427
    'type' => MENU_CALLBACK,
428
    // Expected callback arguments: uuid.
429
  );
430

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

    
445
  $items['cdm_dataportal/reference'] = array(
446
    'page callback' => 'cdm_dataportal_view_reference',
447
    'access arguments' => array('access cdm content'),
448
    'type' => MENU_CALLBACK,
449
    // Expected callback arguments: uuid.
450
  );
451

    
452
  $items['cdm_dataportal/reference/list'] = array(
453
    'page callback' => 'cdm_dataportal_view_reference_list',
454
    'access arguments' => array('access cdm content'),
455
    'type' => MENU_CALLBACK,
456
    // Expected callback arguments: uuid.
457
  );
458

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

    
467
  $items['cdm_dataportal/polytomousKey'] = array(
468
    'page callback' => 'cdm_dataportal_view_polytomousKey',
469
    'access arguments' => array('access cdm content'),
470
    'type' => MENU_CALLBACK,
471
    // Expected callback arguments: polytomousKey->uuid.
472
  );
473

    
474
  $items['cdm_dataportal/search'] = array(
475
    'page callback' => 'cdm_dataportal_view_search_advanced',
476
    'access arguments' => array('access cdm content'),
477
    'type' => MENU_CALLBACK,
478
  );
479

    
480
  $items['cdm_dataportal/search/advanced'] = array(
481
    'title' => 'Advanced', // will be passed through t()
482
    'page callback' => 'cdm_dataportal_view_search_advanced',
483
    'access arguments' => array('access cdm content'),
484
    'type' => MENU_DEFAULT_LOCAL_TASK,
485
  );
486

    
487
  $items['cdm_dataportal/search/taxon_by_description'] = array(
488
    'title' => 'By content category', // will be passed through t()
489
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
490
    'access arguments' => array('access cdm content'),
491
    'type' => MENU_LOCAL_TASK,
492
  );
493

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

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

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

    
528
  // --- Local tasks for Taxon.
529
  // --- tabbed taxon page
530
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
531
    $items['cdm_dataportal/taxon/%'] = array(
532
      'title' => cdm_taxonpage_tab_label('General'),
533
      'page callback' => 'cdm_dataportal_taxon_page_view',
534
      'access arguments' => array('access cdm content'),
535
      'type' => MENU_CALLBACK,
536
      'weight' => 1,
537
      'page arguments' => array(2, "description")
538
      , // Expected callback arguments: taxon_uuid.
539
    );
540

    
541
    $items['cdm_dataportal/taxon/%/all'] = array(
542
      'title' => cdm_taxonpage_tab_label('General'),
543
      'page callback' => 'cdm_dataportal_taxon_page_view',
544
      'access arguments' => array('access cdm content'),
545
      'type' => MENU_CALLBACK,
546
      'weight' => 2,
547
      'page arguments' => array(2, "all")
548
      , // Expected callback arguments: taxon_uuid.
549
    );
550

    
551
    $items['cdm_dataportal/taxon/%/description'] = array(
552
      'title' => cdm_taxonpage_tab_label('General'),
553
      'page callback' => 'cdm_dataportal_taxon_page_view',
554
      'access arguments' => array('access cdm content'),
555
      'type' => MENU_DEFAULT_LOCAL_TASK,
556
      'weight' => 2,
557
      'page arguments' => array(2, "description")
558
      , // Expected callback arguments: taxon_uuid.
559
    );
560

    
561
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
562
      'title' => cdm_taxonpage_tab_label('Synonymy'),
563
      'page callback' => 'cdm_dataportal_taxon_page_view',
564
      'access arguments' => array('access cdm content'),
565
      'type' => MENU_LOCAL_TASK,
566
      'weight' => 4,
567
      'page arguments' => array(2, "synonymy", 4)
568
      , // Expected callback arguments: taxon_uuid and ...
569
    );
570
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
571
      'title' => cdm_taxonpage_tab_label('Images'),
572
      'page callback' => 'cdm_dataportal_taxon_page_view',
573
      'access arguments' => array('access cdm content'),
574
      'type' => MENU_LOCAL_TASK,
575
      'weight' => 5,
576
      'page arguments' => array(2, "images")
577
      , // Expected callback arguments: taxon_uuid.
578
    );
579

    
580
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
581
      'title' => cdm_taxonpage_tab_label('Specimens'),
582
      'page callback' => 'cdm_dataportal_taxon_page_view',
583
      'access arguments' => array('access cdm content'),
584
      'type' => MENU_LOCAL_TASK,
585
      'weight' => 6,
586
      'page arguments' => array(2, "specimens")
587
      , // Expected callback arguments: taxon_uuid.
588
    );
589

    
590
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
591
      'title' => cdm_taxonpage_tab_label('Keys'),
592
      'page callback' => 'cdm_dataportal_taxon_page_view',
593
      'access arguments' => array('access cdm content'),
594
      'type' => MENU_LOCAL_TASK,
595
      'weight' => 6,
596
      'page arguments' => array(2, "keys")
597
      , // Expected callback arguments: taxon_uuid.
598
    );
599

    
600
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
601
      'title' => cdm_taxonpage_tab_label('Experts'),
602
        'page callback' => 'cdm_dataportal_taxon_page_view',
603
        'access arguments' => array('access cdm content'),
604
        'type' => MENU_LOCAL_TASK,
605
        'weight' => 6,
606
        'page arguments' => array(2, "experts")
607
    , // Expected callback arguments: taxon_uuid.
608
    );
609

    
610
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
611
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
612
        'access arguments' => array('access cdm content'),
613
        'page arguments' => array(3,4,5),
614
        'type' => MENU_CALLBACK
615
    );
616
  }
617

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

    
630
  return $items;
631
}
632

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

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

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

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

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

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

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

    
673

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

    
677
/**
678
 * Implements hook_requirements($phase)
679
 */
680
function cdm_dataportal_requirements($phase) {
681
    $requirements = array();
682
    if($phase == 'runtime'){
683

    
684
    }
685
    return $requirements;
686
}
687

    
688

    
689
/**
690
 * The function generate form for own user cdm dataportal configurations.
691
 */
692
function cdm_dataportal_user_form($form, &$form_state) {
693

    
694
  global $user;
695
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
696

    
697
  $form['taxon_page_tabs'] = array(
698
      '#type' => 'fieldset',
699
      '#tree' => true,
700
      '#title' => t('Taxon page tabs'),
701
  );
702

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

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

    
720

    
721
  if(false){
722
    $form['developer_options'] = array(
723
        '#type' => 'fieldset',
724
        '#tree' => true,
725
        '#title' => t('Developer options'),
726
    );
727

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

    
741
  $form['submit'] = array(
742
    '#type' => 'submit',
743
    '#value' => t('Submit'),
744
  );
745

    
746
  return $form;
747
}
748

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

    
760
  // FIXME: this is completely wrong, see user_profile_form_submit()
761

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

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

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

    
789
/**
790
 * Implements hook_block_info().
791
 */
792
function cdm_dataportal_block_info() {
793

    
794
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
795
    // $block[1]["info"] = t("CDM DataPortal Credits");
796
    $block["2"] = array(
797
        "info" => t("CDM - Search Taxa"),
798
        "cache" => DRUPAL_NO_CACHE
799
      );
800
    // $block[3]["info"] = t("CDM Filters");
801
    $block["4"]["info"] = t("CDM  - Dataportal Print");
802
    $block["keys"]["info"] = t("CDM - Identification keys");
803
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
804
    $block["classification_breadcrumbs"] =  array(
805
        'info' => t('CDM - Classification breadcrumbs'),
806
        'cache' => DRUPAL_CACHE_PER_PAGE
807
      );
808
    $block["taxonomic_children"] =  array(
809
      'info' => t('CDM - Taxonomic children'),
810
      'cache' => DRUPAL_CACHE_PER_PAGE
811
    );
812
    $block["back_to_search_results"] =  array(
813
      'title' => '<none>',
814
      'info' => t('CDM - Back to search Results'),
815
      'cache' => DRUPAL_CACHE_PER_PAGE,
816
      'visibility' => BLOCK_VISIBILITY_LISTED,
817
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
818
    );
819

    
820
    return $block;
821
}
822

    
823
/**
824
 * Implements hook_block_view().
825
 */
826
function cdm_dataportal_block_view($delta) {
827
  // TODO Rename block deltas (e.g. '2') to readable strings.
828
  switch ($delta) {
829
    // case 'delta-1':
830
    // $block['subject'] = t('Credits');
831
    // $block['content'] = theme('cdm_credits');
832
    // return $block;
833
    case '2':
834
      $block['subject'] = t('Search taxa');
835
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
836
      $block['content'] = drupal_render($form);
837

    
838
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
839
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
840
      }
841
      return $block;
842
    case '4':
843
      $block['subject'] = '';
844
      $block['content'] = theme('cdm_print_button');
845
      return $block;
846
    case "keys":
847
      $block['subject'] = t('Identification Keys');
848
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
849
      return $block;
850
    case "fundedByEDIT":
851
      // t('Funded by EDIT');
852
      $text = '<none>';
853
      $block['subject'] = $text;
854
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
855
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
856
        'attributes' => array("target" => "EDIT"),
857
        'absolute' => TRUE,
858
        'html' => TRUE,
859
      ));
860
      return $block;
861
    case 'classification_breadcrumbs':
862
      $taxon_uuid = get_current_taxon_uuid();
863
      $block['subject'] = '<none>';
864
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
865
      return $block;
866
    case 'taxonomic_children':
867
      $taxon_uuid = get_current_taxon_uuid();
868
      $block['subject'] = '<none>';
869
      $block['content'] = compose_taxonomic_children($taxon_uuid);
870
      return $block;
871
    case 'back_to_search_results':
872
      $block['subject'] = '<none>';
873
      if (isset($_SESSION['cdm']['search'])) {
874
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
875
      }
876
      return $block;
877
    default:
878
      return null;
879
  }
880
}
881

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

    
892
  if(!isset($taxon_uuid)){
893
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
894
      $taxon_uuid = $_REQUEST['currentTaxon'];
895
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
896
      $taxon_uuid = arg(2);
897
    } else {
898
      $taxon_uuid = null;
899
    }
900
  }
901

    
902
  return $taxon_uuid;
903
}
904

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

    
920
/*
921
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
922
 $_SESSION['cdm'] = NULL;
923
 if(is_string($cdm_ws_uri_update)){
924
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
925
 }
926
 }
927

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

    
937
/**
938
 * creates a  selector form for taxonomic trees.
939
 *
940
 * @return array
941
 *  a drupal form array
942
 */
943
function cdm_taxonomictree_selector() {
944
  _add_js_treeselector();
945

    
946
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
947
  return $form;
948
}
949

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

    
958
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
959
  $form['#action'] = $url;
960

    
961
  $form['var'] = array(
962
    '#weight' => -3,
963
    '#type' => 'hidden',
964
    '#value' => '[cdm][taxonomictree_uuid]',
965
  );
966

    
967
  $destination_array = drupal_get_destination();
968
  $destination = $destination_array['destination'];
969

    
970
  $form['destination'] = array(
971
    '#weight' => -3,
972
    '#type' => 'hidden',
973
    '#value' =>  $destination,
974
  );
975

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

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

    
996
  return $form;
997

    
998
}
999

    
1000
/**
1001
 *
1002
 * @ingroup compose
1003
 */
1004
function compose_classification_selector() {
1005

    
1006
  $destination_array = drupal_get_destination();
1007
  $destination = $destination_array['destination'];
1008

    
1009
  $options = cdm_get_taxontrees_as_options();
1010
  $items = array();
1011
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1012

    
1013
  $current_classification_uuid = get_current_classification_uuid();
1014

    
1015

    
1016
  foreach($options as $uuid=>$label){
1017
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1018

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

    
1039
  $render_array = array(
1040
    '#theme' => 'item_list',
1041
    '#type' => 'ul',
1042
    '#items' => $items
1043
  );
1044

    
1045
  return $render_array;
1046
}
1047

    
1048

    
1049
/* UNREACHABLE since action of form directly links to view.
1050
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1051

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

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

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

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

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

    
1112
/**
1113
 * @todo Please document this function.
1114
 * @see http://drupal.org/node/1354
1115
 */
1116
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1117

    
1118
  cdm_check_valid_portal_page();
1119

    
1120
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1121
  return theme('cdm_reference_page', array('reference' => $reference));
1122
}
1123

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

    
1134
/**
1135
 * @todo Please document this function.
1136
 * @see http://drupal.org/node/1354
1137
 */
1138
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1139

    
1140
  cdm_check_valid_portal_page();
1141

    
1142
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1143
  return theme('cdm_media_page', array(
1144
    'media' => $media,
1145
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1146
    'partId' => $part,
1147
    ));
1148
}
1149

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

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

    
1178
  static $media = NULL;
1179

    
1180
  if(!isset($media)) {
1181
    $media = array();
1182
  }
1183
  if (!isset($media[$taxon->uuid])) {
1184

    
1185
    // --- GET Images --- //
1186
    $mediaQueryParameters = array(
1187
        "type" => "ImageFile",
1188
    );
1189

    
1190
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1191
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1192
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1193

    
1194
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1195
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1196
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1197
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1198

    
1199
    $ws_endpoint = NULL;
1200
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1201
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1202
    } else {
1203
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1204
    }
1205

    
1206
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1207
        array(
1208
            $taxon->uuid,
1209
        ),
1210
        queryString($mediaQueryParameters)
1211
       );
1212
  }
1213

    
1214
  return $media[$taxon->uuid];
1215
}
1216

    
1217
/**
1218
 *
1219
 * @param Taxon $taxon
1220
 *   A CDM Taxon entitiy
1221
 *
1222
 * @return array
1223
 *   An array of CDM SpecimenOrObservation entities
1224
 *
1225
function _load_occurences_for_taxon($taxon){
1226

    
1227
  static $occurences = NULL;
1228

    
1229
  if(!isset($occurences)) {
1230
    $occurences = array();
1231
  }
1232

    
1233
  if (!isset($occurences[$taxon->uuid])){
1234

    
1235
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1236
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1237
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1238

    
1239
    $by_associatedtaxon_query = http_build_query(array(
1240
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1241
        'relationships' => implode(',', $relationship_choice['direct']),
1242
        'pageSize' => null // all hits in one page
1243
    )
1244
    );
1245

    
1246
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1247
        null,
1248
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1249
    );
1250

    
1251

    
1252
    if(isset($pager->records[0])){
1253
      $occurences[$taxon->uuid] =  $pager->records;
1254
    }
1255
  }
1256
  return $occurences[$taxon->uuid];
1257
}
1258
 */
1259

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

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

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

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

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

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

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

    
1417
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1418

    
1419
  if (!$polytomousKeyNode) {
1420
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1421
    return;
1422
  }
1423

    
1424
  // Load children.
1425
  foreach ($polytomousKeyNode->children as &$childNode) {
1426
    _load_polytomousKeySubGraph($childNode);
1427
  }
1428

    
1429
  // Load subkey.
1430
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1431

    
1432
  // Load taxon.
1433
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1434
  _load_taxonBase($polytomousKeyNode->taxon);
1435
  return;
1436
}
1437

    
1438
/**
1439
 * @todo Please document this function.
1440
 * @see http://drupal.org/node/1354
1441
 */
1442
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1443

    
1444
  cdm_check_valid_portal_page();
1445

    
1446
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1447

    
1448
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1449
  if (is_array($sourcePager->records)) {
1450
    $polytomousKey->sources = $sourcePager->records;
1451
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1452
  }
1453

    
1454
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1455
  if (is_array($annotationPager->records)) {
1456
    $polytomousKey->annotations = $annotationPager->records;
1457
  }
1458

    
1459
  _load_polytomousKeySubGraph($polytomousKey->root);
1460
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1461
}
1462

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

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

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

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

    
1533
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1534
    'taxon' => $taxon
1535
  ));
1536

    
1537
  // Check if the taxon id contained in the currently selected tree.
1538
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1539

    
1540
  if (!$taxon_in_current_classification) {
1541
    $classifications = get_classifications_for_taxon($taxon);
1542
    RenderHints::pushToRenderStack('not_in_current_classification');
1543
    $taxon_name_markup = render_taxon_or_name($taxon);
1544

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

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

    
1570
  // Render the taxon page.
1571
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1572
  $taxonpage->content = drupal_render($render_array);
1573

    
1574
  return $taxonpage;
1575
}
1576

    
1577
/**
1578
 * Creates a specimen page view.
1579
 * @param string $uuid the UUID of the specimen
1580
 * @return array|string
1581
 */
1582
function cdm_dataportal_specimen_page_view($uuid) {
1583

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

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

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

    
1620
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1621
        'specimen' => $specimen
1622
    ));
1623

    
1624
    // Render the specimen page.
1625
    $render_array = compose_cdm_specimen_page($uuid);
1626
    $specimenpage->content = drupal_render($render_array);
1627

    
1628
    return $specimenpage;
1629
}
1630

    
1631
/**
1632
 *
1633
 * Creates a named area view.
1634
 * @param string $uuid the UUID of the specimen
1635
 *  * @return object
1636
 *   An object with two fields:
1637
 *     - title: the page title
1638
 *     - content: the page content
1639
 */
1640

    
1641
function cdm_dataportal_named_area_view($uuid) {
1642
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1643
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1644
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1645
    return FALSE;
1646
  }
1647
  $named_area_page = new stdClass();
1648

    
1649
  $named_area_page->title = $named_area->representation_L10n;
1650

    
1651
  // Render the specimen page.
1652
  $render_array = compose_cdm_named_area_page($uuid);
1653
  $named_area_page->content = drupal_render($render_array);
1654

    
1655
  return $named_area_page;
1656
}
1657

    
1658
function cdm_dataportal_named_area_page_view($uuid) {
1659

    
1660
  cdm_check_valid_portal_page();
1661

    
1662
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1663
  if (!empty($named_area_page)) {
1664
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1665
  }
1666
  else {
1667
    return '';
1668
  }
1669

    
1670

    
1671
}
1672

    
1673
/**
1674
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1675
 *
1676
 * The node page shows the taxon name title and the list of taxon related
1677
 * with such taxon. Name on the tree already in use.
1678
 *
1679
 * @param UUID $taxon_name_uuid
1680
 *   The uuid of the CDM TaxonName to show a name page for
1681
 * @param UUID $taxon_to_hide_uuid
1682
 *   A taxon which should not be displayed in the taxon list
1683
 * @param UUID $highlite_synonym_uuid
1684
 *   Optinal parameter wich takes another taxon uuid, if given the
1685
 *   target taxon pages will show the syonymy tab where the taxon
1686
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1687
 *   in case it is found on this page.
1688
 *
1689
 * @return mixed
1690
 *   The formatted name page as node.
1691
 */
1692
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1693

    
1694
  cdm_check_valid_portal_page();
1695

    
1696
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1697
  if (!empty($taxonname_page)) {
1698
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1699
  }
1700
  else {
1701
    return '';
1702
  }
1703
}
1704

    
1705
/**
1706
 * View function for a TaxonName page.
1707
 *
1708
 * The name page lists all taxa for which the name specified by the
1709
 * $taxon_name_uuid is being used. I case there is only one name the
1710
 * page automatically redirects ti the according taxon page. Otherwise
1711
 * the list of names is displayed.
1712
 *
1713
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1714
 * list of taxa. This is useful for example when referencing from a taxon
1715
 * to the name page and the referring taxon should not be repeaded in the
1716
 * name page.
1717
 *
1718
 *
1719
 * @param UUID $taxon_name_uuid
1720
 *   The uuid of the CDM TaxonName to show a name page for
1721
 * @param UUID $taxon_to_hide_uuid
1722
 *   A taxon which should not be displayed in the taxon list
1723
 * @param UUID $highlite_synonym_uuid
1724
 *   Optinal parameter wich takes another taxon uuid, if given the
1725
 *   target taxon pages will show the syonymy tab where the taxon
1726
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1727
 *   in case it is found on this page.
1728
 *
1729
 * @return object
1730
 *   An object with two fields:
1731
 *     - title: the page title
1732
 *     - content: the page content
1733
 */
1734
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1735
  // Getting the full taxonname object from the server.
1736
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1737
  if (!$taxon_name) {
1738
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1739
    return FALSE;
1740
  }
1741
  // Searching for all the taxa connected with the taxon name on the tree
1742
  // in use.
1743
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1744
  $request_params = array();
1745
  $request_params['query'] = $name_cache;
1746
  $request_params['tree'] = get_current_classification_uuid();
1747
  $request_params['doTaxa'] = 1;
1748
  $request_params['doSynonyms'] = 1;
1749
  $request_params['doTaxaByCommonNames'] = 0;
1750
  $request_params['matchMode'] = "EXACT";
1751
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1752

    
1753
  // Removing the name where we came from.
1754
  foreach ($taxon_pager->records as $k => &$taxon) {
1755
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1756
      unset($taxon_pager->records[$k]);
1757
    }
1758
  }
1759
  // Show the taxa list or go to the singular taxon.
1760
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1761
    $singleTaxon = array_pop($taxon_pager->records);
1762
    if ($singleTaxon->class != "Taxon") {
1763
      // It is a Synonym -> look for the accepted.
1764
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1765
      if (!empty($highlite_synonym_uuid)) {
1766
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1767
      }
1768
      else {
1769
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1770
      }
1771
    }
1772
    else {
1773
      // It is an accepted taxon.
1774
      if (!empty($highlite_synonym_uuid)) {
1775
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1776
      }
1777
      else {
1778
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1779
      }
1780
    }
1781
  }
1782
  else {// More than one taxa case.
1783
    $taxon_name_page = new stdClass();
1784
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1785
    if ($taxon_pager->records) {
1786
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1787
    }
1788
    else {
1789
      $taxon_name_page->content = 'This name is not assigned to a taxon.';
1790
    }
1791
    return $taxon_name_page;
1792
  }
1793
}
1794

    
1795
/**
1796
 * Creates a page with the advance search form.
1797
 *
1798
 * NOTE: The advance search form allows searching for taxa.
1799
 */
1800
function cdm_dataportal_view_search_advanced() {
1801
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1802
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1803
}
1804

    
1805
/**
1806
 * Creates a page with the search form for searching by taxon descriptions.
1807
 */
1808
function cdm_dataportal_view_search_taxon_by_description() {
1809
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1810
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1811
}
1812

    
1813
/**
1814
 * Executes the search and generates the result list of taxa.
1815
 */
1816
function cdm_dataportal_view_search_results_taxon() {
1817

    
1818
  $taxonPager = cdm_dataportal_search_execute();
1819

    
1820
  $showThumbnails = do_showThumbnails();
1821

    
1822
  $setSessionUri = url('cdm_api/setvalue/session', array(
1823
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1824
  ));
1825

    
1826
  drupal_add_js('jQuery(document).ready(function() {
1827

    
1828
      // init
1829
      if(' . $showThumbnails . ' == 1){
1830
          jQuery(\'.media_gallery\').show(20);
1831
      } else {
1832
          jQuery(\'.media_gallery\').hide(20);
1833
      }
1834

    
1835
      // add change handler
1836
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1837
      function(event){
1838
        var state = 0;
1839
        if(jQuery(this).is(\':checked\')){
1840
          jQuery(\'.media_gallery\').show(20);
1841
          state = 1;
1842
        } else {
1843
          jQuery(\'.media_gallery\').hide(20);
1844
        }
1845
        // store state in session variable
1846
        var uri = \'' . $setSessionUri . '\' + state;
1847
        jQuery.get(uri);
1848
      });
1849
  });',
1850
  array('type' => "inline", 'scope' => JS_DEFAULT));
1851

    
1852
  drupal_set_title(t('Search results'), PASS_THROUGH);
1853

    
1854
  return theme('cdm_search_results', array(
1855
    'pager' => $taxonPager,
1856
    'path' => 'cdm_dataportal/search/results/taxon',
1857
    ));
1858
}
1859

    
1860
/**
1861
 * Provides the standart image wich indicated a loading process
1862
 *
1863
 * @return string
1864
 *  The img html tag
1865
 */
1866
function loading_image_html() {
1867
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1868
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1869
}
1870

    
1871
/**
1872
 * Returns the state of the the showThumbnails flag set in the
1873
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1874
 *
1875
 * @return boolean
1876
 *    returns 1 if the flag is set
1877
 */
1878
function do_showThumbnails() {
1879
  static $showThumbnails = null;
1880

    
1881
  if($showThumbnails == null) {
1882
    $showThumbnails = 0;
1883
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1884
      $showThumbnails = 0;
1885
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1886
      $showThumbnails = is_array($search_gallery_settings)
1887
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1888
        && (
1889
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1890
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1891
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1892
            )
1893
         ? 1 : 0;
1894

    
1895
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1896
    }
1897
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1898
    if (!is_numeric($showThumbnails)) {
1899
      $showThumbnails = 1;
1900
    }
1901
  }
1902

    
1903
  return $showThumbnails;
1904
}
1905

    
1906

    
1907
/* ====================== other functions ====================== */
1908
/**
1909
 * Creates a URL to the taxon page specified by the $uuid parameter.
1910
 *
1911
 * The URL will be prepended with a path element to a specific taxon page tab.
1912
 *
1913
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1914
 * be set globally in the administrative settings or individually in the user
1915
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1916
 * the last portal will stay on this last tab.
1917
 *
1918
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1919
 * internal mechanism by a specific value.
1920
 *
1921
 * @param string $uuid
1922
 *   The UUID of the taxon.
1923
 * @param string $page_tab
1924
 *   Overwriting the preset mechanism by defining specific value for the
1925
 *   taxon page tab.
1926
 *
1927
 * @return string
1928
 *   The created URL.
1929
 */
1930
function path_to_taxon($uuid, $page_tab = FALSE) {
1931

    
1932
  $tab = get_default_taxon_tab();
1933
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1934

    
1935
  if (!$uuid) {
1936
    return FALSE;
1937
  }
1938

    
1939
  if ($page_tab) {
1940
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1941
  }
1942
  elseif (!$tab || strtolower($tab) == 'general') {
1943
    return 'cdm_dataportal/taxon/' . $uuid;
1944
  }
1945
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1946
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1947
  }
1948
  else {
1949
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1950
  }
1951
}
1952

    
1953
function path_to_specimen($uuid) {
1954

    
1955
    if (!$uuid) {
1956
        return FALSE;
1957
    }
1958
    else {
1959
        return 'cdm_dataportal/specimen/' . $uuid;
1960
    }
1961
}
1962

    
1963
function path_to_named_area($uuid) {
1964

    
1965
  if (!$uuid) {
1966
    return FALSE;
1967
  }
1968
  else {
1969
    return 'cdm_dataportal/named_area/' . $uuid;
1970
  }
1971
}
1972

    
1973
/**
1974
 * Creates a URL to show a synonmy in the according taxon page.
1975
 *
1976
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1977
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1978
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1979
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1980
 * in the page
1981
 *
1982
 * @param string $synonymUuid
1983
 *    The uuid of the synonym
1984
 * @param string $acceptedUuid
1985
 *    The uuid of the according accepted taxon
1986
 * @return string
1987
 *    The URL to show a synonmy in the according taxon page
1988
 */
1989
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1990
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1991
  return url($acceptedPath, array(
1992
      'query' => array(
1993
        // highlite the synony in the synonymy
1994
        'highlite' => $synonymUuid,
1995
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1996
        // see theme_taxon_page_title()
1997
        'acceptedFor' => $synonymUuid
1998
      ),
1999
      'fragment' => $synonymUuid
2000
  ));
2001

    
2002
}
2003

    
2004
/**
2005
 * Compses the drupal path to the key identified by the uuid.
2006
 *
2007
 * @param string $keyType
2008
 *    the key typer corresponds to the specific class of the CDM
2009
 *    IdentificationKey. Possible values are
2010
 *      -PolytomousKey
2011
 *      -MultimediaKey
2012
 *      - ...
2013
 * @param UUID $keyUuid
2014
 *   The UUID of the key
2015
 */
2016
function path_to_key($keyType, $keyUuid) {
2017
  if (!$keyUuid || !$keyType) {
2018
    return FALSE;
2019
  }
2020
  $keyType{0} = strtolower($keyType{0});
2021
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2022
}
2023

    
2024
/**
2025
 * @todo Please document this function.
2026
 * @see http://drupal.org/node/1354
2027
 */
2028
function path_to_reference($uuid) {
2029
  if (!$uuid) {
2030
    return FALSE;
2031
  }
2032
  return 'cdm_dataportal/reference/' . $uuid;
2033
}
2034

    
2035
/**
2036
 * Creates the path to a cdm_dataportal taxon name page.
2037
 *
2038
 * @param UUID $taxon_name_uuid
2039
 *   The uuid of the CDM TaxonName to show a name page for
2040
 * @param UUID $taxon_to_hide_uuid
2041
 *   A taxon which should not be displayed in the taxon list
2042
 * @param UUID $highlite_synonym_uuid
2043
 *   Optinal parameter wich takes another taxon uuid, if given the
2044
 *   target taxon pages will show the syonymy tab where the taxon
2045
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
2046
 *   in case it is found on this page.
2047
 *
2048
 * @return a URI path element as string
2049
 */
2050
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2051
  $res = FALSE;
2052
  if ($name_uuid) {
2053
    $res = 'cdm_dataportal/name/' . $name_uuid;
2054
  }
2055
  if($taxon_to_hide_uuid){
2056
    $res .= '/' . $taxon_to_hide_uuid;
2057
    if($synonym_uuid){
2058
      $res .= '/' . $synonym_uuid;
2059
    }
2060
  }
2061
  return $res;
2062
}
2063

    
2064
/**
2065
 * @todo Please document this function.
2066
 * @see http://drupal.org/node/1354
2067
 */
2068
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2069
  if (!$uuid) {
2070
    return FALSE;
2071
  }
2072
  $out = 'cdm_dataportal/media/' . $uuid;
2073
  if ($representaion_uuid) {
2074
    $out .= '/' . $representaion_uuid;
2075
    if (is_numeric($partId)) {
2076
      $out .= '/' . $partId;
2077
    }
2078
  }
2079
  return $out;
2080
}
2081

    
2082
/**
2083
 * Compares thisRank with thatRank.
2084
 *
2085
 * Returns a negative integer, zero, or a positive integer
2086
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2087
 * e.g:
2088
 * <ul>
2089
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2090
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2091
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2092
 * </ul>
2093
 * <p>
2094
 * This compare logic of the underlying webservice is the
2095
 * <b>inverse logic</b> of the the one implemented in
2096
 * java.lang.Comparable#compareTo(java.lang.Object)
2097
 *
2098
 * @param $thisRankUuid
2099
 * @param $thatRankUuid
2100
 *
2101
 * @return int
2102
 *   A negative integer, zero, or a positive integer
2103
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2104
 */
2105
function rank_compare($thisRankUuid, $thatRankUuid) {
2106
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2107
  return $result->Integer;
2108
}
2109

    
2110
/**
2111
 * Composes an HTML element class attribute value composed of
2112
 * the short-name of the cdm class and the uuid of the entity.
2113
 * This class attribute should be used wherever an cdm-entity is rendered.
2114
 *
2115
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2116
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2117
 * Taxon uuid is added also as taxon_uuid:<uuid>
2118
 *
2119
 * These according class selectors in css must be escaped, eg:
2120
 *    .cdm\:TextData
2121
 *
2122
 * @param $cdmEntity
2123
 *    A CDM entity or TaxonNodeDTO
2124
 */
2125
function html_class_attribute_ref($cdmEntity) {
2126

    
2127
  $attributes = '';
2128
  if (is_cdm_entity($cdmEntity)) {
2129
    $attributes =  "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2130
  }
2131
  if($cdmEntity->class == 'TaxonNodeDto'){
2132
    $attributes .= " taxon_uuid:"  . $cdmEntity->taxonUuid . " sec_uuid:"  . $cdmEntity->secUuid;;
2133
  }
2134
  if($cdmEntity->class == 'Taxon' && isset($cdmEntity->sec->uuid)){
2135
    $attributes .= " sec_uuid:"  . $cdmEntity->sec->uuid;
2136
  }
2137
  return $attributes;
2138
}
2139

    
2140

    
2141
/**
2142
 * Creates a short version of a taxonname.
2143
 *
2144
 * The short name is created by using the taggedTitle field of
2145
 * TaxonNodeDTO instances.
2146
 * If the taggedTitle if empty the fullname will be returned.
2147
 *
2148
 * @param object $taxonNodeDTO
2149
 *   A TaxonNodeDTO object
2150
 *
2151
 * @return string
2152
 */
2153
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2154

    
2155
  $nameStr = '';
2156

    
2157
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2158

    
2159
  // Get all tagged text tokens of the scientific name.
2160
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2161
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2162
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2163
    }
2164
  }
2165
  $nameStr = trim($nameStr);
2166

    
2167
  if ($nameStr) {
2168

    
2169
    // Do not return short names for these.
2170
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2171
      return $nameStr;
2172
    }
2173

    
2174
    /*
2175
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2176
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2177
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2178
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2179
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2180
    */
2181
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2182
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2183
      return $matches[1][0] . "." . $matches[3][0];
2184
    }
2185
    else {
2186
      return $nameStr;
2187
    }
2188
  }
2189
  else {
2190
    return $taxonNodeDTO->titleCache;
2191
  }
2192
}
2193

    
2194
/**
2195
 * Check if a taxon is accepted by the current taxonomic tree.
2196
 *
2197
 * @param mixed $taxon
2198
 *   The Taxon obkect to check.
2199
 *
2200
 * @return bool
2201
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2202
 */
2203
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2204

    
2205
  $defaultTreeUuid = get_current_classification_uuid();
2206

    
2207
  if (isset($taxon->taxonNodes)) {
2208
    $taxonNodes = $taxon->taxonNodes;
2209
  }
2210
  else {
2211
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2212
  }
2213

    
2214
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2215
    foreach ($taxonNodes as $node) {
2216
      if (isset($node->classification)){
2217
        if(is_object($node->classification)) {
2218
          if ($node->classification->uuid == $defaultTreeUuid) {
2219
            return TRUE;
2220
          }
2221
        }
2222
        else {
2223
          if ($node->classification == $defaultTreeUuid) {
2224
            return TRUE;
2225
          }
2226
        }
2227
      }
2228
    }
2229
  }
2230

    
2231
  return FALSE;
2232
}
2233

    
2234
/**
2235
 * Checks is the source has one of the given types.
2236
 *
2237
 * @param object $source
2238
 *   The original source entity
2239
 * @param array $types
2240
 *   An array of elementd of the OriginalSourceType enumeration
2241
 *   If not set the default will be used which is:
2242
 *    - Lineage
2243
 *    - PrimaryMediaSource
2244
 *    - PrimaryTaxonomicSource
2245
 *    - Unknown
2246
 *    - Other
2247
 * @return boolean
2248
 */
2249
  function _is_original_source_type($source, $types = null) {
2250
    // this is the default
2251
    // maybe this should also be put into the settings
2252
    static $default = array(
2253
      OriginalSourceType::Lineage,
2254
      OriginalSourceType::PrimaryMediaSource,
2255
      OriginalSourceType::PrimaryTaxonomicSource,
2256
      OriginalSourceType::Unknown,
2257
      OriginalSourceType::Other,
2258
    );
2259

    
2260
    if(!$types){
2261
      $types = $default;
2262
    }
2263
    return isset($source->type) && in_array($source->type, $types);
2264
  }
2265

    
2266
/**
2267
 * @todo Please document this function.
2268
 * @see http://drupal.org/node/1354
2269
 */
2270
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2271
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2272
}
2273

    
2274

    
2275
/**
2276
 * Collects all the media from a list of description elements.
2277
 *
2278
 * @param array $descriptionElements
2279
 *   The description elements from which to collect the media.
2280
 *
2281
 * @return array
2282
 *   The output with all the collected media.
2283
 */
2284
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2285

    
2286
  $outArrayOfMedia = array();
2287

    
2288
  // Avoiding a warning box in Drupal for Flora Malesiana.
2289
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2290
    foreach ($descriptionElements as $descriptionElement) {
2291
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2292
        foreach ($descriptionElement->media as $media) {
2293
          if (is_object($media)) {
2294
            $outArrayOfMedia[] = $media;
2295
          }
2296
        }
2297
      }
2298
    }
2299
  }
2300
  return $outArrayOfMedia;
2301
}
2302

    
2303
/**
2304
 * @todo Please document this function.
2305
 * @see http://drupal.org/node/1354
2306
 *
2307
 * @param array $cdm_entities
2308
 *   An array of CdmBase instances or a single instance.
2309
 * @param string $footnote_list_key_suggestion
2310
 *
2311
 * @return unknown
2312
 */
2313
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2314

    
2315
   static $annotations_types_filter = null;
2316
   if(!$annotations_types_filter) {
2317
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2318
   }
2319

    
2320
  $footNoteKeys = array();
2321

    
2322
  // Is argument cdmBase an array?
2323
  if (!is_array($cdm_entities)) {
2324
    $cdmBase_array = array();
2325
    $cdmBase_array[] = $cdm_entities;
2326
  }
2327
  else {
2328
    $cdmBase_array = $cdm_entities;
2329
  }
2330

    
2331
  // Getting the key for the footnotemanager.
2332
  if (isset($footnote_list_key_suggestion)) {
2333
    $footnote_list_key = $footnote_list_key_suggestion;
2334
  }
2335
  else {
2336
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2337
  }
2338

    
2339
  // Adding the footnotes keys.
2340
  foreach ($cdmBase_array as $cdmBase_element) {
2341
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2342
    if (is_array($annotations)) {
2343
      foreach ($annotations as $annotation) {
2344
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2345
      }
2346
    }
2347
  }
2348

    
2349
  return $footNoteKeys;
2350
}
2351

    
2352

    
2353
/**
2354
 * Creates a CDM Dynabox.
2355
 *
2356
 * @param string $dynabox_id
2357
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2358
 * @param string $label
2359
 *   The clickable text to show.
2360
 * @param string $content_url
2361
 *   The cdm REST service request url wich will deliver the content to be shown
2362
 *   once the dynabox toggles open.
2363
 * @param string $theme
2364
 *   The theme to be used for rendering the cdm REST service response with is
2365
 *   returned from the $content_url.
2366
 * @param string $link_alt_text
2367
 *   The value for the alt attribute of the dynabox link.
2368
 * @param array $enclosingtags
2369
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2370
 *   element itself, $enclosingtags[1] is the tag to be used for the
2371
 *   dynabox_content (optional)
2372
 * @param array $attributes
2373
 * @param $content_element_selector
2374
 *   Optional jQuery selector which can be used to reference a dom element which should
2375
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2376
 *  element will be placed in this container.
2377
 *
2378
 * @param string $open_callback
2379
 *   optional javascript call back function to be triggered after toggling the box to
2380
 *   the open state.
2381
 * @param string $close_callback
2382
 *   optional javascript call back function to be triggered after toggling the box to
2383
 *   the closed state.
2384
 * @return string Returns HTML for a dynabox.
2385
 * Returns HTML for a dynabox.
2386
 */
2387
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2388
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2389
                     $content_element_selector = null,
2390
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2391
  $out = '';
2392

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

    
2396
  if(!array_key_exists('class', $attributes)) {
2397
    $attributes['class'] = array();
2398
  }
2399
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2400
  $dynabox_attributes = drupal_attributes($attributes);
2401

    
2402

    
2403
  _add_js_domEvent(); // requires domEvent.js
2404
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2405
  drupal_add_js("
2406
  jQuery(document).ready(
2407
      function() {
2408
        dynabox('". $dynabox_id ."',
2409
          {
2410
            open_callback: " . $open_callback .",
2411
            close_callback: " . $close_callback .
2412
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2413
          }
2414
        );
2415
      }
2416
   );",
2417
   array(
2418
    'type'=>'inline',
2419
    'scope'=>'footer'
2420
    )
2421
  );
2422

    
2423

    
2424
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2425
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2426
  $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>';
2427
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2428
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2429
  $out .= '    </' . $enclosingtags[1] . '>';
2430
  $out .= '  </' . $enclosingtags[0] . '>';
2431
  $out .= '<!-- dynabox end -->';
2432
  return $out;
2433
}
2434

    
2435
/**
2436
 * Checks whether a feature has any description elements.
2437
 *
2438
 * @param mixed $featureNode
2439
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2440
 *
2441
 * @see _mergeFeatureTreeDescriptions()
2442
 *
2443
 * @return bool
2444
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2445
 *   contains at least one non empty TextData or at least one DescriptionElement
2446
 *   of an other type. A TextData element holding a multilanguageText or a
2447
 *   source reference is considered to be not empty.
2448
 *
2449
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2450
 *       see $block_content_is_not_empty in make_feature_block_list() and
2451
 *       $feature_block_has_content in compose_feature_block_items_generic
2452
 */
2453
function has_feature_node_description_elements($featureNode) {
2454

    
2455
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2456
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2457
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2458
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2459
          && $descriptionElement->multilanguageText_L10n->text != ''
2460
          || isset($descriptionElement->sources[0])
2461
          || isset($descriptionElement->media[0]) ) {
2462
          return TRUE;
2463
        }
2464
      }
2465
    }
2466
  }
2467
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2468
    foreach ($featureNode->childNodes as $child) {
2469
      if (has_feature_node_description_elements($child)) {
2470
        return TRUE;
2471
      }
2472
    }
2473
  }
2474
  return FALSE;
2475
}
2476

    
2477
/**
2478
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2479
 *
2480
 * @param $chapter
2481
 *   The taxon page chapter or part
2482
 */
2483
function cdm_check_valid_taxon_page($chapter){
2484
  static $taxon_tabs = null;
2485

    
2486
  cdm_check_valid_portal_page();
2487

    
2488
  if($taxon_tabs == null){
2489
    $taxon_tabs = array('all', 'description');
2490
    foreach(get_taxon_tabs_list() as $tab){
2491
      $taxon_tabs[] = strtolower($tab);
2492
    }
2493
  }
2494

    
2495
  if(!in_array($chapter, $taxon_tabs)){
2496
    // oops this is not a valid chapter name
2497
    http_response_code(404); // 404 = Not Found
2498
  }
2499

    
2500
}
2501

    
2502
/**
2503
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2504
 *
2505
 * @param $chapter
2506
 *   The taxon page chapter or part
2507
 */
2508
function cdm_check_valid_portal_page(){
2509
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2510
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2511
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2512
    http_response_code(404); // 404 = Not Found
2513
    exit('HTTP 404');
2514
  }
2515
}
2516

    
2517
/**
2518
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2519
 *
2520
 * @param $text_a
2521
 * @param $text_b
2522
 * @return string
2523
 */
2524
function diff_viewer($text_a, $text_b) {
2525

    
2526
  static $diff_viewer_count = 0;
2527

    
2528
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2529

    
2530
  // http://code.stephenmorley.org/php/diff-implementation/
2531
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2532
  drupal_add_css(drupal_get_path('module',
2533
      'cdm_dataportal') . '/css/diff.css');
2534
  _add_jquery_ui();
2535
  drupal_add_js(
2536
    'jQuery(document).ready( function(){
2537
        jQuery(\'#' . $element_id . '\').accordion({
2538
        collapsible: true,
2539
        active: false,
2540
        fillSpace: true,
2541
        }).children(\'div\').css({ \'height\': \'auto\' });
2542
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2543
     });'
2544
    , array(
2545
    'type' => 'inline',
2546
    'scope' => 'footer'
2547
  ));
2548

    
2549
  $diff = Diff::compare($text_a,
2550
    $text_b);
2551
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2552
    . Diff::toTable($diff, '', '')
2553
    . '</div></div>';
2554
  return $diff_viewer_markup;
2555
}
2556

    
2557

    
(10-10/18)