Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
201
  }
202

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

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

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

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

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

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

    
282
  global $base_url;
283

    
284

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

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

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

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

    
344

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

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

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

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

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

    
367
    return '';
368
  }
369

    
370

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
638
  return $items;
639
}
640

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

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

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

    
662
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
663

    
664
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
665

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

    
675
  $parameters['cacheL2_refresh'] ='1';
676

    
677

    
678
  drupal_goto($base_path, array('query' => $parameters));
679
}
680

    
681
/**
682
 * The function generate form for own user cdm dataportal configurations.
683
 */
684
function cdm_dataportal_user_form($form, &$form_state) {
685

    
686
  global $user;
687
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
688

    
689
  $form['taxon_page_tabs'] = array(
690
      '#type' => 'fieldset',
691
      '#tree' => true,
692
      '#title' => t('Taxon page tabs'),
693
  );
694

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

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

    
712

    
713
  if(false){
714
    $form['developer_options'] = array(
715
        '#type' => 'fieldset',
716
        '#tree' => true,
717
        '#title' => t('Developer options'),
718
    );
719

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

    
733
  $form['submit'] = array(
734
    '#type' => 'submit',
735
    '#value' => t('Submit'),
736
  );
737

    
738
  return $form;
739
}
740

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

    
752
  // FIXME: this is completely wrong, see user_profile_form_submit()
753

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

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

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

    
781
/**
782
 * Implements hook_block_info().
783
 */
784
function cdm_dataportal_block_info() {
785

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

    
812
    return $block;
813
}
814

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

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

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

    
884
  if(!isset($taxon_uuid)){
885
    if(isset($_REQUEST['currentTaxon']) && is_uuid($_REQUEST['currentTaxon'])) {
886
      $taxon_uuid = $_REQUEST['currentTaxon'];
887
    } else if (arg(1) == 'taxon' && is_uuid(arg(2))) {
888
      $taxon_uuid = arg(2);
889
    } else {
890
      $taxon_uuid = null;
891
    }
892
  }
893

    
894
  return $taxon_uuid;
895
}
896

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

    
912
/*
913
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
914
 $_SESSION['cdm'] = NULL;
915
 if(is_string($cdm_ws_uri_update)){
916
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
917
 }
918
 }
919

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

    
929
/**
930
 * creates a  selector form for taxonomic trees.
931
 *
932
 * @return array
933
 *  a drupal form array
934
 */
935
function cdm_taxonomictree_selector() {
936
  _add_js_treeselector();
937

    
938
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
939
  return $form;
940
}
941

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

    
950
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
951
  $form['#action'] = $url;
952

    
953
  $form['var'] = array(
954
    '#weight' => -3,
955
    '#type' => 'hidden',
956
    '#value' => '[cdm][taxonomictree_uuid]',
957
  );
958

    
959
  $destination_array = drupal_get_destination();
960
  $destination = $destination_array['destination'];
961

    
962
  $form['destination'] = array(
963
    '#weight' => -3,
964
    '#type' => 'hidden',
965
    '#value' =>  $destination,
966
  );
967

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

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

    
988
  return $form;
989

    
990
}
991

    
992
/**
993
 *
994
 * @ingroup compose
995
 */
996
function compose_classification_selector() {
997

    
998
  $destination_array = drupal_get_destination();
999
  $destination = $destination_array['destination'];
1000

    
1001
  $options = cdm_get_taxontrees_as_options();
1002
  $items = array();
1003
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
1004

    
1005
  $current_classification_uuid = get_current_classification_uuid();
1006

    
1007

    
1008
  foreach($options as $uuid=>$label){
1009
    if(!$taxontree_includes || !empty($taxontree_includes[$uuid])){
1010

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

    
1031
  $render_array = array(
1032
    '#theme' => 'item_list',
1033
    '#type' => 'ul',
1034
    '#items' => $items
1035
  );
1036

    
1037
  return $render_array;
1038
}
1039

    
1040

    
1041
/* UNREACHABLE since action of form directly links to view.
1042
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1043

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

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

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

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

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

    
1104
/**
1105
 * @todo Please document this function.
1106
 * @see http://drupal.org/node/1354
1107
 */
1108
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1109

    
1110
  cdm_check_valid_portal_page();
1111

    
1112
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1113
  return theme('cdm_reference_page', array('reference' => $reference));
1114
}
1115

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

    
1126
/**
1127
 * @todo Please document this function.
1128
 * @see http://drupal.org/node/1354
1129
 */
1130
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1131

    
1132
  cdm_check_valid_portal_page();
1133

    
1134
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1135
  return theme('cdm_media_page', array(
1136
    'media' => $media,
1137
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1138
    'partId' => $part,
1139
    ));
1140
}
1141

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

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

    
1170
  static $media = NULL;
1171

    
1172
  if(!isset($media)) {
1173
    $media = array();
1174
  }
1175
  if (!isset($media[$taxon->uuid])) {
1176

    
1177
    // --- GET Images --- //
1178
    $mediaQueryParameters = array(
1179
        "type" => "ImageFile",
1180
    );
1181

    
1182
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1183
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1184
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1185

    
1186
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1187
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1188
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1189
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1190

    
1191
    $ws_endpoint = NULL;
1192
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1193
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1194
    } else {
1195
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1196
    }
1197

    
1198
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1199
        array(
1200
            $taxon->uuid,
1201
        ),
1202
        queryString($mediaQueryParameters)
1203
       );
1204
  }
1205

    
1206
  return $media[$taxon->uuid];
1207
}
1208

    
1209
/**
1210
 *
1211
 * @param Taxon $taxon
1212
 *   A CDM Taxon entitiy
1213
 *
1214
 * @return array
1215
 *   An array of CDM SpecimenOrObservation entities
1216
 *
1217
function _load_occurences_for_taxon($taxon){
1218

    
1219
  static $occurences = NULL;
1220

    
1221
  if(!isset($occurences)) {
1222
    $occurences = array();
1223
  }
1224

    
1225
  if (!isset($occurences[$taxon->uuid])){
1226

    
1227
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1228
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1229
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1230

    
1231
    $by_associatedtaxon_query = http_build_query(array(
1232
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1233
        'relationships' => implode(',', $relationship_choice['direct']),
1234
        'pageSize' => null // all hits in one page
1235
    )
1236
    );
1237

    
1238
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1239
        null,
1240
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1241
    );
1242

    
1243

    
1244
    if(isset($pager->records[0])){
1245
      $occurences[$taxon->uuid] =  $pager->records;
1246
    }
1247
  }
1248
  return $occurences[$taxon->uuid];
1249
}
1250
 */
1251

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

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

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

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

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

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

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

    
1409
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1410

    
1411
  if (!$polytomousKeyNode) {
1412
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1413
    return;
1414
  }
1415

    
1416
  // Load children.
1417
  foreach ($polytomousKeyNode->children as &$childNode) {
1418
    _load_polytomousKeySubGraph($childNode);
1419
  }
1420

    
1421
  // Load subkey.
1422
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1423

    
1424
  // Load taxon.
1425
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1426
  _load_taxonBase($polytomousKeyNode->taxon);
1427
  return;
1428
}
1429

    
1430
/**
1431
 * @todo Please document this function.
1432
 * @see http://drupal.org/node/1354
1433
 */
1434
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1435

    
1436
  cdm_check_valid_portal_page();
1437

    
1438
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1439

    
1440
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1441
  if (is_array($sourcePager->records)) {
1442
    $polytomousKey->sources = $sourcePager->records;
1443
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1444
  }
1445

    
1446
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1447
  if (is_array($annotationPager->records)) {
1448
    $polytomousKey->annotations = $annotationPager->records;
1449
  }
1450

    
1451
  _load_polytomousKeySubGraph($polytomousKey->root);
1452
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1453
}
1454

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

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

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

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

    
1525
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1526
    'taxon' => $taxon
1527
  ));
1528

    
1529
  // Check if the taxon id contained in the currently selected tree.
1530
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1531

    
1532
  if (!$taxon_in_current_classification) {
1533
    $classifications = get_classifications_for_taxon($taxon);
1534
    RenderHints::pushToRenderStack('not_in_current_classification');
1535
    $taxon_name_markup = render_taxon_or_name($taxon);
1536

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

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

    
1562
  // Render the taxon page.
1563
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1564
  $taxonpage->content = drupal_render($render_array);
1565

    
1566
  return $taxonpage;
1567
}
1568

    
1569
/**
1570
 * Creates a specimen page view.
1571
 * @param string $uuid the UUID of the specimen
1572
 * @return array|string
1573
 */
1574
function cdm_dataportal_specimen_page_view($uuid) {
1575

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

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

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

    
1612
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1613
        'specimen' => $specimen
1614
    ));
1615

    
1616
    // Render the specimen page.
1617
    $render_array = compose_cdm_specimen_page($uuid);
1618
    $specimenpage->content = drupal_render($render_array);
1619

    
1620
    return $specimenpage;
1621
}
1622

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

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

    
1641
  $named_area_page->title = $named_area->representation_L10n;
1642

    
1643
  // Render the specimen page.
1644
  $render_array = compose_cdm_named_area_page($uuid);
1645
  $named_area_page->content = drupal_render($render_array);
1646

    
1647
  return $named_area_page;
1648
}
1649

    
1650
function cdm_dataportal_named_area_page_view($uuid) {
1651

    
1652
  cdm_check_valid_portal_page();
1653

    
1654
  $named_area_page = cdm_dataportal_named_area_view($uuid);
1655
  if (!empty($named_area_page)) {
1656
    return cdm_node_show(NODETYPE_NAME, $uuid, $named_area_page->title, $named_area_page->content);
1657
  }
1658
  else {
1659
    return '';
1660
  }
1661

    
1662

    
1663
}
1664

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

    
1686
  cdm_check_valid_portal_page();
1687

    
1688
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1689
  if (!empty($taxonname_page)) {
1690
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1691
  }
1692
  else {
1693
    return '';
1694
  }
1695
}
1696

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

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

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

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

    
1805
/**
1806
 * Executes the search and generates the result list of taxa.
1807
 */
1808
function cdm_dataportal_view_search_results_taxon() {
1809

    
1810
  $taxonPager = cdm_dataportal_search_execute();
1811

    
1812
  $showThumbnails = do_showThumbnails();
1813

    
1814
  $setSessionUri = url('cdm_api/setvalue/session', array(
1815
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1816
  ));
1817

    
1818
  drupal_add_js('jQuery(document).ready(function() {
1819

    
1820
      // init
1821
      if(' . $showThumbnails . ' == 1){
1822
          jQuery(\'.media_gallery\').show(20);
1823
      } else {
1824
          jQuery(\'.media_gallery\').hide(20);
1825
      }
1826

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

    
1844
  drupal_set_title(t('Search results'), PASS_THROUGH);
1845

    
1846
  return theme('cdm_search_results', array(
1847
    'pager' => $taxonPager,
1848
    'path' => 'cdm_dataportal/search/results/taxon',
1849
    ));
1850
}
1851

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

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

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

    
1887
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1888
    }
1889
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1890
    if (!is_numeric($showThumbnails)) {
1891
      $showThumbnails = 1;
1892
    }
1893
  }
1894

    
1895
  return $showThumbnails;
1896
}
1897

    
1898

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

    
1924
  $tab = get_default_taxon_tab();
1925
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1926

    
1927
  if (!$uuid) {
1928
    return FALSE;
1929
  }
1930

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

    
1945
function path_to_specimen($uuid) {
1946

    
1947
    if (!$uuid) {
1948
        return FALSE;
1949
    }
1950
    else {
1951
        return 'cdm_dataportal/specimen/' . $uuid;
1952
    }
1953
}
1954

    
1955
function path_to_named_area($uuid) {
1956

    
1957
  if (!$uuid) {
1958
    return FALSE;
1959
  }
1960
  else {
1961
    return 'cdm_dataportal/named_area/' . $uuid;
1962
  }
1963
}
1964

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

    
1994
}
1995

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

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

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

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

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

    
2102
/**
2103
 * Composes an HTML element class attribute value composed of
2104
 * the shortname of the cdm class and the uuid of the entity.
2105
 * This class attribute should be used whereever an cdm-entity is rendered.
2106
 *
2107
 * These according class selectors in css must be escaped, eg:
2108
 *    .cdm\:TextData
2109
 *
2110
 * @param $cdmEntity
2111
 */
2112
function html_class_attribute_ref($cdmEntity) {
2113

    
2114
  if (is_cdm_entity($cdmEntity)) {
2115
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2116
  }
2117
}
2118

    
2119

    
2120
/**
2121
 * Creates a short version of a taxonname.
2122
 *
2123
 * The short name is created by using the taggedTitle field of
2124
 * TaxonNodeDTO instances.
2125
 * If the taggedTitle if empty the fullname will be returned.
2126
 *
2127
 * @param object $taxonNodeDTO
2128
 *   A TaxonNodeDTO object
2129
 *
2130
 * @return string
2131
 */
2132
function cdm_dataportal_shortname_of($taxonNodeDTO) {
2133

    
2134
  $nameStr = '';
2135

    
2136
  normalize_tagged_text($taxonNodeDTO->taggedTitle);
2137

    
2138
  // Get all tagged text tokens of the scientific name.
2139
  foreach ($taxonNodeDTO->taggedTitle as $tagtxt) {
2140
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2141
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2142
    }
2143
  }
2144
  $nameStr = trim($nameStr);
2145

    
2146
  if ($nameStr) {
2147

    
2148
    // Do not return short names for these.
2149
    if ($taxonNodeDTO->unplaced || $taxonNodeDTO->excluded) {
2150
      return $nameStr;
2151
    }
2152

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

    
2173
/**
2174
 * Check if a taxon is accepted by the current taxonomic tree.
2175
 *
2176
 * @param mixed $taxon
2177
 *   The Taxon obkect to check.
2178
 *
2179
 * @return bool
2180
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2181
 */
2182
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2183

    
2184
  $defaultTreeUuid = get_current_classification_uuid();
2185

    
2186
  if (isset($taxon->taxonNodes)) {
2187
    $taxonNodes = $taxon->taxonNodes;
2188
  }
2189
  else {
2190
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2191
  }
2192

    
2193
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2194
    foreach ($taxonNodes as $node) {
2195
      if (isset($node->classification)){
2196
        if(is_object($node->classification)) {
2197
          if ($node->classification->uuid == $defaultTreeUuid) {
2198
            return TRUE;
2199
          }
2200
        }
2201
        else {
2202
          if ($node->classification == $defaultTreeUuid) {
2203
            return TRUE;
2204
          }
2205
        }
2206
      }
2207
    }
2208
  }
2209

    
2210
  return FALSE;
2211
}
2212

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

    
2239
    if(!$types){
2240
      $types = $default;
2241
    }
2242
    return isset($source->type) && in_array($source->type, $types);
2243
  }
2244

    
2245
/**
2246
 * @todo Please document this function.
2247
 * @see http://drupal.org/node/1354
2248
 */
2249
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2250
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2251
}
2252

    
2253

    
2254
/**
2255
 * Collects all the media from a list of description elements.
2256
 *
2257
 * @param array $descriptionElements
2258
 *   The description elements from which to collect the media.
2259
 *
2260
 * @return array
2261
 *   The output with all the collected media.
2262
 */
2263
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2264

    
2265
  $outArrayOfMedia = array();
2266

    
2267
  // Avoiding a warning box in Drupal for Flora Malesiana.
2268
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2269
    foreach ($descriptionElements as $descriptionElement) {
2270
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2271
        foreach ($descriptionElement->media as $media) {
2272
          if (is_object($media)) {
2273
            $outArrayOfMedia[] = $media;
2274
          }
2275
        }
2276
      }
2277
    }
2278
  }
2279
  return $outArrayOfMedia;
2280
}
2281

    
2282
/**
2283
 * @todo Please document this function.
2284
 * @see http://drupal.org/node/1354
2285
 *
2286
 * @param array $cdm_entities
2287
 *   An array of CdmBase instances or a single instance.
2288
 * @param string $footnote_list_key_suggestion
2289
 *
2290
 * @return unknown
2291
 */
2292
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2293

    
2294
   static $annotations_types_filter = null;
2295
   if(!$annotations_types_filter) {
2296
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2297
   }
2298

    
2299
  $footNoteKeys = array();
2300

    
2301
  // Is argument cdmBase an array?
2302
  if (!is_array($cdm_entities)) {
2303
    $cdmBase_array = array();
2304
    $cdmBase_array[] = $cdm_entities;
2305
  }
2306
  else {
2307
    $cdmBase_array = $cdm_entities;
2308
  }
2309

    
2310
  // Getting the key for the footnotemanager.
2311
  if (isset($footnote_list_key_suggestion)) {
2312
    $footnote_list_key = $footnote_list_key_suggestion;
2313
  }
2314
  else {
2315
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2316
  }
2317

    
2318
  // Adding the footnotes keys.
2319
  foreach ($cdmBase_array as $cdmBase_element) {
2320
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2321
    if (is_array($annotations)) {
2322
      foreach ($annotations as $annotation) {
2323
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2324
      }
2325
    }
2326
  }
2327

    
2328
  return $footNoteKeys;
2329
}
2330

    
2331

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

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

    
2375
  if(!array_key_exists('class', $attributes)) {
2376
    $attributes['class'] = array();
2377
  }
2378
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2379
  $dynabox_attributes = drupal_attributes($attributes);
2380

    
2381

    
2382
  _add_js_domEvent(); // requires domEvent.js
2383
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2384
  drupal_add_js("
2385
  jQuery(document).ready(
2386
      function() {
2387
        dynabox('". $dynabox_id ."',
2388
          {
2389
            open_callback: " . $open_callback .",
2390
            close_callback: " . $close_callback .
2391
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2392
          }
2393
        );
2394
      }
2395
   );",
2396
   array(
2397
    'type'=>'inline',
2398
    'scope'=>'footer'
2399
    )
2400
  );
2401

    
2402

    
2403
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2404
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2405
  $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>';
2406
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2407
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2408
  $out .= '    </' . $enclosingtags[1] . '>';
2409
  $out .= '  </' . $enclosingtags[0] . '>';
2410
  $out .= '<!-- dynabox end -->';
2411
  return $out;
2412
}
2413

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

    
2434
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2435
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2436
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2437
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2438
          && $descriptionElement->multilanguageText_L10n->text != ''
2439
          || isset($descriptionElement->sources[0])
2440
          || isset($descriptionElement->media[0]) ) {
2441
          return TRUE;
2442
        }
2443
      }
2444
    }
2445
  }
2446
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2447
    foreach ($featureNode->childNodes as $child) {
2448
      if (has_feature_node_description_elements($child)) {
2449
        return TRUE;
2450
      }
2451
    }
2452
  }
2453
  return FALSE;
2454
}
2455

    
2456
/**
2457
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2458
 *
2459
 * @param $chapter
2460
 *   The taxon page chapter or part
2461
 */
2462
function cdm_check_valid_taxon_page($chapter){
2463
  static $taxon_tabs = null;
2464

    
2465
  cdm_check_valid_portal_page();
2466

    
2467
  if($taxon_tabs == null){
2468
    $taxon_tabs = array('all', 'description');
2469
    foreach(get_taxon_tabs_list() as $tab){
2470
      $taxon_tabs[] = strtolower($tab);
2471
    }
2472
  }
2473

    
2474
  if(!in_array($chapter, $taxon_tabs)){
2475
    // oops this is not a valid chapter name
2476
    http_response_code(404); // 404 = Not Found
2477
  }
2478

    
2479
}
2480

    
2481
/**
2482
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2483
 *
2484
 * @param $chapter
2485
 *   The taxon page chapter or part
2486
 */
2487
function cdm_check_valid_portal_page(){
2488
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2489
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2490
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2491
    http_response_code(404); // 404 = Not Found
2492
    exit('HTTP 404');
2493
  }
2494
}
2495

    
2496
/**
2497
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2498
 *
2499
 * @param $text_a
2500
 * @param $text_b
2501
 * @return string
2502
 */
2503
function diff_viewer($text_a, $text_b) {
2504

    
2505
  static $diff_viewer_count = 0;
2506

    
2507
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2508

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

    
2528
  $diff = Diff::compare($text_a,
2529
    $text_b);
2530
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2531
    . Diff::toTable($diff, '', '')
2532
    . '</div></div>';
2533
  return $diff_viewer_markup;
2534
}
2535

    
2536

    
(10-10/16)