Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_dataportal.module @ 8385a9f2

History | View | Annotate | Download (80.2 KB)

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

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

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

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

    
149
  function _add_js_openlayers() {
150

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

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

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

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

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

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

    
198
  }
199

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

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

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

    
263
  /**
264
   * @todo Please document this function.
265
   * @see http://drupal.org/node/1354
266
   */
267
  function _add_js_cluetip() {
268

    
269
    // TODO replace by
270
    // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
271
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
272
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
273
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
274
    if(variable_get('cdm_js_devel_mode', FALSE)){
275
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
276
    }
277
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
278
    drupal_add_js("jQuery(document).ready(function(){
279
        jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
280
          splitTitle: '|',
281
          showTitle: true,
282
          activation: 'hover',
283
          sicky: true,
284
          arrows: true,
285
          dropShadow: false,
286
          cluetipClass: 'rounded'
287
        });
288
      });",
289
      array(
290
        'type' => 'inline',
291
        'scope' => 'footer'
292
      )
293
    );
294
  }
295

    
296
  /**
297
   * @todo Please document this function.
298
   * @see http://drupal.org/node/1354
299
   */
300
  function _add_js_ahah() {
301

    
302
    _add_js_domEvent(); // requires domEvent.js
303
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
304
  }
305

    
306
/**
307
 * @todo Please document this function.
308
 * @see http://drupal.org/node/1354
309
 */
310
function _add_js_taxonomic_children($jquery_selector) {
311

    
312
  global $base_url;
313

    
314

    
315
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.cdm.taxonomic_children.js');
316
  
317
  drupal_add_js('jQuery(document).ready(function() {
318
        jQuery(\'' . $jquery_selector . '\').taxonomic_children({
319
          // hoverClass: "fa-rotate-90",
320
          // activeClass: "fa-rotate-90",
321
          classificationUuid: "' . get_current_classification_uuid() . '",
322
          taxonUuid: "' . get_current_taxon_uuid() . '",
323
          cdmWebappBaseUri: "' . variable_get('cdm_webservice_url', '') . '",
324
          proxyBaseUri: "' . $base_url . '",
325
          
326
        });
327
      });
328
      ', array('type' => 'inline'));
329
}
330

    
331
  /**
332
   * Adds the external javascript file for domEvent.js.
333
   *
334
   * @see drupal_add_js()
335
   */
336
  function _add_js_domEvent() {
337
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
338
  }
339

    
340
  function _add_jquery_ui()
341
  {
342
    drupal_add_css(drupal_get_path('module',
343
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
344
    drupal_add_js(drupal_get_path('module',
345
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
346
      array(
347
        'type' => 'file',
348
        'weight' => JS_LIBRARY,
349
        'cache' => TRUE,
350
        'preprocess' => FALSE
351
      )
352
    );
353
  }
354

    
355
  /**
356
   * Provides the markup for an font awesome icon.
357
   *
358
   * The icons is created in default size without any extra features.
359
   *
360
   * The available icons are listed here http://fontawesome.io/cheatsheet/
361
   * fontawesome icons have much more features than implemented here in this function,
362
   * for spinning icons, fixed width icons, rotation, etc please checkout the
363
   * examples at http://fontawesome.io/examples/
364
   *
365
   * @parameter $icon_name
366
   *  The name of the icon which starts with 'fa-'
367
   *
368
   * @return String
369
   *    the markup for the icon in an <i> tag
370
   *
371
   */
372
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
373

    
374

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

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

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

    
387
    if($icon_name){
388
      if(!isset($attributes['class'])){
389
        $attributes['class'] = array();
390
      }
391
      $attributes['class'][] = 'fa';
392
      $attributes['class'][] = $icon_name;
393

    
394
      return '<i ' . drupal_attributes($attributes) . '></i>';
395
    }
396

    
397
    return '';
398
  }
399

    
400

    
401
  /* ====================== hook implementations ====================== */
402
  /**
403
   * Implements hook_permission().
404
   *
405
   * Valid permissions for this module.
406
   *
407
   * @return array
408
   *   An array of valid permissions for the cdm_dataportal module.
409
   */
410
  function cdm_dataportal_permission() {
411
    return array(
412
      'administer cdm_dataportal' => array(
413
        'title' => t('Administer CDM DataPortal settings'),
414
        'description' => t("Access the settings pages specific for the cdm_dataportal module"),
415
      )
416
    );
417
  }
418

    
419
/**
420
 * Implements hook_menu().
421
 */
422
function cdm_dataportal_menu() {
423
  $items = array();
424

    
425
  // @see settings.php.
426
  cdm_dataportal_menu_admin($items);
427
  cdm_dataportal_menu_help($items);
428

    
429
  $items['cdm_dataportal/names'] = array(
430
    'page callback' => 'cdm_dataportal_view_names',
431
    'access arguments' => array('access content'),
432
    'type' => MENU_CALLBACK,
433
  );
434

    
435
  // Optional callback arguments: page.
436
  $items['cdm_dataportal/taxon'] = array(
437
    'page callback' => 'cdm_dataportal_taxon_page_view',
438
    'access arguments' => array('access content'),
439
    'type' => MENU_CALLBACK,
440
    // Expected callback arguments: uuid.
441
  );
442

    
443
   // Optional callback arguments: page.
444
    //FIXME point to view/page method in this module
445
    $items['cdm_dataportal/specimen'] = array(
446
        'page callback' => 'cdm_dataportal_specimen_page_view',
447
        'access arguments' => array('access content'),
448
        'type' => MENU_CALLBACK,
449
        // Expected callback arguments: uuid.
450
    );
451

    
452
  $items['cdm_dataportal/name'] = array(
453
    'page callback' => 'cdm_dataportal_name_page_view',
454
      /*
455
    'page arguments' => array(
456
       'taxon_name_uuid',
457
       'taxon_to_hide_uuid',
458
       'synonym_uuid' => NULL
459
      ),
460
      */
461
    'access arguments' => array('access content'),
462
    'type' => MENU_CALLBACK,
463
    // Expected callback arguments: uuid.
464
  );
465

    
466
  $items['cdm_dataportal/reference'] = array(
467
    'page callback' => 'cdm_dataportal_view_reference',
468
    'access arguments' => array('access content'),
469
    'type' => MENU_CALLBACK,
470
    // Expected callback arguments: uuid.
471
  );
472

    
473
  $items['cdm_dataportal/reference/list'] = array(
474
    'page callback' => 'cdm_dataportal_view_reference_list',
475
    'access arguments' => array('access content'),
476
    'type' => MENU_CALLBACK,
477
    // Expected callback arguments: uuid.
478
  );
479

    
480
  $items['cdm_dataportal/media'] = array(
481
    'page callback' => 'cdm_dataportal_view_media',
482
    'access arguments' => array('access content'),
483
    'type' => MENU_CALLBACK,
484
    // Expected callback arguments:
485
    // uuid, mediarepresentation_uuid, part_uuid or part#.
486
  );
487

    
488
  $items['cdm_dataportal/polytomousKey'] = array(
489
    'page callback' => 'cdm_dataportal_view_polytomousKey',
490
    'access arguments' => array('access content'),
491
    'type' => MENU_CALLBACK,
492
    // Expected callback arguments: polytomousKey->uuid.
493
  );
494

    
495
  $items['cdm_dataportal/search'] = array(
496
    'page callback' => 'cdm_dataportal_view_search_advanced',
497
    'access arguments' => array('access content'),
498
    'type' => MENU_CALLBACK,
499
  );
500

    
501
  $items['cdm_dataportal/search/advanced'] = array(
502
    'title' => 'Advanced', // will be passed through t()
503
    'page callback' => 'cdm_dataportal_view_search_advanced',
504
    'access arguments' => array('access content'),
505
    'type' => MENU_DEFAULT_LOCAL_TASK,
506
  );
507

    
508
  $items['cdm_dataportal/search/taxon_by_description'] = array(
509
    'title' => 'By content category', // will be passed through t()
510
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
511
    'access arguments' => array('access content'),
512
    'type' => MENU_LOCAL_TASK,
513
  );
514

    
515
  $items['cdm_dataportal/search/results/taxon'] = array(
516
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
517
    'access arguments' => array('access content'),
518
    'type' => MENU_CALLBACK,
519
  );
520
  /*
521
   $items['cdm/xml2json'] = array(
522
   'page callback' => 'cdm_view_xml2json',
523
   'access arguments' => array('access content'),
524
   'type' => MENU_CALLBACK,
525
   );
526
   */
527

    
528
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
529
  // User configuration of cdm_dataportal.
530
  $items['user/%/cdm_dataportal'] = array(
531
    'title' => 'cdm_dataportal',
532
    'access arguments' => array('access content'),
533
    'page callback' => 'drupal_get_form',
534
    'page arguments' => array('cdm_dataportal_user_form'),
535
    'type' => MENU_LOCAL_TASK,
536
    'weight' => 10,
537
  );
538
  // }
539

    
540
  // 'May not cache' in D5.
541
  $items['cdm_dataportal/name/%'] = array(
542
    // 'page callback' => 'cdm_dataportal_view_name',
543
    'page callback' => 'cdm_dataportal_name_page_view',
544
    'page arguments' => array(2, 3, 4),
545
    'access arguments' => array('access content'),
546
    'type' => MENU_CALLBACK,
547
  );
548

    
549
  // --- Local tasks for Taxon.
550
  // --- tabbed taxon page
551
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
552
    $items['cdm_dataportal/taxon/%'] = array(
553
      'title' => '@tabname',
554
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
555
      'page callback' => 'cdm_dataportal_taxon_page_view',
556
      'access arguments' => array('access content'),
557
      'type' => MENU_CALLBACK,
558
      'weight' => 1,
559
      'page arguments' => array(2, "description")
560
      , // Expected callback arguments: taxon_uuid.
561
    );
562

    
563
    $items['cdm_dataportal/taxon/%/all'] = array(
564
      'title' => '@tabname',
565
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
566
      'page callback' => 'cdm_dataportal_taxon_page_view',
567
      'access arguments' => array('access content'),
568
      'type' => MENU_CALLBACK,
569
      'weight' => 2,
570
      'page arguments' => array(2, "all")
571
      , // Expected callback arguments: taxon_uuid.
572
    );
573

    
574
    $items['cdm_dataportal/taxon/%/description'] = array(
575
      'title' => '@tabname',
576
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'General'))),
577
      'page callback' => 'cdm_dataportal_taxon_page_view',
578
      'access arguments' => array('access content'),
579
      'type' => MENU_DEFAULT_LOCAL_TASK,
580
      'weight' => 2,
581
      'page arguments' => array(2, "description")
582
      , // Expected callback arguments: taxon_uuid.
583
    );
584

    
585
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
586
      'title' => '@tabname',
587
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy'))),
588
      'page callback' => 'cdm_dataportal_taxon_page_view',
589
      'access arguments' => array('access content'),
590
      'type' => MENU_LOCAL_TASK,
591
      'weight' => 4,
592
      'page arguments' => array(2, "synonymy", 4)
593
      , // Expected callback arguments: taxon_uuid and ...
594
    );
595
    $items['cdm_dataportal/taxon/%/images'] = array( // Images
596
      'title' => '@tabname',
597
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Images'))),
598
      'page callback' => 'cdm_dataportal_taxon_page_view',
599
      'access arguments' => array('access content'),
600
      'type' => MENU_LOCAL_TASK,
601
      'weight' => 5,
602
      'page arguments' => array(2, "images")
603
      , // Expected callback arguments: taxon_uuid.
604
    );
605

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

    
617
    $items['cdm_dataportal/taxon/%/keys'] = array( // Keys
618
      'title' => '@tabname',
619
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys'))),
620
      'page callback' => 'cdm_dataportal_taxon_page_view',
621
      'access arguments' => array('access content'),
622
      'type' => MENU_LOCAL_TASK,
623
      'weight' => 6,
624
      'page arguments' => array(2, "keys")
625
      , // Expected callback arguments: taxon_uuid.
626
    );
627

    
628
    $items['cdm_dataportal/taxon/%/experts'] = array( // Experts
629
      'title' => '@tabname',
630
      'title arguments' => array('@tabname' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts'))),
631
        'page callback' => 'cdm_dataportal_taxon_page_view',
632
        'access arguments' => array('access content'),
633
        'type' => MENU_LOCAL_TASK,
634
        'weight' => 6,
635
        'page arguments' => array(2, "experts")
636
    , // Expected callback arguments: taxon_uuid.
637
    );
638

    
639
    $items['cdm_dataportal/taxon/autosuggest/%/%/%/'] = array(
640
        'page callback' => 'cdm_dataportal_taxon_autosuggest',
641
        'access arguments' => array('access taxon autosuggest'),
642
        'page arguments' => array(3,4,5),
643
        'type' => MENU_CALLBACK
644
    );
645
  }
646

    
647
  // --- refresh link for all cdmnode types
648
  foreach (cdm_get_nodetypes() as $type=>$name) {
649
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
650
        'title' => 'Refresh',
651
        'page callback' => 'cdm_dataportal_refresh_node',
652
        'access arguments' => array('administer cdm_dataportal'),
653
        'type' => MENU_LOCAL_TASK,
654
        'weight' => 100,
655
        'page arguments' => array($name, 2)
656
    );
657
  }
658

    
659
  return $items;
660
}
661

    
662
/**
663
 * Implements hook_init().
664
 *
665
 */
666
function cdm_dataportal_init() {
667
  //FIXME To add CSS or JS that should be present on all pages, modules
668
  //      should not implement this hook, but declare these files in their .info file.
669
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
670
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
671
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
672

    
673
  if(variable_get('cdm_debug_mode', FALSE)){
674
    $file = 'temporary://drupal_debug.txt';
675
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
676
  }
677

    
678
  $bibliography_settings = get_bibliography_settings();
679
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
680
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
681
}
682

    
683
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
684

    
685
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
686

    
687
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
688
    // force reloading of all and notify user about this special loading
689
    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: ')
690
        . l('Back to tabbed taxon page', $base_path));
691
    $base_path .= '/all';
692
  } else {
693
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
694
  }
695

    
696
  $parameters['cacheL2_refresh'] ='1';
697

    
698

    
699
  drupal_goto($base_path, array('query' => $parameters));
700
}
701

    
702
/**
703
 * The function generate form for own user cdm dataportal configurations.
704
 */
705
function cdm_dataportal_user_form($form, &$form_state) {
706

    
707
  global $user;
708
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
709

    
710
  $form['taxon_page_tabs'] = array(
711
      '#type' => 'fieldset',
712
      '#tree' => true,
713
      '#title' => t('Taxon page tabs'),
714
  );
715

    
716
  $form['taxon_page_tabs']['user_defined'] = array(
717
    '#type' => 'checkbox',
718
    '#title' => t('Activate user default configuration'),
719
    '#default_value' => variable_get($checkbox_value, 0),
720
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
721
  );
722

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

    
733

    
734
  if(false){
735
    $form['developer_options'] = array(
736
        '#type' => 'fieldset',
737
        '#tree' => true,
738
        '#title' => t('Developer options'),
739
    );
740

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

    
754
  $form['submit'] = array(
755
    '#type' => 'submit',
756
    '#value' => t('Submit'),
757
  );
758

    
759
  return $form;
760
}
761

    
762
/**
763
 * Form submission handler for user_form().
764
 *
765
 * Submits the user cdm dataportal configurations.
766
 */
767
function cdm_dataportal_user_form_submit($form, &$form_state) {
768
  global $user;
769
  $msg_type = 'status';
770
  $username = $user->name;
771
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
772

    
773
  // FIXME: this is completely wrong, see user_profile_form_submit()
774

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

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

    
794
  }
795
  else {
796
    // Problem with the user id => variables wont be saved.
797
    $msg_type = 'warning';
798
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
799
  }
800
}
801

    
802
/**
803
 * Implements hook_block_info().
804
 */
805
function cdm_dataportal_block_info() {
806

    
807
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
808
    // $block[1]["info"] = t("CDM DataPortal Credits");
809
    $block["2"] = array(
810
        "info" => t("CDM Search Taxa"),
811
        "cache" => DRUPAL_NO_CACHE
812
      );
813
    // $block[3]["info"] = t("CDM Filters");
814
    $block["4"]["info"] = t("CDM Dataportal Print");
815
    $block["keys"]["info"] = t("CDM identification keys");
816
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
817
    $block["classification_breadcrumbs"] =  array(
818
        'info' => t('Classification breadcrumbs'),
819
        'cache' => DRUPAL_CACHE_PER_PAGE
820
      );
821
    $block["taxonomic_children"] =  array(
822
      'info' => t('Taxonomic children'),
823
      'cache' => DRUPAL_CACHE_PER_PAGE
824
    );
825

    
826
    return $block;
827
}
828

    
829
/**
830
 * Implements hook_block_view().
831
 */
832
function cdm_dataportal_block_view($delta) {
833
  // TODO Rename block deltas (e.g. '2') to readable strings.
834
  switch ($delta) {
835
    // case 'delta-1':
836
    // $block['subject'] = t('Credits');
837
    // $block['content'] = theme('cdm_credits');
838
    // return $block;
839
    case '2':
840
      $block['subject'] = t('Search taxa');
841
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
842
      $block['content'] = drupal_render($form);
843

    
844
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
845
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
846
      }
847
      return $block;
848
    case '4':
849
      $block['subject'] = '';
850
      $block['content'] = theme('cdm_print_button');
851
      return $block;
852
    case "keys":
853
      $block['subject'] = t('Identification Keys');
854
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
855
      return $block;
856
    case "fundedByEDIT":
857
      // t('Funded by EDIT');
858
      $text = '<none>';
859
      $block['subject'] = $text;
860
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
861
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
862
        'attributes' => array("target" => "EDIT"),
863
        'absolute' => TRUE,
864
        'html' => TRUE,
865
      ));
866
      return $block;
867
    case 'classification_breadcrumbs':
868
      $taxon_uuid = get_current_taxon_uuid();
869
      $block['subject'] = '<none>';
870
      $block['content'] = compose_classification_breadcrumbs($taxon_uuid);
871
      return $block;
872
    case 'taxonomic_children':
873
      $taxon_uuid = get_current_taxon_uuid();
874
      $block['subject'] = '<none>';
875
      $block['content'] = compose_taxonomic_children($taxon_uuid);
876
      return $block;
877
  }
878
}
879

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

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

    
900
  return $taxon_uuid;
901
}
902

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

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

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

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

    
944
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
945
  return $form;
946
}
947

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

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

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

    
965
  $destination_array = drupal_get_destination();
966
  $destination = $destination_array['destination'];
967

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

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

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

    
994
  return $form;
995

    
996
}
997

    
998
/**
999
 *
1000
 * @ingroup compose
1001
 */
1002
function compose_classification_selector() {
1003

    
1004
  $destination_array = drupal_get_destination();
1005
  $destination = $destination_array['destination'];
1006

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

    
1011
  $current_classification_uuid = get_current_classification_uuid();
1012

    
1013

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

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

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

    
1043
  return $render_array;
1044
}
1045

    
1046

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

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

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

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

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

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

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

    
1116
  cdm_check_valid_portal_page();
1117

    
1118
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1119
  return theme('cdm_reference_page', array('reference' => $reference));
1120
}
1121

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

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

    
1138
  cdm_check_valid_portal_page();
1139

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

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

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

    
1176
  static $media = NULL;
1177

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

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

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

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

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

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

    
1212
  return $media[$taxon->uuid];
1213
}
1214

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

    
1225
  static $occurences = NULL;
1226

    
1227
  if(!isset($occurences)) {
1228
    $occurences = array();
1229
  }
1230

    
1231
  if (!isset($occurences[$taxon->uuid])){
1232

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

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

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

    
1249

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1442
  cdm_check_valid_portal_page();
1443

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1572
  return $taxonpage;
1573
}
1574

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

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

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

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

    
1618
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1619
        'specimen' => $specimen
1620
    ));
1621

    
1622
    // Render the specimen page.
1623
    $render_array = compose_cdm_specimen_page($uuid);
1624
    $specimenpage->content = drupal_render($render_array);
1625

    
1626
    return $specimenpage;
1627
}
1628

    
1629
/**
1630
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1631
 *
1632
 * The node page shows the taxon name title and the list of taxon related
1633
 * with such taxon. Name on the tree already in use.
1634
 *
1635
 * @param UUID $taxon_name_uuid
1636
 *   The uuid of the CDM TaxonNameBase to show a name page for
1637
 * @param UUID $taxon_to_hide_uuid
1638
 *   A taxon which should not be displayed in the taxon list
1639
 * @param UUID $highlite_synonym_uuid
1640
 *   Optinal parameter wich takes another taxon uuid, if given the
1641
 *   target taxon pages will show the syonymy tab where the taxon
1642
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1643
 *   in case it is found on this page.
1644
 *
1645
 * @return mixed
1646
 *   The formatted name page as node.
1647
 */
1648
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1649

    
1650
  cdm_check_valid_portal_page();
1651

    
1652
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1653
  if (!empty($taxonname_page)) {
1654
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1655
  }
1656
  else {
1657
    return '';
1658
  }
1659
}
1660

    
1661
/**
1662
 * View function for a TaxonNameBase page.
1663
 *
1664
 * The name page lists all taxa for which the name specified by the
1665
 * $taxon_name_uuid is being used. I case there is only one name the
1666
 * page automatically redirects ti the according taxon page. Otherwise
1667
 * the list of names is displayed.
1668
 *
1669
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1670
 * list of taxa. This is useful for example when referencing from a taxon
1671
 * to the name page and the referring taxon should not be repeaded in the
1672
 * name page.
1673
 *
1674
 *
1675
 * @param UUID $taxon_name_uuid
1676
 *   The uuid of the CDM TaxonNameBase to show a name page for
1677
 * @param UUID $taxon_to_hide_uuid
1678
 *   A taxon which should not be displayed in the taxon list
1679
 * @param UUID $highlite_synonym_uuid
1680
 *   Optinal parameter wich takes another taxon uuid, if given the
1681
 *   target taxon pages will show the syonymy tab where the taxon
1682
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1683
 *   in case it is found on this page.
1684
 *
1685
 * @return object
1686
 *   An object with two fields:
1687
 *     - title: the page title
1688
 *     - content: the page content
1689
 */
1690
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1691
  // Getting the full taxonname object from the server.
1692
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1693
  if (!$taxon_name) {
1694
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1695
    return FALSE;
1696
  }
1697
  // Searching for all the taxa connected with the taxon name on the tree
1698
  // in use.
1699
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1700
  $request_params = array();
1701
  $request_params['query'] = $name_cache;
1702
  $request_params['tree'] = get_current_classification_uuid();
1703
  $request_params['doTaxa'] = 1;
1704
  $request_params['doSynonyms'] = 1;
1705
  $request_params['doTaxaByCommonNames'] = 0;
1706
  $request_params['matchMode'] = "EXACT";
1707
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1708

    
1709
  // Removing the name where we came from.
1710
  foreach ($taxon_pager->records as $k => &$taxon) {
1711
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1712
      unset($taxon_pager->records[$k]);
1713
    }
1714
  }
1715
  // Show the taxa list or go to the singular taxon.
1716
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1717
    $singleTaxon = array_pop($taxon_pager->records);
1718
    if ($singleTaxon->class != "Taxon") {
1719
      // It is a Synonym -> look for the accepted.
1720
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1721
      if (!empty($highlite_synonym_uuid)) {
1722
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1723
      }
1724
      else {
1725
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1726
      }
1727
    }
1728
    else {
1729
      // It is an accepted taxon.
1730
      if (!empty($highlite_synonym_uuid)) {
1731
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1732
      }
1733
      else {
1734
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1735
      }
1736
    }
1737
  }
1738
  else {// More than one taxa case.
1739
    $taxon_name_page = new stdClass();
1740
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1741
    if ($taxon_pager->records) {
1742
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1743
    }
1744
    else {
1745
      $taxon_name_page->content = 'This name has no taxa';
1746
    }
1747
    return $taxon_name_page;
1748
  }
1749
}
1750

    
1751
/**
1752
 * Creates a page with the advance search form.
1753
 *
1754
 * NOTE: The advance search form allows searching for taxa.
1755
 */
1756
function cdm_dataportal_view_search_advanced() {
1757
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1758
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1759
}
1760

    
1761
/**
1762
 * Creates a page with the search form for searching by taxon descriptions.
1763
 */
1764
function cdm_dataportal_view_search_taxon_by_description() {
1765
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1766
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1767
}
1768

    
1769
/**
1770
 * Executes the search and generates the result list of taxa.
1771
 */
1772
function cdm_dataportal_view_search_results_taxon() {
1773

    
1774
  $taxonPager = cdm_dataportal_search_execute();
1775

    
1776
  $showThumbnails = do_showThumbnails();
1777

    
1778
  $setSessionUri = url('cdm_api/setvalue/session', array(
1779
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1780
  ));
1781

    
1782
  drupal_add_js('jQuery(document).ready(function() {
1783

    
1784
      // init
1785
      if(' . $showThumbnails . ' == 1){
1786
          jQuery(\'.media_gallery\').show(20);
1787
      } else {
1788
          jQuery(\'.media_gallery\').hide(20);
1789
      }
1790

    
1791
      // add change handler
1792
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1793
      function(event){
1794
        var state = 0;
1795
        if(jQuery(this).is(\':checked\')){
1796
          jQuery(\'.media_gallery\').show(20);
1797
          state = 1;
1798
        } else {
1799
          jQuery(\'.media_gallery\').hide(20);
1800
        }
1801
        // store state in session variable
1802
        var uri = \'' . $setSessionUri . '\' + state;
1803
        jQuery.get(uri);
1804
      });
1805
  });',
1806
  array('type' => "inline", 'scope' => JS_DEFAULT));
1807

    
1808
  drupal_set_title(t('Search results'), PASS_THROUGH);
1809

    
1810
  return theme('cdm_search_results', array(
1811
    'pager' => $taxonPager,
1812
    'path' => 'cdm_dataportal/search/results/taxon',
1813
    ));
1814
}
1815

    
1816
/**
1817
 * Provides the standart image wich indicated a loading process
1818
 *
1819
 * @return string
1820
 *  The img html tag
1821
 */
1822
function loading_image_html() {
1823
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1824
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1825
}
1826

    
1827
/**
1828
 * Returns the state of the the showThumbnails flag set in the
1829
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1830
 *
1831
 * @return boolean
1832
 *    returns 1 if the flag is set
1833
 */
1834
function do_showThumbnails() {
1835
  static $showThumbnails = null;
1836

    
1837
  if($showThumbnails == null) {
1838
    $showThumbnails = 0;
1839
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1840
      $showThumbnails = 0;
1841
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1842
      $showThumbnails = is_array($search_gallery_settings)
1843
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1844
        && (
1845
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1846
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1847
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1848
            )
1849
         ? 1 : 0;
1850

    
1851
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1852
    }
1853
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1854
    if (!is_numeric($showThumbnails)) {
1855
      $showThumbnails = 1;
1856
    }
1857
  }
1858

    
1859
  return $showThumbnails;
1860
}
1861

    
1862

    
1863
/* ====================== other functions ====================== */
1864
/**
1865
 * Creates a URL to the taxon page specified by the $uuid parameter.
1866
 *
1867
 * The URL will be prepended with a path element to a specific taxon page tab.
1868
 *
1869
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1870
 * be set globally in the administrative settings or individually in the user
1871
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1872
 * the last portal will stay on this last tab.
1873
 *
1874
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1875
 * internal mechanism by a specific value.
1876
 *
1877
 * @param string $uuid
1878
 *   The UUID of the taxon.
1879
 * @param string $page_tab
1880
 *   Overwriting the preset mechanism by defining specific value for the
1881
 *   taxon page tab.
1882
 *
1883
 * @return string
1884
 *   The created URL.
1885
 */
1886
function path_to_taxon($uuid, $page_tab = FALSE) {
1887

    
1888
  $tab = get_default_taxon_tab();
1889
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1890

    
1891
  if (!$uuid) {
1892
    return FALSE;
1893
  }
1894

    
1895
  if ($page_tab) {
1896
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1897
  }
1898
  elseif (!$tab || strtolower($tab) == 'general') {
1899
    return 'cdm_dataportal/taxon/' . $uuid;
1900
  }
1901
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1902
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1903
  }
1904
  else {
1905
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1906
  }
1907
}
1908

    
1909
function path_to_specimen($uuid) {
1910

    
1911
    if (!$uuid) {
1912
        return FALSE;
1913
    }
1914
    else {
1915
        return 'cdm_dataportal/specimen/' . $uuid;
1916
    }
1917
}
1918

    
1919
/**
1920
 * Creates a URL to show a synonmy in the according taxon page.
1921
 *
1922
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1923
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1924
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1925
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1926
 * in the page
1927
 *
1928
 * @param string $synonymUuid
1929
 *    The uuid of the synonym
1930
 * @param string $acceptedUuid
1931
 *    The uuid of the according accepted taxon
1932
 * @return string
1933
 *    The URL to show a synonmy in the according taxon page
1934
 */
1935
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1936
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1937
  return url($acceptedPath, array(
1938
      'query' => array(
1939
        // highlite the synony in the synonymy
1940
        'highlite' => $synonymUuid,
1941
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1942
        // see theme_taxon_page_title()
1943
        'acceptedFor' => $synonymUuid
1944
      ),
1945
      'fragment' => $synonymUuid
1946
  ));
1947

    
1948
}
1949

    
1950
/**
1951
 * Compses the drupal path to the key identified by the uuid.
1952
 *
1953
 * @param string $keyType
1954
 *    the key typer corresponds to the specific class of the CDM
1955
 *    IdentificationKey. Possible values are
1956
 *      -PolytomousKey
1957
 *      -MultimediaKey
1958
 *      - ...
1959
 * @param UUID $keyUuid
1960
 *   The UUID of the key
1961
 */
1962
function path_to_key($keyType, $keyUuid) {
1963
  if (!$keyUuid || !$keyType) {
1964
    return FALSE;
1965
  }
1966
  $keyType{0} = strtolower($keyType{0});
1967
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1968
}
1969

    
1970
/**
1971
 * @todo Please document this function.
1972
 * @see http://drupal.org/node/1354
1973
 */
1974
function path_to_reference($uuid) {
1975
  if (!$uuid) {
1976
    return FALSE;
1977
  }
1978
  return 'cdm_dataportal/reference/' . $uuid;
1979
}
1980

    
1981
/**
1982
 * Creates the path to a cdm_dataportal taxon name page.
1983
 *
1984
 * @param UUID $taxon_name_uuid
1985
 *   The uuid of the CDM TaxonNameBase to show a name page for
1986
 * @param UUID $taxon_to_hide_uuid
1987
 *   A taxon which should not be displayed in the taxon list
1988
 * @param UUID $highlite_synonym_uuid
1989
 *   Optinal parameter wich takes another taxon uuid, if given the
1990
 *   target taxon pages will show the syonymy tab where the taxon
1991
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1992
 *   in case it is found on this page.
1993
 *
1994
 * @return a URI path element as string
1995
 */
1996
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1997
  $res = FALSE;
1998
  if ($name_uuid) {
1999
    $res = 'cdm_dataportal/name/' . $name_uuid;
2000
  }
2001
  if($taxon_to_hide_uuid){
2002
    $res .= '/' . $taxon_to_hide_uuid;
2003
    if($synonym_uuid){
2004
      $res .= '/' . $synonym_uuid;
2005
    }
2006
  }
2007
  return $res;
2008
}
2009

    
2010
/**
2011
 * @todo Please document this function.
2012
 * @see http://drupal.org/node/1354
2013
 */
2014
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
2015
  if (!$uuid) {
2016
    return FALSE;
2017
  }
2018
  $out = 'cdm_dataportal/media/' . $uuid;
2019
  if ($representaion_uuid) {
2020
    $out .= '/' . $representaion_uuid;
2021
    if ($partId !== FALSE) {
2022
      $out .= '/' . $partId;
2023
    }
2024
  }
2025
  return $out;
2026
}
2027

    
2028
/**
2029
 * Compares thisRank with thatRank.
2030
 *
2031
 * Returns a negative integer, zero, or a positive integer
2032
 * as the of thisRank is higher than, equal to, or lower than thatRank.
2033
 * e.g:
2034
 * <ul>
2035
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
2036
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
2037
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
2038
 * </ul>
2039
 * <p>
2040
 * This compare logic of the underlying webservice is the
2041
 * <b>inverse logic</b> of the the one implemented in
2042
 * java.lang.Comparable#compareTo(java.lang.Object)
2043
 *
2044
 * @param $thisRankUuid
2045
 * @param $thatRankUuid
2046
 *
2047
 * @return int
2048
 *   A negative integer, zero, or a positive integer
2049
 *   as the thisRank is lower than, equal to, or higher than thatRank.
2050
 */
2051
function rank_compare($thisRankUuid, $thatRankUuid) {
2052
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
2053
  return $result->Integer;
2054
}
2055

    
2056
/**
2057
 * Composes an HTML element class attribute value composed of
2058
 * the shortname of the cdm class and the uuid of the entity.
2059
 * This class attribute should be used whereever an cdm-entity is rendered.
2060
 *
2061
 * These according class selectors in css must be escaped, eg:
2062
 *    .cdm\:TextData
2063
 *
2064
 * @param $cdmEntity
2065
 */
2066
function html_class_attribute_ref($cdmEntity) {
2067

    
2068
  if (is_cdm_entity($cdmEntity)) {
2069
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
2070
  }
2071
}
2072

    
2073

    
2074
/**
2075
 * Creates a short taxonname.
2076
 *
2077
 * The short name is created by using the taggedTitle field of
2078
 * NameSTO or NameTO instances.
2079
 * If the taggedTitle if empty the fullname will be returned.
2080
 *
2081
 * @param unknown_type $name
2082
 *   Name or TreeNode.
2083
 *
2084
 * @return string
2085
 */
2086
function cdm_dataportal_shortname_of($name) {
2087
  $nameStr = '';
2088

    
2089
  normalize_tagged_text($name->taggedTitle);
2090

    
2091
  // Get all tagged text tokens of the scientific name.
2092
  foreach ($name->taggedTitle as $tagtxt) {
2093
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
2094
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
2095
    }
2096
  }
2097
  $nameStr = trim($nameStr);
2098

    
2099
  if ($nameStr) {
2100

    
2101
    // Do not return short names for these.
2102
    if ($name->unplaced || $name->excluded) {
2103
      return $nameStr;
2104
    }
2105

    
2106
    /*
2107
    1st capture group (^[a-zA-Z]): First letter of uninomial.
2108
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
2109
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
2110
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
2111
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
2112
    */
2113
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
2114
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
2115
      return $matches[1][0] . "." . $matches[3][0];
2116
    }
2117
    else {
2118
      return $nameStr;
2119
    }
2120
  }
2121
  else {
2122
    return $name->titleCache;
2123
  }
2124
}
2125

    
2126
/**
2127
 * Check if a taxon is accepted by the current taxonomic tree.
2128
 *
2129
 * @param mixed $taxon
2130
 *   The Taxon obkect to check.
2131
 *
2132
 * @return bool
2133
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
2134
 */
2135
function _cdm_dataportal_acceptedByCurrentView($taxon) {
2136

    
2137
  $defaultTreeUuid = get_current_classification_uuid();
2138

    
2139
  if (isset($taxon->taxonNodes)) {
2140
    $taxonNodes = $taxon->taxonNodes;
2141
  }
2142
  else {
2143
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
2144
  }
2145

    
2146
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2147
    foreach ($taxonNodes as $node) {
2148
      if (isset($node->classification)){
2149
        if(is_object($node->classification)) {
2150
          if ($node->classification->uuid == $defaultTreeUuid) {
2151
            return TRUE;
2152
          }
2153
        }
2154
        else {
2155
          if ($node->classification == $defaultTreeUuid) {
2156
            return TRUE;
2157
          }
2158
        }
2159
      }
2160
    }
2161
  }
2162

    
2163
  return FALSE;
2164
}
2165

    
2166
/**
2167
 * Checks is the source has one of the given types.
2168
 *
2169
 * @param object $source
2170
 *   The original source entity
2171
 * @param array $types
2172
 *   An array of elementd of the OriginalSourceType enumeration
2173
 *   If not set the default will be used which is:
2174
 *    - Lineage
2175
 *    - PrimaryMediaSource
2176
 *    - PrimaryTaxonomicSource
2177
 *    - Unknown
2178
 *    - Other
2179
 * @return boolean
2180
 */
2181
  function _is_original_source_type($source, $types = null) {
2182
    // this is the default
2183
    // maybe this should also be put into the settings
2184
    static $default = array(
2185
      OriginalSourceType::Lineage,
2186
      OriginalSourceType::PrimaryMediaSource,
2187
      OriginalSourceType::PrimaryTaxonomicSource,
2188
      OriginalSourceType::Unknown,
2189
      OriginalSourceType::Other,
2190
    );
2191

    
2192
    if(!$types){
2193
      $types = $default;
2194
    }
2195
    return isset($source->type) && in_array($source->type, $types);
2196
  }
2197

    
2198
/**
2199
 * @todo Please document this function.
2200
 * @see http://drupal.org/node/1354
2201
 */
2202
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2203
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2204
}
2205

    
2206

    
2207
/**
2208
 * Collects all the media from a list of description elements.
2209
 *
2210
 * @param array $descriptionElements
2211
 *   The description elements from which to collect the media.
2212
 *
2213
 * @return array
2214
 *   The output with all the collected media.
2215
 */
2216
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2217

    
2218
  $outArrayOfMedia = array();
2219

    
2220
  // Avoiding a warning box in Drupal for Flora Malesiana.
2221
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2222
    foreach ($descriptionElements as $descriptionElement) {
2223
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2224
        foreach ($descriptionElement->media as $media) {
2225
          if (is_object($media)) {
2226
            $outArrayOfMedia[] = $media;
2227
          }
2228
        }
2229
      }
2230
    }
2231
  }
2232
  return $outArrayOfMedia;
2233
}
2234

    
2235
/**
2236
 * @todo Please document this function.
2237
 * @see http://drupal.org/node/1354
2238
 *
2239
 * @param array $cdm_entities
2240
 *   An array of CdmBase instances or a single instance.
2241
 * @param string $footnote_list_key_suggestion
2242
 *
2243
 * @return unknown
2244
 */
2245
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2246

    
2247
   static $annotations_types_filter = null;
2248
   if(!$annotations_types_filter) {
2249
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2250
   }
2251

    
2252
  $footNoteKeys = array();
2253

    
2254
  // Is argument cdmBase an array?
2255
  if (!is_array($cdm_entities)) {
2256
    $cdmBase_array = array();
2257
    $cdmBase_array[] = $cdm_entities;
2258
  }
2259
  else {
2260
    $cdmBase_array = $cdm_entities;
2261
  }
2262

    
2263
  // Getting the key for the footnotemanager.
2264
  if (isset($footnote_list_key_suggestion)) {
2265
    $footnote_list_key = $footnote_list_key_suggestion;
2266
  }
2267
  else {
2268
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2269
  }
2270

    
2271
  // Adding the footnotes keys.
2272
  foreach ($cdmBase_array as $cdmBase_element) {
2273
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2274
    if (is_array($annotations)) {
2275
      foreach ($annotations as $annotation) {
2276
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2277
      }
2278
    }
2279
  }
2280

    
2281
  return $footNoteKeys;
2282
}
2283

    
2284

    
2285
/**
2286
 * Creates a CDM Dynabox.
2287
 *
2288
 * @param string $dynabox_id
2289
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2290
 * @param string $label
2291
 *   The clickable text to show.
2292
 * @param string $content_url
2293
 *   The cdm REST service request url wich will deliver the content to be shown
2294
 *   once the dynabox toggles open.
2295
 * @param string $theme
2296
 *   The theme to be used for rendering the cdm REST service response with is
2297
 *   returned from the $content_url.
2298
 * @param string $link_alt_text
2299
 *   The value for the alt attribute of the dynabox link.
2300
 * @param array $enclosingtags
2301
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2302
 *   element itself, $enclosingtags[1] is the tag to be used for the
2303
 *   dynabox_content (optional)
2304
 * @param array $attributes
2305
 * @param $content_element_selector
2306
 *   Optional jQuery selector which can be used to reference a dom element which should
2307
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2308
 *  element will be placed in this container.
2309
 *
2310
 * @param string $open_callback
2311
 *   optional javascript call back function to be triggered after toggling the box to
2312
 *   the open state.
2313
 * @param string $close_callback
2314
 *   optional javascript call back function to be triggered after toggling the box to
2315
 *   the closed state.
2316
 * @return string Returns HTML for a dynabox.
2317
 * Returns HTML for a dynabox.
2318
 */
2319
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2320
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2321
                     $content_element_selector = null,
2322
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2323
  $out = '';
2324

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

    
2328
  if(!array_key_exists('class', $attributes)) {
2329
    $attributes['class'] = array();
2330
  }
2331
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2332
  $dynabox_attributes = drupal_attributes($attributes);
2333

    
2334

    
2335
  _add_js_domEvent(); // requires domEvent.js
2336
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2337
  drupal_add_js("
2338
  jQuery(document).ready(
2339
      function() {
2340
        dynabox('". $dynabox_id ."',
2341
          {
2342
            open_callback: " . $open_callback .",
2343
            close_callback: " . $close_callback .
2344
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2345
          }
2346
        );
2347
      }
2348
   );",
2349
   array(
2350
    'type'=>'inline',
2351
    'scope'=>'footer'
2352
    )
2353
  );
2354

    
2355

    
2356
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2357
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2358
  $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>';
2359
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2360
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2361
  $out .= '    </' . $enclosingtags[1] . '>';
2362
  $out .= '  </' . $enclosingtags[0] . '>';
2363
  $out .= '<!-- dynabox end -->';
2364
  return $out;
2365
}
2366

    
2367
/**
2368
 * Checks whether a feature has any description elements.
2369
 *
2370
 * @param mixed $featureNode
2371
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2372
 *
2373
 * @see _mergeFeatureTreeDescriptions()
2374
 *
2375
 * @return bool
2376
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2377
 *   contains at least one non empty TextData or at least one DescriptionElement
2378
 *   of an other type. A TextData element holding a multilanguageText or a
2379
 *   source reference is considered to be not empty.
2380
 *
2381
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2382
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2383
 *       $feature_block_has_content in compose_feature_block_items_generic
2384
 */
2385
function has_feature_node_description_elements($featureNode) {
2386

    
2387
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2388
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2389
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2390
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2391
          && $descriptionElement->multilanguageText_L10n->text != ''
2392
          || isset($descriptionElement->sources[0])
2393
          || isset($descriptionElement->media[0]) ) {
2394
          return TRUE;
2395
        }
2396
      }
2397
    }
2398
  }
2399
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2400
    foreach ($featureNode->childNodes as $child) {
2401
      if (has_feature_node_description_elements($child)) {
2402
        return TRUE;
2403
      }
2404
    }
2405
  }
2406
  return FALSE;
2407
}
2408

    
2409
/**
2410
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2411
 *
2412
 * @param $chapter
2413
 *   The taxon page chapter or part
2414
 */
2415
function cdm_check_valid_taxon_page($chapter){
2416
  static $taxon_tabs = null;
2417

    
2418
  cdm_check_valid_portal_page();
2419

    
2420
  if($taxon_tabs == null){
2421
    $taxon_tabs = array('all', 'description');
2422
    foreach(get_taxon_tabs_list() as $tab){
2423
      $taxon_tabs[] = strtolower($tab);
2424
    }
2425
  }
2426

    
2427
  if(!in_array($chapter, $taxon_tabs)){
2428
    // oops this is not a valid chapter name
2429
    http_response_code(404); // 404 = Not Found
2430
  }
2431

    
2432
}
2433

    
2434
/**
2435
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2436
 *
2437
 * @param $chapter
2438
 *   The taxon page chapter or part
2439
 */
2440
function cdm_check_valid_portal_page(){
2441
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2442
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2443
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2444
    http_response_code(404); // 404 = Not Found
2445
    exit('HTTP 404');
2446
  }
2447
}
2448

    
2449
/**
2450
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2451
 *
2452
 * @param $text_a
2453
 * @param $text_b
2454
 * @return string
2455
 */
2456
function diff_viewer($text_a, $text_b) {
2457

    
2458
  static $diff_viewer_count = 0;
2459

    
2460
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2461

    
2462
  // http://code.stephenmorley.org/php/diff-implementation/
2463
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2464
  drupal_add_css(drupal_get_path('module',
2465
      'cdm_dataportal') . '/css/diff.css');
2466
  _add_jquery_ui();
2467
  drupal_add_js(
2468
    'jQuery(document).ready( function(){
2469
        jQuery(\'#' . $element_id . '\').accordion({
2470
        collapsible: true,
2471
        active: false,
2472
        fillSpace: true,
2473
        }).children(\'div\').css({ \'height\': \'auto\' });
2474
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2475
     });'
2476
    , array(
2477
    'type' => 'inline',
2478
    'scope' => 'footer'
2479
  ));
2480

    
2481
  $diff = Diff::compare($text_a,
2482
    $text_b);
2483
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2484
    . Diff::toTable($diff, '', '')
2485
    . '</div></div>';
2486
  return $diff_viewer_markup;
2487
}
2488

    
2489

    
Add picture from clipboard (Maximum size: 40 MB)