Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

    
266
  /**
267
   * @todo Please document this function.
268
   * @see http://drupal.org/node/1354
269
   */
270
  function _add_js_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
  $items['cdm_dataportal/search/registration'] = array(
500
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
501
    'access arguments' => array('access cdm content'),
502
    'type' => MENU_CALLBACK,
503
  );
504

    
505
  /*
506
   $items['cdm/xml2json'] = array(
507
   'page callback' => 'cdm_view_xml2json',
508
   'access arguments' => array('access cdm content'),
509
   'type' => MENU_CALLBACK,
510
   );
511
   */
512

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

    
525
  // 'May not cache' in D5.
526
  $items['cdm_dataportal/name/%'] = array(
527
    // 'page callback' => 'cdm_dataportal_view_name',
528
    'page callback' => 'cdm_dataportal_name_page_view',
529
    'page arguments' => array(2, 3, 4),
530
    'access arguments' => array('access cdm content'),
531
    'type' => MENU_CALLBACK,
532
  );
533

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

    
547
    $items['cdm_dataportal/taxon/%/all'] = array(
548
      'title' => cdm_taxonpage_tab_label('General'),
549
      'page callback' => 'cdm_dataportal_taxon_page_view',
550
      'access arguments' => array('access cdm content'),
551
      'type' => MENU_CALLBACK,
552
      'weight' => 2,
553
      'page arguments' => array(2, "all")
554
      , // Expected callback arguments: taxon_uuid.
555
    );
556

    
557
    $items['cdm_dataportal/taxon/%/description'] = array(
558
      'title' => cdm_taxonpage_tab_label('General'),
559
      'page callback' => 'cdm_dataportal_taxon_page_view',
560
      'access arguments' => array('access cdm content'),
561
      'type' => MENU_DEFAULT_LOCAL_TASK,
562
      'weight' => 2,
563
      'page arguments' => array(2, "description")
564
      , // Expected callback arguments: taxon_uuid.
565
    );
566

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

    
586
    $items['cdm_dataportal/taxon/%/specimens'] = array( // Specimens
587
      'title' => cdm_taxonpage_tab_label('Specimens'),
588
      'page callback' => 'cdm_dataportal_taxon_page_view',
589
      'access arguments' => array('access cdm content'),
590
      'type' => MENU_LOCAL_TASK,
591
      'weight' => 6,
592
      'page arguments' => array(2, "specimens")
593
      , // Expected callback arguments: taxon_uuid.
594
    );
595

    
596
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
597
      'title' => cdm_taxonpage_tab_label('Keys'),
598
      'page callback' => 'cdm_dataportal_taxon_page_view',
599
      'access arguments' => array('access cdm content'),
600
      'type' => MENU_LOCAL_TASK,
601
      'weight' => 6,
602
      'page arguments' => array(2, "keys")
603
      , // Expected callback arguments: taxon_uuid.
604
    );
605

    
606
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
607
      'title' => cdm_taxonpage_tab_label('Experts'),
608
        'page callback' => 'cdm_dataportal_taxon_page_view',
609
        'access arguments' => array('access cdm content'),
610
        'type' => MENU_LOCAL_TASK,
611
        'weight' => 6,
612
        'page arguments' => array(2, "experts")
613
    , // Expected callback arguments: taxon_uuid.
614
    );
615

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

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

    
636
  return $items;
637
}
638

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

    
654
  if(variable_get('cdm_debug_mode', FALSE)){
655
    $file = 'temporary://drupal_debug.txt';
656
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
657
  }
658

    
659
  $bibliography_settings = get_bibliography_settings();
660
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
661
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
662
}
663

    
664
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
665

    
666
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
667

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

    
677
  $parameters['cacheL2_refresh'] ='1';
678

    
679

    
680
  drupal_goto($base_path, array('query' => $parameters));
681
}
682

    
683
/**
684
 * Implements hook_requirements($phase)
685
 */
686
function cdm_dataportal_requirements($phase) {
687
    $requirements = array();
688
    if($phase == 'runtime'){
689

    
690
    }
691
    return $requirements;
692
}
693

    
694

    
695
/**
696
 * The function generate form for own user cdm dataportal configurations.
697
 */
698
function cdm_dataportal_user_form($form, &$form_state) {
699

    
700
  global $user;
701
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
702

    
703
  $form['taxon_page_tabs'] = array(
704
      '#type' => 'fieldset',
705
      '#tree' => true,
706
      '#title' => t('Taxon page tabs'),
707
  );
708

    
709
  $form['taxon_page_tabs']['user_defined'] = array(
710
    '#type' => 'checkbox',
711
    '#title' => t('Activate user default configuration'),
712
    '#default_value' => variable_get($checkbox_value, 0),
713
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
714
  );
715

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

    
726

    
727
  if(false){
728
    $form['developer_options'] = array(
729
        '#type' => 'fieldset',
730
        '#tree' => true,
731
        '#title' => t('Developer options'),
732
    );
733

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

    
747
  $form['submit'] = array(
748
    '#type' => 'submit',
749
    '#value' => t('Submit'),
750
  );
751

    
752
  return $form;
753
}
754

    
755
/**
756
 * Form submission handler for user_form().
757
 *
758
 * Submits the user cdm dataportal configurations.
759
 */
760
function cdm_dataportal_user_form_submit($form, &$form_state) {
761
  global $user;
762
  $msg_type = 'status';
763
  $username = $user->name;
764
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
765

    
766
  // FIXME: this is completely wrong, see user_profile_form_submit()
767

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

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

    
787
  }
788
  else {
789
    // Problem with the user id => variables wont be saved.
790
    $msg_type = 'warning';
791
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
792
  }
793
}
794

    
795
/**
796
 * Implements hook_block_info().
797
 */
798
function cdm_dataportal_block_info() {
799

    
800
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
801
    // $block[1]["info"] = t("CDM DataPortal Credits");
802
    $block["2"] = array(
803
        "info" => t("CDM - Search Taxa"),
804
        "cache" => DRUPAL_NO_CACHE
805
      );
806
    // $block[3]["info"] = t("CDM Filters");
807
    $block["4"]["info"] = t("CDM  - Dataportal Print");
808
    $block["keys"]["info"] = t("CDM - Identification keys");
809
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
810
    $block["classification_breadcrumbs"] =  array(
811
        'info' => t('CDM - Classification breadcrumbs'),
812
        'cache' => DRUPAL_CACHE_PER_PAGE
813
      );
814
    $block["taxonomic_children"] =  array(
815
      'info' => t('CDM - Taxonomic children'),
816
      'cache' => DRUPAL_CACHE_PER_PAGE
817
    );
818
    $block["back_to_search_results"] =  array(
819
      'title' => '<none>',
820
      'info' => t('CDM - Back to search Results'),
821
      'cache' => DRUPAL_CACHE_PER_PAGE,
822
      'visibility' => BLOCK_VISIBILITY_LISTED,
823
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
824
    );
825
  $block['registrations_search_filter'] =  array(
826
    'title' => '<none>',
827
    'info' => t('CDM - Registrations search filter'),
828
    'cache' => DRUPAL_CACHE_PER_PAGE,
829
    'visibility' => BLOCK_VISIBILITY_LISTED,
830
    'pages' => "cdm_dataportal/search/registration\ncdm_dataportal/search/registration/*", // multiple page paths separated by "\n"!!!
831
  );
832

    
833
    return $block;
834
}
835

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

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

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

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

    
919
  return $taxon_uuid;
920
}
921

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

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

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

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

    
963
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
964
  return $form;
965
}
966

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

    
975
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
976
  $form['#action'] = $url;
977

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

    
984
  $destination_array = drupal_get_destination();
985
  $destination = $destination_array['destination'];
986

    
987
  $form['destination'] = array(
988
    '#weight' => -3,
989
    '#type' => 'hidden',
990
    '#value' =>  $destination,
991
  );
992

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

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

    
1013
  return $form;
1014

    
1015
}
1016

    
1017
/**
1018
 *
1019
 * @ingroup compose
1020
 */
1021
function compose_classification_selector() {
1022

    
1023
  $destination_array = drupal_get_destination();
1024
  $destination = $destination_array['destination'];
1025

    
1026
  $options = cdm_get_taxontrees_as_options();
1027
  $items = array();
1028
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1029

    
1030
  $current_classification_uuid = get_current_classification_uuid();
1031

    
1032

    
1033
  foreach($options as $uuid=>$label){
1034
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1035

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

    
1056
  $render_array = array(
1057
    '#theme' => 'item_list',
1058
    '#type' => 'ul',
1059
    '#items' => $items
1060
  );
1061

    
1062
  return $render_array;
1063
}
1064

    
1065

    
1066
/* UNREACHABLE since action of form directly links to view.
1067
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1068

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

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

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

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

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

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

    
1135
  cdm_check_valid_portal_page();
1136

    
1137
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1138
  return theme('cdm_reference_page', array('reference' => $reference));
1139
}
1140

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

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

    
1157
  cdm_check_valid_portal_page();
1158

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

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

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

    
1195
  static $media = NULL;
1196

    
1197
  if(!isset($media)) {
1198
    $media = array();
1199
  }
1200
  if (!isset($media[$taxon->uuid])) {
1201

    
1202
    // --- GET Images --- //
1203
    $mediaQueryParameters = array(
1204
        "type" => "ImageFile",
1205
    );
1206

    
1207
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1208
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1209
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1210

    
1211
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1212
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1213
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1214
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1215

    
1216
    $ws_endpoint = NULL;
1217
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1218
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1219
    } else {
1220
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1221
    }
1222

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

    
1231
  return $media[$taxon->uuid];
1232
}
1233

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

    
1244
  static $occurences = NULL;
1245

    
1246
  if(!isset($occurences)) {
1247
    $occurences = array();
1248
  }
1249

    
1250
  if (!isset($occurences[$taxon->uuid])){
1251

    
1252
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1253
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1254
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1255

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

    
1263
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1264
        null,
1265
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1266
    );
1267

    
1268

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

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

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

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

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

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

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

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

    
1434
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1435

    
1436
  if (!$polytomousKeyNode) {
1437
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1438
    return;
1439
  }
1440

    
1441
  // Load children.
1442
  foreach ($polytomousKeyNode->children as &$childNode) {
1443
    _load_polytomousKeySubGraph($childNode);
1444
  }
1445

    
1446
  // Load subkey.
1447
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1448

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

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

    
1461
  cdm_check_valid_portal_page();
1462

    
1463
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1464

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

    
1471
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1472
  if (is_array($annotationPager->records)) {
1473
    $polytomousKey->annotations = $annotationPager->records;
1474
  }
1475

    
1476
  _load_polytomousKeySubGraph($polytomousKey->root);
1477
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1478
}
1479

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

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

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

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

    
1550
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1551
    'taxon' => $taxon
1552
  ));
1553

    
1554
  // Check if the taxon id contained in the currently selected tree.
1555
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1556

    
1557
  if (!$taxon_in_current_classification) {
1558
    $classifications = get_classifications_for_taxon($taxon);
1559
    RenderHints::pushToRenderStack('not_in_current_classification');
1560
    $taxon_name_markup = render_taxon_or_name($taxon);
1561

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

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

    
1587
  // Render the taxon page.
1588
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1589
  $taxonpage->content = drupal_render($render_array);
1590

    
1591
  return $taxonpage;
1592
}
1593

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

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

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

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

    
1637
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1638
        'specimen' => $specimen
1639
    ));
1640

    
1641
    // Render the specimen page.
1642
    $render_array = compose_cdm_specimen_page($uuid);
1643
    $specimenpage->content = drupal_render($render_array);
1644

    
1645
    return $specimenpage;
1646
}
1647

    
1648
/**
1649
 *
1650
 * Creates a named area view.
1651
 * @param string $uuid the UUID of the specimen
1652
 *  * @return object
1653
 *   An object with two fields:
1654
 *     - title: the page title
1655
 *     - content: the page content
1656
 */
1657

    
1658
function cdm_dataportal_named_area_view($uuid) {
1659
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1660
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1661
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1662
    return FALSE;
1663
  }
1664
  $named_area_page = new stdClass();
1665

    
1666
  $named_area_page->title = $named_area->representation_L10n;
1667

    
1668
  // Render the specimen page.
1669
  $render_array = compose_cdm_named_area_page($uuid);
1670
  $named_area_page->content = drupal_render($render_array);
1671

    
1672
  return $named_area_page;
1673
}
1674

    
1675
function cdm_dataportal_named_area_page_view($uuid) {
1676

    
1677
  cdm_check_valid_portal_page();
1678

    
1679
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1680
  if (!empty($named_area_page)) {
1681
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1682
  }
1683
  else {
1684
    return '';
1685
  }
1686

    
1687

    
1688
}
1689

    
1690
/**
1691
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1692
 *
1693
 * The node page shows the taxon name title and the list of taxon related
1694
 * with such taxon. Name on the tree already in use.
1695
 *
1696
 * @param UUID $taxon_name_uuid
1697
 *   The uuid of the CDM TaxonName to show a name page for
1698
 * @param UUID $taxon_to_hide_uuid
1699
 *   A taxon which should not be displayed in the taxon list
1700
 * @param UUID $highlite_synonym_uuid
1701
 *   Optinal parameter wich takes another taxon uuid, if given the
1702
 *   target taxon pages will show the syonymy tab where the taxon
1703
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1704
 *   in case it is found on this page.
1705
 *
1706
 * @return mixed
1707
 *   The formatted name page as node.
1708
 */
1709
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1710

    
1711
  cdm_check_valid_portal_page();
1712

    
1713
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1714
  if (!empty($taxonname_page)) {
1715
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1716
  }
1717
  else {
1718
    return '';
1719
  }
1720
}
1721

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

    
1770
  // Removing the name where we came from.
1771
  foreach ($taxon_pager->records as $k => &$taxon) {
1772
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1773
      unset($taxon_pager->records[$k]);
1774
    }
1775
  }
1776
  // Show the taxa list or go to the singular taxon.
1777
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1778
    $singleTaxon = array_pop($taxon_pager->records);
1779
    if ($singleTaxon->class != "Taxon") {
1780
      // It is a Synonym -> look for the accepted.
1781
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1782
      if (!empty($highlite_synonym_uuid)) {
1783
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1784
      }
1785
      else {
1786
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1787
      }
1788
    }
1789
    else {
1790
      // It is an accepted taxon.
1791
      if (!empty($highlite_synonym_uuid)) {
1792
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1793
      }
1794
      else {
1795
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1796
      }
1797
    }
1798
  }
1799
  else {// More than one taxa case.
1800
    $taxon_name_page = new stdClass();
1801
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1802
    if ($taxon_pager->records) {
1803
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1804
    }
1805
    else {
1806
      $taxon_name_page->content = 'This name is not assigned to a taxon.';
1807
    }
1808
    return $taxon_name_page;
1809
  }
1810
}
1811

    
1812
/**
1813
 * Creates a page with the advance search form.
1814
 *
1815
 * NOTE: The advance search form allows searching for taxa.
1816
 */
1817
function cdm_dataportal_view_search_advanced() {
1818
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1819
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1820
}
1821

    
1822
/**
1823
 * Creates a page with the search form for searching by taxon descriptions.
1824
 */
1825
function cdm_dataportal_view_search_taxon_by_description() {
1826
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1827
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1828
}
1829

    
1830
/**
1831
 * Executes the search and generates the result list of taxa.
1832
 */
1833
function cdm_dataportal_view_search_results_taxon() {
1834

    
1835
  $taxonPager = cdm_dataportal_search_taxon_execute();
1836

    
1837
  $showThumbnails = do_showThumbnails();
1838

    
1839
  $setSessionUri = url('cdm_api/setvalue/session', array(
1840
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1841
  ));
1842

    
1843
  drupal_add_js('jQuery(document).ready(function() {
1844

    
1845
      // init
1846
      if(' . $showThumbnails . ' == 1){
1847
          jQuery(\'.media_gallery\').show(20);
1848
      } else {
1849
          jQuery(\'.media_gallery\').hide(20);
1850
      }
1851

    
1852
      // add change handler
1853
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1854
      function(event){
1855
        var state = 0;
1856
        if(jQuery(this).is(\':checked\')){
1857
          jQuery(\'.media_gallery\').show(20);
1858
          state = 1;
1859
        } else {
1860
          jQuery(\'.media_gallery\').hide(20);
1861
        }
1862
        // store state in session variable
1863
        var uri = \'' . $setSessionUri . '\' + state;
1864
        jQuery.get(uri);
1865
      });
1866
  });',
1867
  array('type' => "inline", 'scope' => JS_DEFAULT));
1868

    
1869
  drupal_set_title(t('Search results'), PASS_THROUGH);
1870

    
1871
  return theme('cdm_search_results', array(
1872
    'pager' => $taxonPager,
1873
    'path' => 'cdm_dataportal/search/results/taxon',
1874
    ));
1875
}
1876

    
1877
/**
1878
 * Executes the search for registrations and generates the result list..
1879
 */
1880
function cdm_dataportal_view_search_registrations_results() {
1881

    
1882
  $block = block_load('cdm_dataportal', 'registrations_search_filter');
1883
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
1884

    
1885
  $registration_pager = cdm_dataportal_search_registrations_execute();
1886

    
1887
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
1888

    
1889
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
1890

    
1891
  $render_array = array_merge($render_array, $registrations_pager_array);
1892

    
1893
  return $render_array;
1894
}
1895

    
1896

    
1897
/**
1898
 * Provides the standart image wich indicated a loading process
1899
 *
1900
 * @return string
1901
 *  The img html tag
1902
 */
1903
function loading_image_html() {
1904
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1905
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1906
}
1907

    
1908
/**
1909
 * Returns the state of the the showThumbnails flag set in the
1910
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1911
 *
1912
 * @return boolean
1913
 *    returns 1 if the flag is set
1914
 */
1915
function do_showThumbnails() {
1916
  static $showThumbnails = null;
1917

    
1918
  if($showThumbnails == null) {
1919
    $showThumbnails = 0;
1920
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1921
      $showThumbnails = 0;
1922
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1923
      $showThumbnails = is_array($search_gallery_settings)
1924
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1925
        && (
1926
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1927
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1928
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1929
            )
1930
         ? 1 : 0;
1931

    
1932
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1933
    }
1934
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1935
    if (!is_numeric($showThumbnails)) {
1936
      $showThumbnails = 1;
1937
    }
1938
  }
1939

    
1940
  return $showThumbnails;
1941
}
1942

    
1943

    
1944

    
1945
/* ====================== other functions ====================== */
1946
/**
1947
 * Creates a URL to the taxon page specified by the $uuid parameter.
1948
 *
1949
 * The URL will be prepended with a path element to a specific taxon page tab.
1950
 *
1951
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1952
 * be set globally in the administrative settings or individually in the user
1953
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1954
 * the last portal will stay on this last tab.
1955
 *
1956
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1957
 * internal mechanism by a specific value.
1958
 *
1959
 * @param string $uuid
1960
 *   The UUID of the taxon.
1961
 * @param string $page_tab
1962
 *   Overwriting the preset mechanism by defining specific value for the
1963
 *   taxon page tab.
1964
 *
1965
 * @return string
1966
 *   The created URL.
1967
 */
1968
function path_to_taxon($uuid, $page_tab = FALSE) {
1969

    
1970
  $tab = get_default_taxon_tab();
1971
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1972

    
1973
  if (!$uuid) {
1974
    return FALSE;
1975
  }
1976

    
1977
  if ($page_tab) {
1978
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1979
  }
1980
  elseif (!$tab || strtolower($tab) == 'general') {
1981
    return 'cdm_dataportal/taxon/' . $uuid;
1982
  }
1983
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1984
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1985
  }
1986
  else {
1987
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1988
  }
1989
}
1990

    
1991
function path_to_specimen($uuid) {
1992

    
1993
    if (!$uuid) {
1994
        return FALSE;
1995
    }
1996
    else {
1997
        return 'cdm_dataportal/specimen/' . $uuid;
1998
    }
1999
}
2000

    
2001
function path_to_named_area($uuid) {
2002

    
2003
  if (!$uuid) {
2004
    return FALSE;
2005
  }
2006
  else {
2007
    return 'cdm_dataportal/named_area/' . $uuid;
2008
  }
2009
}
2010

    
2011
/**
2012
 * Creates a URL to show a synonmy in the according taxon page.
2013
 *
2014
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2015
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2016
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2017
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2018
 * in the page
2019
 *
2020
 * @param string $synonymUuid
2021
 *    The uuid of the synonym
2022
 * @param string $acceptedUuid
2023
 *    The uuid of the according accepted taxon
2024
 * @return string
2025
 *    The URL to show a synonmy in the according taxon page
2026
 */
2027
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2028
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2029
  return url($acceptedPath, array(
2030
      'query' => array(
2031
        // highlite the synony in the synonymy
2032
        'highlite' => $synonymUuid,
2033
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2034
        // see theme_taxon_page_title()
2035
        'acceptedFor' => $synonymUuid
2036
      ),
2037
      'fragment' => $synonymUuid
2038
  ));
2039

    
2040
}
2041

    
2042
/**
2043
 * Compses the drupal path to the key identified by the uuid.
2044
 *
2045
 * @param string $keyType
2046
 *    the key typer corresponds to the specific class of the CDM
2047
 *    IdentificationKey. Possible values are
2048
 *      -PolytomousKey
2049
 *      -MultimediaKey
2050
 *      - ...
2051
 * @param UUID $keyUuid
2052
 *   The UUID of the key
2053
 */
2054
function path_to_key($keyType, $keyUuid) {
2055
  if (!$keyUuid || !$keyType) {
2056
    return FALSE;
2057
  }
2058
  $keyType{0} = strtolower($keyType{0});
2059
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2060
}
2061

    
2062
/**
2063
 * @todo Please document this function.
2064
 * @see http://drupal.org/node/1354
2065
 */
2066
function path_to_reference($uuid) {
2067
  if (!$uuid) {
2068
    return FALSE;
2069
  }
2070
  return 'cdm_dataportal/reference/' . $uuid;
2071
}
2072

    
2073
/**
2074
 * Creates the path to a cdm_dataportal taxon name page.
2075
 *
2076
 * @param UUID $taxon_name_uuid
2077
 *   The uuid of the CDM TaxonName to show a name page for
2078
 * @param UUID $taxon_to_hide_uuid
2079
 *   A taxon which should not be displayed in the taxon list
2080
 * @param UUID $highlite_synonym_uuid
2081
 *   Optinal parameter wich takes another taxon uuid, if given the
2082
 *   target taxon pages will show the syonymy tab where the taxon
2083
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
2084
 *   in case it is found on this page.
2085
 *
2086
 * @return a URI path element as string
2087
 */
2088
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
2089
  $res = FALSE;
2090
  if ($name_uuid) {
2091
    $res = 'cdm_dataportal/name/' . $name_uuid;
2092
  }
2093
  if($taxon_to_hide_uuid){
2094
    $res .= '/' . $taxon_to_hide_uuid;
2095
    if($synonym_uuid){
2096
      $res .= '/' . $synonym_uuid;
2097
    }
2098
  }
2099
  return $res;
2100
}
2101

    
2102
/**
2103
 * @todo Please document this function.
2104
 * @see http://drupal.org/node/1354
2105
 */
2106
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2107
  if (!$uuid) {
2108
    return FALSE;
2109
  }
2110
  $out = 'cdm_dataportal/media/' . $uuid;
2111
  if ($representaion_uuid) {
2112
    $out .= '/' . $representaion_uuid;
2113
    if (is_numeric($partId)) {
2114
      $out .= '/' . $partId;
2115
    }
2116
  }
2117
  return $out;
2118
}
2119

    
2120
/**
2121
 * Compares thisRank with thatRank.
2122
 *
2123
 * Returns a negative integer, zero, or a positive integer
2124
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2125
 * e.g:
2126
 * <ul>
2127
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2128
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2129
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2130
 * </ul>
2131
 * <p>
2132
 * This compare logic of the underlying webservice is the
2133
 * <b>inverse logic</b> of the the one implemented in
2134
 * java.lang.Comparable#compareTo(java.lang.Object)
2135
 *
2136
 * @param $thisRankUuid
2137
 * @param $thatRankUuid
2138
 *
2139
 * @return int
2140
 *   A negative integer, zero, or a positive integer
2141
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2142
 */
2143
function rank_compare($thisRankUuid, $thatRankUuid) {
2144
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2145
  return $result->Integer;
2146
}
2147

    
2148
/**
2149
 * Composes an HTML element class attribute value composed of
2150
 * the short-name of the cdm class and the uuid of the entity.
2151
 * This class attribute should be used wherever an cdm-entity is rendered.
2152
 *
2153
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2154
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2155
 * Taxon uuid is added also as taxon_uuid:<uuid>
2156
 *
2157
 * These according class selectors in css must be escaped, eg:
2158
 *    .cdm\:TextData
2159
 *
2160
 * @param $cdm_entity
2161
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2162
 */
2163
function html_class_attribute_ref($cdm_entity) {
2164

    
2165
  $attributes = '';
2166
  if (is_cdm_entity($cdm_entity)) {
2167
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2168
  } else if($cdm_entity->class == 'TypedEntityReference') {
2169
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2170
  }
2171
  if($cdm_entity->class == 'TaxonNodeDto'){
2172
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2173
  }
2174
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2175
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2176
  }
2177
  return $attributes;
2178
}
2179

    
2180

    
2181
/**
2182
 * Creates a short version of a taxonname.
2183
 *
2184
 * The short name is created by using the taggedTitle field of
2185
 * TaxonNodeDTO instances.
2186
 * If the taggedTitle if empty the fullname will be returned.
2187
 *
2188
 * @param object $taxonNodeDTO
2189
 *   A TaxonNodeDTO object
2190
 *
2191
 * @return string
2192
 */
2193
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2194

    
2195
  $nameStr = '';
2196

    
2197
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2198

    
2199
  // Get all tagged text tokens of the scientific name.
2200
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2201
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2202
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2203
    }
2204
  }
2205
  $nameStr = trim($nameStr);
2206

    
2207
  if ($nameStr) {
2208

    
2209
    // Do not return short names for these.
2210
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2211
      return $nameStr;
2212
    }
2213

    
2214
    /*
2215
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2216
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2217
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2218
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2219
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2220
    */
2221
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2222
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2223
      return $matches[1][0] . "." . $matches[3][0];
2224
    }
2225
    else {
2226
      return $nameStr;
2227
    }
2228
  }
2229
  else {
2230
    return $taxonNodeDTO->titleCache;
2231
  }
2232
}
2233

    
2234
/**
2235
 * Check if a taxon is accepted by the current taxonomic tree.
2236
 *
2237
 * @param mixed $taxon
2238
 *   The Taxon obkect to check.
2239
 *
2240
 * @return bool
2241
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2242
 */
2243
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2244

    
2245
  $defaultTreeUuid = get_current_classification_uuid();
2246

    
2247
  if (isset($taxon->taxonNodes)) {
2248
    $taxonNodes = $taxon->taxonNodes;
2249
  }
2250
  else {
2251
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2252
  }
2253

    
2254
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2255
    foreach ($taxonNodes as $node) {
2256
      if (isset($node->classification)){
2257
        if(is_object($node->classification)) {
2258
          if ($node->classification->uuid == $defaultTreeUuid) {
2259
            return TRUE;
2260
          }
2261
        }
2262
        else {
2263
          if ($node->classification == $defaultTreeUuid) {
2264
            return TRUE;
2265
          }
2266
        }
2267
      }
2268
    }
2269
  }
2270

    
2271
  return FALSE;
2272
}
2273

    
2274
/**
2275
 * Checks is the source has one of the given types.
2276
 *
2277
 * @param object $source
2278
 *   The original source entity
2279
 * @param array $types
2280
 *   An array of elementd of the OriginalSourceType enumeration
2281
 *   If not set the default will be used which is:
2282
 *    - Lineage
2283
 *    - PrimaryMediaSource
2284
 *    - PrimaryTaxonomicSource
2285
 *    - Unknown
2286
 *    - Other
2287
 * @return boolean
2288
 */
2289
  function _is_original_source_type($source, $types = null) {
2290
    // this is the default
2291
    // maybe this should also be put into the settings
2292
    static $default = array(
2293
      OriginalSourceType::Lineage,
2294
      OriginalSourceType::PrimaryMediaSource,
2295
      OriginalSourceType::PrimaryTaxonomicSource,
2296
      OriginalSourceType::Unknown,
2297
      OriginalSourceType::Other,
2298
    );
2299

    
2300
    if(!$types){
2301
      $types = $default;
2302
    }
2303
    return isset($source->type) && in_array($source->type, $types);
2304
  }
2305

    
2306
/**
2307
 * @todo Please document this function.
2308
 * @see http://drupal.org/node/1354
2309
 */
2310
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2311
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2312
}
2313

    
2314

    
2315
/**
2316
 * Collects all the media from a list of description elements.
2317
 *
2318
 * @param array $descriptionElements
2319
 *   The description elements from which to collect the media.
2320
 *
2321
 * @return array
2322
 *   The output with all the collected media.
2323
 */
2324
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2325

    
2326
  $outArrayOfMedia = array();
2327

    
2328
  // Avoiding a warning box in Drupal for Flora Malesiana.
2329
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2330
    foreach ($descriptionElements as $descriptionElement) {
2331
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2332
        foreach ($descriptionElement->media as $media) {
2333
          if (is_object($media)) {
2334
            $outArrayOfMedia[] = $media;
2335
          }
2336
        }
2337
      }
2338
    }
2339
  }
2340
  return $outArrayOfMedia;
2341
}
2342

    
2343
/**
2344
 * @todo Please document this function.
2345
 * @see http://drupal.org/node/1354
2346
 *
2347
 * @param array $cdm_entities
2348
 *   An array of CdmBase instances or a single instance.
2349
 * @param string $footnote_list_key_suggestion
2350
 *
2351
 * @return unknown
2352
 */
2353
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2354

    
2355
   static $annotations_types_filter = null;
2356
   if(!$annotations_types_filter) {
2357
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2358
   }
2359

    
2360
  $footNoteKeys = array();
2361

    
2362
  // Is argument cdmBase an array?
2363
  if (!is_array($cdm_entities)) {
2364
    $cdmBase_array = array();
2365
    $cdmBase_array[] = $cdm_entities;
2366
  }
2367
  else {
2368
    $cdmBase_array = $cdm_entities;
2369
  }
2370

    
2371
  // Getting the key for the footnotemanager.
2372
  if (isset($footnote_list_key_suggestion)) {
2373
    $footnote_list_key = $footnote_list_key_suggestion;
2374
  }
2375
  else {
2376
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2377
  }
2378

    
2379
  // Adding the footnotes keys.
2380
  foreach ($cdmBase_array as $cdmBase_element) {
2381
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2382
    if (is_array($annotations)) {
2383
      foreach ($annotations as $annotation) {
2384
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2385
      }
2386
    }
2387
  }
2388

    
2389
  return $footNoteKeys;
2390
}
2391

    
2392

    
2393
/**
2394
 * Creates a CDM Dynabox.
2395
 *
2396
 * @param string $dynabox_id
2397
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2398
 * @param string $label
2399
 *   The clickable text to show.
2400
 * @param string $content_url
2401
 *   The cdm REST service request url wich will deliver the content to be shown
2402
 *   once the dynabox toggles open.
2403
 * @param string $theme
2404
 *   The theme to be used for rendering the cdm REST service response with is
2405
 *   returned from the $content_url.
2406
 * @param string $link_alt_text
2407
 *   The value for the alt attribute of the dynabox link.
2408
 * @param array $enclosingtags
2409
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2410
 *   element itself, $enclosingtags[1] is the tag to be used for the
2411
 *   dynabox_content (optional)
2412
 * @param array $attributes
2413
 * @param $content_element_selector
2414
 *   Optional jQuery selector which can be used to reference a dom element which should
2415
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2416
 *  element will be placed in this container.
2417
 *
2418
 * @param string $open_callback
2419
 *   optional javascript call back function to be triggered after toggling the box to
2420
 *   the open state.
2421
 * @param string $close_callback
2422
 *   optional javascript call back function to be triggered after toggling the box to
2423
 *   the closed state.
2424
 * @return string Returns HTML for a dynabox.
2425
 * Returns HTML for a dynabox.
2426
 */
2427
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2428
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2429
                     $content_element_selector = null,
2430
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2431
  $out = '';
2432

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

    
2436
  if(!array_key_exists('class', $attributes)) {
2437
    $attributes['class'] = array();
2438
  }
2439
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2440
  $dynabox_attributes = drupal_attributes($attributes);
2441

    
2442

    
2443
  _add_js_domEvent(); // requires domEvent.js
2444
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2445
  drupal_add_js("
2446
  jQuery(document).ready(
2447
      function() {
2448
        dynabox('". $dynabox_id ."',
2449
          {
2450
            open_callback: " . $open_callback .",
2451
            close_callback: " . $close_callback .
2452
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2453
          }
2454
        );
2455
      }
2456
   );",
2457
   array(
2458
    'type'=>'inline',
2459
    'scope'=>'footer'
2460
    )
2461
  );
2462

    
2463

    
2464
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2465
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2466
  $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>';
2467
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2468
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2469
  $out .= '    </' . $enclosingtags[1] . '>';
2470
  $out .= '  </' . $enclosingtags[0] . '>';
2471
  $out .= '<!-- dynabox end -->';
2472
  return $out;
2473
}
2474

    
2475
/**
2476
 * Checks whether a feature has any description elements.
2477
 *
2478
 * @param mixed $featureNode
2479
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2480
 *
2481
 * @see _mergeFeatureTreeDescriptions()
2482
 *
2483
 * @return bool
2484
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2485
 *   contains at least one non empty TextData or at least one DescriptionElement
2486
 *   of an other type. A TextData element holding a multilanguageText or a
2487
 *   source reference is considered to be not empty.
2488
 *
2489
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2490
 *       see $block_content_is_not_empty in make_feature_block_list() and
2491
 *       $feature_block_has_content in compose_feature_block_items_generic
2492
 */
2493
function has_feature_node_description_elements($featureNode) {
2494

    
2495
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2496
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2497
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2498
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2499
          && $descriptionElement->multilanguageText_L10n->text != ''
2500
          || isset($descriptionElement->sources[0])
2501
          || isset($descriptionElement->media[0]) ) {
2502
          return TRUE;
2503
        }
2504
      }
2505
    }
2506
  }
2507
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2508
    foreach ($featureNode->childNodes as $child) {
2509
      if (has_feature_node_description_elements($child)) {
2510
        return TRUE;
2511
      }
2512
    }
2513
  }
2514
  return FALSE;
2515
}
2516

    
2517
/**
2518
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2519
 *
2520
 * @param $chapter
2521
 *   The taxon page chapter or part
2522
 */
2523
function cdm_check_valid_taxon_page($chapter){
2524
  static $taxon_tabs = null;
2525

    
2526
  cdm_check_valid_portal_page();
2527

    
2528
  if($taxon_tabs == null){
2529
    $taxon_tabs = array('all', 'description');
2530
    foreach(get_taxon_tabs_list() as $tab){
2531
      $taxon_tabs[] = strtolower($tab);
2532
    }
2533
  }
2534

    
2535
  if(!in_array($chapter, $taxon_tabs)){
2536
    // oops this is not a valid chapter name
2537
    http_response_code(404); // 404 = Not Found
2538
  }
2539

    
2540
}
2541

    
2542
/**
2543
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2544
 *
2545
 * @param $chapter
2546
 *   The taxon page chapter or part
2547
 */
2548
function cdm_check_valid_portal_page(){
2549
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2550
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2551
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2552
    http_response_code(404); // 404 = Not Found
2553
    exit('HTTP 404');
2554
  }
2555
}
2556

    
2557
/**
2558
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2559
 *
2560
 * @param $text_a
2561
 * @param $text_b
2562
 * @return string
2563
 */
2564
function diff_viewer($text_a, $text_b) {
2565

    
2566
  static $diff_viewer_count = 0;
2567

    
2568
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2569

    
2570
  // http://code.stephenmorley.org/php/diff-implementation/
2571
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2572
  drupal_add_css(drupal_get_path('module',
2573
      'cdm_dataportal') . '/css/diff.css');
2574
  _add_jquery_ui();
2575
  drupal_add_js(
2576
    'jQuery(document).ready( function(){
2577
        jQuery(\'#' . $element_id . '\').accordion({
2578
        collapsible: true,
2579
        active: false,
2580
        fillSpace: true,
2581
        }).children(\'div\').css({ \'height\': \'auto\' });
2582
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2583
     });'
2584
    , array(
2585
    'type' => 'inline',
2586
    'scope' => 'footer'
2587
  ));
2588

    
2589
  $diff = Diff::compare($text_a,
2590
    $text_b);
2591
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2592
    . Diff::toTable($diff, '', '')
2593
    . '</div></div>';
2594
  return $diff_viewer_markup;
2595
}
2596

    
2597

    
(10-10/18)