Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_dataportal.module @ 977bba78

History | View | Annotate | Download (86 KB)

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
  function _add_js_ui_accordion(){
326
    _add_jquery_ui();
327
    drupal_add_js('jQuery(document).ready(function() {
328
        jQuery( "#accordion" ).accordion();
329
      });',
330
      array('type' => 'inline')
331
    );
332
  }
333

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

    
354

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

    
362
      return '<i ' . drupal_attributes($attributes) . '></i>';
363
    }
364

    
365
    return '';
366
  }
367

    
368
/**
369
 * Adds the css  containing the font awesome icons to the html header.
370
 */
371
function _add_font_awesome_font()
372
{
373
//<link href="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css" rel="stylesheet">
374

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

    
378
  drupal_add_html_head_link(
379
    array(
380
      'href' => $font_awesome_css_uri,
381
      'rel' => 'stylesheet'
382
    )
383
  );
384
}
385

    
386

    
387
/* ====================== hook implementations ====================== */
388
  /**
389
   * Implements hook_permission().
390
   *
391
   * Valid permissions for this module.
392
   *
393
   * @return array
394
   *   An array of valid permissions for the cdm_dataportal module.
395
   */
396
  function cdm_dataportal_permission() {
397
    return array(
398
      'administer cdm_dataportal' => array(
399
        'title' => t('Administer CDM DataPortal settings'),
400
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
401
      ),
402
      'access cdm content' => array(
403
        'title' => t('Access CDM content'),
404
        'description' => t("Access content (taxa, names, specimens, etc.) served by the CDM web service."),
405
      ),
406
    );
407
  }
408

    
409
/**
410
 * Implements hook_menu().
411
 */
412
function cdm_dataportal_menu() {
413
  $items = array();
414

    
415
  // @see settings.php.
416
  cdm_dataportal_menu_admin($items);
417
  cdm_dataportal_menu_help($items);
418

    
419
  $items['cdm_dataportal/names'] = array(
420
    'page callback' => 'cdm_dataportal_view_names',
421
    'access arguments' => array('access cdm content'),
422
    'type' => MENU_CALLBACK,
423
  );
424

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

    
433
  $items['cdm_dataportal/specimen'] = array(
434
      'page callback' => 'cdm_dataportal_specimen_page_view',
435
      'access arguments' => array('access cdm content'),
436
      'type' => MENU_CALLBACK,
437
      // Expected callback arguments: uuid.
438
  );
439

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

    
447
  $items['cdm_dataportal/name'] = array(
448
    'page callback' => 'cdm_dataportal_name_page_view',
449
      /*
450
    'page arguments' => array(
451
       'taxon_name_uuid',
452
       'taxon_to_hide_uuid',
453
       'synonym_uuid' => NULL
454
      ),
455
      */
456
    'access arguments' => array('access cdm content'),
457
    'type' => MENU_CALLBACK,
458
    // Expected callback arguments: uuid.
459
  );
460

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

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

    
475
  $items['cdm_dataportal/media'] = array(
476
    'page callback' => 'cdm_dataportal_view_media',
477
    'access arguments' => array('access cdm content'),
478
    'type' => MENU_CALLBACK,
479
    // Expected callback arguments:
480
    // uuid, mediarepresentation_uuid, part_uuid or part#.
481
  );
482

    
483
  $items['cdm_dataportal/polytomousKey'] = array(
484
    'page callback' => 'cdm_dataportal_view_polytomousKey',
485
    'access arguments' => array('access cdm content'),
486
    'type' => MENU_CALLBACK,
487
    // Expected callback arguments: polytomousKey->uuid.
488
  );
489

    
490
  $items['cdm_dataportal/search'] = array(
491
    'page callback' => 'cdm_dataportal_view_search_advanced',
492
    'access arguments' => array('access cdm content'),
493
    'type' => MENU_CALLBACK,
494
  );
495

    
496
  $items['cdm_dataportal/search/advanced'] = array(
497
    'title' => 'Advanced', // will be passed through t()
498
    'page callback' => 'cdm_dataportal_view_search_advanced',
499
    'access arguments' => array('access cdm content'),
500
    'type' => MENU_DEFAULT_LOCAL_TASK,
501
  );
502

    
503
  $items['cdm_dataportal/search/taxon_by_description'] = array(
504
    'title' => 'By content category', // will be passed through t()
505
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
506
    'access arguments' => array('access cdm content'),
507
    'type' => MENU_LOCAL_TASK,
508
  );
509
  $items['cdm_dataportal/search/results/taxon'] = array(
510
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
511
    'access arguments' => array('access cdm content'),
512
    'type' => MENU_CALLBACK,
513
  );
514
  /*
515
   * MENU_CALLBACK at cdm_dataportal/registration-search is needed to make the
516
   * tabs in the subordinate paths work, accessing this 'page' will cause the
517
   * MENU_DEFAULT_LOCAL_TASK being displayed
518
   */
519
  $items['cdm_dataportal/registration-search'] = array(
520
    'title' => 'Search', // will be passed through t()
521
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
522
    'page arguments' => array("filter"),
523
    'access arguments' => array('access cdm content'),
524
    'type' => MENU_CALLBACK,
525
  );
526
  /*
527
   * the MENU_DEFAULT_LOCAL_TASK creates a tab for the MENU_CALLBACK
528
   * defined at a higher level of the path (cdm_dataportal/registration-search)
529
   */
530
  $items['cdm_dataportal/registration-search/filter'] = array(
531
    'title' => 'Search', // will be passed through t()
532
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
533
    'page arguments' => array("filter"),
534
    'access arguments' => array('access cdm content'),
535
    'type' => MENU_DEFAULT_LOCAL_TASK,
536
  );
537
  /*
538
   * the MENU_LOCAL_TASK creates another tab
539
   */
540
  $items['cdm_dataportal/registration-search/taxongraph'] = array(
541
    'title' => 'Taxonomic search', // will be passed through t()
542
    'page callback' => 'cdm_dataportal_view_search_registrations_results',
543
    'page arguments' => array("taxongraph"),
544
    'access arguments' => array('access cdm content'),
545
    'type' => MENU_LOCAL_TASK,
546
  );
547

    
548
  // Optional callback arguments: page.
549
  $items['cdm_dataportal/registration'] = array(
550
    'page callback' => 'cdm_dataportal_registration_page_view',
551
    'access arguments' => array('access cdm content'),
552
    'type' => MENU_CALLBACK,
553
    // Expected callback arguments: uuid.
554
  );
555

    
556
  /*
557
   $items['cdm/xml2json'] = array(
558
   'page callback' => 'cdm_view_xml2json',
559
   'access arguments' => array('access cdm content'),
560
   'type' => MENU_CALLBACK,
561
   );
562
   */
563

    
564
  // 'May not cache' in D5.
565
  $items['cdm_dataportal/name/%'] = array(
566
    // 'page callback' => 'cdm_dataportal_view_name',
567
    'page callback' => 'cdm_dataportal_name_page_view',
568
    'page arguments' => array(2, 3, 4),
569
    'access arguments' => array('access cdm content'),
570
    'type' => MENU_CALLBACK,
571
  );
572

    
573
  // --- Local tasks for Taxon.
574
  // --- tabbed taxon page
575
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
576
    $items['cdm_dataportal/taxon/%'] = array(
577
      'title' => cdm_taxonpage_tab_label('General'),
578
      'page callback' => 'cdm_dataportal_taxon_page_view',
579
      'access arguments' => array('access cdm content'),
580
      'type' => MENU_CALLBACK,
581
      'weight' => 1,
582
      'page arguments' => array(2, "description")
583
      , // Expected callback arguments: taxon_uuid.
584
    );
585

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

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

    
606
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
607
      'title' => cdm_taxonpage_tab_label('Synonymy'),
608
      'page callback' => 'cdm_dataportal_taxon_page_view',
609
      'access arguments' => array('access cdm content'),
610
      'type' => MENU_LOCAL_TASK,
611
      'weight' => 4,
612
      'page arguments' => array(2, "synonymy", 4)
613
      , // Expected callback arguments: taxon_uuid and ...
614
    );
615
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
616
      'title' => cdm_taxonpage_tab_label('Images'),
617
      'page callback' => 'cdm_dataportal_taxon_page_view',
618
      'access arguments' => array('access cdm content'),
619
      'type' => MENU_LOCAL_TASK,
620
      'weight' => 5,
621
      'page arguments' => array(2, "images")
622
      , // Expected callback arguments: taxon_uuid.
623
    );
624

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

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

    
645
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
646
      'title' => cdm_taxonpage_tab_label('Experts'),
647
        'page callback' => 'cdm_dataportal_taxon_page_view',
648
        'access arguments' => array('access cdm content'),
649
        'type' => MENU_LOCAL_TASK,
650
        'weight' => 6,
651
        'page arguments' => array(2, "experts")
652
    , // Expected callback arguments: taxon_uuid.
653
    );
654

    
655
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
656
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
657
        'access arguments' => array('access cdm content'),
658
        'page arguments' => array(3,4,5),
659
        'type' => MENU_CALLBACK
660
    );
661
  }
662

    
663
  // --- refresh link for all cdmnode types
664
  foreach (cdm_get_nodetypes() as $type=>$name) {
665
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
666
        'title' => 'Refresh',
667
        'page callback' => 'cdm_dataportal_refresh_node',
668
        'access arguments' => array('administer cdm_dataportal'),
669
        'type' => MENU_LOCAL_TASK,
670
        'weight' => 100,
671
        'page arguments' => array($name, 2)
672
    );
673
  }
674

    
675
  return $items;
676
}
677

    
678
/**
679
 * Implements hook_init().
680
 *
681
 */
682
function cdm_dataportal_init() {
683
  if (!path_is_admin(current_path())) {
684
    //FIXME To add CSS or JS that should be present on all pages, modules
685
    //      should not implement this hook, but declare these files in their .info file.
686
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
687
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
688
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
689
  } else {
690
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
691
  }
692

    
693
  if(variable_get('cdm_debug_mode', FALSE)){
694
    $file = 'temporary://drupal_debug.txt';
695
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
696
  }
697

    
698
  $bibliography_settings = get_bibliography_settings();
699
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
700
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
701
}
702

    
703
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
704

    
705
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
706

    
707
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
708
    // force reloading of all and notify user about this special loading
709
    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: ')
710
        . l('Back to tabbed taxon page', $base_path));
711
    $base_path .= '/all';
712
  } else {
713
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
714
  }
715

    
716
  $parameters['cacheL2_refresh'] ='1';
717

    
718

    
719
  drupal_goto($base_path, array('query' => $parameters));
720
}
721

    
722
/**
723
 * Implements hook_requirements($phase)
724
 */
725
function cdm_dataportal_requirements($phase) {
726
    $requirements = array();
727
    if($phase == 'runtime'){
728

    
729
    }
730
    return $requirements;
731
}
732

    
733
/**
734
 * Implements hook_block_info().
735
 */
736
function cdm_dataportal_block_info() {
737

    
738
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
739
    // $block[1]["info"] = t("CDM DataPortal Credits");
740
    $block["2"] = array(
741
        "info" => t("CDM - Search Taxa"),
742
        "cache" => DRUPAL_NO_CACHE
743
      );
744
    // $block[3]["info"] = t("CDM Filters");
745
    $block["4"]["info"] = t("CDM  - Dataportal Print");
746
    $block["keys"]["info"] = t("CDM - Identification keys");
747
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
748
    $block["classification_breadcrumbs"] =  array(
749
        'info' => t('CDM - Classification breadcrumbs'),
750
        'cache' => DRUPAL_CACHE_PER_PAGE
751
      );
752
    $block["taxonomic_children"] =  array(
753
      'info' => t('CDM - Taxonomic children'),
754
      'cache' => DRUPAL_CACHE_PER_PAGE
755
    );
756
    $block["back_to_search_results"] =  array(
757
      'title' => '<none>',
758
      'info' => t('CDM - Back to search Results'),
759
      'cache' => DRUPAL_CACHE_PER_PAGE,
760
      'visibility' => BLOCK_VISIBILITY_LISTED,
761
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
762
    );
763
  $block['registrations_search_filter'] =  array(
764
    'title' => 'Filter registrations',
765
    'info' => t('CDM - Registrations search filter'),
766
    'cache' => DRUPAL_CACHE_PER_PAGE,
767
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
768
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
769
  );
770
  $block['registrations_search_taxongraph'] =  array(
771
    'title' => 'Taxonomic registration search',
772
    'info' => t('CDM - Registrations search by taxon graph'),
773
    'cache' => DRUPAL_CACHE_PER_PAGE,
774
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
775
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
776
  );
777
  $block['registrations_search'] =  array(
778
    'title' => 'Search',
779
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
780
    'cache' => DRUPAL_CACHE_PER_PAGE,
781
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
782
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
783
  );
784
  return $block;
785
}
786

    
787
/**
788
 * Implements hook_block_view().
789
 */
790
function cdm_dataportal_block_view($delta) {
791
  // TODO Rename block deltas (e.g. '2') to readable strings.
792
  switch ($delta) {
793
    // case 'delta-1':
794
    // $block['subject'] = t('Credits');
795
    // $block['content'] = theme('cdm_credits');
796
    // return $block;
797
    case '2':
798
      $block['subject'] = t('Search taxa');
799
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
800
      $block['content'] = drupal_render($form);
801

    
802
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
803
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
804
      }
805
      return $block;
806
    case '4':
807
      $block['subject'] = '';
808
      $block['content'] = theme('cdm_print_button');
809
      return $block;
810
    case "keys":
811
      $block['subject'] = t('Identification Keys');
812
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
813
      return $block;
814
    case "fundedByEDIT":
815
      // t('Funded by EDIT');
816
      $text = '<none>';
817
      $block['subject'] = $text;
818
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
819
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
820
        'attributes' => array("target" => "EDIT"),
821
        'absolute' => TRUE,
822
        'html' => TRUE,
823
      ));
824
      return $block;
825
    case 'classification_breadcrumbs':
826
      $taxon_uuid = get_current_taxon_uuid();
827
      $block['subject'] = '<none>';
828
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
829
      return $block;
830
    case 'taxonomic_children':
831
      $taxon_uuid = get_current_taxon_uuid();
832
      $block['subject'] = '<none>';
833
      $block['content'] = compose_taxonomic_children($taxon_uuid);
834
      return $block;
835
    case 'back_to_search_results':
836
      $block['subject'] = '<none>';
837
      if (isset($_SESSION['cdm']['search'])) {
838
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
839
      }
840
      return $block;
841
    case 'registrations_search_filter':
842
      $block['subject'] = '<none>';
843
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
844
      return $block;
845
    case 'registrations_search_taxongraph':
846
      $block['subject'] = '<none>';
847
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
848
      return $block;
849
    case 'registrations_search':
850
      _add_js_ui_accordion();
851
      _add_font_awesome_font();
852
      $block['subject'] = '<none>';
853
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
854
      $filter_form['#prefix'] = '<div>';
855
      $filter_form['#suffix'] = '</div>';
856
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
857
      $taxongraph_form['#prefix'] = '<div>';
858
      $taxongraph_form['#suffix'] = '</div>';
859
      $block['content'] = array(
860
        'accordion' => array(
861
          '#markup' => '',
862
          '#prefix' => '<div id="accordion">',
863
          '#suffix' => '</div>',
864
          'content' => array(
865
            array('#markup' => '<h3>Filter</h3>'),
866
            $filter_form,
867
            array('#markup' => '<h3>Taxon graph</h3>'),
868
            $taxongraph_form,
869
          )
870
        )
871
    );
872
       return $block;
873
    default:
874
      return null;
875
  }
876
}
877

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

    
888
  if(!isset($taxon_uuid)){
889
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
890
      $taxon_uuid = $_REQUEST['currentTaxon'];
891
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
892
      $taxon_uuid = arg(2);
893
    } else {
894
      $taxon_uuid = null;
895
    }
896
  }
897

    
898
  return $taxon_uuid;
899
}
900

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

    
916
/*
917
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
918
 $_SESSION['cdm'] = NULL;
919
 if(is_string($cdm_ws_uri_update)){
920
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
921
 }
922
 }
923

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

    
933
/**
934
 * creates a  selector form for taxonomic trees.
935
 *
936
 * @return array
937
 *  a drupal form array
938
 */
939
function cdm_taxonomictree_selector() {
940
  _add_js_treeselector();
941

    
942
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
943
  return $form;
944
}
945

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

    
954
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
955
  $form['#action'] = $url;
956

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

    
963
  $destination_array = drupal_get_destination();
964
  $destination = $destination_array['destination'];
965

    
966
  $form['destination'] = array(
967
    '#weight' => -3,
968
    '#type' => 'hidden',
969
    '#value' =>  $destination,
970
  );
971

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

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

    
992
  return $form;
993

    
994
}
995

    
996
/**
997
 *
998
 * @ingroup compose
999
 */
1000
function compose_classification_selector() {
1001

    
1002
  $destination_array = drupal_get_destination();
1003
  $destination = $destination_array['destination'];
1004

    
1005
  $options = cdm_get_taxontrees_as_options();
1006
  $items = array();
1007
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1008

    
1009
  $current_classification_uuid = get_current_classification_uuid();
1010

    
1011

    
1012
  foreach($options as $uuid=>$label){
1013
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1014

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

    
1035
  $render_array = array(
1036
    '#theme' => 'item_list',
1037
    '#type' => 'ul',
1038
    '#items' => $items
1039
  );
1040

    
1041
  return $render_array;
1042
}
1043

    
1044

    
1045
/* UNREACHABLE since action of form directly links to view.
1046
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1047

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

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

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

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

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

    
1108
/**
1109
 * @todo Please document this function.
1110
 * @see http://drupal.org/node/1354
1111
 * @throws Exception
1112
 */
1113
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1114

    
1115
  cdm_check_valid_portal_page();
1116

    
1117
  return compose_cdm_reference_page($uuid);
1118
}
1119

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

    
1130
/**
1131
 * @todo Please document this function.
1132
 * @see http://drupal.org/node/1354
1133
 */
1134
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1135

    
1136
  cdm_check_valid_portal_page();
1137

    
1138
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1139
  return theme('cdm_media_page', array(
1140
    'media' => $media,
1141
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1142
    'partId' => $part,
1143
    ));
1144
}
1145

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

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

    
1174
  static $media = NULL;
1175

    
1176
  if(!isset($media)) {
1177
    $media = array();
1178
  }
1179
  if (!isset($media[$taxon->uuid])) {
1180

    
1181
    // --- GET Images --- //
1182
    $mediaQueryParameters = array(
1183
        "type" => "ImageFile",
1184
    );
1185

    
1186
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1187
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1188
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1189

    
1190
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1191
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1192
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1193
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1194

    
1195
    $ws_endpoint = NULL;
1196
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1197
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1198
    } else {
1199
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1200
    }
1201

    
1202
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1203
        array(
1204
            $taxon->uuid,
1205
        ),
1206
        queryString($mediaQueryParameters)
1207
       );
1208
  }
1209

    
1210
  return $media[$taxon->uuid];
1211
}
1212

    
1213
/**
1214
 *
1215
 * @param Taxon $taxon
1216
 *   A CDM Taxon entitiy
1217
 *
1218
 * @return array
1219
 *   An array of CDM SpecimenOrObservation entities
1220
 *
1221
function _load_occurences_for_taxon($taxon){
1222

    
1223
  static $occurences = NULL;
1224

    
1225
  if(!isset($occurences)) {
1226
    $occurences = array();
1227
  }
1228

    
1229
  if (!isset($occurences[$taxon->uuid])){
1230

    
1231
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1232
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1233
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1234

    
1235
    $by_associatedtaxon_query = http_build_query(array(
1236
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1237
        'relationships' => implode(',', $relationship_choice['direct']),
1238
        'pageSize' => null // all hits in one page
1239
    )
1240
    );
1241

    
1242
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1243
        null,
1244
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1245
    );
1246

    
1247

    
1248
    if(isset($pager->records[0])){
1249
      $occurences[$taxon->uuid] =  $pager->records;
1250
    }
1251
  }
1252
  return $occurences[$taxon->uuid];
1253
}
1254
 */
1255

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

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

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

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

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

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

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

    
1415
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1416

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

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

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

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

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

    
1442
  cdm_check_valid_portal_page();
1443

    
1444
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1445

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1574
  return $taxonpage;
1575
}
1576

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

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

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

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

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

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

    
1629
    return $specimenpage;
1630
}
1631

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

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

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

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

    
1656
  return $named_area_page;
1657
}
1658

    
1659
function cdm_dataportal_named_area_page_view($uuid) {
1660

    
1661
  cdm_check_valid_portal_page();
1662

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

    
1671

    
1672
}
1673

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

    
1695
  cdm_check_valid_portal_page();
1696

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

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

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

    
1796
/**
1797
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1798
 *
1799
 * @param string  $registration_identifier_encoded
1800
 *   The persistent identifier of the registration urlencoded.
1801
 * @return mixed
1802
 *   The formatted registration page as node.
1803
 */
1804
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
1805

    
1806
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
1807
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
1808
  return cdm_node_show_simulate($registration_page);
1809
}
1810

    
1811
function cdm_dataportal_registration_view($registration_identifier_encoded) {
1812

    
1813
  $registration_identifier = urldecode($registration_identifier_encoded);
1814

    
1815
  $render_array = array();
1816
  $registration_dto = cdm_ws_get(CDM_WS_REGISTRATION_DTO_BY_IDENTIFIER . $registration_identifier_encoded);
1817
  if($registration_dto){
1818
    drupal_set_title(t('Registration Id:') . ' ' . $registration_identifier, PASS_THROUGH);
1819

    
1820
    $render_array = compose_registration_dto_full($registration_dto, true);
1821

    
1822
  } else {
1823
    $status_text = cdm_ws_get(CDM_WS_REGISTRATION_STATUS_BY_IDENTIFIER, array($registration_identifier));
1824
    if(isset($status_text->String)) {
1825
      $status_text = strtolower($status_text->String);
1826
      if($status_text == 'preparation' || $status_text == 'curation'){
1827
        $status_text = 'in ' . $status_text;
1828
      }
1829
      drupal_set_title(t('Registration ' . $status_text), PASS_THROUGH);
1830
      //$status_message;
1831
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " is " . $status_text, "status");
1832
    } else {
1833
      drupal_set_title(t('Registration not found'), PASS_THROUGH);
1834
      drupal_set_message("A registration with the identifier  " . $registration_identifier . " does not exist", "warning");
1835
    }
1836
  }
1837

    
1838
  $render_array = array(
1839
    '#prefix' => '<div id="registration">',
1840
    'registration' => $render_array,
1841
    '#suffix' => '</div>',
1842
  );
1843

    
1844
  return $render_array ;
1845
}
1846

    
1847

    
1848
/**
1849
 * Creates a page with the advance search form.
1850
 *
1851
 * NOTE: The advance search form allows searching for taxa.
1852
 */
1853
function cdm_dataportal_view_search_advanced() {
1854
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1855
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1856
}
1857

    
1858
/**
1859
 * Creates a page with the search form for searching by taxon descriptions.
1860
 */
1861
function cdm_dataportal_view_search_taxon_by_description() {
1862
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1863
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1864
}
1865

    
1866
/**
1867
 * Executes the search and generates the result list of taxa.
1868
 */
1869
function cdm_dataportal_view_search_results_taxon() {
1870

    
1871
  $taxonPager = cdm_dataportal_search_taxon_execute();
1872

    
1873
  $showThumbnails = do_showThumbnails();
1874

    
1875
  $setSessionUri = url('cdm_api/setvalue/session', array(
1876
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1877
  ));
1878

    
1879
  drupal_add_js('jQuery(document).ready(function() {
1880

    
1881
      // init
1882
      if(' . $showThumbnails . ' == 1){
1883
          jQuery(\'.media_gallery\').show(20);
1884
      } else {
1885
          jQuery(\'.media_gallery\').hide(20);
1886
      }
1887

    
1888
      // add change handler
1889
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1890
      function(event){
1891
        var state = 0;
1892
        if(jQuery(this).is(\':checked\')){
1893
          jQuery(\'.media_gallery\').show(20);
1894
          state = 1;
1895
        } else {
1896
          jQuery(\'.media_gallery\').hide(20);
1897
        }
1898
        // store state in session variable
1899
        var uri = \'' . $setSessionUri . '\' + state;
1900
        jQuery.get(uri);
1901
      });
1902
  });',
1903
  array('type' => "inline", 'scope' => JS_DEFAULT));
1904

    
1905
  drupal_set_title(t('Search results'), PASS_THROUGH);
1906

    
1907
  return theme('cdm_search_taxa_results', array(
1908
    'pager' => $taxonPager,
1909
    'path' => 'cdm_dataportal/search/results/taxon',
1910
    ));
1911
}
1912

    
1913
/**
1914
 * Executes the search for registrations and generates the result list..
1915
 */
1916
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
1917

    
1918
  switch($mode ){
1919
    case 'taxongraph':
1920
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
1921
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
1922
      break;
1923
    case 'filter':
1924
    default:
1925
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
1926
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
1927
  }
1928
  $block->title = null;
1929

    
1930
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
1931

    
1932
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
1933
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
1934
  $render_array = array_merge($render_array, $registrations_pager_array);
1935

    
1936
  return $render_array;
1937
}
1938

    
1939

    
1940
/**
1941
 * Provides the standart image wich indicated a loading process
1942
 *
1943
 * @return string
1944
 *  The img html tag
1945
 */
1946
function loading_image_html() {
1947
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1948
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1949
}
1950

    
1951
/**
1952
 * Returns the state of the the showThumbnails flag set in the
1953
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1954
 *
1955
 * @return boolean
1956
 *    returns 1 if the flag is set
1957
 */
1958
function do_showThumbnails() {
1959
  static $showThumbnails = null;
1960

    
1961
  if($showThumbnails == null) {
1962
    $showThumbnails = 0;
1963
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1964
      $showThumbnails = 0;
1965
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1966
      $showThumbnails = is_array($search_gallery_settings)
1967
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1968
        && (
1969
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1970
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1971
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1972
            )
1973
         ? 1 : 0;
1974

    
1975
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1976
    }
1977
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1978
    if (!is_numeric($showThumbnails)) {
1979
      $showThumbnails = 1;
1980
    }
1981
  }
1982

    
1983
  return $showThumbnails;
1984
}
1985

    
1986

    
1987

    
1988
/* ====================== other functions ====================== */
1989
/**
1990
 * Creates a URL to the taxon page specified by the $uuid parameter.
1991
 *
1992
 * The URL will be prepended with a path element to a specific taxon page tab.
1993
 *
1994
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1995
 * be set globally in the administrative settings or individually in the user
1996
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1997
 * the last portal will stay on this last tab.
1998
 *
1999
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2000
 * internal mechanism by a specific value.
2001
 *
2002
 * @param string $uuid
2003
 *   The UUID of the taxon.
2004
 * @param string $page_tab
2005
 *   Overwriting the preset mechanism by defining specific value for the
2006
 *   taxon page tab.
2007
 *
2008
 * @return string
2009
 *   The created URL.
2010
 */
2011
function path_to_taxon($uuid, $page_tab = FALSE) {
2012

    
2013
  $tab = get_default_taxon_tab();
2014
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2015

    
2016
  if (!$uuid) {
2017
    return FALSE;
2018
  }
2019

    
2020
  if ($page_tab) {
2021
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2022
  }
2023
  elseif (!$tab || strtolower($tab) == 'general') {
2024
    return 'cdm_dataportal/taxon/' . $uuid;
2025
  }
2026
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2027
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2028
  }
2029
  else {
2030
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2031
  }
2032
}
2033

    
2034
function path_to_specimen($uuid) {
2035

    
2036
    if (!$uuid) {
2037
        return FALSE;
2038
    }
2039
    else {
2040
        return 'cdm_dataportal/specimen/' . $uuid;
2041
    }
2042
}
2043

    
2044
function path_to_named_area($uuid) {
2045

    
2046
  if (!$uuid) {
2047
    return FALSE;
2048
  }
2049
  else {
2050
    return 'cdm_dataportal/named_area/' . $uuid;
2051
  }
2052
}
2053

    
2054
/**
2055
 * Creates a URL to show a synonmy in the according taxon page.
2056
 *
2057
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2058
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2059
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2060
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2061
 * in the page
2062
 *
2063
 * @param string $synonymUuid
2064
 *    The uuid of the synonym
2065
 * @param string $acceptedUuid
2066
 *    The uuid of the according accepted taxon
2067
 * @return string
2068
 *    The URL to show a synonmy in the according taxon page
2069
 */
2070
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2071
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2072
  return url($acceptedPath, array(
2073
      'query' => array(
2074
        // highlite the synony in the synonymy
2075
        'highlite' => $synonymUuid,
2076
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2077
        // see theme_taxon_page_title()
2078
        'acceptedFor' => $synonymUuid
2079
      ),
2080
      'fragment' => $synonymUuid
2081
  ));
2082

    
2083
}
2084

    
2085
/**
2086
 * Composes the drupal path to the key identified by the uuid.
2087
 *
2088
 * @param string $keyType
2089
 *    the key typer corresponds to the specific class of the CDM
2090
 *    IdentificationKey. Possible values are
2091
 *      -PolytomousKey
2092
 *      -MultimediaKey
2093
 *      - ...
2094
 * @param string $keyUuid
2095
 *   The UUID of the key
2096
 */
2097
function path_to_key($keyType, $keyUuid) {
2098
  if (!$keyUuid || !$keyType) {
2099
    return FALSE;
2100
  }
2101
  $keyType{0} = strtolower($keyType{0});
2102
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2103
}
2104

    
2105
/**
2106
 * Composes the drupal path to the reference identified by the uuid.
2107
 *
2108
 * @param $uuid string String representation of the registration entity uuid.
2109
 *
2110
 * @return string
2111
 *  The drupal path
2112
 *
2113
 */
2114
function path_to_reference($uuid) {
2115
  if (!$uuid) {
2116
    return FALSE;
2117
  }
2118
  return 'cdm_dataportal/reference/' . $uuid;
2119
}
2120

    
2121
/**
2122
 * Composes the drupal path to the reference identified by the uuid.
2123
 *
2124
 * @param string $identifier
2125
 *  The persistent identifier of the registration entity (Registration.identifier).
2126
 * @return string
2127
 *  The drupal path
2128
 */
2129
function path_to_registration($identifier) {
2130

    
2131
  if(variable_get(CDM_REGISTRATION_PRESISTENT_IDENTIFIER_AS_LINK)){
2132
    return $identifier;
2133
  } else {
2134
    return 'cdm_dataportal/registration/' . urlencode($identifier);
2135
  }
2136
}
2137

    
2138
/**
2139
 * Creates the path to a cdm_dataportal taxon name page.
2140
 *
2141
 * @param string $taxon_name_uuid
2142
 *   The uuid as string of the CDM TaxonName to show a name page for
2143
 * @param string $taxon_to_hide_uuid
2144
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2145
 * @param string $highlited_synonym_uuid
2146
 *   Optional parameter which takes another taxon uuid, if given the
2147
 *   target taxon pages will show the synonymy tab where the taxon
2148
 *   referenced by the $highlite_synonym_uuid will be highlighted
2149
 *   in case it is found on this page.
2150
 *
2151
 * @return string
2152
 *  URI path element as string
2153
 */
2154
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL) {
2155
  $res = FALSE;
2156
  if ($name_uuid) {
2157
    $res = 'cdm_dataportal/name/' . $name_uuid;
2158
  }
2159
  if($taxon_to_hide_uuid){
2160
    $res .= '/' . $taxon_to_hide_uuid;
2161
    if($highlited_synonym_uuid){
2162
      $res .= '/' . $highlited_synonym_uuid;
2163
    }
2164
  }
2165
  return $res;
2166
}
2167

    
2168
/**
2169
 * Composes the drupal path to the media entity identified by the uuid.
2170
 *
2171
 * @param string $uuid
2172
 *  The persistent identifier of the entity entity
2173
 * @return string
2174
 *  The drupal path
2175
 */
2176
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2177
  if (!$uuid) {
2178
    return FALSE;
2179
  }
2180
  $out = 'cdm_dataportal/media/' . $uuid;
2181
  if ($representaion_uuid) {
2182
    $out .= '/' . $representaion_uuid;
2183
    if (is_numeric($partId)) {
2184
      $out .= '/' . $partId;
2185
    }
2186
  }
2187
  return $out;
2188
}
2189

    
2190
/**
2191
 * Compares thisRank with thatRank.
2192
 *
2193
 * Returns a negative integer, zero, or a positive integer
2194
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2195
 * e.g:
2196
 * <ul>
2197
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2198
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2199
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2200
 * </ul>
2201
 * <p>
2202
 * This compare logic of the underlying webservice is the
2203
 * <b>inverse logic</b> of the the one implemented in
2204
 * java.lang.Comparable#compareTo(java.lang.Object)
2205
 *
2206
 * @param $thisRankUuid
2207
 * @param $thatRankUuid
2208
 *
2209
 * @return int
2210
 *   A negative integer, zero, or a positive integer
2211
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2212
 */
2213
function rank_compare($thisRankUuid, $thatRankUuid) {
2214
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2215
  return $result->Integer;
2216
}
2217

    
2218
/**
2219
 * Composes an HTML element class attribute value composed of
2220
 * the short-name of the cdm class and the uuid of the entity.
2221
 * This class attribute should be used wherever an cdm-entity is rendered.
2222
 *
2223
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2224
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2225
 * Taxon uuid is added also as taxon_uuid:<uuid>
2226
 *
2227
 * These according class selectors in css must be escaped, eg:
2228
 *    .cdm\:TextData
2229
 *
2230
 * @param $cdm_entity
2231
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2232
 */
2233
function html_class_attribute_ref($cdm_entity) {
2234

    
2235
  $attributes = '';
2236
  if (is_cdm_entity($cdm_entity)) {
2237
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2238
  } else if($cdm_entity->class == 'TypedEntityReference') {
2239
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2240
  }
2241
  if($cdm_entity->class == 'TaxonNodeDto'){
2242
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2243
  }
2244
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2245
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2246
  }
2247
  return $attributes;
2248
}
2249

    
2250

    
2251
/**
2252
 * Creates a short version of a taxonname.
2253
 *
2254
 * The short name is created by using the taggedTitle field of
2255
 * TaxonNodeDTO instances.
2256
 * If the taggedTitle if empty the fullname will be returned.
2257
 *
2258
 * @param object $taxonNodeDTO
2259
 *   A TaxonNodeDTO object
2260
 *
2261
 * @return string
2262
 */
2263
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2264

    
2265
  $nameStr = '';
2266

    
2267
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2268

    
2269
  // Get all tagged text tokens of the scientific name.
2270
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2271
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2272
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2273
    }
2274
  }
2275
  $nameStr = trim($nameStr);
2276

    
2277
  if ($nameStr) {
2278

    
2279
    // Do not return short names for these.
2280
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2281
      return $nameStr;
2282
    }
2283

    
2284
    /*
2285
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2286
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2287
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2288
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2289
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2290
    */
2291
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2292
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2293
      return $matches[1][0] . "." . $matches[3][0];
2294
    }
2295
    else {
2296
      return $nameStr;
2297
    }
2298
  }
2299
  else {
2300
    return $taxonNodeDTO->titleCache;
2301
  }
2302
}
2303

    
2304
/**
2305
 * Check if a taxon is accepted by the current taxonomic tree.
2306
 *
2307
 * @param mixed $taxon
2308
 *   The Taxon obkect to check.
2309
 *
2310
 * @return bool
2311
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2312
 */
2313
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2314

    
2315
  $defaultTreeUuid = get_current_classification_uuid();
2316

    
2317
  if (isset($taxon->taxonNodes)) {
2318
    $taxonNodes = $taxon->taxonNodes;
2319
  }
2320
  else {
2321
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2322
  }
2323

    
2324
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2325
    foreach ($taxonNodes as $node) {
2326
      if (isset($node->classification)){
2327
        if(is_object($node->classification)) {
2328
          if ($node->classification->uuid == $defaultTreeUuid) {
2329
            return TRUE;
2330
          }
2331
        }
2332
        else {
2333
          if ($node->classification == $defaultTreeUuid) {
2334
            return TRUE;
2335
          }
2336
        }
2337
      }
2338
    }
2339
  }
2340

    
2341
  return FALSE;
2342
}
2343

    
2344
/**
2345
 * Checks is the source has one of the given types.
2346
 *
2347
 * @param object $source
2348
 *   The original source entity
2349
 * @param array $types
2350
 *   An array of elementd of the OriginalSourceType enumeration
2351
 *   If not set the default will be used which is:
2352
 *    - Lineage
2353
 *    - PrimaryMediaSource
2354
 *    - PrimaryTaxonomicSource
2355
 *    - Unknown
2356
 *    - Other
2357
 * @return boolean
2358
 */
2359
  function _is_original_source_type($source, $types = null) {
2360
    // this is the default
2361
    // maybe this should also be put into the settings
2362
    static $default = array(
2363
      OriginalSourceType::Lineage,
2364
      OriginalSourceType::PrimaryMediaSource,
2365
      OriginalSourceType::PrimaryTaxonomicSource,
2366
      OriginalSourceType::Unknown,
2367
      OriginalSourceType::Other,
2368
    );
2369

    
2370
    if(!$types){
2371
      $types = $default;
2372
    }
2373
    return isset($source->type) && in_array($source->type, $types);
2374
  }
2375

    
2376
/**
2377
 * Collects all the media from a list of description elements.
2378
 *
2379
 * @param array $descriptionElements
2380
 *   The description elements from which to collect the media.
2381
 *
2382
 * @return array
2383
 *   The output with all the collected media.
2384
 */
2385
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2386

    
2387
  $outArrayOfMedia = array();
2388

    
2389
  // Avoiding a warning box in Drupal for Flora Malesiana.
2390
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2391
    foreach ($descriptionElements as $descriptionElement) {
2392
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2393
        foreach ($descriptionElement->media as $media) {
2394
          if (is_object($media)) {
2395
            $outArrayOfMedia[] = $media;
2396
          }
2397
        }
2398
      }
2399
    }
2400
  }
2401
  return $outArrayOfMedia;
2402
}
2403

    
2404
/**
2405
 * Fetches the list of visible annotations for each of the cdm entities and returns the footnote keys for them.
2406
 *
2407
 * The footnotes are passed to the FootnoteManager in order to store the annotations and to create the footnote keys.
2408
 *
2409
 * @see cdm_fetch_visible_annotations()
2410
 *
2411
 * @param array $cdm_entities
2412
 *   An array of CdmBase instances or a single instance.
2413
 * @param string $footnote_list_key_suggestion
2414
 *
2415
 * @return array of footnote keys
2416
 */
2417
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2418

    
2419
  $footNoteKeys = array();
2420

    
2421
  // Is argument cdmBase an array?
2422
  if (!is_array($cdm_entities)) {
2423
    $cdmBase_array = array();
2424
    $cdmBase_array[] = $cdm_entities;
2425
  }
2426
  else {
2427
    $cdmBase_array = $cdm_entities;
2428
  }
2429

    
2430
  // Getting the key for the footnotemanager.
2431
  if (isset($footnote_list_key_suggestion)) {
2432
    $footnote_list_key = $footnote_list_key_suggestion;
2433
  }
2434
  else {
2435
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2436
  }
2437

    
2438
  // Adding the footnotes keys.
2439
  foreach ($cdmBase_array as $cdmBase_element) {
2440
    $annotations = cdm_fetch_visible_annotations($cdmBase_element);
2441
    if (is_array($annotations)) {
2442
      foreach ($annotations as $annotation) {
2443
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2444
      }
2445
    }
2446
  }
2447

    
2448
  return $footNoteKeys;
2449
}
2450

    
2451

    
2452
/**
2453
 * Creates a CDM Dynabox.
2454
 *
2455
 * @param string $dynabox_id
2456
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2457
 * @param string $label
2458
 *   The clickable text to show.
2459
 * @param string $content_url
2460
 *   The cdm REST service request url wich will deliver the content to be shown
2461
 *   once the dynabox toggles open.
2462
 * @param string $theme
2463
 *   The theme to be used for rendering the cdm REST service response with is
2464
 *   returned from the $content_url.
2465
 * @param string $link_alt_text
2466
 *   The value for the alt attribute of the dynabox link.
2467
 * @param array $enclosingtags
2468
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2469
 *   element itself, $enclosingtags[1] is the tag to be used for the
2470
 *   dynabox_content (optional)
2471
 * @param array $attributes
2472
 * @param $content_element_selector
2473
 *   Optional jQuery selector which can be used to reference a dom element which should
2474
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2475
 *  element will be placed in this container.
2476
 *
2477
 * @param string $open_callback
2478
 *   optional javascript call back function to be triggered after toggling the box to
2479
 *   the open state.
2480
 * @param string $close_callback
2481
 *   optional javascript call back function to be triggered after toggling the box to
2482
 *   the closed state.
2483
 * @return string Returns HTML for a dynabox.
2484
 * Returns HTML for a dynabox.
2485
 */
2486
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2487
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2488
                     $content_element_selector = null,
2489
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2490
  $out = '';
2491

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

    
2495
  if(!array_key_exists('class', $attributes)) {
2496
    $attributes['class'] = array();
2497
  }
2498
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2499
  $dynabox_attributes = drupal_attributes($attributes);
2500

    
2501

    
2502
  _add_js_domEvent(); // requires domEvent.js
2503
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2504
  drupal_add_js("
2505
  jQuery(document).ready(
2506
      function() {
2507
        dynabox('". $dynabox_id ."',
2508
          {
2509
            open_callback: " . $open_callback .",
2510
            close_callback: " . $close_callback .
2511
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2512
          }
2513
        );
2514
      }
2515
   );",
2516
   array(
2517
    'type'=>'inline',
2518
    'scope'=>'footer'
2519
    )
2520
  );
2521

    
2522

    
2523
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2524
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2525
  $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>';
2526
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2527
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2528
  $out .= '    </' . $enclosingtags[1] . '>';
2529
  $out .= '  </' . $enclosingtags[0] . '>';
2530
  $out .= '<!-- dynabox end -->';
2531
  return $out;
2532
}
2533

    
2534
/**
2535
 * Checks whether a feature has any description elements.
2536
 *
2537
 * @param mixed $featureNode
2538
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2539
 *
2540
 * @see _mergeFeatureTreeDescriptions()
2541
 *
2542
 * @return bool
2543
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2544
 *   contains at least one non empty TextData or at least one DescriptionElement
2545
 *   of an other type. A TextData element holding a multilanguageText or a
2546
 *   source reference is considered to be not empty.
2547
 *
2548
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2549
 *       see $block_content_is_not_empty in make_feature_block_list() and
2550
 *       $feature_block_has_content in compose_feature_block_items_generic
2551
 */
2552
function has_feature_node_description_elements($featureNode) {
2553

    
2554
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2555
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2556
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2557
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2558
          && $descriptionElement->multilanguageText_L10n->text != ''
2559
          || isset($descriptionElement->sources[0])
2560
          || isset($descriptionElement->media[0]) ) {
2561
          return TRUE;
2562
        }
2563
      }
2564
    }
2565
  }
2566
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2567
    foreach ($featureNode->childNodes as $child) {
2568
      if (has_feature_node_description_elements($child)) {
2569
        return TRUE;
2570
      }
2571
    }
2572
  }
2573
  return FALSE;
2574
}
2575

    
2576
/**
2577
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2578
 *
2579
 * @param $chapter
2580
 *   The taxon page chapter or part
2581
 */
2582
function cdm_check_valid_taxon_page($chapter){
2583
  static $taxon_tabs = null;
2584

    
2585
  cdm_check_valid_portal_page();
2586

    
2587
  if($taxon_tabs == null){
2588
    $taxon_tabs = array('all', 'description');
2589
    foreach(get_taxon_tabs_list() as $tab){
2590
      $taxon_tabs[] = strtolower($tab);
2591
    }
2592
  }
2593

    
2594
  if(!in_array($chapter, $taxon_tabs)){
2595
    // oops this is not a valid chapter name
2596
    http_response_code(404); // 404 = Not Found
2597
  }
2598

    
2599
}
2600

    
2601
/**
2602
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2603
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2604
 *
2605
 * @param $preg_pattern
2606
 *   Optional regular expression pattern to be used in preg_match().
2607
 */
2608
function cdm_check_valid_portal_page($preg_pattern = null){
2609
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2610
  if($preg_pattern === null){
2611
    $preg_pattern = $ends_with_file_suffix_pattern;
2612
  }
2613
  if(preg_match($preg_pattern, $_GET['q'])){
2614
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2615
    http_response_code(404); // 404 = Not Found
2616
    exit('HTTP 404');
2617
  }
2618
}
2619

    
2620
/**
2621
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2622
 *
2623
 * @param $text_a
2624
 * @param $text_b
2625
 * @return string
2626
 */
2627
function diff_viewer($text_a, $text_b) {
2628

    
2629
  static $diff_viewer_count = 0;
2630

    
2631
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2632

    
2633
  // http://code.stephenmorley.org/php/diff-implementation/
2634
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2635
  drupal_add_css(drupal_get_path('module',
2636
      'cdm_dataportal') . '/css/diff.css');
2637
  _add_jquery_ui();
2638
  drupal_add_js(
2639
    'jQuery(document).ready( function(){
2640
        jQuery(\'#' . $element_id . '\').accordion({
2641
        collapsible: true,
2642
        active: false,
2643
        fillSpace: true,
2644
        }).children(\'div\').css({ \'height\': \'auto\' });
2645
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2646
     });'
2647
    , array(
2648
    'type' => 'inline',
2649
    'scope' => 'footer'
2650
  ));
2651

    
2652
  $diff = Diff::compare($text_a,
2653
    $text_b);
2654
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2655
    . Diff::toTable($diff, '', '')
2656
    . '</div></div>';
2657
  return $diff_viewer_markup;
2658
}
2659

    
2660

    
Add picture from clipboard (Maximum size: 40 MB)