Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

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

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

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

    
282
  global $base_url;
283

    
284

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

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

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

    
325
  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
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
565
  // User configuration of cdm_dataportal.
566
  $items['user/%/cdm_dataportal'] = array(
567
    'title' => 'cdm_dataportal',
568
    'access arguments' => array('access cdm content'),
569
    'page callback' => 'drupal_get_form',
570
    'page arguments' => array('cdm_dataportal_user_form'),
571
    'type' => MENU_LOCAL_TASK,
572
    'weight' => 10,
573
  );
574
  // }
575

    
576
  // 'May not cache' in D5.
577
  $items['cdm_dataportal/name/%'] = array(
578
    // 'page callback' => 'cdm_dataportal_view_name',
579
    'page callback' => 'cdm_dataportal_name_page_view',
580
    'page arguments' => array(2, 3, 4),
581
    'access arguments' => array('access cdm content'),
582
    'type' => MENU_CALLBACK,
583
  );
584

    
585
  // --- Local tasks for Taxon.
586
  // --- tabbed taxon page
587
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
588
    $items['cdm_dataportal/taxon/%'] = array(
589
      'title' => cdm_taxonpage_tab_label('General'),
590
      'page callback' => 'cdm_dataportal_taxon_page_view',
591
      'access arguments' => array('access cdm content'),
592
      'type' => MENU_CALLBACK,
593
      'weight' => 1,
594
      'page arguments' => array(2, "description")
595
      , // Expected callback arguments: taxon_uuid.
596
    );
597

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

    
608
    $items['cdm_dataportal/taxon/%/description'] = array(
609
      'title' => cdm_taxonpage_tab_label('General'),
610
      'page callback' => 'cdm_dataportal_taxon_page_view',
611
      'access arguments' => array('access cdm content'),
612
      'type' => MENU_DEFAULT_LOCAL_TASK,
613
      'weight' => 2,
614
      'page arguments' => array(2, "description")
615
      , // Expected callback arguments: taxon_uuid.
616
    );
617

    
618
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
619
      'title' => cdm_taxonpage_tab_label('Synonymy'),
620
      'page callback' => 'cdm_dataportal_taxon_page_view',
621
      'access arguments' => array('access cdm content'),
622
      'type' => MENU_LOCAL_TASK,
623
      'weight' => 4,
624
      'page arguments' => array(2, "synonymy", 4)
625
      , // Expected callback arguments: taxon_uuid and ...
626
    );
627
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
628
      'title' => cdm_taxonpage_tab_label('Images'),
629
      'page callback' => 'cdm_dataportal_taxon_page_view',
630
      'access arguments' => array('access cdm content'),
631
      'type' => MENU_LOCAL_TASK,
632
      'weight' => 5,
633
      'page arguments' => array(2, "images")
634
      , // Expected callback arguments: taxon_uuid.
635
    );
636

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

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

    
657
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
658
      'title' => cdm_taxonpage_tab_label('Experts'),
659
        'page callback' => 'cdm_dataportal_taxon_page_view',
660
        'access arguments' => array('access cdm content'),
661
        'type' => MENU_LOCAL_TASK,
662
        'weight' => 6,
663
        'page arguments' => array(2, "experts")
664
    , // Expected callback arguments: taxon_uuid.
665
    );
666

    
667
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
668
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
669
        'access arguments' => array('access cdm content'),
670
        'page arguments' => array(3,4,5),
671
        'type' => MENU_CALLBACK
672
    );
673
  }
674

    
675
  // --- refresh link for all cdmnode types
676
  foreach (cdm_get_nodetypes() as $type=>$name) {
677
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
678
        'title' => 'Refresh',
679
        'page callback' => 'cdm_dataportal_refresh_node',
680
        'access arguments' => array('administer cdm_dataportal'),
681
        'type' => MENU_LOCAL_TASK,
682
        'weight' => 100,
683
        'page arguments' => array($name, 2)
684
    );
685
  }
686

    
687
  return $items;
688
}
689

    
690
/**
691
 * Implements hook_init().
692
 *
693
 */
694
function cdm_dataportal_init() {
695
  if (!path_is_admin(current_path())) {
696
    //FIXME To add CSS or JS that should be present on all pages, modules
697
    //      should not implement this hook, but declare these files in their .info file.
698
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
699
    // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
700
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
701
  } else {
702
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_settings.css');
703
  }
704

    
705
  if(variable_get('cdm_debug_mode', FALSE)){
706
    $file = 'temporary://drupal_debug.txt';
707
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
708
  }
709

    
710
  $bibliography_settings = get_bibliography_settings();
711
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
712
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
713
}
714

    
715
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
716

    
717
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
718

    
719
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
720
    // force reloading of all and notify user about this special loading
721
    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: ')
722
        . l('Back to tabbed taxon page', $base_path));
723
    $base_path .= '/all';
724
  } else {
725
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
726
  }
727

    
728
  $parameters['cacheL2_refresh'] ='1';
729

    
730

    
731
  drupal_goto($base_path, array('query' => $parameters));
732
}
733

    
734
/**
735
 * Implements hook_requirements($phase)
736
 */
737
function cdm_dataportal_requirements($phase) {
738
    $requirements = array();
739
    if($phase == 'runtime'){
740

    
741
    }
742
    return $requirements;
743
}
744

    
745

    
746
/**
747
 * The function generate form for own user cdm dataportal configurations.
748
 */
749
function cdm_dataportal_user_form($form, &$form_state) {
750

    
751
  global $user;
752
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
753

    
754
  $form['taxon_page_tabs'] = array(
755
      '#type' => 'fieldset',
756
      '#tree' => true,
757
      '#title' => t('Taxon page tabs'),
758
  );
759

    
760
  $form['taxon_page_tabs']['user_defined'] = array(
761
    '#type' => 'checkbox',
762
    '#title' => t('Activate user default configuration'),
763
    '#default_value' => variable_get($checkbox_value, 0),
764
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
765
  );
766

    
767
  $form['taxon_page_tabs']['default_tab'] = array(
768
    '#type' => 'select',
769
    '#title' => t('Default tab to display'),
770
    '#default_value' => get_default_taxon_tab(TRUE),
771
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
772
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
773
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
774
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
775
  );
776

    
777

    
778
  if(false){
779
    $form['developer_options'] = array(
780
        '#type' => 'fieldset',
781
        '#tree' => true,
782
        '#title' => t('Developer options'),
783
    );
784

    
785
    $form['developer_options']['show_render_path'] = array(
786
      '#type' => 'checkbox',
787
      '#title' => t('Display the render path for each taxon name.'),
788
      '#default_value' => variable_get($checkbox_value, 0),
789
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
790
        array(
791
            '!link' => l(
792
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
793
            )
794
        ),
795
    );
796
  }
797

    
798
  $form['submit'] = array(
799
    '#type' => 'submit',
800
    '#value' => t('Submit'),
801
  );
802

    
803
  return $form;
804
}
805

    
806
/**
807
 * Form submission handler for user_form().
808
 *
809
 * Submits the user cdm dataportal configurations.
810
 */
811
function cdm_dataportal_user_form_submit($form, &$form_state) {
812
  global $user;
813
  $msg_type = 'status';
814
  $username = $user->name;
815
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
816

    
817
  // FIXME: this is completely wrong, see user_profile_form_submit()
818

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

    
822
    // DEFAULT_TAXON_TAB
823
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
824
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
825
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
826
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
827
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
828
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
829
        '!tab' => $variable[variable_get($variable_to_use, 0)],
830
        '!user' => $username,
831
      ))), $msg_type);
832
    }
833
    else {
834
      drupal_set_message(check_plain(t('The user default tab wont be used for
835
        the next taxon site, check the box if you want to use the user default configuration.')));
836
    }
837

    
838
  }
839
  else {
840
    // Problem with the user id => variables wont be saved.
841
    $msg_type = 'warning';
842
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
843
  }
844
}
845

    
846
/**
847
 * Implements hook_block_info().
848
 */
849
function cdm_dataportal_block_info() {
850

    
851
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
852
    // $block[1]["info"] = t("CDM DataPortal Credits");
853
    $block["2"] = array(
854
        "info" => t("CDM - Search Taxa"),
855
        "cache" => DRUPAL_NO_CACHE
856
      );
857
    // $block[3]["info"] = t("CDM Filters");
858
    $block["4"]["info"] = t("CDM  - Dataportal Print");
859
    $block["keys"]["info"] = t("CDM - Identification keys");
860
    $block["fundedByEDIT"]["info"] = t('CDM - Powered by EDIT');
861
    $block["classification_breadcrumbs"] =  array(
862
        'info' => t('CDM - Classification breadcrumbs'),
863
        'cache' => DRUPAL_CACHE_PER_PAGE
864
      );
865
    $block["taxonomic_children"] =  array(
866
      'info' => t('CDM - Taxonomic children'),
867
      'cache' => DRUPAL_CACHE_PER_PAGE
868
    );
869
    $block["back_to_search_results"] =  array(
870
      'title' => '<none>',
871
      'info' => t('CDM - Back to search Results'),
872
      'cache' => DRUPAL_CACHE_PER_PAGE,
873
      'visibility' => BLOCK_VISIBILITY_LISTED,
874
      'pages' => "cdm_dataportal/taxon/*", // multiple page paths separated by "\n"!!!
875
    );
876
  $block['registrations_search_filter'] =  array(
877
    'title' => 'Filter registrations',
878
    'info' => t('CDM - Registrations search filter'),
879
    'cache' => DRUPAL_CACHE_PER_PAGE,
880
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
881
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
882
  );
883
  $block['registrations_search_taxongraph'] =  array(
884
    'title' => 'Taxonomic registration search',
885
    'info' => t('CDM - Registrations search by taxon graph'),
886
    'cache' => DRUPAL_CACHE_PER_PAGE,
887
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
888
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
889
  );
890
  $block['registrations_search'] =  array(
891
    'title' => 'Search',
892
    'info' => t('CDM - Registrations search combining filter and taxon graph search' ),
893
    'cache' => DRUPAL_CACHE_PER_PAGE,
894
    'visibility' => BLOCK_VISIBILITY_NOTLISTED,
895
    'pages' => "cdm_dataportal/registration-search\ncdm_dataportal/registration-search/*", // multiple page paths separated by "\n"!!!
896
  );
897
  return $block;
898
}
899

    
900
/**
901
 * Implements hook_block_view().
902
 */
903
function cdm_dataportal_block_view($delta) {
904
  // TODO Rename block deltas (e.g. '2') to readable strings.
905
  switch ($delta) {
906
    // case 'delta-1':
907
    // $block['subject'] = t('Credits');
908
    // $block['content'] = theme('cdm_credits');
909
    // return $block;
910
    case '2':
911
      $block['subject'] = t('Search taxa');
912
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
913
      $block['content'] = drupal_render($form);
914

    
915
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
916
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
917
      }
918
      return $block;
919
    case '4':
920
      $block['subject'] = '';
921
      $block['content'] = theme('cdm_print_button');
922
      return $block;
923
    case "keys":
924
      $block['subject'] = t('Identification Keys');
925
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
926
      return $block;
927
    case "fundedByEDIT":
928
      // t('Funded by EDIT');
929
      $text = '<none>';
930
      $block['subject'] = $text;
931
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
932
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
933
        'attributes' => array("target" => "EDIT"),
934
        'absolute' => TRUE,
935
        'html' => TRUE,
936
      ));
937
      return $block;
938
    case 'classification_breadcrumbs':
939
      $taxon_uuid = get_current_taxon_uuid();
940
      $block['subject'] = '<none>';
941
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
942
      return $block;
943
    case 'taxonomic_children':
944
      $taxon_uuid = get_current_taxon_uuid();
945
      $block['subject'] = '<none>';
946
      $block['content'] = compose_taxonomic_children($taxon_uuid);
947
      return $block;
948
    case 'back_to_search_results':
949
      $block['subject'] = '<none>';
950
      if (isset($_SESSION['cdm']['search'])) {
951
        $block['content'] = l(t('Back to search result'), "http://" . $_SERVER['SERVER_NAME'] . $_SESSION['cdm']['last_search']);
952
      }
953
      return $block;
954
    case 'registrations_search_filter':
955
      $block['subject'] = '<none>';
956
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_filter_form'); // see cdm_dataportal_search_registration_filter_form($form, &$form_state)
957
      return $block;
958
    case 'registrations_search_taxongraph':
959
      $block['subject'] = '<none>';
960
      $block['content'] = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form'); // see cdm_dataportal_search_registration_taxongraph_form($form, &$form_state)
961
      return $block;
962
    case 'registrations_search':
963
      _add_js_ui_accordion();
964
      _add_font_awesome_font();
965
      $block['subject'] = '<none>';
966
      $filter_form = drupal_get_form('cdm_dataportal_search_registration_filter_form');
967
      $filter_form['#prefix'] = '<div>';
968
      $filter_form['#suffix'] = '</div>';
969
      $taxongraph_form = drupal_get_form('cdm_dataportal_search_registration_taxongraph_form');
970
      $taxongraph_form['#prefix'] = '<div>';
971
      $taxongraph_form['#suffix'] = '</div>';
972
      $block['content'] = array(
973
        'accordion' => array(
974
          '#markup' => '',
975
          '#prefix' => '<div id="accordion">',
976
          '#suffix' => '</div>',
977
          'content' => array(
978
            array('#markup' => '<h3>Filter</h3>'),
979
            $filter_form,
980
            array('#markup' => '<h3>Taxon graph</h3>'),
981
            $taxongraph_form,
982
          )
983
        )
984
    );
985
       return $block;
986
    default:
987
      return null;
988
  }
989
}
990

    
991
/**
992
 * Provides the uuid of the taxon for pages with the path ./taxon/{taxon_uuid}
993
 *
994
 * @return string
995
 *   the taxon uuid or NULL
996
 */
997
function get_current_taxon_uuid()
998
{
999
  static $taxon_uuid;
1000

    
1001
  if(!isset($taxon_uuid)){
1002
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
1003
      $taxon_uuid = $_REQUEST['currentTaxon'];
1004
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
1005
      $taxon_uuid = arg(2);
1006
    } else {
1007
      $taxon_uuid = null;
1008
    }
1009
  }
1010

    
1011
  return $taxon_uuid;
1012
}
1013

    
1014
/**
1015
 * Returns the currently classification tree in use.
1016
 *
1017
 * @return string
1018
 *   The uuid of the currently focused classification
1019
 */
1020
function get_current_classification_uuid() {
1021
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1022
    return $_SESSION['cdm']['taxonomictree_uuid'];
1023
  }
1024
  else {
1025
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1026
  }
1027
}
1028

    
1029
/*
1030
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
1031
 $_SESSION['cdm'] = NULL;
1032
 if(is_string($cdm_ws_uri_update)){
1033
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
1034
 }
1035
 }
1036

    
1037
 function cdm_dataportal_session_validate(){
1038
 if(!isset($_SESSION['cdm']['ws_uri'])){
1039
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
1040
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
1041
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
1042
 }
1043
 }
1044
 */
1045

    
1046
/**
1047
 * creates a  selector form for taxonomic trees.
1048
 *
1049
 * @return array
1050
 *  a drupal form array
1051
 */
1052
function cdm_taxonomictree_selector() {
1053
  _add_js_treeselector();
1054

    
1055
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
1056
  return $form;
1057
}
1058

    
1059
/**
1060
 * @todo Please document this function.
1061
 * @see http://drupal.org/node/1354
1062
 *
1063
 * @deprecated use compose_classification_selector instead
1064
 */
1065
function cdm_taxonomictree_selector_form($form, &$form_state) {
1066

    
1067
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
1068
  $form['#action'] = $url;
1069

    
1070
  $form['var'] = array(
1071
    '#weight' => -3,
1072
    '#type' => 'hidden',
1073
    '#value' => '[cdm][taxonomictree_uuid]',
1074
  );
1075

    
1076
  $destination_array = drupal_get_destination();
1077
  $destination = $destination_array['destination'];
1078

    
1079
  $form['destination'] = array(
1080
    '#weight' => -3,
1081
    '#type' => 'hidden',
1082
    '#value' =>  $destination,
1083
  );
1084

    
1085
  $options = cdm_get_taxontrees_as_options();
1086
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1087
  if($taxontree_includes){
1088
    $filtered_options = array();
1089
    foreach($options as $uuid=>$label){
1090
      if(!empty($taxontree_includes[$uuid])){
1091
        $filtered_options[$uuid] = $label;
1092
      }
1093
    }
1094
    $options = $filtered_options;
1095
  }
1096

    
1097
  $form['val'] = array(
1098
    '#type' => 'select',
1099
    '#title' => t('Available classifications'),
1100
    '#default_value' => get_current_classification_uuid(),
1101
    '#options' => $options,
1102
    '#attributes' => array('class' => array('highlite-first-child')),
1103
  );
1104

    
1105
  return $form;
1106

    
1107
}
1108

    
1109
/**
1110
 *
1111
 * @ingroup compose
1112
 */
1113
function compose_classification_selector() {
1114

    
1115
  $destination_array = drupal_get_destination();
1116
  $destination = $destination_array['destination'];
1117

    
1118
  $options = cdm_get_taxontrees_as_options();
1119
  $items = array();
1120
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1121

    
1122
  $current_classification_uuid = get_current_classification_uuid();
1123

    
1124

    
1125
  foreach($options as $uuid=>$label){
1126
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1127

    
1128
      $class_attributes = '';
1129
      if($current_classification_uuid == $uuid){
1130
        $class_attributes  = array('focused');
1131
      }
1132
      $items[] = array(
1133
        'data' => l($label,
1134
          'cdm_api/setvalue/session',
1135
          array(
1136
            'query' => array(
1137
              'destination' => $destination,
1138
              'val' => $uuid,
1139
              'var' => '[cdm][taxonomictree_uuid]'
1140
            ),
1141
          )
1142
        ),
1143
        'class' => $class_attributes
1144
      );
1145
    }
1146
  }
1147

    
1148
  $render_array = array(
1149
    '#theme' => 'item_list',
1150
    '#type' => 'ul',
1151
    '#items' => $items
1152
  );
1153

    
1154
  return $render_array;
1155
}
1156

    
1157

    
1158
/* UNREACHABLE since action of form directly links to view.
1159
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1160

    
1161
 $_SESSION['cdm']['search'] = $form_values;
1162
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1163
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1164
 //$paramstr = compose_url_prameterstr($form_values);
1165
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1166
 }
1167
 */
1168
/* ====================== menu callback functions ====================== */
1169
/**
1170
 * @todo Please document this function.
1171
 * @see http://drupal.org/node/1354
1172
 */
1173
/*
1174
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1175
  static $comment_node_disabled =  0;
1176
  static $comment_node_read_only =  1;
1177
  static $comment_node_read_write =  2;
1178

    
1179
  if ($form_id == 'node_type_form'
1180
   && isset($form['identity']['type'])
1181
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1182
  ) {
1183
    $form['workflow']['comment'] = array(
1184
      '#type' => 'radios',
1185
      '#title' => t('Default comment setting'),
1186
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1187
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1188
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1189
    );
1190
  }
1191
}
1192
*/
1193

    
1194
/**
1195
 * Displays a list of the known taxonomic names.
1196
 *
1197
 * When the list of taxonomic names is displayed, long lists are split up into
1198
 * multiple pages.
1199
 *
1200
 * TODO: Parameters are still preliminary.
1201
 *
1202
 * @param string $beginsWith
1203
 * @param string $page
1204
 *   Page number to diplay defaults to page 1.
1205
 * @param bool $onlyAccepted
1206
 */
1207
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1208

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

    
1211
  /*
1212
  // FIXME the filter for accepted names will be a form element, thus this
1213
  // widget should be generated via form api preferably as block.
1214
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1215
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1216
  $out .= theme('cdm_listof_taxa', $taxonPager);
1217
  return $out;
1218
  */
1219
}
1220

    
1221
/**
1222
 * @todo Please document this function.
1223
 * @see http://drupal.org/node/1354
1224
 * @throws Exception
1225
 */
1226
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1227

    
1228
  cdm_check_valid_portal_page();
1229

    
1230
  return compose_cdm_reference_page($uuid);
1231
}
1232

    
1233
/**
1234
 * Creates a view on a all references contained in the portal.
1235
 *
1236
 * This function is used at the path cdm_dataportal/reference/list
1237
 */
1238
function cdm_dataportal_view_reference_list($pageNumber) {
1239
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1240
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
1241
}
1242

    
1243
/**
1244
 * @todo Please document this function.
1245
 * @see http://drupal.org/node/1354
1246
 */
1247
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1248

    
1249
  cdm_check_valid_portal_page();
1250

    
1251
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1252
  return theme('cdm_media_page', array(
1253
    'media' => $media,
1254
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1255
    'partId' => $part,
1256
    ));
1257
}
1258

    
1259
/**
1260
 * @todo Please document this function.
1261
 * @see http://drupal.org/node/1354
1262
 */
1263
function _load_taxonBase(&$taxonBase) {
1264
  if (isset($taxonBase->uuid)) {
1265
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1266
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1267
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1268
  }
1269
}
1270

    
1271
/**
1272
 * Loads the media associated to the given taxon from the cdm server.
1273
 * The aggregation settings regarding taxon relathionships and
1274
 * taxonnomic childen are taken into account.
1275
 *
1276
 * The media lists are cached in a static variable.
1277
 *
1278
 * @param Taxon $taxon
1279
 *   A CDM Taxon entitiy
1280
 *
1281
 * @return array
1282
 *   An array of CDM Media entities
1283
 *
1284
 */
1285
function _load_media_for_taxon($taxon) {
1286

    
1287
  static $media = NULL;
1288

    
1289
  if(!isset($media)) {
1290
    $media = array();
1291
  }
1292
  if (!isset($media[$taxon->uuid])) {
1293

    
1294
    // --- GET Images --- //
1295
    $mediaQueryParameters = array(
1296
        "type" => "ImageFile",
1297
    );
1298

    
1299
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1300
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1301
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1302

    
1303
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1304
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1305
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1306
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1307

    
1308
    $ws_endpoint = NULL;
1309
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1310
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1311
    } else {
1312
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1313
    }
1314

    
1315
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1316
        array(
1317
            $taxon->uuid,
1318
        ),
1319
        queryString($mediaQueryParameters)
1320
       );
1321
  }
1322

    
1323
  return $media[$taxon->uuid];
1324
}
1325

    
1326
/**
1327
 *
1328
 * @param Taxon $taxon
1329
 *   A CDM Taxon entitiy
1330
 *
1331
 * @return array
1332
 *   An array of CDM SpecimenOrObservation entities
1333
 *
1334
function _load_occurences_for_taxon($taxon){
1335

    
1336
  static $occurences = NULL;
1337

    
1338
  if(!isset($occurences)) {
1339
    $occurences = array();
1340
  }
1341

    
1342
  if (!isset($occurences[$taxon->uuid])){
1343

    
1344
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1345
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1346
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1347

    
1348
    $by_associatedtaxon_query = http_build_query(array(
1349
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1350
        'relationships' => implode(',', $relationship_choice['direct']),
1351
        'pageSize' => null // all hits in one page
1352
    )
1353
    );
1354

    
1355
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1356
        null,
1357
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1358
    );
1359

    
1360

    
1361
    if(isset($pager->records[0])){
1362
      $occurences[$taxon->uuid] =  $pager->records;
1363
    }
1364
  }
1365
  return $occurences[$taxon->uuid];
1366
}
1367
 */
1368

    
1369
/**
1370
 * Gets a Drupal variable, string or array and returns it.
1371
 *
1372
 * Similar to the variable_get() function of Drupal, except that this function
1373
 * is able to handle arrays correctly. This function is especially useful
1374
 * when dealing with collections of settings form elements (#tree = TRUE).
1375
 *
1376
 * @param string $variableKey
1377
 *   The Unique key of the Drupal variable in the Drupal variables table.
1378
 * @param string $defaultValueString
1379
 *   A string as for example derived from a CONSTANT.
1380
 *
1381
 * @return mixed
1382
 *   usually an array, depending on the nature of the variable.
1383
 *
1384
 * TODO compare with get_array_variable_merged() duplicate functions?
1385
 * @deprecated rather use get_array_variable_merged() since this function
1386
 * used an array as second parameter
1387
 */
1388
function mixed_variable_get($variableKey, $defaultValueString) {
1389
  $systemDefaults = unserialize($defaultValueString);
1390
  $storedSettings = variable_get($variableKey, array());
1391
  if (is_array($storedSettings)) {
1392
    // TODO better use drupal_array_merge_deep() ?
1393
    $settings = array_merge($systemDefaults, $storedSettings);
1394
  }
1395
  else {
1396
    $settings = $systemDefaults;
1397
  }
1398
  return $settings;
1399
}
1400

    
1401
/**
1402
 * Recursive function to convert an object into an array.
1403
 * also subordinate objects will be converted.
1404
 *
1405
 * @param object $object
1406
 *  the object to be converted
1407
 * @return array
1408
 *  The array
1409
 */
1410
function object_to_array($object) {
1411
  if(is_object($object) || is_array($object)) {
1412
    $array = (array)$object;
1413
    foreach ($array as $key=>$value){
1414
      $array[$key] = object_to_array($value);
1415
    }
1416
    return $array;
1417
  } else {
1418
    return $object;
1419
  }
1420
}
1421

    
1422
/**
1423
 * Searches the $collection for the cdm entitiy given as $element.
1424
 *
1425
 * The elements are compared by their UUID.
1426
 *
1427
 * @param $element
1428
 *  the CDM entitiy to search for
1429
 * @param $collection
1430
 *  the list of CDM entities to search in
1431
 *
1432
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1433
 *
1434
 */
1435
function contains_cdm_entitiy($element, $collection) {
1436
  $result = FALSE;
1437
  foreach ($collection as $a) {
1438
    if ($a->uuid == $element->uuid) {
1439
      $result = TRUE;
1440
    }
1441
  }
1442
  return $result;
1443
}
1444

    
1445
/**
1446
 * Fiters the array $entity_list of CDM entities by the list
1447
 * of $excludes. Any element contained in the $excludes will be removed
1448
 * from included int the retuned list.
1449
 *
1450
 * If the $entity_list is not an array the $excludes will be returned.
1451
 */
1452
function filter_cdm_entity_list($entity_list, $excludes) {
1453
  if (is_array($entity_list)) {
1454
    $result = $entity_list;
1455
    if ($excludes) {
1456
      foreach ($excludes as $exclude) {
1457
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1458
          $result[] = $exclude;
1459
        }
1460
      }
1461
    }
1462
  }
1463
  else {
1464
    $result = $excludes;
1465
  }
1466
  return $result;
1467
}
1468

    
1469
/**
1470
 * Wraps the given $html string into a render array suitable for drupal_render()
1471
 *
1472
 * @param $html
1473
 *   the html string, see
1474
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1475
 * @param $weight
1476
 *   A positive or negative number (integer or decimal).
1477
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1478
 * @param $prefix
1479
 *   Optional markup for the '#prefix' element of the render array
1480
 * @param $suffix
1481
 *   Optional markup for the '#suffix' element of the render array
1482
 *
1483
 * @return array
1484
 *   A render array
1485
 *
1486
 */
1487
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1488
  $render_array = array(
1489
    '#markup' => $html
1490
      );
1491
  if (is_numeric($weight)) {
1492
    $render_array['#weight'] = $weight;
1493
  }
1494
  if($prefix){
1495
    $render_array['#prefix'] = $prefix;
1496
  }
1497
  if($suffix) {
1498
    $render_array['#suffix'] = $suffix;
1499
  }
1500
  return $render_array;
1501
}
1502

    
1503
/**
1504
 * Loads the subgraph of a given PolytomousKeyNode.
1505
 *
1506
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1507
 * the CDM REST service.
1508
 *
1509
 * @param mixed $polytomousKeyNode
1510
 *   PolytomousKeyNode passed by reference.
1511
 *
1512
 * @return void
1513
 */
1514
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1515

    
1516
  if (!$polytomousKeyNode) {
1517
    return;
1518
  }
1519
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1520
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1521
    return;
1522
  }
1523
  if (!is_uuid($polytomousKeyNode->uuid)) {
1524
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1525
    return;
1526
  }
1527

    
1528
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1529

    
1530
  if (!$polytomousKeyNode) {
1531
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1532
    return;
1533
  }
1534

    
1535
  // Load children.
1536
  foreach ($polytomousKeyNode->children as &$childNode) {
1537
    _load_polytomousKeySubGraph($childNode);
1538
  }
1539

    
1540
  // Load subkey.
1541
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1542

    
1543
  // Load taxon.
1544
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1545
  _load_taxonBase($polytomousKeyNode->taxon);
1546
  return;
1547
}
1548

    
1549
/**
1550
 * @todo Please document this function.
1551
 * @see http://drupal.org/node/1354
1552
 */
1553
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1554

    
1555
  cdm_check_valid_portal_page();
1556

    
1557
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1558

    
1559
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1560
  if (is_array($sourcePager->records)) {
1561
    $polytomousKey->sources = $sourcePager->records;
1562
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1563
  }
1564

    
1565
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1566
  if (is_array($annotationPager->records)) {
1567
    $polytomousKey->annotations = $annotationPager->records;
1568
  }
1569

    
1570
  _load_polytomousKeySubGraph($polytomousKey->root);
1571
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1572
}
1573

    
1574
/**
1575
 * Creates a taxon page view or a chapter of it.
1576
 *
1577
 * The taxon page gives detailed information on a taxon, it shows:
1578
 *  - Taxon name.
1579
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1580
 *    heterotypic and finally followed by misapplied names.
1581
 *    The list is ordered historically.
1582
 *  - All description associated with the taxon.
1583
 *
1584
 * @param string $uuid
1585
 * @param string $chapter
1586
 *   Name of the part to display, valid values are:
1587
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1588
 *
1589
 * @return string
1590
 */
1591
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all') {
1592

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

    
1605
  // Display the page for the taxon defined by $uuid.
1606
  // set_last_taxon_page_tab(arg(3));
1607
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1608
  if (!empty($taxonpage)) {
1609
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1610
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1611
  }
1612
  else {
1613
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1614
    return '';
1615
  }
1616
}
1617

    
1618
/**
1619
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1620
 * which has two fields, one for the page title and one for the content. Later on in the
1621
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1622
 * function as the function parameters $title and $content.
1623
 *
1624
 * @param string $uuid
1625
 *   the uuid of the taxon to show
1626
 * @param string $chapter
1627
 *   Name of the part to display, valid values are:
1628
 *   'description', 'images', 'synonymy', 'all'.
1629
 *
1630
 * @return object with the following fields:
1631
 *   - title : the title of the page
1632
 *   - content: the content of the page
1633
 *
1634
 * @throws Exception
1635
 *
1636
 */
1637
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1638
  // Taxon object.
1639
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1640
  if (empty($taxon)) {
1641
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1642
    return null;
1643
  }
1644
  $taxonpage = new stdClass();
1645

    
1646
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1647
    'taxon' => $taxon
1648
  ));
1649

    
1650
  // Check if the taxon id contained in the currently selected tree.
1651
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1652

    
1653
  if (!$taxon_in_current_classification) {
1654
    $classifications = get_classifications_for_taxon($taxon);
1655
    RenderHints::pushToRenderStack('not_in_current_classification');
1656
    $taxon_name_markup = render_taxon_or_name($taxon);
1657

    
1658
    if (count($classifications) == 0) {
1659
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1660
        array(
1661
        '!taxonname' => $taxon_name_markup,
1662
        )
1663
      ), 'warning');
1664
    }
1665
    else {
1666
      $trees = '';
1667
      foreach ($classifications as $classification) {
1668
        if (isset($classification->titleCache)) {
1669
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1670
        }
1671
      }
1672

    
1673
      drupal_set_message(format_plural(count($trees),
1674
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1675
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1676
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1677
        ) ,
1678
        'warning');
1679
    }
1680
    RenderHints::popFromRenderStack();
1681
  }
1682

    
1683
  // Render the taxon page.
1684
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1685
  $taxonpage->content = drupal_render($render_array);
1686

    
1687
  return $taxonpage;
1688
}
1689

    
1690
/**
1691
 * Creates a specimen page view.
1692
 * @param string $uuid the UUID of the specimen
1693
 * @return array|string
1694
 */
1695
function cdm_dataportal_specimen_page_view($uuid) {
1696

    
1697
    //cdm_check_valid_taxon_page($chapter);
1698
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1699
    // show a warning in case the javascript development mode is anabled
1700
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1701
        drupal_set_message(t('The !url1 is enabled.
1702
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1703
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1704
        )),
1705
            'warning'
1706
        );
1707
    }
1708

    
1709
    // Display the page for the specimen defined by $uuid.
1710
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1711
    if (!empty($specimenpage)) {
1712
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1713
    }
1714
    else {
1715
        return '';
1716
    }
1717
}
1718

    
1719
/**
1720
 *
1721
 * Creates a specimen view.
1722
 * @param string $uuid the UUID of the specimen
1723
 * @return array|string
1724
 */
1725
function cdm_dataportal_specimen_view($uuid) {
1726
    //TODO: get the derivateDTO and don't call the webservice a second time in compose_cdm_specimen_page
1727
    $specimen = cdm_ws_get(CDM_WS_PORTAL_OCCURRENCE, $uuid);
1728
    if (empty($specimen)) {
1729
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1730
        return FALSE;
1731
    }
1732
    $specimenpage = new stdClass();
1733

    
1734
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1735
        'specimen' => $specimen
1736
    ));
1737

    
1738
    // Render the specimen page.
1739
    $render_array = compose_cdm_specimen_page($specimen);
1740
    $specimenpage->content = drupal_render($render_array);
1741

    
1742
    return $specimenpage;
1743
}
1744

    
1745
/**
1746
 *
1747
 * Creates a named area view.
1748
 * @param string $uuid the UUID of the specimen
1749
 *  * @return object
1750
 *   An object with two fields:
1751
 *     - title: the page title
1752
 *     - content: the page content
1753
 */
1754

    
1755
function cdm_dataportal_named_area_view($uuid) {
1756
  $named_area = cdm_ws_get(CDM_WS_PORTAL_TERM, $uuid);
1757
  if (empty($named_area) || $named_area->class !== 'NamedArea') {
1758
    drupal_set_title(t('Named area does not exist'), PASS_THROUGH);
1759
    return FALSE;
1760
  }
1761
  $named_area_page = new stdClass();
1762

    
1763
  $named_area_page->title = $named_area->representation_L10n;
1764

    
1765
  // Render the specimen page.
1766
  $render_array = compose_cdm_named_area_page($uuid);
1767
  $named_area_page->content = drupal_render($render_array);
1768

    
1769
  return $named_area_page;
1770
}
1771

    
1772
function cdm_dataportal_named_area_page_view($uuid) {
1773

    
1774
  cdm_check_valid_portal_page();
1775

    
1776
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1777
  if (!empty($named_area_page)) {
1778
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1779
  }
1780
  else {
1781
    return '';
1782
  }
1783

    
1784

    
1785
}
1786

    
1787
/**
1788
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1789
 *
1790
 * The node page shows the taxon name title and the list of taxon related
1791
 * with such taxon. Name on the tree already in use.
1792
 *
1793
 * @param string $taxon_name_uuid
1794
 *   The uuid of the CDM TaxonName to show a name page for
1795
 * @param string $taxon_to_hide_uuid
1796
 *   A taxon which should not be displayed in the taxon list
1797
 * @param string $highlite_synonym_uuid
1798
 *   Optinal parameter wich takes another taxon uuid, if given the
1799
 *   target taxon pages will show the syonymy tab where the taxon
1800
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1801
 *   in case it is found on this page.
1802
 *
1803
 * @return mixed
1804
 *   The formatted name page as node.
1805
 */
1806
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1807

    
1808
  cdm_check_valid_portal_page();
1809

    
1810
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1811
  if (!empty($taxonname_page)) {
1812
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1813
  }
1814
  else {
1815
    return '';
1816
  }
1817
}
1818

    
1819
/**
1820
 * View function for a TaxonName page.
1821
 *
1822
 * The name page lists all taxa for which the name specified by the
1823
 * $taxon_name_uuid is being used. I case there is only one name the
1824
 * page automatically redirects ti the according taxon page. Otherwise
1825
 * the list of names is displayed.
1826
 *
1827
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1828
 * list of taxa. This is useful for example when referencing from a taxon
1829
 * to the name page and the referring taxon should not be repeaded in the
1830
 * name page.
1831
 *
1832
 *
1833
 * @param string $taxon_name_uuid
1834
 *   The uuid of the CDM TaxonName to show a name page for
1835
 * @param string $taxon_to_hide_uuid
1836
 *   A taxon which should not be displayed in the taxon list
1837
 * @param string $highlite_synonym_uuid
1838
 *   Optinal parameter wich takes another taxon uuid, if given the
1839
 *   target taxon pages will show the syonymy tab where the taxon
1840
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1841
 *   in case it is found on this page.
1842
 *
1843
 * @return object
1844
 *   An object with two fields:
1845
 *     - title: the page title
1846
 *     - content: the page content
1847
 */
1848
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1849
  // Getting the full taxonname object from the server.
1850
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1851
  if (!$taxon_name) {
1852
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1853
    return FALSE;
1854
  }
1855
  // Searching for all the taxa connected with the taxon name on the tree
1856
  // in use.
1857
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1858
  $request_params = array();
1859
  $request_params['query'] = $name_cache;
1860
  $request_params['tree'] = get_current_classification_uuid();
1861
  $request_params['doTaxa'] = 1;
1862
  $request_params['doSynonyms'] = 1;
1863
  $request_params['doTaxaByCommonNames'] = 0;
1864
  $request_params['matchMode'] = "EXACT";
1865
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1866

    
1867
  // Removing the name where we came from.
1868
  foreach ($taxon_pager->records as $k => &$taxon) {
1869
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1870
      unset($taxon_pager->records[$k]);
1871
    }
1872
  }
1873
  // Show the taxa list or go to the singular taxon.
1874
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1875
    $singleTaxon = array_pop($taxon_pager->records);
1876
    if ($singleTaxon->class != "Taxon") {
1877
      // It is a Synonym -> look for the accepted.
1878
      $accepted_taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid), 'classificationFilter=' . get_current_classification_uuid());
1879
      if (!empty($highlite_synonym_uuid)) {
1880
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1881
      }
1882
      else {
1883
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxon->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1884
      }
1885
    }
1886
    else {
1887
      // It is an accepted taxon.
1888
      if (!empty($highlite_synonym_uuid)) {
1889
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1890
      }
1891
      else {
1892
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1893
      }
1894
    }
1895
  }
1896
  else {// More than one taxa case.
1897
    $taxon_name_page = new stdClass();
1898
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1899
    if ($taxon_pager->records) {
1900
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1901
    }
1902
    else {
1903
      $taxon_name_page->content = 'This name is not assigned to a taxon.';
1904
    }
1905
    return $taxon_name_page;
1906
  }
1907
}
1908

    
1909
/**
1910
 * Returns a registration page as a Drupal node to be rendered by Drupal.
1911
 *
1912
 * @param string  $registration_identifier_encoded
1913
 *   The persistent identifier of the registration urlencoded.
1914
 * @return mixed
1915
 *   The formatted registration page as node.
1916
 */
1917
function cdm_dataportal_registration_page_view($registration_identifier_encoded) {
1918

    
1919
  cdm_check_valid_portal_page("/\/cdm_dataportal\/registration\/.*$/");
1920
  $registration_page = cdm_dataportal_registration_view($registration_identifier_encoded);
1921
  return cdm_node_show_simulate($registration_page);
1922
}
1923

    
1924
function cdm_dataportal_registration_view($registration_identifier_encoded) {
1925

    
1926
  $registration_identifier = urldecode($registration_identifier_encoded);
1927

    
1928

    
1929

    
1930
  $render_array = array();
1931
  $registration_dto = cdm_ws_get("registrationDTO/identifier/" . $registration_identifier_encoded);
1932
  if($registration_dto){
1933
    drupal_set_title(t('Registration') . ' ' . $registration_identifier, PASS_THROUGH);
1934

    
1935
    $render_array = compose_registation_dto($registration_dto);
1936

    
1937
    if($registration_dto->nameRef){
1938
      $name_relations = cdm_ws_fetch_all(str_replace("$0", $registration_dto->nameRef->uuid, CDM_WS_PORTAL_NAME_NAME_RELATIONS));
1939
      $render_array['name_relations'] = markup_to_render_array(render_name_relationships_of($name_relations, $registration_dto->nameRef->uuid, null, false));
1940
    }
1941

    
1942
    if(is_object($registration_dto->orderdTypeDesignationWorkingSets)){
1943
      $field_unit_uuids = array();
1944
      foreach((array)$registration_dto->orderdTypeDesignationWorkingSets as $field_unit_ref => $obj){
1945
        $tokens = explode("#", $field_unit_ref);
1946
        $field_unit_uuids[] = $tokens[1];
1947
      }
1948
      $render_array['specimen_table'] = compose_specimen_table($field_unit_uuids);
1949
    }
1950

    
1951
  } else {
1952
    drupal_set_title(t('Registration not found'), PASS_THROUGH);
1953
    $render_array['error'] = markup_to_render_array("A registration with the identifier  " . $registration_identifier . " does not exist.");
1954
  }
1955

    
1956
  return $render_array ;
1957
}
1958

    
1959
/**
1960
 * Composes information for a registation from a dtp object
1961
 *
1962
 * @param $registration_dto
1963
 *
1964
 * @return array
1965
 *    A drupal render array
1966
 *
1967
 * @ingroup compose
1968
 */
1969
function compose_registation_dto($registration_dto, $with_citation = true, $with_identifier = false)
1970
{
1971
  $render_array = array();
1972
  $media_link_map = array();
1973
  if($registration_dto->registrationDate){
1974
    $date_string = format_datetime($registration_dto->registrationDate);
1975
    if(isset($registration_dto->institutionTitleCache)){
1976
      $registration_date_insitute_markup =
1977
        t("Registration at @date in @institution", array(
1978
          '@date' => $date_string,
1979
          '@institution' => $registration_dto->institutionTitleCache,
1980
        ));
1981
    } else {
1982
      $registration_date_insitute_markup =
1983
        t("Registration at @date", array(
1984
          '@date' => $date_string
1985
        ));
1986
    }
1987
    $render_array['publication_date_and_office'] = markup_to_render_array('<p>'.$registration_date_insitute_markup . '</p>', -100);
1988
  }
1989
  $taggged_text_expanded = cdm_tagged_text_expand_entity_references($registration_dto->summaryTaggedText);
1990
  foreach ($taggged_text_expanded  as $tagged_text){
1991
    if(isset($tagged_text->entityReference->type) && $tagged_text->entityReference->type == 'SpecimenTypeDesignation') {
1992
      $mediaDTOs = cdm_ws_get('typedesignation/$0/media', array($tagged_text->entityReference->uuid));
1993
      if(isset($mediaDTOs[0]->uri)){
1994
          $media_url_key = '{link-' . $mediaDTOs[0]->uuid . '}';
1995
          $tagged_text->text = str_replace('[icon]', '[icon]' . $media_url_key, $tagged_text->text);
1996
          $media_link_map[$media_url_key] =  cdm_external_uri($mediaDTOs[0]->uri, true);
1997
      }
1998
    }
1999
  }
2000
  $registation_markup = cdm_tagged_text_to_markup($taggged_text_expanded);
2001
  foreach($media_link_map as $media_url_key => $link){
2002
    $registation_markup = str_replace($media_url_key, $link, $registation_markup);
2003
  }
2004
  if($with_identifier){
2005
    $registation_markup .= " " . l ($registration_dto->identifier, $registration_dto->identifier);
2006
  }
2007
  $render_array['summary'] = markup_to_render_array("<div>" . $registation_markup . "</div>");
2008

    
2009
  if ($with_citation) {
2010
    $render_array['citation'] = markup_to_render_array("<div class=\"" . html_class_attribute_ref(new TypedEntityReference("Reference", $registration_dto->citationUuid)) . "\">"
2011
      . l($registration_dto->bibliographicCitationString, path_to_reference($registration_dto->citationUuid))
2012
      . "</br>&nbsp;</div>");
2013
  }
2014

    
2015
  return $render_array;
2016
}
2017

    
2018

    
2019
/**
2020
 * Creates a page with the advance search form.
2021
 *
2022
 * NOTE: The advance search form allows searching for taxa.
2023
 */
2024
function cdm_dataportal_view_search_advanced() {
2025
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
2026
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
2027
}
2028

    
2029
/**
2030
 * Creates a page with the search form for searching by taxon descriptions.
2031
 */
2032
function cdm_dataportal_view_search_taxon_by_description() {
2033
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
2034
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
2035
}
2036

    
2037
/**
2038
 * Executes the search and generates the result list of taxa.
2039
 */
2040
function cdm_dataportal_view_search_results_taxon() {
2041

    
2042
  $taxonPager = cdm_dataportal_search_taxon_execute();
2043

    
2044
  $showThumbnails = do_showThumbnails();
2045

    
2046
  $setSessionUri = url('cdm_api/setvalue/session', array(
2047
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
2048
  ));
2049

    
2050
  drupal_add_js('jQuery(document).ready(function() {
2051

    
2052
      // init
2053
      if(' . $showThumbnails . ' == 1){
2054
          jQuery(\'.media_gallery\').show(20);
2055
      } else {
2056
          jQuery(\'.media_gallery\').hide(20);
2057
      }
2058

    
2059
      // add change handler
2060
      jQuery(\'#showThumbnails input.showThumbnails\').change(
2061
      function(event){
2062
        var state = 0;
2063
        if(jQuery(this).is(\':checked\')){
2064
          jQuery(\'.media_gallery\').show(20);
2065
          state = 1;
2066
        } else {
2067
          jQuery(\'.media_gallery\').hide(20);
2068
        }
2069
        // store state in session variable
2070
        var uri = \'' . $setSessionUri . '\' + state;
2071
        jQuery.get(uri);
2072
      });
2073
  });',
2074
  array('type' => "inline", 'scope' => JS_DEFAULT));
2075

    
2076
  drupal_set_title(t('Search results'), PASS_THROUGH);
2077

    
2078
  return theme('cdm_search_taxa_results', array(
2079
    'pager' => $taxonPager,
2080
    'path' => 'cdm_dataportal/search/results/taxon',
2081
    ));
2082
}
2083

    
2084
/**
2085
 * Executes the search for registrations and generates the result list..
2086
 */
2087
function cdm_dataportal_view_search_registrations_results($mode = 'filter') {
2088

    
2089
  switch($mode ){
2090
    case 'taxongraph':
2091
      $block = block_load('cdm_dataportal', 'registrations_search_taxongraph');
2092
      $registration_pager = cdm_dataportal_search_registrations_taxongraph_execute();
2093
      break;
2094
    case 'filter':
2095
    default:
2096
      $block = block_load('cdm_dataportal', 'registrations_search_filter');
2097
      $registration_pager = cdm_dataportal_search_registrations_filter_execute();
2098
  }
2099
  $block->title = null;
2100

    
2101
  drupal_set_title(t('Search registrations'), PASS_THROUGH);
2102

    
2103
  $render_array = _block_get_renderable_array(_block_render_blocks(array($block)));
2104
  $registrations_pager_array = compose_registrations_search_results($registration_pager);
2105
  $render_array = array_merge($render_array, $registrations_pager_array);
2106

    
2107
  return $render_array;
2108
}
2109

    
2110

    
2111
/**
2112
 * Provides the standart image wich indicated a loading process
2113
 *
2114
 * @return string
2115
 *  The img html tag
2116
 */
2117
function loading_image_html() {
2118
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
2119
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
2120
}
2121

    
2122
/**
2123
 * Returns the state of the the showThumbnails flag set in the
2124
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
2125
 *
2126
 * @return boolean
2127
 *    returns 1 if the flag is set
2128
 */
2129
function do_showThumbnails() {
2130
  static $showThumbnails = null;
2131

    
2132
  if($showThumbnails == null) {
2133
    $showThumbnails = 0;
2134
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
2135
      $showThumbnails = 0;
2136
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
2137
      $showThumbnails = is_array($search_gallery_settings)
2138
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
2139
        && (
2140
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
2141
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
2142
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
2143
            )
2144
         ? 1 : 0;
2145

    
2146
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
2147
    }
2148
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
2149
    if (!is_numeric($showThumbnails)) {
2150
      $showThumbnails = 1;
2151
    }
2152
  }
2153

    
2154
  return $showThumbnails;
2155
}
2156

    
2157

    
2158

    
2159
/* ====================== other functions ====================== */
2160
/**
2161
 * Creates a URL to the taxon page specified by the $uuid parameter.
2162
 *
2163
 * The URL will be prepended with a path element to a specific taxon page tab.
2164
 *
2165
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
2166
 * be set globally in the administrative settings or individually in the user
2167
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
2168
 * the last portal will stay on this last tab.
2169
 *
2170
 * A third option is offerered by the $page_tab parameter which allows overwriting this
2171
 * internal mechanism by a specific value.
2172
 *
2173
 * @param string $uuid
2174
 *   The UUID of the taxon.
2175
 * @param string $page_tab
2176
 *   Overwriting the preset mechanism by defining specific value for the
2177
 *   taxon page tab.
2178
 *
2179
 * @return string
2180
 *   The created URL.
2181
 */
2182
function path_to_taxon($uuid, $page_tab = FALSE) {
2183

    
2184
  $tab = get_default_taxon_tab();
2185
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
2186

    
2187
  if (!$uuid) {
2188
    return FALSE;
2189
  }
2190

    
2191
  if ($page_tab) {
2192
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
2193
  }
2194
  elseif (!$tab || strtolower($tab) == 'general') {
2195
    return 'cdm_dataportal/taxon/' . $uuid;
2196
  }
2197
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
2198
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
2199
  }
2200
  else {
2201
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
2202
  }
2203
}
2204

    
2205
function path_to_specimen($uuid) {
2206

    
2207
    if (!$uuid) {
2208
        return FALSE;
2209
    }
2210
    else {
2211
        return 'cdm_dataportal/specimen/' . $uuid;
2212
    }
2213
}
2214

    
2215
function path_to_named_area($uuid) {
2216

    
2217
  if (!$uuid) {
2218
    return FALSE;
2219
  }
2220
  else {
2221
    return 'cdm_dataportal/named_area/' . $uuid;
2222
  }
2223
}
2224

    
2225
/**
2226
 * Creates a URL to show a synonmy in the according taxon page.
2227
 *
2228
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
2229
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
2230
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
2231
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
2232
 * in the page
2233
 *
2234
 * @param string $synonymUuid
2235
 *    The uuid of the synonym
2236
 * @param string $acceptedUuid
2237
 *    The uuid of the according accepted taxon
2238
 * @return string
2239
 *    The URL to show a synonmy in the according taxon page
2240
 */
2241
function uri_to_synonym($synonymUuid, $acceptedUuid) {
2242
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
2243
  return url($acceptedPath, array(
2244
      'query' => array(
2245
        // highlite the synony in the synonymy
2246
        'highlite' => $synonymUuid,
2247
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
2248
        // see theme_taxon_page_title()
2249
        'acceptedFor' => $synonymUuid
2250
      ),
2251
      'fragment' => $synonymUuid
2252
  ));
2253

    
2254
}
2255

    
2256
/**
2257
 * Composes the drupal path to the key identified by the uuid.
2258
 *
2259
 * @param string $keyType
2260
 *    the key typer corresponds to the specific class of the CDM
2261
 *    IdentificationKey. Possible values are
2262
 *      -PolytomousKey
2263
 *      -MultimediaKey
2264
 *      - ...
2265
 * @param string $keyUuid
2266
 *   The UUID of the key
2267
 */
2268
function path_to_key($keyType, $keyUuid) {
2269
  if (!$keyUuid || !$keyType) {
2270
    return FALSE;
2271
  }
2272
  $keyType{0} = strtolower($keyType{0});
2273
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
2274
}
2275

    
2276
/**
2277
 * Composes the drupal path to the reference identified by the uuid.
2278
 *
2279
 * @param $uuid string String representation of the registration entity uuid.
2280
 *
2281
 * @return string
2282
 *  The drupal path
2283
 *
2284
 */
2285
function path_to_reference($uuid) {
2286
  if (!$uuid) {
2287
    return FALSE;
2288
  }
2289
  return 'cdm_dataportal/reference/' . $uuid;
2290
}
2291

    
2292
/**
2293
 * Composes the drupal path to the reference identified by the uuid.
2294
 *
2295
 * @param string $identifier
2296
 *  The persistent identifier of the registration entity (Registration.identifier).
2297
 * @return string
2298
 *  The drupal path
2299
 */
2300
function path_to_registration($identifier) {
2301

    
2302
  return 'cdm_dataportal/registration/' . urlencode($identifier);
2303
}
2304

    
2305
/**
2306
 * Creates the path to a cdm_dataportal taxon name page.
2307
 *
2308
 * @param string $taxon_name_uuid
2309
 *   The uuid as string of the CDM TaxonName to show a name page for
2310
 * @param string $taxon_to_hide_uuid
2311
 *   The uuid as string of a taxon which should not be displayed in the taxon list
2312
 * @param string $highlited_synonym_uuid
2313
 *   Optional parameter which takes another taxon uuid, if given the
2314
 *   target taxon pages will show the synonymy tab where the taxon
2315
 *   referenced by the $highlite_synonym_uuid will be highlighted
2316
 *   in case it is found on this page.
2317
 *
2318
 * @return string
2319
 *  URI path element as string
2320
 */
2321
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $highlited_synonym_uuid  = NULL) {
2322
  $res = FALSE;
2323
  if ($name_uuid) {
2324
    $res = 'cdm_dataportal/name/' . $name_uuid;
2325
  }
2326
  if($taxon_to_hide_uuid){
2327
    $res .= '/' . $taxon_to_hide_uuid;
2328
    if($highlited_synonym_uuid){
2329
      $res .= '/' . $highlited_synonym_uuid;
2330
    }
2331
  }
2332
  return $res;
2333
}
2334

    
2335
/**
2336
 * Composes the drupal path to the media entity identified by the uuid.
2337
 *
2338
 * @param string $uuid
2339
 *  The persistent identifier of the entity entity
2340
 * @return string
2341
 *  The drupal path
2342
 */
2343
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2344
  if (!$uuid) {
2345
    return FALSE;
2346
  }
2347
  $out = 'cdm_dataportal/media/' . $uuid;
2348
  if ($representaion_uuid) {
2349
    $out .= '/' . $representaion_uuid;
2350
    if (is_numeric($partId)) {
2351
      $out .= '/' . $partId;
2352
    }
2353
  }
2354
  return $out;
2355
}
2356

    
2357
/**
2358
 * Compares thisRank with thatRank.
2359
 *
2360
 * Returns a negative integer, zero, or a positive integer
2361
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2362
 * e.g:
2363
 * <ul>
2364
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2365
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2366
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2367
 * </ul>
2368
 * <p>
2369
 * This compare logic of the underlying webservice is the
2370
 * <b>inverse logic</b> of the the one implemented in
2371
 * java.lang.Comparable#compareTo(java.lang.Object)
2372
 *
2373
 * @param $thisRankUuid
2374
 * @param $thatRankUuid
2375
 *
2376
 * @return int
2377
 *   A negative integer, zero, or a positive integer
2378
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2379
 */
2380
function rank_compare($thisRankUuid, $thatRankUuid) {
2381
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2382
  return $result->Integer;
2383
}
2384

    
2385
/**
2386
 * Composes an HTML element class attribute value composed of
2387
 * the short-name of the cdm class and the uuid of the entity.
2388
 * This class attribute should be used wherever an cdm-entity is rendered.
2389
 *
2390
 * In case of Taxon entities or TaxonNodeDTOs the secReference is also added
2391
 * to the class attributes as 'sec_uuid:<uuid>'. In case of TaxonNodeDTOs the
2392
 * Taxon uuid is added also as taxon_uuid:<uuid>
2393
 *
2394
 * These according class selectors in css must be escaped, eg:
2395
 *    .cdm\:TextData
2396
 *
2397
 * @param $cdm_entity
2398
 *    A CDM entity, TaxonNodeDTO or TypedEntityReference
2399
 */
2400
function html_class_attribute_ref($cdm_entity) {
2401

    
2402
  $attributes = '';
2403
  if (is_cdm_entity($cdm_entity)) {
2404
    $attributes =  "cdm:" . $cdm_entity->class . " uuid:" . $cdm_entity->uuid;
2405
  } else if($cdm_entity->class == 'TypedEntityReference') {
2406
    $attributes =  "cdm:" . $cdm_entity->type . " uuid:" . $cdm_entity->uuid;
2407
  }
2408
  if($cdm_entity->class == 'TaxonNodeDto'){
2409
    $attributes .= " taxon_uuid:"  . $cdm_entity->taxonUuid . " sec_uuid:"  . $cdm_entity->secUuid;;
2410
  }
2411
  if($cdm_entity->class == 'Taxon' && isset($cdm_entity->sec->uuid)){
2412
    $attributes .= " sec_uuid:"  . $cdm_entity->sec->uuid;
2413
  }
2414
  return $attributes;
2415
}
2416

    
2417

    
2418
/**
2419
 * Creates a short version of a taxonname.
2420
 *
2421
 * The short name is created by using the taggedTitle field of
2422
 * TaxonNodeDTO instances.
2423
 * If the taggedTitle if empty the fullname will be returned.
2424
 *
2425
 * @param object $taxonNodeDTO
2426
 *   A TaxonNodeDTO object
2427
 *
2428
 * @return string
2429
 */
2430
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2431

    
2432
  $nameStr = '';
2433

    
2434
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2435

    
2436
  // Get all tagged text tokens of the scientific name.
2437
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2438
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2439
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2440
    }
2441
  }
2442
  $nameStr = trim($nameStr);
2443

    
2444
  if ($nameStr) {
2445

    
2446
    // Do not return short names for these.
2447
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2448
      return $nameStr;
2449
    }
2450

    
2451
    /*
2452
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2453
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2454
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2455
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2456
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2457
    */
2458
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2459
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2460
      return $matches[1][0] . "." . $matches[3][0];
2461
    }
2462
    else {
2463
      return $nameStr;
2464
    }
2465
  }
2466
  else {
2467
    return $taxonNodeDTO->titleCache;
2468
  }
2469
}
2470

    
2471
/**
2472
 * Check if a taxon is accepted by the current taxonomic tree.
2473
 *
2474
 * @param mixed $taxon
2475
 *   The Taxon obkect to check.
2476
 *
2477
 * @return bool
2478
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2479
 */
2480
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2481

    
2482
  $defaultTreeUuid = get_current_classification_uuid();
2483

    
2484
  if (isset($taxon->taxonNodes)) {
2485
    $taxonNodes = $taxon->taxonNodes;
2486
  }
2487
  else {
2488
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2489
  }
2490

    
2491
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2492
    foreach ($taxonNodes as $node) {
2493
      if (isset($node->classification)){
2494
        if(is_object($node->classification)) {
2495
          if ($node->classification->uuid == $defaultTreeUuid) {
2496
            return TRUE;
2497
          }
2498
        }
2499
        else {
2500
          if ($node->classification == $defaultTreeUuid) {
2501
            return TRUE;
2502
          }
2503
        }
2504
      }
2505
    }
2506
  }
2507

    
2508
  return FALSE;
2509
}
2510

    
2511
/**
2512
 * Checks is the source has one of the given types.
2513
 *
2514
 * @param object $source
2515
 *   The original source entity
2516
 * @param array $types
2517
 *   An array of elementd of the OriginalSourceType enumeration
2518
 *   If not set the default will be used which is:
2519
 *    - Lineage
2520
 *    - PrimaryMediaSource
2521
 *    - PrimaryTaxonomicSource
2522
 *    - Unknown
2523
 *    - Other
2524
 * @return boolean
2525
 */
2526
  function _is_original_source_type($source, $types = null) {
2527
    // this is the default
2528
    // maybe this should also be put into the settings
2529
    static $default = array(
2530
      OriginalSourceType::Lineage,
2531
      OriginalSourceType::PrimaryMediaSource,
2532
      OriginalSourceType::PrimaryTaxonomicSource,
2533
      OriginalSourceType::Unknown,
2534
      OriginalSourceType::Other,
2535
    );
2536

    
2537
    if(!$types){
2538
      $types = $default;
2539
    }
2540
    return isset($source->type) && in_array($source->type, $types);
2541
  }
2542

    
2543
/**
2544
 * Collects all the media from a list of description elements.
2545
 *
2546
 * @param array $descriptionElements
2547
 *   The description elements from which to collect the media.
2548
 *
2549
 * @return array
2550
 *   The output with all the collected media.
2551
 */
2552
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2553

    
2554
  $outArrayOfMedia = array();
2555

    
2556
  // Avoiding a warning box in Drupal for Flora Malesiana.
2557
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2558
    foreach ($descriptionElements as $descriptionElement) {
2559
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2560
        foreach ($descriptionElement->media as $media) {
2561
          if (is_object($media)) {
2562
            $outArrayOfMedia[] = $media;
2563
          }
2564
        }
2565
      }
2566
    }
2567
  }
2568
  return $outArrayOfMedia;
2569
}
2570

    
2571
/**
2572
 * @todo Please document this function.
2573
 * @see http://drupal.org/node/1354
2574
 *
2575
 * @param array $cdm_entities
2576
 *   An array of CdmBase instances or a single instance.
2577
 * @param string $footnote_list_key_suggestion
2578
 *
2579
 * @return unknown
2580
 */
2581
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2582

    
2583
   static $annotations_types_filter = null;
2584
   if(!$annotations_types_filter) {
2585
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2586
   }
2587

    
2588
  $footNoteKeys = array();
2589

    
2590
  // Is argument cdmBase an array?
2591
  if (!is_array($cdm_entities)) {
2592
    $cdmBase_array = array();
2593
    $cdmBase_array[] = $cdm_entities;
2594
  }
2595
  else {
2596
    $cdmBase_array = $cdm_entities;
2597
  }
2598

    
2599
  // Getting the key for the footnotemanager.
2600
  if (isset($footnote_list_key_suggestion)) {
2601
    $footnote_list_key = $footnote_list_key_suggestion;
2602
  }
2603
  else {
2604
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2605
  }
2606

    
2607
  // Adding the footnotes keys.
2608
  foreach ($cdmBase_array as $cdmBase_element) {
2609
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2610
    if (is_array($annotations)) {
2611
      foreach ($annotations as $annotation) {
2612
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2613
      }
2614
    }
2615
  }
2616

    
2617
  return $footNoteKeys;
2618
}
2619

    
2620

    
2621
/**
2622
 * Creates a CDM Dynabox.
2623
 *
2624
 * @param string $dynabox_id
2625
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2626
 * @param string $label
2627
 *   The clickable text to show.
2628
 * @param string $content_url
2629
 *   The cdm REST service request url wich will deliver the content to be shown
2630
 *   once the dynabox toggles open.
2631
 * @param string $theme
2632
 *   The theme to be used for rendering the cdm REST service response with is
2633
 *   returned from the $content_url.
2634
 * @param string $link_alt_text
2635
 *   The value for the alt attribute of the dynabox link.
2636
 * @param array $enclosingtags
2637
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2638
 *   element itself, $enclosingtags[1] is the tag to be used for the
2639
 *   dynabox_content (optional)
2640
 * @param array $attributes
2641
 * @param $content_element_selector
2642
 *   Optional jQuery selector which can be used to reference a dom element which should
2643
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2644
 *  element will be placed in this container.
2645
 *
2646
 * @param string $open_callback
2647
 *   optional javascript call back function to be triggered after toggling the box to
2648
 *   the open state.
2649
 * @param string $close_callback
2650
 *   optional javascript call back function to be triggered after toggling the box to
2651
 *   the closed state.
2652
 * @return string Returns HTML for a dynabox.
2653
 * Returns HTML for a dynabox.
2654
 */
2655
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2656
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2657
                     $content_element_selector = null,
2658
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2659
  $out = '';
2660

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

    
2664
  if(!array_key_exists('class', $attributes)) {
2665
    $attributes['class'] = array();
2666
  }
2667
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2668
  $dynabox_attributes = drupal_attributes($attributes);
2669

    
2670

    
2671
  _add_js_domEvent(); // requires domEvent.js
2672
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2673
  drupal_add_js("
2674
  jQuery(document).ready(
2675
      function() {
2676
        dynabox('". $dynabox_id ."',
2677
          {
2678
            open_callback: " . $open_callback .",
2679
            close_callback: " . $close_callback .
2680
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2681
          }
2682
        );
2683
      }
2684
   );",
2685
   array(
2686
    'type'=>'inline',
2687
    'scope'=>'footer'
2688
    )
2689
  );
2690

    
2691

    
2692
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2693
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2694
  $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>';
2695
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2696
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2697
  $out .= '    </' . $enclosingtags[1] . '>';
2698
  $out .= '  </' . $enclosingtags[0] . '>';
2699
  $out .= '<!-- dynabox end -->';
2700
  return $out;
2701
}
2702

    
2703
/**
2704
 * Checks whether a feature has any description elements.
2705
 *
2706
 * @param mixed $featureNode
2707
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2708
 *
2709
 * @see _mergeFeatureTreeDescriptions()
2710
 *
2711
 * @return bool
2712
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2713
 *   contains at least one non empty TextData or at least one DescriptionElement
2714
 *   of an other type. A TextData element holding a multilanguageText or a
2715
 *   source reference is considered to be not empty.
2716
 *
2717
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2718
 *       see $block_content_is_not_empty in make_feature_block_list() and
2719
 *       $feature_block_has_content in compose_feature_block_items_generic
2720
 */
2721
function has_feature_node_description_elements($featureNode) {
2722

    
2723
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2724
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2725
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2726
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2727
          && $descriptionElement->multilanguageText_L10n->text != ''
2728
          || isset($descriptionElement->sources[0])
2729
          || isset($descriptionElement->media[0]) ) {
2730
          return TRUE;
2731
        }
2732
      }
2733
    }
2734
  }
2735
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2736
    foreach ($featureNode->childNodes as $child) {
2737
      if (has_feature_node_description_elements($child)) {
2738
        return TRUE;
2739
      }
2740
    }
2741
  }
2742
  return FALSE;
2743
}
2744

    
2745
/**
2746
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2747
 *
2748
 * @param $chapter
2749
 *   The taxon page chapter or part
2750
 */
2751
function cdm_check_valid_taxon_page($chapter){
2752
  static $taxon_tabs = null;
2753

    
2754
  cdm_check_valid_portal_page();
2755

    
2756
  if($taxon_tabs == null){
2757
    $taxon_tabs = array('all', 'description');
2758
    foreach(get_taxon_tabs_list() as $tab){
2759
      $taxon_tabs[] = strtolower($tab);
2760
    }
2761
  }
2762

    
2763
  if(!in_array($chapter, $taxon_tabs)){
2764
    // oops this is not a valid chapter name
2765
    http_response_code(404); // 404 = Not Found
2766
  }
2767

    
2768
}
2769

    
2770
/**
2771
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise.
2772
 * The test applied by default it a check for the query parameter 'q' ending with a file suffix like '*.*'
2773
 *
2774
 * @param $preg_pattern
2775
 *   Optional regular expression pattern to be used in preg_match().
2776
 */
2777
function cdm_check_valid_portal_page($preg_pattern = null){
2778
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2779
  if($preg_pattern === null){
2780
    $preg_pattern = $ends_with_file_suffix_pattern;
2781
  }
2782
  if(preg_match($preg_pattern, $_GET['q'])){
2783
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2784
    http_response_code(404); // 404 = Not Found
2785
    exit('HTTP 404');
2786
  }
2787
}
2788

    
2789
/**
2790
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2791
 *
2792
 * @param $text_a
2793
 * @param $text_b
2794
 * @return string
2795
 */
2796
function diff_viewer($text_a, $text_b) {
2797

    
2798
  static $diff_viewer_count = 0;
2799

    
2800
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2801

    
2802
  // http://code.stephenmorley.org/php/diff-implementation/
2803
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2804
  drupal_add_css(drupal_get_path('module',
2805
      'cdm_dataportal') . '/css/diff.css');
2806
  _add_jquery_ui();
2807
  drupal_add_js(
2808
    'jQuery(document).ready( function(){
2809
        jQuery(\'#' . $element_id . '\').accordion({
2810
        collapsible: true,
2811
        active: false,
2812
        fillSpace: true,
2813
        }).children(\'div\').css({ \'height\': \'auto\' });
2814
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2815
     });'
2816
    , array(
2817
    'type' => 'inline',
2818
    'scope' => 'footer'
2819
  ));
2820

    
2821
  $diff = Diff::compare($text_a,
2822
    $text_b);
2823
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2824
    . Diff::toTable($diff, '', '')
2825
    . '</div></div>';
2826
  return $diff_viewer_markup;
2827
}
2828

    
2829

    
(10-10/18)