Project

General

Profile

Download (80 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
   // Optional callback arguments: page.
418
    //FIXME point to view/page method in this module
419
    $items['cdm_dataportal/specimen'] = array(
420
        'page callback' => 'cdm_dataportal_specimen_page_view',
421
        'access arguments' => array('access cdm content'),
422
        'type' => MENU_CALLBACK,
423
        // Expected callback arguments: uuid.
424
    );
425

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

    
440
  $items['cdm_dataportal/reference'] = array(
441
    'page callback' => 'cdm_dataportal_view_reference',
442
    'access arguments' => array('access cdm content'),
443
    'type' => MENU_CALLBACK,
444
    // Expected callback arguments: uuid.
445
  );
446

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

    
454
  $items['cdm_dataportal/media'] = array(
455
    'page callback' => 'cdm_dataportal_view_media',
456
    'access arguments' => array('access cdm content'),
457
    'type' => MENU_CALLBACK,
458
    // Expected callback arguments:
459
    // uuid, mediarepresentation_uuid, part_uuid or part#.
460
  );
461

    
462
  $items['cdm_dataportal/polytomousKey'] = array(
463
    'page callback' => 'cdm_dataportal_view_polytomousKey',
464
    'access arguments' => array('access cdm content'),
465
    'type' => MENU_CALLBACK,
466
    // Expected callback arguments: polytomousKey->uuid.
467
  );
468

    
469
  $items['cdm_dataportal/search'] = array(
470
    'page callback' => 'cdm_dataportal_view_search_advanced',
471
    'access arguments' => array('access cdm content'),
472
    'type' => MENU_CALLBACK,
473
  );
474

    
475
  $items['cdm_dataportal/search/advanced'] = array(
476
    'title' => 'Advanced', // will be passed through t()
477
    'page callback' => 'cdm_dataportal_view_search_advanced',
478
    'access arguments' => array('access cdm content'),
479
    'type' => MENU_DEFAULT_LOCAL_TASK,
480
  );
481

    
482
  $items['cdm_dataportal/search/taxon_by_description'] = array(
483
    'title' => 'By content category', // will be passed through t()
484
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
485
    'access arguments' => array('access cdm content'),
486
    'type' => MENU_LOCAL_TASK,
487
  );
488

    
489
  $items['cdm_dataportal/search/results/taxon'] = array(
490
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
491
    'access arguments' => array('access cdm content'),
492
    'type' => MENU_CALLBACK,
493
  );
494
  /*
495
   $items['cdm/xml2json'] = array(
496
   'page callback' => 'cdm_view_xml2json',
497
   'access arguments' => array('access cdm content'),
498
   'type' => MENU_CALLBACK,
499
   );
500
   */
501

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

    
514
  // 'May not cache' in D5.
515
  $items['cdm_dataportal/name/%'] = array(
516
    // 'page callback' => 'cdm_dataportal_view_name',
517
    'page callback' => 'cdm_dataportal_name_page_view',
518
    'page arguments' => array(2, 3, 4),
519
    'access arguments' => array('access cdm content'),
520
    'type' => MENU_CALLBACK,
521
  );
522

    
523
  // --- Local tasks for Taxon.
524
  // --- tabbed taxon page
525
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
526
    $items['cdm_dataportal/taxon/%'] = array(
527
      'title' => '@tabname',
528
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
529
      'page callback' => 'cdm_dataportal_taxon_page_view',
530
      'access arguments' => array('access cdm content'),
531
      'type' => MENU_CALLBACK,
532
      'weight' => 1,
533
      'page arguments' => array(2, "description")
534
      , // Expected callback arguments: taxon_uuid.
535
    );
536

    
537
    $items['cdm_dataportal/taxon/%/all'] = array(
538
      'title' => '@tabname',
539
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
540
      'page callback' => 'cdm_dataportal_taxon_page_view',
541
      'access arguments' => array('access cdm content'),
542
      'type' => MENU_CALLBACK,
543
      'weight' => 2,
544
      'page arguments' => array(2, "all")
545
      , // Expected callback arguments: taxon_uuid.
546
    );
547

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

    
559
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
560
      'title' => '@tabname',
561
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy'))),
562
      'page callback' => 'cdm_dataportal_taxon_page_view',
563
      'access arguments' => array('access cdm content'),
564
      'type' => MENU_LOCAL_TASK,
565
      'weight' => 4,
566
      'page arguments' => array(2, "synonymy", 4)
567
      , // Expected callback arguments: taxon_uuid and ...
568
    );
569
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
570
      'title' => '@tabname',
571
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => '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' => '@tabname',
582
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens'))),
583
      'page callback' => 'cdm_dataportal_taxon_page_view',
584
      'access arguments' => array('access cdm content'),
585
      'type' => MENU_LOCAL_TASK,
586
      'weight' => 6,
587
      'page arguments' => array(2, "specimens")
588
      , // Expected callback arguments: taxon_uuid.
589
    );
590

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

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

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

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

    
633
  return $items;
634
}
635

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

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

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

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

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

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

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

    
672

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

    
676
/**
677
 * The function generate form for own user cdm dataportal configurations.
678
 */
679
function cdm_dataportal_user_form($form, &$form_state) {
680

    
681
  global $user;
682
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
683

    
684
  $form['taxon_page_tabs'] = array(
685
      '#type' => 'fieldset',
686
      '#tree' => true,
687
      '#title' => t('Taxon page tabs'),
688
  );
689

    
690
  $form['taxon_page_tabs']['user_defined'] = array(
691
    '#type' => 'checkbox',
692
    '#title' => t('Activate user default configuration'),
693
    '#default_value' => variable_get($checkbox_value, 0),
694
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
695
  );
696

    
697
  $form['taxon_page_tabs']['default_tab'] = array(
698
    '#type' => 'select',
699
    '#title' => t('Default tab to display'),
700
    '#default_value' => get_default_taxon_tab(TRUE),
701
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
702
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
703
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
704
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
705
  );
706

    
707

    
708
  if(false){
709
    $form['developer_options'] = array(
710
        '#type' => 'fieldset',
711
        '#tree' => true,
712
        '#title' => t('Developer options'),
713
    );
714

    
715
    $form['developer_options']['show_render_path'] = array(
716
      '#type' => 'checkbox',
717
      '#title' => t('Display the render path for each taxon name.'),
718
      '#default_value' => variable_get($checkbox_value, 0),
719
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
720
        array(
721
            '!link' => l(
722
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
723
            )
724
        ),
725
    );
726
  }
727

    
728
  $form['submit'] = array(
729
    '#type' => 'submit',
730
    '#value' => t('Submit'),
731
  );
732

    
733
  return $form;
734
}
735

    
736
/**
737
 * Form submission handler for user_form().
738
 *
739
 * Submits the user cdm dataportal configurations.
740
 */
741
function cdm_dataportal_user_form_submit($form, &$form_state) {
742
  global $user;
743
  $msg_type = 'status';
744
  $username = $user->name;
745
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
746

    
747
  // FIXME: this is completely wrong, see user_profile_form_submit()
748

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

    
752
    // DEFAULT_TAXON_TAB
753
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
754
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
755
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
756
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
757
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
758
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
759
        '!tab' => $variable[variable_get($variable_to_use, 0)],
760
        '!user' => $username,
761
      ))), $msg_type);
762
    }
763
    else {
764
      drupal_set_message(check_plain(t('The user default tab wont be used for
765
        the next taxon site, check the box if you want to use the user default configuration.')));
766
    }
767

    
768
  }
769
  else {
770
    // Problem with the user id => variables wont be saved.
771
    $msg_type = 'warning';
772
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
773
  }
774
}
775

    
776
/**
777
 * Implements hook_block_info().
778
 */
779
function cdm_dataportal_block_info() {
780

    
781
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
782
    // $block[1]["info"] = t("CDM DataPortal Credits");
783
    $block["2"] = array(
784
        "info" => t("CDM - Search Taxa"),
785
        "cache" => DRUPAL_NO_CACHE
786
      );
787
    // $block[3]["info"] = t("CDM Filters");
788
    $block["4"]["info"] = t("CDM  - Dataportal Print");
789
    $block["keys"]["info"] = t("CDM - Identification keys");
790
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
791
    $block["classification_breadcrumbs"] =  array(
792
        'info' => t('CDM - Classification breadcrumbs'),
793
        'cache' => DRUPAL_CACHE_PER_PAGE
794
      );
795
    $block["taxonomic_children"] =  array(
796
      'info' => t('CDM - Taxonomic children'),
797
      'cache' => DRUPAL_CACHE_PER_PAGE
798
    );
799
    $block["back_to_search_results"] =  array(
800
      'title' => '<none>',
801
      'info' => t('CDM - Back to search Results'),
802
      'cache' => DRUPAL_CACHE_PER_PAGE,
803
      'visibility' => BLOCK_VISIBILITY_LISTED,
804
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
805
    );
806

    
807
    return $block;
808
}
809

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

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

    
869
/**
870
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
871
 *
872
 * @return string
873
 *   the taxon uuid or NULL
874
 */
875
function get_current_taxon_uuid()
876
{
877
  static $taxon_uuid;
878

    
879
  if(!isset($taxon_uuid)){
880
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
881
      $taxon_uuid = $_REQUEST['currentTaxon'];
882
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
883
      $taxon_uuid = arg(2);
884
    } else {
885
      $taxon_uuid = null;
886
    }
887
  }
888

    
889
  return $taxon_uuid;
890
}
891

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

    
907
/*
908
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
909
 $_SESSION['cdm'] = NULL;
910
 if(is_string($cdm_ws_uri_update)){
911
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
912
 }
913
 }
914

    
915
 function cdm_dataportal_session_validate(){
916
 if(!isset($_SESSION['cdm']['ws_uri'])){
917
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
918
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
919
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
920
 }
921
 }
922
 */
923

    
924
/**
925
 * creates a  selector form for taxonomic trees.
926
 *
927
 * @return array
928
 *  a drupal form array
929
 */
930
function cdm_taxonomictree_selector() {
931
  _add_js_treeselector();
932

    
933
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
934
  return $form;
935
}
936

    
937
/**
938
 * @todo Please document this function.
939
 * @see http://drupal.org/node/1354
940
 *
941
 * @deprecated use compose_classification_selector instead
942
 */
943
function cdm_taxonomictree_selector_form($form, &$form_state) {
944

    
945
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
946
  $form['#action'] = $url;
947

    
948
  $form['var'] = array(
949
    '#weight' => -3,
950
    '#type' => 'hidden',
951
    '#value' => '[cdm][taxonomictree_uuid]',
952
  );
953

    
954
  $destination_array = drupal_get_destination();
955
  $destination = $destination_array['destination'];
956

    
957
  $form['destination'] = array(
958
    '#weight' => -3,
959
    '#type' => 'hidden',
960
    '#value' =>  $destination,
961
  );
962

    
963
  $options = cdm_get_taxontrees_as_options();
964
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
965
  if($taxontree_includes){
966
    $filtered_options = array();
967
    foreach($options as $uuid=>$label){
968
      if(!empty($taxontree_includes[$uuid])){
969
        $filtered_options[$uuid] = $label;
970
      }
971
    }
972
    $options = $filtered_options;
973
  }
974

    
975
  $form['val'] = array(
976
    '#type' => 'select',
977
    '#title' => t('Available classifications'),
978
    '#default_value' => get_current_classification_uuid(),
979
    '#options' => $options,
980
    '#attributes' => array('class' => array('highlite-first-child')),
981
  );
982

    
983
  return $form;
984

    
985
}
986

    
987
/**
988
 *
989
 * @ingroup compose
990
 */
991
function compose_classification_selector() {
992

    
993
  $destination_array = drupal_get_destination();
994
  $destination = $destination_array['destination'];
995

    
996
  $options = cdm_get_taxontrees_as_options();
997
  $items = array();
998
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
999

    
1000
  $current_classification_uuid = get_current_classification_uuid();
1001

    
1002

    
1003
  foreach($options as $uuid=>$label){
1004
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1005

    
1006
      $class_attributes = '';
1007
      if($current_classification_uuid == $uuid){
1008
        $class_attributes  = array('focused');
1009
      }
1010
      $items[] = array(
1011
        'data' => l($label,
1012
          'cdm_api/setvalue/session',
1013
          array(
1014
            'query' => array(
1015
              'destination' => $destination,
1016
              'val' => $uuid,
1017
              'var' => '[cdm][taxonomictree_uuid]'
1018
            ),
1019
          )
1020
        ),
1021
        'class' => $class_attributes
1022
      );
1023
    }
1024
  }
1025

    
1026
  $render_array = array(
1027
    '#theme' => 'item_list',
1028
    '#type' => 'ul',
1029
    '#items' => $items
1030
  );
1031

    
1032
  return $render_array;
1033
}
1034

    
1035

    
1036
/* UNREACHABLE since action of form directly links to view.
1037
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1038

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

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

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

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

    
1089
  /*
1090
  // FIXME the filter for accepted names will be a form element, thus this
1091
  // widget should be generated via form api preferably as block.
1092
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1093
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1094
  $out .= theme('cdm_listof_taxa', $taxonPager);
1095
  return $out;
1096
  */
1097
}
1098

    
1099
/**
1100
 * @todo Please document this function.
1101
 * @see http://drupal.org/node/1354
1102
 */
1103
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1104

    
1105
  cdm_check_valid_portal_page();
1106

    
1107
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1108
  return theme('cdm_reference_page', array('reference' => $reference));
1109
}
1110

    
1111
/**
1112
 * Creates a view on a all references contained in the portal.
1113
 *
1114
 * This function is used at the path cdm_dataportal/reference/list
1115
 */
1116
function cdm_dataportal_view_reference_list($pageNumber) {
1117
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1118
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1119
}
1120

    
1121
/**
1122
 * @todo Please document this function.
1123
 * @see http://drupal.org/node/1354
1124
 */
1125
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1126

    
1127
  cdm_check_valid_portal_page();
1128

    
1129
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1130
  return theme('cdm_media_page', array(
1131
    'media' => $media,
1132
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1133
    'partId' => $part,
1134
    ));
1135
}
1136

    
1137
/**
1138
 * @todo Please document this function.
1139
 * @see http://drupal.org/node/1354
1140
 */
1141
function _load_taxonBase(&$taxonBase) {
1142
  if (isset($taxonBase->uuid)) {
1143
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1144
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1145
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1146
  }
1147
}
1148

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

    
1165
  static $media = NULL;
1166

    
1167
  if(!isset($media)) {
1168
    $media = array();
1169
  }
1170
  if (!isset($media[$taxon->uuid])) {
1171

    
1172
    // --- GET Images --- //
1173
    $mediaQueryParameters = array(
1174
        "type" => "ImageFile",
1175
    );
1176

    
1177
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1178
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1179
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1180

    
1181
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1182
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1183
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1184
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1185

    
1186
    $ws_endpoint = NULL;
1187
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1188
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1189
    } else {
1190
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1191
    }
1192

    
1193
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1194
        array(
1195
            $taxon->uuid,
1196
        ),
1197
        queryString($mediaQueryParameters)
1198
       );
1199
  }
1200

    
1201
  return $media[$taxon->uuid];
1202
}
1203

    
1204
/**
1205
 *
1206
 * @param Taxon $taxon
1207
 *   A CDM Taxon entitiy
1208
 *
1209
 * @return array
1210
 *   An array of CDM SpecimenOrObservation entities
1211
 *
1212
function _load_occurences_for_taxon($taxon){
1213

    
1214
  static $occurences = NULL;
1215

    
1216
  if(!isset($occurences)) {
1217
    $occurences = array();
1218
  }
1219

    
1220
  if (!isset($occurences[$taxon->uuid])){
1221

    
1222
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1223
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1224
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1225

    
1226
    $by_associatedtaxon_query = http_build_query(array(
1227
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1228
        'relationships' => implode(',', $relationship_choice['direct']),
1229
        'pageSize' => null // all hits in one page
1230
    )
1231
    );
1232

    
1233
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1234
        null,
1235
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1236
    );
1237

    
1238

    
1239
    if(isset($pager->records[0])){
1240
      $occurences[$taxon->uuid] =  $pager->records;
1241
    }
1242
  }
1243
  return $occurences[$taxon->uuid];
1244
}
1245
 */
1246

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

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

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

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

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

    
1379
/**
1380
 * Loads the subgraph of a given PolytomousKeyNode.
1381
 *
1382
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1383
 * the CDM REST service.
1384
 *
1385
 * @param mixed $polytomousKeyNode
1386
 *   PolytomousKeyNode passed by reference.
1387
 *
1388
 * @return void
1389
 */
1390
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1391

    
1392
  if (!$polytomousKeyNode) {
1393
    return;
1394
  }
1395
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1396
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1397
    return;
1398
  }
1399
  if (!is_uuid($polytomousKeyNode->uuid)) {
1400
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1401
    return;
1402
  }
1403

    
1404
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1405

    
1406
  if (!$polytomousKeyNode) {
1407
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1408
    return;
1409
  }
1410

    
1411
  // Load children.
1412
  foreach ($polytomousKeyNode->children as &$childNode) {
1413
    _load_polytomousKeySubGraph($childNode);
1414
  }
1415

    
1416
  // Load subkey.
1417
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1418

    
1419
  // Load taxon.
1420
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1421
  _load_taxonBase($polytomousKeyNode->taxon);
1422
  return;
1423
}
1424

    
1425
/**
1426
 * @todo Please document this function.
1427
 * @see http://drupal.org/node/1354
1428
 */
1429
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1430

    
1431
  cdm_check_valid_portal_page();
1432

    
1433
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1434

    
1435
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1436
  if (is_array($sourcePager->records)) {
1437
    $polytomousKey->sources = $sourcePager->records;
1438
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1439
  }
1440

    
1441
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1442
  if (is_array($annotationPager->records)) {
1443
    $polytomousKey->annotations = $annotationPager->records;
1444
  }
1445

    
1446
  _load_polytomousKeySubGraph($polytomousKey->root);
1447
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1448
}
1449

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

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

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

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

    
1520
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1521
    'taxon' => $taxon
1522
  ));
1523

    
1524
  // Check if the taxon id contained in the currently selected tree.
1525
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1526

    
1527
  if (!$taxon_in_current_classification) {
1528
    $classifications = get_classifications_for_taxon($taxon);
1529
    RenderHints::pushToRenderStack('not_in_current_classification');
1530
    $taxon_name_markup = render_taxon_or_name($taxon);
1531

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

    
1547
      drupal_set_message(format_plural(count($trees),
1548
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1549
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1550
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1551
        ) ,
1552
        'warning');
1553
    }
1554
    RenderHints::popFromRenderStack();
1555
  }
1556

    
1557
  // Render the taxon page.
1558
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1559
  $taxonpage->content = drupal_render($render_array);
1560

    
1561
  return $taxonpage;
1562
}
1563

    
1564
/**
1565
 * Creates a specimen page view.
1566
 * @param string $uuid the UUID of the specimen
1567
 * @return array|string
1568
 */
1569
function cdm_dataportal_specimen_page_view($uuid) {
1570

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

    
1583
    // Display the page for the specimen defined by $uuid.
1584
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1585
    if (!empty($specimenpage)) {
1586
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1587
    }
1588
    else {
1589
        return '';
1590
    }
1591
}
1592

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

    
1607
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1608
        'specimen' => $specimen
1609
    ));
1610

    
1611
    // Render the specimen page.
1612
    $render_array = compose_cdm_specimen_page($uuid);
1613
    $specimenpage->content = drupal_render($render_array);
1614

    
1615
    return $specimenpage;
1616
}
1617

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

    
1639
  cdm_check_valid_portal_page();
1640

    
1641
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1642
  if (!empty($taxonname_page)) {
1643
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1644
  }
1645
  else {
1646
    return '';
1647
  }
1648
}
1649

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

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

    
1740
/**
1741
 * Creates a page with the advance search form.
1742
 *
1743
 * NOTE: The advance search form allows searching for taxa.
1744
 */
1745
function cdm_dataportal_view_search_advanced() {
1746
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1747
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1748
}
1749

    
1750
/**
1751
 * Creates a page with the search form for searching by taxon descriptions.
1752
 */
1753
function cdm_dataportal_view_search_taxon_by_description() {
1754
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1755
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1756
}
1757

    
1758
/**
1759
 * Executes the search and generates the result list of taxa.
1760
 */
1761
function cdm_dataportal_view_search_results_taxon() {
1762

    
1763
  $taxonPager = cdm_dataportal_search_execute();
1764

    
1765
  $showThumbnails = do_showThumbnails();
1766

    
1767
  $setSessionUri = url('cdm_api/setvalue/session', array(
1768
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1769
  ));
1770

    
1771
  drupal_add_js('jQuery(document).ready(function() {
1772

    
1773
      // init
1774
      if(' . $showThumbnails . ' == 1){
1775
          jQuery(\'.media_gallery\').show(20);
1776
      } else {
1777
          jQuery(\'.media_gallery\').hide(20);
1778
      }
1779

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

    
1797
  drupal_set_title(t('Search results'), PASS_THROUGH);
1798

    
1799
  return theme('cdm_search_results', array(
1800
    'pager' => $taxonPager,
1801
    'path' => 'cdm_dataportal/search/results/taxon',
1802
    ));
1803
}
1804

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

    
1816
/**
1817
 * Returns the state of the the showThumbnails flag set in the
1818
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1819
 *
1820
 * @return boolean
1821
 *    returns 1 if the flag is set
1822
 */
1823
function do_showThumbnails() {
1824
  static $showThumbnails = null;
1825

    
1826
  if($showThumbnails == null) {
1827
    $showThumbnails = 0;
1828
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1829
      $showThumbnails = 0;
1830
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1831
      $showThumbnails = is_array($search_gallery_settings)
1832
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1833
        && (
1834
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1835
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1836
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1837
            )
1838
         ? 1 : 0;
1839

    
1840
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1841
    }
1842
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1843
    if (!is_numeric($showThumbnails)) {
1844
      $showThumbnails = 1;
1845
    }
1846
  }
1847

    
1848
  return $showThumbnails;
1849
}
1850

    
1851

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

    
1877
  $tab = get_default_taxon_tab();
1878
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1879

    
1880
  if (!$uuid) {
1881
    return FALSE;
1882
  }
1883

    
1884
  if ($page_tab) {
1885
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1886
  }
1887
  elseif (!$tab || strtolower($tab) == 'general') {
1888
    return 'cdm_dataportal/taxon/' . $uuid;
1889
  }
1890
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1891
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1892
  }
1893
  else {
1894
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1895
  }
1896
}
1897

    
1898
function path_to_specimen($uuid) {
1899

    
1900
    if (!$uuid) {
1901
        return FALSE;
1902
    }
1903
    else {
1904
        return 'cdm_dataportal/specimen/' . $uuid;
1905
    }
1906
}
1907

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

    
1937
}
1938

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

    
1959
/**
1960
 * @todo Please document this function.
1961
 * @see http://drupal.org/node/1354
1962
 */
1963
function path_to_reference($uuid) {
1964
  if (!$uuid) {
1965
    return FALSE;
1966
  }
1967
  return 'cdm_dataportal/reference/' . $uuid;
1968
}
1969

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

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

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

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

    
2057
  if (is_cdm_entity($cdmEntity)) {
2058
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2059
  }
2060
}
2061

    
2062

    
2063
/**
2064
 * Creates a short version of a taxonname.
2065
 *
2066
 * The short name is created by using the taggedTitle field of
2067
 * TaxonNodeDTO instances.
2068
 * If the taggedTitle if empty the fullname will be returned.
2069
 *
2070
 * @param object $taxonNodeDTO
2071
 *   A TaxonNodeDTO object
2072
 *
2073
 * @return string
2074
 */
2075
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2076

    
2077
  $nameStr = '';
2078

    
2079
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2080

    
2081
  // Get all tagged text tokens of the scientific name.
2082
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2083
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2084
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2085
    }
2086
  }
2087
  $nameStr = trim($nameStr);
2088

    
2089
  if ($nameStr) {
2090

    
2091
    // Do not return short names for these.
2092
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2093
      return $nameStr;
2094
    }
2095

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

    
2116
/**
2117
 * Check if a taxon is accepted by the current taxonomic tree.
2118
 *
2119
 * @param mixed $taxon
2120
 *   The Taxon obkect to check.
2121
 *
2122
 * @return bool
2123
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2124
 */
2125
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2126

    
2127
  $defaultTreeUuid = get_current_classification_uuid();
2128

    
2129
  if (isset($taxon->taxonNodes)) {
2130
    $taxonNodes = $taxon->taxonNodes;
2131
  }
2132
  else {
2133
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2134
  }
2135

    
2136
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2137
    foreach ($taxonNodes as $node) {
2138
      if (isset($node->classification)){
2139
        if(is_object($node->classification)) {
2140
          if ($node->classification->uuid == $defaultTreeUuid) {
2141
            return TRUE;
2142
          }
2143
        }
2144
        else {
2145
          if ($node->classification == $defaultTreeUuid) {
2146
            return TRUE;
2147
          }
2148
        }
2149
      }
2150
    }
2151
  }
2152

    
2153
  return FALSE;
2154
}
2155

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

    
2182
    if(!$types){
2183
      $types = $default;
2184
    }
2185
    return isset($source->type) && in_array($source->type, $types);
2186
  }
2187

    
2188
/**
2189
 * @todo Please document this function.
2190
 * @see http://drupal.org/node/1354
2191
 */
2192
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2193
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2194
}
2195

    
2196

    
2197
/**
2198
 * Collects all the media from a list of description elements.
2199
 *
2200
 * @param array $descriptionElements
2201
 *   The description elements from which to collect the media.
2202
 *
2203
 * @return array
2204
 *   The output with all the collected media.
2205
 */
2206
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2207

    
2208
  $outArrayOfMedia = array();
2209

    
2210
  // Avoiding a warning box in Drupal for Flora Malesiana.
2211
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2212
    foreach ($descriptionElements as $descriptionElement) {
2213
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2214
        foreach ($descriptionElement->media as $media) {
2215
          if (is_object($media)) {
2216
            $outArrayOfMedia[] = $media;
2217
          }
2218
        }
2219
      }
2220
    }
2221
  }
2222
  return $outArrayOfMedia;
2223
}
2224

    
2225
/**
2226
 * @todo Please document this function.
2227
 * @see http://drupal.org/node/1354
2228
 *
2229
 * @param array $cdm_entities
2230
 *   An array of CdmBase instances or a single instance.
2231
 * @param string $footnote_list_key_suggestion
2232
 *
2233
 * @return unknown
2234
 */
2235
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2236

    
2237
   static $annotations_types_filter = null;
2238
   if(!$annotations_types_filter) {
2239
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2240
   }
2241

    
2242
  $footNoteKeys = array();
2243

    
2244
  // Is argument cdmBase an array?
2245
  if (!is_array($cdm_entities)) {
2246
    $cdmBase_array = array();
2247
    $cdmBase_array[] = $cdm_entities;
2248
  }
2249
  else {
2250
    $cdmBase_array = $cdm_entities;
2251
  }
2252

    
2253
  // Getting the key for the footnotemanager.
2254
  if (isset($footnote_list_key_suggestion)) {
2255
    $footnote_list_key = $footnote_list_key_suggestion;
2256
  }
2257
  else {
2258
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2259
  }
2260

    
2261
  // Adding the footnotes keys.
2262
  foreach ($cdmBase_array as $cdmBase_element) {
2263
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2264
    if (is_array($annotations)) {
2265
      foreach ($annotations as $annotation) {
2266
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2267
      }
2268
    }
2269
  }
2270

    
2271
  return $footNoteKeys;
2272
}
2273

    
2274

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

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

    
2318
  if(!array_key_exists('class', $attributes)) {
2319
    $attributes['class'] = array();
2320
  }
2321
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2322
  $dynabox_attributes = drupal_attributes($attributes);
2323

    
2324

    
2325
  _add_js_domEvent(); // requires domEvent.js
2326
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2327
  drupal_add_js("
2328
  jQuery(document).ready(
2329
      function() {
2330
        dynabox('". $dynabox_id ."',
2331
          {
2332
            open_callback: " . $open_callback .",
2333
            close_callback: " . $close_callback .
2334
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2335
          }
2336
        );
2337
      }
2338
   );",
2339
   array(
2340
    'type'=>'inline',
2341
    'scope'=>'footer'
2342
    )
2343
  );
2344

    
2345

    
2346
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2347
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2348
  $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>';
2349
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2350
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2351
  $out .= '    </' . $enclosingtags[1] . '>';
2352
  $out .= '  </' . $enclosingtags[0] . '>';
2353
  $out .= '<!-- dynabox end -->';
2354
  return $out;
2355
}
2356

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

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

    
2399
/**
2400
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2401
 *
2402
 * @param $chapter
2403
 *   The taxon page chapter or part
2404
 */
2405
function cdm_check_valid_taxon_page($chapter){
2406
  static $taxon_tabs = null;
2407

    
2408
  cdm_check_valid_portal_page();
2409

    
2410
  if($taxon_tabs == null){
2411
    $taxon_tabs = array('all', 'description');
2412
    foreach(get_taxon_tabs_list() as $tab){
2413
      $taxon_tabs[] = strtolower($tab);
2414
    }
2415
  }
2416

    
2417
  if(!in_array($chapter, $taxon_tabs)){
2418
    // oops this is not a valid chapter name
2419
    http_response_code(404); // 404 = Not Found
2420
  }
2421

    
2422
}
2423

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

    
2439
/**
2440
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2441
 *
2442
 * @param $text_a
2443
 * @param $text_b
2444
 * @return string
2445
 */
2446
function diff_viewer($text_a, $text_b) {
2447

    
2448
  static $diff_viewer_count = 0;
2449

    
2450
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2451

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

    
2471
  $diff = Diff::compare($text_a,
2472
    $text_b);
2473
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2474
    . Diff::toTable($diff, '', '')
2475
    . '</div></div>';
2476
  return $diff_viewer_markup;
2477
}
2478

    
2479

    
(10-10/16)