Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

    
126
  function _add_js_resizable_element($selector, $y_axis_only) {
127

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

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

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

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

    
282
  global $base_url;
283

    
284

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

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

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

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

    
344

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

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

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

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

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

    
367
    return '';
368
  }
369

    
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
630
  return $items;
631
}
632

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

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

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

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

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

    
662
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
663
    // force reloading of all and notify user about this special loading
664
    drupal_set_message(t('The level 2 cache has been cleared for all tabs of this taxon page at once, please click here to return to the tabbed page: ')
665
        . l('Back to tabbed taxon page', $base_path));
666
    $base_path .= '/all';
667
  } else {
668
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
669
  }
670

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

    
673

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

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

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

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

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

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

    
708

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

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

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

    
734
  return $form;
735
}
736

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

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

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

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

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

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

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

    
808
    return $block;
809
}
810

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

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

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

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

    
890
  return $taxon_uuid;
891
}
892

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

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

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

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

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

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

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

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

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

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

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

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

    
984
  return $form;
985

    
986
}
987

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

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

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

    
1001
  $current_classification_uuid = get_current_classification_uuid();
1002

    
1003

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

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

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

    
1033
  return $render_array;
1034
}
1035

    
1036

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

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

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

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

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

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

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

    
1106
  cdm_check_valid_portal_page();
1107

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

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

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

    
1128
  cdm_check_valid_portal_page();
1129

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

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

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

    
1166
  static $media = NULL;
1167

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

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

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

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

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

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

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

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

    
1215
  static $occurences = NULL;
1216

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

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

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

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

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

    
1239

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1432
  cdm_check_valid_portal_page();
1433

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1562
  return $taxonpage;
1563
}
1564

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

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

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

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

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

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

    
1616
    return $specimenpage;
1617
}
1618

    
1619
/**
1620
 *
1621
 * Creates a named area view.
1622
 * @param string $uuid the UUID of the specimen
1623
 *  * @return object
1624
 *   An object with two fields:
1625
 *     - title: the page title
1626
 *     - content: the page content
1627
 */
1628

    
1629
function cdm_dataportal_named_area_view($uuid) {
1630
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1631
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1632
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1633
    return FALSE;
1634
  }
1635
  $named_area_page = new stdClass();
1636

    
1637
  $named_area_page->title = $named_area->representation_L10n;
1638

    
1639
  // Render the specimen page.
1640
  $render_array = compose_cdm_named_area_page($uuid);
1641
  $named_area_page->content = drupal_render($render_array);
1642

    
1643
  return $named_area_page;
1644
}
1645

    
1646
function cdm_dataportal_named_area_page_view($uuid) {
1647

    
1648
  cdm_check_valid_portal_page();
1649

    
1650
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1651
  if (!empty($named_area_page)) {
1652
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1653
  }
1654
  else {
1655
    return '';
1656
  }
1657

    
1658

    
1659
}
1660

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

    
1682
  cdm_check_valid_portal_page();
1683

    
1684
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1685
  if (!empty($taxonname_page)) {
1686
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1687
  }
1688
  else {
1689
    return '';
1690
  }
1691
}
1692

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

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

    
1783
/**
1784
 * Creates a page with the advance search form.
1785
 *
1786
 * NOTE: The advance search form allows searching for taxa.
1787
 */
1788
function cdm_dataportal_view_search_advanced() {
1789
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1790
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1791
}
1792

    
1793
/**
1794
 * Creates a page with the search form for searching by taxon descriptions.
1795
 */
1796
function cdm_dataportal_view_search_taxon_by_description() {
1797
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1798
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1799
}
1800

    
1801
/**
1802
 * Executes the search and generates the result list of taxa.
1803
 */
1804
function cdm_dataportal_view_search_results_taxon() {
1805

    
1806
  $taxonPager = cdm_dataportal_search_execute();
1807

    
1808
  $showThumbnails = do_showThumbnails();
1809

    
1810
  $setSessionUri = url('cdm_api/setvalue/session', array(
1811
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1812
  ));
1813

    
1814
  drupal_add_js('jQuery(document).ready(function() {
1815

    
1816
      // init
1817
      if(' . $showThumbnails . ' == 1){
1818
          jQuery(\'.media_gallery\').show(20);
1819
      } else {
1820
          jQuery(\'.media_gallery\').hide(20);
1821
      }
1822

    
1823
      // add change handler
1824
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1825
      function(event){
1826
        var state = 0;
1827
        if(jQuery(this).is(\':checked\')){
1828
          jQuery(\'.media_gallery\').show(20);
1829
          state = 1;
1830
        } else {
1831
          jQuery(\'.media_gallery\').hide(20);
1832
        }
1833
        // store state in session variable
1834
        var uri = \'' . $setSessionUri . '\' + state;
1835
        jQuery.get(uri);
1836
      });
1837
  });',
1838
  array('type' => "inline", 'scope' => JS_DEFAULT));
1839

    
1840
  drupal_set_title(t('Search results'), PASS_THROUGH);
1841

    
1842
  return theme('cdm_search_results', array(
1843
    'pager' => $taxonPager,
1844
    'path' => 'cdm_dataportal/search/results/taxon',
1845
    ));
1846
}
1847

    
1848
/**
1849
 * Provides the standart image wich indicated a loading process
1850
 *
1851
 * @return string
1852
 *  The img html tag
1853
 */
1854
function loading_image_html() {
1855
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1856
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1857
}
1858

    
1859
/**
1860
 * Returns the state of the the showThumbnails flag set in the
1861
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1862
 *
1863
 * @return boolean
1864
 *    returns 1 if the flag is set
1865
 */
1866
function do_showThumbnails() {
1867
  static $showThumbnails = null;
1868

    
1869
  if($showThumbnails == null) {
1870
    $showThumbnails = 0;
1871
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1872
      $showThumbnails = 0;
1873
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1874
      $showThumbnails = is_array($search_gallery_settings)
1875
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1876
        && (
1877
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1878
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1879
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1880
            )
1881
         ? 1 : 0;
1882

    
1883
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1884
    }
1885
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1886
    if (!is_numeric($showThumbnails)) {
1887
      $showThumbnails = 1;
1888
    }
1889
  }
1890

    
1891
  return $showThumbnails;
1892
}
1893

    
1894

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

    
1920
  $tab = get_default_taxon_tab();
1921
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1922

    
1923
  if (!$uuid) {
1924
    return FALSE;
1925
  }
1926

    
1927
  if ($page_tab) {
1928
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1929
  }
1930
  elseif (!$tab || strtolower($tab) == 'general') {
1931
    return 'cdm_dataportal/taxon/' . $uuid;
1932
  }
1933
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1934
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1935
  }
1936
  else {
1937
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1938
  }
1939
}
1940

    
1941
function path_to_specimen($uuid) {
1942

    
1943
    if (!$uuid) {
1944
        return FALSE;
1945
    }
1946
    else {
1947
        return 'cdm_dataportal/specimen/' . $uuid;
1948
    }
1949
}
1950

    
1951
function path_to_named_area($uuid) {
1952

    
1953
  if (!$uuid) {
1954
    return FALSE;
1955
  }
1956
  else {
1957
    return 'cdm_dataportal/named_area/' . $uuid;
1958
  }
1959
}
1960

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

    
1990
}
1991

    
1992
/**
1993
 * Compses the drupal path to the key identified by the uuid.
1994
 *
1995
 * @param string $keyType
1996
 *    the key typer corresponds to the specific class of the CDM
1997
 *    IdentificationKey. Possible values are
1998
 *      -PolytomousKey
1999
 *      -MultimediaKey
2000
 *      - ...
2001
 * @param UUID $keyUuid
2002
 *   The UUID of the key
2003
 */
2004
function path_to_key($keyType, $keyUuid) {
2005
  if (!$keyUuid || !$keyType) {
2006
    return FALSE;
2007
  }
2008
  $keyType{0} = strtolower($keyType{0});
2009
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2010
}
2011

    
2012
/**
2013
 * @todo Please document this function.
2014
 * @see http://drupal.org/node/1354
2015
 */
2016
function path_to_reference($uuid) {
2017
  if (!$uuid) {
2018
    return FALSE;
2019
  }
2020
  return 'cdm_dataportal/reference/' . $uuid;
2021
}
2022

    
2023
/**
2024
 * Creates the path to a cdm_dataportal taxon name page.
2025
 *
2026
 * @param UUID $taxon_name_uuid
2027
 *   The uuid of the CDM TaxonNameBase to show a name page for
2028
 * @param UUID $taxon_to_hide_uuid
2029
 *   A taxon which should not be displayed in the taxon list
2030
 * @param UUID $highlite_synonym_uuid
2031
 *   Optinal parameter wich takes another taxon uuid, if given the
2032
 *   target taxon pages will show the syonymy tab where the taxon
2033
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
2034
 *   in case it is found on this page.
2035
 *
2036
 * @return a URI path element as string
2037
 */
2038
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2039
  $res = FALSE;
2040
  if ($name_uuid) {
2041
    $res = 'cdm_dataportal/name/' . $name_uuid;
2042
  }
2043
  if($taxon_to_hide_uuid){
2044
    $res .= '/' . $taxon_to_hide_uuid;
2045
    if($synonym_uuid){
2046
      $res .= '/' . $synonym_uuid;
2047
    }
2048
  }
2049
  return $res;
2050
}
2051

    
2052
/**
2053
 * @todo Please document this function.
2054
 * @see http://drupal.org/node/1354
2055
 */
2056
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2057
  if (!$uuid) {
2058
    return FALSE;
2059
  }
2060
  $out = 'cdm_dataportal/media/' . $uuid;
2061
  if ($representaion_uuid) {
2062
    $out .= '/' . $representaion_uuid;
2063
    if (is_numeric($partId)) {
2064
      $out .= '/' . $partId;
2065
    }
2066
  }
2067
  return $out;
2068
}
2069

    
2070
/**
2071
 * Compares thisRank with thatRank.
2072
 *
2073
 * Returns a negative integer, zero, or a positive integer
2074
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2075
 * e.g:
2076
 * <ul>
2077
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2078
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2079
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2080
 * </ul>
2081
 * <p>
2082
 * This compare logic of the underlying webservice is the
2083
 * <b>inverse logic</b> of the the one implemented in
2084
 * java.lang.Comparable#compareTo(java.lang.Object)
2085
 *
2086
 * @param $thisRankUuid
2087
 * @param $thatRankUuid
2088
 *
2089
 * @return int
2090
 *   A negative integer, zero, or a positive integer
2091
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2092
 */
2093
function rank_compare($thisRankUuid, $thatRankUuid) {
2094
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2095
  return $result->Integer;
2096
}
2097

    
2098
/**
2099
 * Composes an HTML element class attribute value composed of
2100
 * the short-name of the cdm class and the uuid of the entity.
2101
 * This class attribute should be used wherever an cdm-entity is rendered.
2102
 *
2103
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2104
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2105
 * Taxon uuid is added also as taxon_uuid:<uuid>
2106
 *
2107
 * These according class selectors in css must be escaped, eg:
2108
 *    .cdm\:TextData
2109
 *
2110
 * @param $cdmEntity
2111
 *    A CDM entity or TaxonNodeDTO
2112
 */
2113
function html_class_attribute_ref($cdmEntity) {
2114

    
2115
  $attributes = '';
2116
  if (is_cdm_entity($cdmEntity)) {
2117
    $attributes =  "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2118
  }
2119
  if($cdmEntity->class == 'TaxonNodeDto'){
2120
    $attributes .= " taxon_uuid:"  . $cdmEntity->taxonUuid . " sec_uuid:"  . $cdmEntity->secUuid;;
2121
  }
2122
  if($cdmEntity->class == 'Taxon' && isset($cdmEntity->sec->uuid)){
2123
    $attributes .= " sec_uuid:"  . $cdmEntity->sec->uuid;
2124
  }
2125
  return $attributes;
2126
}
2127

    
2128

    
2129
/**
2130
 * Creates a short version of a taxonname.
2131
 *
2132
 * The short name is created by using the taggedTitle field of
2133
 * TaxonNodeDTO instances.
2134
 * If the taggedTitle if empty the fullname will be returned.
2135
 *
2136
 * @param object $taxonNodeDTO
2137
 *   A TaxonNodeDTO object
2138
 *
2139
 * @return string
2140
 */
2141
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2142

    
2143
  $nameStr = '';
2144

    
2145
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2146

    
2147
  // Get all tagged text tokens of the scientific name.
2148
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2149
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2150
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2151
    }
2152
  }
2153
  $nameStr = trim($nameStr);
2154

    
2155
  if ($nameStr) {
2156

    
2157
    // Do not return short names for these.
2158
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2159
      return $nameStr;
2160
    }
2161

    
2162
    /*
2163
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2164
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2165
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2166
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2167
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2168
    */
2169
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2170
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2171
      return $matches[1][0] . "." . $matches[3][0];
2172
    }
2173
    else {
2174
      return $nameStr;
2175
    }
2176
  }
2177
  else {
2178
    return $taxonNodeDTO->titleCache;
2179
  }
2180
}
2181

    
2182
/**
2183
 * Check if a taxon is accepted by the current taxonomic tree.
2184
 *
2185
 * @param mixed $taxon
2186
 *   The Taxon obkect to check.
2187
 *
2188
 * @return bool
2189
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2190
 */
2191
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2192

    
2193
  $defaultTreeUuid = get_current_classification_uuid();
2194

    
2195
  if (isset($taxon->taxonNodes)) {
2196
    $taxonNodes = $taxon->taxonNodes;
2197
  }
2198
  else {
2199
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2200
  }
2201

    
2202
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2203
    foreach ($taxonNodes as $node) {
2204
      if (isset($node->classification)){
2205
        if(is_object($node->classification)) {
2206
          if ($node->classification->uuid == $defaultTreeUuid) {
2207
            return TRUE;
2208
          }
2209
        }
2210
        else {
2211
          if ($node->classification == $defaultTreeUuid) {
2212
            return TRUE;
2213
          }
2214
        }
2215
      }
2216
    }
2217
  }
2218

    
2219
  return FALSE;
2220
}
2221

    
2222
/**
2223
 * Checks is the source has one of the given types.
2224
 *
2225
 * @param object $source
2226
 *   The original source entity
2227
 * @param array $types
2228
 *   An array of elementd of the OriginalSourceType enumeration
2229
 *   If not set the default will be used which is:
2230
 *    - Lineage
2231
 *    - PrimaryMediaSource
2232
 *    - PrimaryTaxonomicSource
2233
 *    - Unknown
2234
 *    - Other
2235
 * @return boolean
2236
 */
2237
  function _is_original_source_type($source, $types = null) {
2238
    // this is the default
2239
    // maybe this should also be put into the settings
2240
    static $default = array(
2241
      OriginalSourceType::Lineage,
2242
      OriginalSourceType::PrimaryMediaSource,
2243
      OriginalSourceType::PrimaryTaxonomicSource,
2244
      OriginalSourceType::Unknown,
2245
      OriginalSourceType::Other,
2246
    );
2247

    
2248
    if(!$types){
2249
      $types = $default;
2250
    }
2251
    return isset($source->type) && in_array($source->type, $types);
2252
  }
2253

    
2254
/**
2255
 * @todo Please document this function.
2256
 * @see http://drupal.org/node/1354
2257
 */
2258
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2259
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2260
}
2261

    
2262

    
2263
/**
2264
 * Collects all the media from a list of description elements.
2265
 *
2266
 * @param array $descriptionElements
2267
 *   The description elements from which to collect the media.
2268
 *
2269
 * @return array
2270
 *   The output with all the collected media.
2271
 */
2272
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2273

    
2274
  $outArrayOfMedia = array();
2275

    
2276
  // Avoiding a warning box in Drupal for Flora Malesiana.
2277
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2278
    foreach ($descriptionElements as $descriptionElement) {
2279
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2280
        foreach ($descriptionElement->media as $media) {
2281
          if (is_object($media)) {
2282
            $outArrayOfMedia[] = $media;
2283
          }
2284
        }
2285
      }
2286
    }
2287
  }
2288
  return $outArrayOfMedia;
2289
}
2290

    
2291
/**
2292
 * @todo Please document this function.
2293
 * @see http://drupal.org/node/1354
2294
 *
2295
 * @param array $cdm_entities
2296
 *   An array of CdmBase instances or a single instance.
2297
 * @param string $footnote_list_key_suggestion
2298
 *
2299
 * @return unknown
2300
 */
2301
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2302

    
2303
   static $annotations_types_filter = null;
2304
   if(!$annotations_types_filter) {
2305
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2306
   }
2307

    
2308
  $footNoteKeys = array();
2309

    
2310
  // Is argument cdmBase an array?
2311
  if (!is_array($cdm_entities)) {
2312
    $cdmBase_array = array();
2313
    $cdmBase_array[] = $cdm_entities;
2314
  }
2315
  else {
2316
    $cdmBase_array = $cdm_entities;
2317
  }
2318

    
2319
  // Getting the key for the footnotemanager.
2320
  if (isset($footnote_list_key_suggestion)) {
2321
    $footnote_list_key = $footnote_list_key_suggestion;
2322
  }
2323
  else {
2324
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2325
  }
2326

    
2327
  // Adding the footnotes keys.
2328
  foreach ($cdmBase_array as $cdmBase_element) {
2329
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2330
    if (is_array($annotations)) {
2331
      foreach ($annotations as $annotation) {
2332
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2333
      }
2334
    }
2335
  }
2336

    
2337
  return $footNoteKeys;
2338
}
2339

    
2340

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

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

    
2384
  if(!array_key_exists('class', $attributes)) {
2385
    $attributes['class'] = array();
2386
  }
2387
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2388
  $dynabox_attributes = drupal_attributes($attributes);
2389

    
2390

    
2391
  _add_js_domEvent(); // requires domEvent.js
2392
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2393
  drupal_add_js("
2394
  jQuery(document).ready(
2395
      function() {
2396
        dynabox('". $dynabox_id ."',
2397
          {
2398
            open_callback: " . $open_callback .",
2399
            close_callback: " . $close_callback .
2400
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2401
          }
2402
        );
2403
      }
2404
   );",
2405
   array(
2406
    'type'=>'inline',
2407
    'scope'=>'footer'
2408
    )
2409
  );
2410

    
2411

    
2412
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2413
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2414
  $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>';
2415
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2416
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2417
  $out .= '    </' . $enclosingtags[1] . '>';
2418
  $out .= '  </' . $enclosingtags[0] . '>';
2419
  $out .= '<!-- dynabox end -->';
2420
  return $out;
2421
}
2422

    
2423
/**
2424
 * Checks whether a feature has any description elements.
2425
 *
2426
 * @param mixed $featureNode
2427
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2428
 *
2429
 * @see _mergeFeatureTreeDescriptions()
2430
 *
2431
 * @return bool
2432
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2433
 *   contains at least one non empty TextData or at least one DescriptionElement
2434
 *   of an other type. A TextData element holding a multilanguageText or a
2435
 *   source reference is considered to be not empty.
2436
 *
2437
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2438
 *       see $block_content_is_not_empty in make_feature_block_list() and
2439
 *       $feature_block_has_content in compose_feature_block_items_generic
2440
 */
2441
function has_feature_node_description_elements($featureNode) {
2442

    
2443
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2444
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2445
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2446
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2447
          && $descriptionElement->multilanguageText_L10n->text != ''
2448
          || isset($descriptionElement->sources[0])
2449
          || isset($descriptionElement->media[0]) ) {
2450
          return TRUE;
2451
        }
2452
      }
2453
    }
2454
  }
2455
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2456
    foreach ($featureNode->childNodes as $child) {
2457
      if (has_feature_node_description_elements($child)) {
2458
        return TRUE;
2459
      }
2460
    }
2461
  }
2462
  return FALSE;
2463
}
2464

    
2465
/**
2466
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2467
 *
2468
 * @param $chapter
2469
 *   The taxon page chapter or part
2470
 */
2471
function cdm_check_valid_taxon_page($chapter){
2472
  static $taxon_tabs = null;
2473

    
2474
  cdm_check_valid_portal_page();
2475

    
2476
  if($taxon_tabs == null){
2477
    $taxon_tabs = array('all', 'description');
2478
    foreach(get_taxon_tabs_list() as $tab){
2479
      $taxon_tabs[] = strtolower($tab);
2480
    }
2481
  }
2482

    
2483
  if(!in_array($chapter, $taxon_tabs)){
2484
    // oops this is not a valid chapter name
2485
    http_response_code(404); // 404 = Not Found
2486
  }
2487

    
2488
}
2489

    
2490
/**
2491
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2492
 *
2493
 * @param $chapter
2494
 *   The taxon page chapter or part
2495
 */
2496
function cdm_check_valid_portal_page(){
2497
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2498
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2499
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2500
    http_response_code(404); // 404 = Not Found
2501
    exit('HTTP 404');
2502
  }
2503
}
2504

    
2505
/**
2506
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2507
 *
2508
 * @param $text_a
2509
 * @param $text_b
2510
 * @return string
2511
 */
2512
function diff_viewer($text_a, $text_b) {
2513

    
2514
  static $diff_viewer_count = 0;
2515

    
2516
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2517

    
2518
  // http://code.stephenmorley.org/php/diff-implementation/
2519
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2520
  drupal_add_css(drupal_get_path('module',
2521
      'cdm_dataportal') . '/css/diff.css');
2522
  _add_jquery_ui();
2523
  drupal_add_js(
2524
    'jQuery(document).ready( function(){
2525
        jQuery(\'#' . $element_id . '\').accordion({
2526
        collapsible: true,
2527
        active: false,
2528
        fillSpace: true,
2529
        }).children(\'div\').css({ \'height\': \'auto\' });
2530
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2531
     });'
2532
    , array(
2533
    'type' => 'inline',
2534
    'scope' => 'footer'
2535
  ));
2536

    
2537
  $diff = Diff::compare($text_a,
2538
    $text_b);
2539
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2540
    . Diff::toTable($diff, '', '')
2541
    . '</div></div>';
2542
  return $diff_viewer_markup;
2543
}
2544

    
2545

    
(10-10/18)