Project

General

Profile

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

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

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

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

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

    
51

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

    
54

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

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

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

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

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

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

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

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

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

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

    
126
  function _add_js_openlayers() {
127

    
128
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
129
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
130

    
131
    if(variable_get('cdm_js_devel_mode', FALSE)){
132
      // develooper mode libs
133
  //     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
134
      $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
135
      $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
136
    }
137

    
138
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
139
      array(
140
        'type' => 'file',
141
        'weight' => JS_LIBRARY,
142
        'cache' => TRUE,
143
        'preprocess' => FALSE
144
      )
145
    );
146

    
147
    // see https://github.com/proj4js/proj4js
148
    // http://openlayers.org/dev/examples/using-proj4js.html
149
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
150
      array(
151
        'type' => 'file',
152
        'weight' => JS_LIBRARY,
153
        'cache' => TRUE,
154
      )
155
    );
156

    
157
    // configure the theme
158
    $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
159
    $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
160
    drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
161
        'type' => 'inline',
162
        'weight' => JS_LIBRARY,
163
        'cache' => TRUE,
164
        'preprocess' => FALSE
165
      ));
166

    
167
    drupal_add_css($openlayers_theme_path . 'style.tidy.css',
168
      array(
169
        'type' => 'file',
170
        'cache' => TRUE,
171
        'preprocess' => FALSE
172
      )
173
    );
174

    
175
  }
176

    
177
  /**
178
   * @todo Please document this function.
179
   * @see http://drupal.org/node/1354
180
   */
181
  function _add_js_thickbox() {
182
    // ---- jQuery thickbox:
183
    /*
184
    * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
185
    * not triggered because of problems with compat-1.0.js' see INSTALL.txt
186
    */
187
    // drupal_add_js(drupal_get_path('module',
188
    // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
189
    //
190
    // Add a setting for the path to cdm_dataportal module, used to find the path
191
    // for the loading animation image in thickbox.
192
    drupal_add_js(array(
193
    'cdm_dataportal' => array(
194
    'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
195
    )
196
    ),
197
    'setting'
198
        );
199
        drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
200
        drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
201
  }
202

    
203
  /**
204
   * @todo Please document this function.
205
   * @see http://drupal.org/node/1354
206
   */
207
  function _add_js_lightbox($galleryID) {
208
    /*
209
     * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
210
    * allow using the "alt" attribute for captions instead of the "title"
211
    * attribute
212
    */
213
    $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
214
    $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
215
    drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
216
    drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
217
    drupal_add_js('jQuery(document).ready(function() {
218
        jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
219
          fixedNavigation:  true,
220
          imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
221
          imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
222
          imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
223
          imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
224
          imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
225
          adjustToWindow: true
226
        });
227
      });
228
      ', array('type' => 'inline'));
229
  }
230

    
231
  /**
232
   * @todo Please document this function.
233
   * @see http://drupal.org/node/1354
234
   */
235
  function _add_js_footnotes() {
236
    _add_js_domEvent();
237
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
238
  }
239

    
240
  /**
241
   * @todo Please document this function.
242
   * @see http://drupal.org/node/1354
243
   */
244
  function _add_js_cluetip() {
245

    
246
    // TODO replace by
247
    // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
248
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
249
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
250
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
251
    if(variable_get('cdm_js_devel_mode', FALSE)){
252
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
253
    }
254
    drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
255
    drupal_add_js("jQuery(document).ready(function(){
256
        jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
257
          splitTitle: '|',
258
          showTitle: true,
259
          activation: 'hover',
260
          sicky: true,
261
          arrows: true,
262
          dropShadow: false,
263
          cluetipClass: 'rounded'
264
        });
265
      });", array('type' => 'inline'));
266
  }
267

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

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

    
278
  /**
279
   * Adds the external javascript file for domEvent.js.
280
   *
281
   * @see drupal_add_js()
282
   */
283
  function _add_js_domEvent() {
284
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
285
  }
286

    
287
  function _add_jquery_ui()
288
  {
289
    drupal_add_css(drupal_get_path('module',
290
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/themes/base/jquery.ui.all.css');
291
    drupal_add_js(drupal_get_path('module',
292
        'cdm_dataportal') . '/js/jquery-ui-1.8.24/ui/jquery-ui.js',
293
      array(
294
        'type' => 'file',
295
        'weight' => JS_LIBRARY,
296
        'cache' => TRUE,
297
        'preprocess' => FALSE
298
      )
299
    );
300
  }
301

    
302
  /**
303
   * Provides the markup for an font awesome icon.
304
   *
305
   * The icons is created in default size without any extra features.
306
   *
307
   * The available icons are listed here http://fontawesome.io/cheatsheet/
308
   * fontawesome icons have much more features than implemented here in this function,
309
   * for spinning icons, fixed width icons, rotation, etc please checkout the
310
   * examples at http://fontawesome.io/examples/
311
   *
312
   * @parameter $icon_name
313
   *  The name of the icon which starts with 'fa-'
314
   *
315
   * @return String
316
   *    the markup for the icon in an <i> tag
317
   *
318
   */
319
  function font_awesome_icon_markup($icon_name = NULL, $attributes = array()){
320

    
321

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

    
324
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.5.0/css/font-awesome.min.css';
325
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.5.0/css/font-awesome.min.css";
326

    
327
    drupal_add_html_head_link(
328
      array(
329
        'href' => $font_awesome_css_uri,
330
        'rel' => 'stylesheet'
331
      )
332
    );
333

    
334
    if($icon_name){
335
      if(!isset($attributes['class'])){
336
        $attributes['class'] = array();
337
      }
338
      $attributes['class'][] = 'fa';
339
      $attributes['class'][] = $icon_name;
340

    
341
      return '<i ' . drupal_attributes($attributes) . '></i>';
342
    }
343

    
344
    return '';
345
  }
346

    
347

    
348
  /* ====================== hook implementations ====================== */
349
  /**
350
   * Implements hook_permission().
351
   *
352
   * Valid permissions for this module.
353
   *
354
   * @return array
355
   *   An array of valid permissions for the portfolio module.
356
   */
357
  function cdm_dataportal_permission() {
358
    return array(
359
      'administer cdm_dataportal' => array(
360
        'title' => t('administer cdm_dataportal'),
361
        'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
362
      ),
363
      'cdm_dataportal view notes' => array(
364
        'title' => t('cdm_dataportal view notes'),
365
        'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
366
      ),
367
      // TODO Which other permissions are required?
368
      // -> check the WP6 requirements document.
369
    );
370
  }
371

    
372
/**
373
 * Implements hook_menu().
374
 */
375
function cdm_dataportal_menu() {
376
  $items = array();
377

    
378
  // @see settings.php.
379
  cdm_dataportal_menu_admin($items);
380
  cdm_dataportal_menu_help($items);
381

    
382
  $items['cdm_dataportal/names'] = array(
383
    'page callback' => 'cdm_dataportal_view_names',
384
    'access arguments' => array('access content'),
385
    'type' => MENU_CALLBACK,
386
  );
387

    
388
  // Optional callback arguments: page.
389
  $items['cdm_dataportal/taxon'] = array(
390
    'page callback' => 'cdm_dataportal_taxon_page_view',
391
    'access arguments' => array('access content'),
392
    'type' => MENU_CALLBACK,
393
    // Expected callback arguments: uuid.
394
  );
395

    
396
   // Optional callback arguments: page.
397
    //FIXME point to view/page method in this module
398
    $items['cdm_dataportal/specimen'] = array(
399
        'page callback' => 'cdm_dataportal_specimen_page_view',
400
        'access arguments' => array('access content'),
401
        'type' => MENU_CALLBACK,
402
        // Expected callback arguments: uuid.
403
    );
404

    
405
  $items['cdm_dataportal/name'] = array(
406
    'page callback' => 'cdm_dataportal_name_page_view',
407
      /*
408
    'page arguments' => array(
409
       'taxon_name_uuid',
410
       'taxon_to_hide_uuid',
411
       'synonym_uuid' => NULL
412
      ),
413
      */
414
    'access arguments' => array('access content'),
415
    'type' => MENU_CALLBACK,
416
    // Expected callback arguments: uuid.
417
  );
418

    
419
  $items['cdm_dataportal/reference'] = array(
420
    'page callback' => 'cdm_dataportal_view_reference',
421
    'access arguments' => array('access content'),
422
    'type' => MENU_CALLBACK,
423
    // Expected callback arguments: uuid.
424
  );
425

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

    
433
  $items['cdm_dataportal/media'] = array(
434
    'page callback' => 'cdm_dataportal_view_media',
435
    'access arguments' => array('access content'),
436
    'type' => MENU_CALLBACK,
437
    // Expected callback arguments:
438
    // uuid, mediarepresentation_uuid, part_uuid or part#.
439
  );
440

    
441
  $items['cdm_dataportal/polytomousKey'] = array(
442
    'page callback' => 'cdm_dataportal_view_polytomousKey',
443
    'access arguments' => array('access content'),
444
    'type' => MENU_CALLBACK,
445
    // Expected callback arguments: polytomousKey->uuid.
446
  );
447

    
448
  $items['cdm_dataportal/search'] = array(
449
    'page callback' => 'cdm_dataportal_view_search_advanced',
450
    'access arguments' => array('access content'),
451
    'type' => MENU_CALLBACK,
452
  );
453

    
454
  $items['cdm_dataportal/search/advanced'] = array(
455
    'title' => 'Advanced tt', // will be passed through t()
456
   // 'title arguments' => array('!title' => 'Advanced tt'), // will be passed through t()
457
    'page callback' => 'cdm_dataportal_view_search_advanced',
458
    'access arguments' => array('access content'),
459
    'type' => MENU_DEFAULT_LOCAL_TASK,
460
  );
461

    
462
  $items['cdm_dataportal/search/taxon_by_description'] = array(
463
    'title' => 'By factual data tt', // will be passed through t()
464
    'title arguments' => array('!title' => 'By factual data tt'), // will be passed through t()
465
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
466
    'access arguments' => array('access content'),
467
    'type' => MENU_LOCAL_TASK,
468
  );
469

    
470
  $items['cdm_dataportal/search/results/taxon'] = array(
471
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
472
    'access arguments' => array('access content'),
473
    'type' => MENU_CALLBACK,
474
  );
475
  /*
476
   $items['cdm/xml2json'] = array(
477
   'page callback' => 'cdm_view_xml2json',
478
   'access arguments' => array('access content'),
479
   'type' => MENU_CALLBACK,
480
   );
481
   */
482

    
483
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
484
  // User configuration of cdm_dataportal.
485
  $items['user/%/cdm_dataportal'] = array(
486
    'title' => 'cdm_dataportal',
487
    'access arguments' => array('access content'),
488
    'page callback' => 'drupal_get_form',
489
    'page arguments' => array('cdm_dataportal_user_form'),
490
    'type' => MENU_LOCAL_TASK,
491
    'weight' => 10,
492
  );
493
  // }
494

    
495
  // 'May not cache' in D5.
496
  $items['cdm_dataportal/name/%'] = array(
497
    // 'page callback' => 'cdm_dataportal_view_name',
498
    'page callback' => 'cdm_dataportal_name_page_view',
499
    'page arguments' => array(2, 3, 4),
500
    'access arguments' => array('access content'),
501
    'type' => MENU_CALLBACK,
502
  );
503

    
504
  // --- Local tasks for Taxon.
505
  // --- tabbed taxon page
506
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
507
    $items['cdm_dataportal/taxon/%'] = array(
508
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
509
      'page callback' => 'cdm_dataportal_taxon_page_view',
510
      'access arguments' => array('access content'),
511
      'type' => MENU_CALLBACK,
512
      'weight' => 1,
513
      'page arguments' => array(2, "description")
514
      , // Expected callback arguments: taxon_uuid.
515
    );
516

    
517
    $items['cdm_dataportal/taxon/%/all'] = array(
518
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
519
      'page callback' => 'cdm_dataportal_taxon_page_view',
520
      'access arguments' => array('access content'),
521
      'type' => MENU_CALLBACK,
522
      'weight' => 2,
523
      'page arguments' => array(2, "all")
524
      , // Expected callback arguments: taxon_uuid.
525
    );
526

    
527
    $items['cdm_dataportal/taxon/%/description'] = array(
528
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
529
      'page callback' => 'cdm_dataportal_taxon_page_view',
530
      'access arguments' => array('access content'),
531
      'type' => MENU_DEFAULT_LOCAL_TASK,
532
      'weight' => 2,
533
      'page arguments' => array(2, "description")
534
      , // Expected callback arguments: taxon_uuid.
535
    );
536

    
537
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
538
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
539
      'page callback' => 'cdm_dataportal_taxon_page_view',
540
      'access arguments' => array('access content'),
541
      'type' => MENU_LOCAL_TASK,
542
      'weight' => 4,
543
      'page arguments' => array(2, "synonymy", 4)
544
      , // Expected callback arguments: taxon_uuid and ...
545
    );
546
    $items['cdm_dataportal/taxon/%/images'] = array(
547
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
548
      'page callback' => 'cdm_dataportal_taxon_page_view',
549
      'access arguments' => array('access content'),
550
      'type' => MENU_LOCAL_TASK,
551
      'weight' => 5,
552
      'page arguments' => array(2, "images")
553
      , // Expected callback arguments: taxon_uuid.
554
    );
555

    
556
    $items['cdm_dataportal/taxon/%/specimens'] = array(
557
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
558
      'page callback' => 'cdm_dataportal_taxon_page_view',
559
      'access arguments' => array('access content'),
560
      'type' => MENU_LOCAL_TASK,
561
      'weight' => 6,
562
      'page arguments' => array(2, "specimens")
563
      , // Expected callback arguments: taxon_uuid.
564
    );
565

    
566
    $items['cdm_dataportal/taxon/%/keys'] = array(
567
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
568
      'page callback' => 'cdm_dataportal_taxon_page_view',
569
      'access arguments' => array('access content'),
570
      'type' => MENU_LOCAL_TASK,
571
      'weight' => 6,
572
      'page arguments' => array(2, "keys")
573
      , // Expected callback arguments: taxon_uuid.
574
    );
575

    
576
    $items['cdm_dataportal/taxon/%/experts'] = array(
577
        'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Experts')),
578
        'page callback' => 'cdm_dataportal_taxon_page_view',
579
        'access arguments' => array('access content'),
580
        'type' => MENU_LOCAL_TASK,
581
        'weight' => 6,
582
        'page arguments' => array(2, "experts")
583
    , // Expected callback arguments: taxon_uuid.
584
    );
585
  }
586

    
587
  // --- refresh link for all cdmnode types
588
  foreach (cdm_get_nodetypes() as $type=>$name) {
589
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
590
        'title' => t('Refresh'),
591
        'page callback' => 'cdm_dataportal_refresh_node',
592
        'access arguments' => array('administer cdm_dataportal'),
593
        'type' => MENU_LOCAL_TASK,
594
        'weight' => 100,
595
        'page arguments' => array($name, 2)
596
    );
597
  }
598

    
599
  return $items;
600
}
601

    
602
/**
603
 * Implements hook_init().
604
 *
605
 */
606
function cdm_dataportal_init() {
607
  //FIXME To add CSS or JS that should be present on all pages, modules
608
  //      should not implement this hook, but declare these files in their .info file.
609
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
610
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
611
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
612

    
613
  if(variable_get('cdm_debug_mode', FALSE)){
614
    $file = 'temporary://drupal_debug.txt';
615
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
616
  }
617

    
618
  $bibliography_settings = get_bibliography_settings();
619
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
620
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
621
}
622

    
623
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
624

    
625
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
626

    
627
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
628
    // force reloading of all and notify user about this special loading
629
    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: ')
630
        . l('Back to tabbed taxon page', $base_path));
631
    $base_path .= '/all';
632
  } else {
633
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
634
  }
635

    
636
  $parameters['cacheL2_refresh'] ='1';
637

    
638

    
639
  drupal_goto($base_path, array('query' => $parameters));
640
}
641

    
642
/**
643
 * The function generate form for own user cdm dataportal configurations.
644
 */
645
function cdm_dataportal_user_form($form, &$form_state) {
646

    
647
  global $user;
648
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
649

    
650
  $form['taxon_page_tabs'] = array(
651
      '#type' => 'fieldset',
652
      '#tree' => true,
653
      '#title' => t('Taxon page tabs'),
654
  );
655

    
656
  $form['taxon_page_tabs']['user_defined'] = array(
657
    '#type' => 'checkbox',
658
    '#title' => t('Activate user default configuration'),
659
    '#default_value' => variable_get($checkbox_value, 0),
660
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
661
  );
662

    
663
  $form['taxon_page_tabs']['default_tab'] = array(
664
    '#type' => 'select',
665
    '#title' => t('Default tab to display'),
666
    '#default_value' => get_default_taxon_tab(TRUE),
667
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
668
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
669
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
670
              to be rendered will be the synonymy of the accepted taxon and not the above selected tab.'),
671
  );
672

    
673

    
674
  if(false){
675
    $form['developer_options'] = array(
676
        '#type' => 'fieldset',
677
        '#tree' => true,
678
        '#title' => t('Developer options'),
679
    );
680

    
681
    $form['developer_options']['show_render_path'] = array(
682
      '#type' => 'checkbox',
683
      '#title' => t('Display the render path for each taxon name.'),
684
      '#default_value' => variable_get($checkbox_value, 0),
685
      '#description' => t('This option is very helpful if you are editing the !link for taxon names.',
686
        array(
687
            '!link' => l(
688
              'render template', 'admin/config/cdm_dataportal/settings/layout', array('fragment' => 'edit-cdm-name-render-templates'))
689
            )
690
        ),
691
    );
692
  }
693

    
694
  $form['submit'] = array(
695
    '#type' => 'submit',
696
    '#value' => t('Submit'),
697
  );
698

    
699
  return $form;
700
}
701

    
702
/**
703
 * Form submission handler for user_form().
704
 *
705
 * Submits the user cdm dataportal configurations.
706
 */
707
function cdm_dataportal_user_form_submit($form, &$form_state) {
708
  global $user;
709
  $msg_type = 'status';
710
  $username = $user->name;
711
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
712

    
713
  // FIXME: this is completely wrong, see user_profile_form_submit()
714

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

    
718
    // DEFAULT_TAXON_TAB
719
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
720
    variable_set($variable_to_use . '_active', $form_state['values']['taxon_page_tabs']['user_defined']);
721
    variable_set($variable_to_use, $form_state['values']['taxon_page_tabs']['default_tab']);
722
    if ($form_state['values']['taxon_page_tabs']['user_defined']) {
723
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
724
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
725
        '!tab' => $variable[variable_get($variable_to_use, 0)],
726
        '!user' => $username,
727
      ))), $msg_type);
728
    }
729
    else {
730
      drupal_set_message(check_plain(t('The user default tab wont be used for
731
        the next taxon site, check the box if you want to use the user default configuration.')));
732
    }
733

    
734
  }
735
  else {
736
    // Problem with the user id => variables wont be saved.
737
    $msg_type = 'warning';
738
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
739
  }
740
}
741

    
742
/**
743
 * Implements hook_block_info().
744
 */
745
function cdm_dataportal_block_info() {
746

    
747
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
748
    // $block[1]["info"] = t("CDM DataPortal Credits");
749
    $block["2"] = array(
750
        "info" => t("CDM Search Taxa"),
751
        "cache" => DRUPAL_NO_CACHE
752
      );
753
    // $block[3]["info"] = t("CDM Filters");
754
    $block["4"]["info"] = t("CDM Dataportal Print");
755
    $block["keys"]["info"] = t("CDM identification keys");
756
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
757
    $block["classification_breadcrumbs"] =  array(
758
        'info' => t('Classification breadcrumbs'),
759
        'cache' => DRUPAL_CACHE_PER_PAGE
760
      );
761

    
762
    return $block;
763
}
764

    
765
/**
766
 * Implements hook_block_view().
767
 */
768
function cdm_dataportal_block_view($delta) {
769
  // TODO Rename block deltas (e.g. '2') to readable strings.
770
  switch ($delta) {
771
    // case 'delta-1':
772
    // $block['subject'] = t('Credits');
773
    // $block['content'] = theme('cdm_credits');
774
    // return $block;
775
    case '2':
776
      $block['subject'] = t('Search taxa');
777
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
778
      $block['content'] = drupal_render($form);
779

    
780
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
781
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
782
      }
783
      return $block;
784
    case '4':
785
      $block['subject'] = '';
786
      $block['content'] = theme('cdm_print_button');
787
      return $block;
788
    case "keys":
789
      $block['subject'] = t('Identification Keys');
790
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
791
      return $block;
792
    case "fundedByEDIT":
793
      // t('Funded by EDIT');
794
      $text = '<none>';
795
      $block['subject'] = $text;
796
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
797
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
798
        'attributes' => array("target" => "EDIT"),
799
        'absolute' => TRUE,
800
        'html' => TRUE,
801
      ));
802
      return $block;
803
    case 'classification_breadcrumbs':
804
      if (arg(1) == 'taxon' && is_uuid(arg(2))) {
805
        $block['subject'] = '<none>';
806
        $block['content'] = compose_classification_breadcrumbs(arg(2));
807
        return $block;
808
      }
809
      break;
810
  }
811
}
812

    
813
/*
814
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
815
 $_SESSION['cdm'] = NULL;
816
 if(is_string($cdm_ws_uri_update)){
817
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
818
 }
819
 }
820

    
821
 function cdm_dataportal_session_validate(){
822
 if(!isset($_SESSION['cdm']['ws_uri'])){
823
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
824
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
825
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
826
 }
827
 }
828
 */
829

    
830
/**
831
 * creates a  selector form for taxonomic trees.
832
 *
833
 * @return a drupal form array
834
 */
835
function cdm_taxonomictree_selector() {
836
  _add_js_treeselector();
837

    
838
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
839
  return $form;
840
}
841

    
842
/**
843
 * @todo Please document this function.
844
 * @see http://drupal.org/node/1354
845
 */
846
function cdm_taxonomictree_selector_form($form, &$form_state) {
847

    
848
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
849
  $form['#action'] = $url;
850

    
851
  $form['var'] = array(
852
    '#weight' => -3,
853
    '#type' => 'hidden',
854
    '#value' => '[cdm][taxonomictree_uuid]',
855
  );
856

    
857
  $destination_array = drupal_get_destination();
858
  $destination = $destination_array['destination'];
859

    
860
  $form['destination'] = array(
861
    '#weight' => -3,
862
    '#type' => 'hidden',
863
    '#value' =>  $destination,
864
  );
865

    
866
  $options = cdm_get_taxontrees_as_options();
867
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
868
  if($taxontree_includes){
869
    $filtered_options = array();
870
    foreach($options as $uuid=>$label){
871
      if(!empty($taxontree_includes[$uuid])){
872
        $filtered_options[$uuid] = $label;
873
      }
874
    }
875
    $options = $filtered_options;
876
  }
877

    
878
  $form['val'] = array(
879
    '#type' => 'select',
880
    '#title' => t('Available classifications'),
881
    '#default_value' => get_current_classification_uuid(),
882
    '#options' => $options,
883
    '#attributes' => array('class' => array('highlite-first-child'))
884
  );
885

    
886
  return $form;
887

    
888
}
889

    
890
/* UNREACHABLE since action of form directly links to view.
891
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
892

    
893
 $_SESSION['cdm']['search'] = $form_values;
894
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
895
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
896
 //$paramstr = compose_url_prameterstr($form_values);
897
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
898
 }
899
 */
900
/* ====================== menu callback functions ====================== */
901
/**
902
 * @todo Please document this function.
903
 * @see http://drupal.org/node/1354
904
 */
905
/*
906
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
907
  static $comment_node_disabled =  0;
908
  static $comment_node_read_only =  1;
909
  static $comment_node_read_write =  2;
910

    
911
  if ($form_id == 'node_type_form'
912
   && isset($form['identity']['type'])
913
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
914
  ) {
915
    $form['workflow']['comment'] = array(
916
      '#type' => 'radios',
917
      '#title' => t('Default comment setting'),
918
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
919
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
920
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
921
    );
922
  }
923
}
924
*/
925

    
926
/**
927
 * Displays a list of the known taxonomic names.
928
 *
929
 * When the list of taxonomic names is displayed, long lists are split up into
930
 * multiple pages.
931
 *
932
 * TODO: Parameters are still preliminary.
933
 *
934
 * @param string $beginsWith
935
 * @param string $page
936
 *   Page number to diplay defaults to page 1.
937
 * @param bool $onlyAccepted
938
 */
939
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
940

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

    
943
  /*
944
  // FIXME the filter for accepted names will be a form element, thus this
945
  // widget should be generated via form api preferably as block.
946
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
947
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
948
  $out .= theme('cdm_listof_taxa', $taxonPager);
949
  return $out;
950
  */
951
}
952

    
953
/**
954
 * @todo Please document this function.
955
 * @see http://drupal.org/node/1354
956
 */
957
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
958

    
959
  cdm_check_valid_portal_page();
960

    
961
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
962
  return theme('cdm_reference_page', array('reference' => $reference));
963
}
964

    
965
/**
966
 * Creates a view on a all references contained in the portal.
967
 *
968
 * This function is used at the path cdm_dataportal/reference/list
969
 */
970
function cdm_dataportal_view_reference_list($pageNumber) {
971
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
972
  cdm_reference_pager($referencePager, 'cdm_dataportal/reference/list/');
973
}
974

    
975
/**
976
 * @todo Please document this function.
977
 * @see http://drupal.org/node/1354
978
 */
979
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
980

    
981
  cdm_check_valid_portal_page();
982

    
983
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
984
  return theme('cdm_media_page', array(
985
    'media' => $media,
986
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
987
    'partId' => $part,
988
    ));
989
}
990

    
991
/**
992
 * @todo Please document this function.
993
 * @see http://drupal.org/node/1354
994
 */
995
function _load_taxonBase(&$taxonBase) {
996
  if (isset($taxonBase->uuid)) {
997
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
998
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
999
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1000
  }
1001
}
1002

    
1003
/**
1004
 * Loads the media associated to the given taxon from the cdm server.
1005
 * The aggregation settings regarding taxon relathionships and
1006
 * taxonnomic childen are taken into account.
1007
 *
1008
 * The media lists are cached in a static variable.
1009
 *
1010
 * @param Taxon $taxon
1011
 *   A CDM Taxon entitiy
1012
 *
1013
 * @return array
1014
 *   An array of CDM Media entities
1015
 *
1016
 */
1017
function _load_media_for_taxon($taxon) {
1018

    
1019
  static $media = NULL;
1020

    
1021
  if(!isset($media)) {
1022
    $media = array();
1023
  }
1024
  if (!isset($media[$taxon->uuid])) {
1025

    
1026
    // --- GET Images --- //
1027
    $mediaQueryParameters = array(
1028
        "type" => "ImageFile",
1029
    );
1030

    
1031
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1032
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1033
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1034

    
1035
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1036
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1037
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1038
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1039

    
1040
    $ws_endpoint = NULL;
1041
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1042
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1043
    } else {
1044
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1045
    }
1046

    
1047
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1048
        array(
1049
            $taxon->uuid,
1050
        ),
1051
        queryString($mediaQueryParameters)
1052
       );
1053
  }
1054

    
1055
  return $media[$taxon->uuid];
1056
}
1057

    
1058
/**
1059
 *
1060
 * @param Taxon $taxon
1061
 *   A CDM Taxon entitiy
1062
 *
1063
 * @return array
1064
 *   An array of CDM SpecimenOrObservation entities
1065
 *
1066
function _load_occurences_for_taxon($taxon){
1067

    
1068
  static $occurences = NULL;
1069

    
1070
  if(!isset($occurences)) {
1071
    $occurences = array();
1072
  }
1073

    
1074
  if (!isset($occurences[$taxon->uuid])){
1075

    
1076
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1077
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1078
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1079

    
1080
    $by_associatedtaxon_query = http_build_query(array(
1081
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1082
        'relationships' => implode(',', $relationship_choice['direct']),
1083
        'pageSize' => null // all hits in one page
1084
    )
1085
    );
1086

    
1087
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1088
        null,
1089
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1090
    );
1091

    
1092

    
1093
    if(isset($pager->records[0])){
1094
      $occurences[$taxon->uuid] =  $pager->records;
1095
    }
1096
  }
1097
  return $occurences[$taxon->uuid];
1098
}
1099
 */
1100

    
1101
/**
1102
 * Gets a Drupal variable, string or array and returns it.
1103
 *
1104
 * Similar to the variable_get() function of Drupal, except that this function
1105
 * is able to handle arrays correctly. This function is especially useful
1106
 * when dealing with collections of settings form elements (#tree = TRUE).
1107
 *
1108
 * @param string $variableKey
1109
 *   The Unique key of the Drupal variable in the Drupal variables table.
1110
 * @param string $defaultValueString
1111
 *   A string as for example derived from a CONSTANT.
1112
 *
1113
 * @return mixed
1114
 *   usually an array, depending on the nature of the variable.
1115
 *
1116
 * TODO compare with get_array_variable_merged() duplicate functions?
1117
 * @deprecated rather use get_array_variable_merged() since this function
1118
 * used an array as second parameter
1119
 */
1120
function mixed_variable_get($variableKey, $defaultValueString) {
1121
  $systemDefaults = unserialize($defaultValueString);
1122
  $storedSettings = variable_get($variableKey, array());
1123
  if (is_array($storedSettings)) {
1124
    // TODO better use drupal_array_merge_deep() ?
1125
    $settings = array_merge($systemDefaults, $storedSettings);
1126
  }
1127
  else {
1128
    $settings = $systemDefaults;
1129
  }
1130
  return $settings;
1131
}
1132

    
1133
/**
1134
 * Recursive function to convert an object into an array.
1135
 * also subordinate objects will be converted.
1136
 *
1137
 * @param object $object
1138
 * @return the array
1139
 */
1140
function convert_to_array($object) {
1141
  if(is_object($object) || is_array($object)) {
1142
    $array = (array)$object;
1143
    foreach ($array as $key=>$value){
1144
      $array[$key] = convert_to_array($value);
1145
    }
1146
    return $array;
1147
  } else {
1148
    return $object;
1149
  }
1150
}
1151

    
1152
/**
1153
 * Searches the $collection for the cdm entitiy given as $element.
1154
 *
1155
 * The elements are compared by their UUID.
1156
 *
1157
 * @param $element
1158
 *  the CDM entitiy to search for
1159
 * @param $collection
1160
 *  the list of CDM entities to search in
1161
 *
1162
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1163
 *
1164
 */
1165
function contains_cdm_entitiy($element, $collection) {
1166
  $result = FALSE;
1167
  foreach ($collection as $a) {
1168
    if ($a->uuid == $element->uuid) {
1169
      $result = TRUE;
1170
    }
1171
  }
1172
  return $result;
1173
}
1174

    
1175
/**
1176
 * Fiters the array $entity_list of CDM entities by the list
1177
 * of $excludes. Any element contained in the $excludes will be removed
1178
 * from included int the retuned list.
1179
 *
1180
 * If the $entity_list is not an array the $excludes will be returned.
1181
 */
1182
function filter_cdm_entity_list($entity_list, $excludes) {
1183
  if (is_array($entity_list)) {
1184
    $result = $entity_list;
1185
    if ($excludes) {
1186
      foreach ($excludes as $exclude) {
1187
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1188
          $result[] = $exclude;
1189
        }
1190
      }
1191
    }
1192
  }
1193
  else {
1194
    $result = $excludes;
1195
  }
1196
  return $result;
1197
}
1198

    
1199
/**
1200
 * Wraps the given $html string into a render array suitable for drupal_render()
1201
 *
1202
 * @param $html
1203
 *   the html string, see
1204
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1205
 * @param $weight
1206
 *   A positive or negative number (integer or decimal).
1207
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1208
 * @param $prefix
1209
 *   Optional markup for the '#prefix' element of the render array
1210
 * @param $suffix
1211
 *   Optional markup for the '#suffix' element of the render array
1212
 *
1213
 * @return array
1214
 *   A render array
1215
 *
1216
 */
1217
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1218
  $render_array = array(
1219
    '#markup' => $html
1220
      );
1221
  if (is_numeric($weight)) {
1222
    $render_array['#weight'] = $weight;
1223
  }
1224
  if($prefix){
1225
    $render_array['#prefix'] = $prefix;
1226
  }
1227
  if($suffix) {
1228
    $render_array['#suffix'] = $suffix;
1229
  }
1230
  return $render_array;
1231
}
1232

    
1233
/**
1234
 * Loads the subgraph of a given PolytomousKeyNode.
1235
 *
1236
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1237
 * the CDM REST service.
1238
 *
1239
 * @param mixed $polytomousKeyNode
1240
 *   PolytomousKeyNode passed by reference.
1241
 *
1242
 * @return void
1243
 */
1244
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1245

    
1246
  if (!$polytomousKeyNode) {
1247
    return;
1248
  }
1249
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1250
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1251
    return;
1252
  }
1253
  if (!is_uuid($polytomousKeyNode->uuid)) {
1254
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1255
    return;
1256
  }
1257

    
1258
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1259

    
1260
  if (!$polytomousKeyNode) {
1261
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1262
    return;
1263
  }
1264

    
1265
  // Load children.
1266
  foreach ($polytomousKeyNode->children as &$childNode) {
1267
    _load_polytomousKeySubGraph($childNode);
1268
  }
1269

    
1270
  // Load subkey.
1271
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1272

    
1273
  // Load taxon.
1274
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1275
  _load_taxonBase($polytomousKeyNode->taxon);
1276
  return;
1277
}
1278

    
1279
/**
1280
 * @todo Please document this function.
1281
 * @see http://drupal.org/node/1354
1282
 */
1283
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1284

    
1285
  cdm_check_valid_portal_page();
1286

    
1287
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1288

    
1289
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1290
  if (is_array($sourcePager->records)) {
1291
    $polytomousKey->sources = $sourcePager->records;
1292
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1293
  }
1294

    
1295
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1296
  if (is_array($annotationPager->records)) {
1297
    $polytomousKey->annotations = $annotationPager->records;
1298
  }
1299

    
1300
  _load_polytomousKeySubGraph($polytomousKey->root);
1301
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1302
}
1303

    
1304
/**
1305
 * Creates a taxon page view or a chapter of it.
1306
 *
1307
 * The taxon page gives detailed information on a taxon, it shows:
1308
 *  - Taxon name.
1309
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1310
 *    heterotypic and finally followed by misapplied names.
1311
 *    The list is ordered historically.
1312
 *  - All description associated with the taxon.
1313
 *
1314
 * @param string $uuid
1315
 * @param string $chapter
1316
 *   Name of the part to display, valid values are:
1317
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1318
 *
1319
 * @return unknown_type
1320
 */
1321
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1322

    
1323
  cdm_check_valid_taxon_page($chapter);
1324
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1325
  // show a warning in case the javascript development mode is anabled
1326
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1327
    drupal_set_message(t('The !url1 is enabled.
1328
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1329
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1330
    )),
1331
    'warning'
1332
        );
1333
  }
1334

    
1335
  // Display the page for the taxon defined by $uuid.
1336
  // set_last_taxon_page_tab(arg(3));
1337
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1338
  if (!empty($taxonpage)) {
1339
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1340
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1341
  }
1342
  else {
1343
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1344
    return '';
1345
  }
1346
}
1347

    
1348
/**
1349
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1350
 * which has two fields, one for the page title and one for the content. Later on in the
1351
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1352
 * function as the function parameters $title and $content.
1353
 *
1354
 * @param string $uuid
1355
 *   the uuid of the taxon to show
1356
 * @param string $chapter
1357
 *   Name of the part to display, valid values are:
1358
 *   'description', 'images', 'synonymy', 'all'.
1359
 *
1360
 * @return taxonpage object with the following fields:
1361
 *   - title : the title of the page
1362
 *   - content: the content of the page
1363
 *
1364
 */
1365
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1366
  // Taxon object.
1367
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1368
  if (empty($taxon)) {
1369
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1370
    return FALSE;
1371
  }
1372
  $taxonpage = new stdClass();
1373

    
1374
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1375
    'taxon' => $taxon
1376
  ));
1377

    
1378
  // Check if the taxon id contained in the currently selected tree.
1379
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1380

    
1381
  if (!$taxon_in_current_classification) {
1382
    $classifications = get_classifications_for_taxon($taxon);
1383
    RenderHints::pushToRenderStack('not_in_current_classification');
1384
    $taxon_name_markup = render_taxon_or_name($taxon);
1385

    
1386
    if (count($classifications) == 0) {
1387
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification.',
1388
        array(
1389
        '!taxonname' => $taxon_name_markup,
1390
        )
1391
      ), 'warning');
1392
    }
1393
    else {
1394
      $trees = '';
1395
      foreach ($classifications as $classification) {
1396
        if (isset($classification->titleCache)) {
1397
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1398
        }
1399
      }
1400

    
1401
      drupal_set_message(format_plural(count($trees),
1402
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in this one: !trees',
1403
          'This concept of the taxon !taxonname is not contained as an accepted taxon in the currently chosen classification, but in one of these: !trees',
1404
          array('!taxonname' => $taxon_name_markup, '!trees' => $trees)
1405
        ) ,
1406
        'warning');
1407
    }
1408
    RenderHints::popFromRenderStack();
1409
  }
1410

    
1411
  // Render the taxon page.
1412
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1413
  $taxonpage->content = drupal_render($render_array);
1414

    
1415
  return $taxonpage;
1416
}
1417

    
1418
/**
1419
 * Creates a specimen page view.
1420
 * @param string $uuid the UUID of the specimen
1421
 * @return array|string
1422
 */
1423
function cdm_dataportal_specimen_page_view($uuid) {
1424

    
1425
    //cdm_check_valid_taxon_page($chapter);
1426
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1427
    // show a warning in case the javascript development mode is anabled
1428
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1429
        drupal_set_message(t('The !url1 is enabled.
1430
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1431
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1432
        )),
1433
            'warning'
1434
        );
1435
    }
1436

    
1437
    // Display the page for the specimen defined by $uuid.
1438
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1439
    if (!empty($specimenpage)) {
1440
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1441
    }
1442
    else {
1443
        return '';
1444
    }
1445
}
1446

    
1447
/**
1448
 *
1449
 * Creates a specimen view.
1450
 * @param string $uuid the UUID of the specimen
1451
 * @return array|string
1452
 */
1453
function cdm_dataportal_specimen_view($uuid) {
1454
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1455
    if (empty($specimen)) {
1456
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1457
        return FALSE;
1458
    }
1459
    $specimenpage = new stdClass();
1460

    
1461
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1462
        'specimen' => $specimen
1463
    ));
1464

    
1465
    // Render the specimen page.
1466
    $render_array = compose_cdm_specimen_page($uuid);
1467
    $specimenpage->content = drupal_render($render_array);
1468

    
1469
    return $specimenpage;
1470
}
1471

    
1472
/**
1473
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1474
 *
1475
 * The node page shows the taxon name title and the list of taxon related
1476
 * with such taxon. Name on the tree already in use.
1477
 *
1478
 * @param UUID $taxon_name_uuid
1479
 *   The uuid of the CDM TaxonNameBase to show a name page for
1480
 * @param UUID $taxon_to_hide_uuid
1481
 *   A taxon which should not be displayed in the taxon list
1482
 * @param UUID $highlite_synonym_uuid
1483
 *   Optinal parameter wich takes another taxon uuid, if given the
1484
 *   target taxon pages will show the syonymy tab where the taxon
1485
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1486
 *   in case it is found on this page.
1487
 *
1488
 * @return mixed
1489
 *   The formatted name page as node.
1490
 */
1491
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1492

    
1493
  cdm_check_valid_portal_page();
1494

    
1495
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1496
  if (!empty($taxonname_page)) {
1497
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1498
  }
1499
  else {
1500
    return '';
1501
  }
1502
}
1503

    
1504
/**
1505
 * View function for a TaxonNameBase page.
1506
 *
1507
 * The name page lists all taxa for which the name specified by the
1508
 * $taxon_name_uuid is being used. I case there is only one name the
1509
 * page automatically redirects ti the according taxon page. Otherwise
1510
 * the list of names is displayed.
1511
 *
1512
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1513
 * list of taxa. This is useful for example when referencing from a taxon
1514
 * to the name page and the referring taxon should not be repeaded in the
1515
 * name page.
1516
 *
1517
 *
1518
 * @param UUID $taxon_name_uuid
1519
 *   The uuid of the CDM TaxonNameBase to show a name page for
1520
 * @param UUID $taxon_to_hide_uuid
1521
 *   A taxon which should not be displayed in the taxon list
1522
 * @param UUID $highlite_synonym_uuid
1523
 *   Optinal parameter wich takes another taxon uuid, if given the
1524
 *   target taxon pages will show the syonymy tab where the taxon
1525
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1526
 *   in case it is found on this page.
1527
 *
1528
 * @return object
1529
 *   An object with two fields:
1530
 *     - title: the page title
1531
 *     - content: the page content
1532
 */
1533
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1534
  // Getting the full taxonname object from the server.
1535
  $taxon_name = cdm_ws_get(CDM_WS_PORTAL_NAME, array($taxon_name_uuid));
1536
  if (!$taxon_name) {
1537
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1538
    return FALSE;
1539
  }
1540
  // Searching for all the taxa connected with the taxon name on the tree
1541
  // in use.
1542
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1543
  $request_params = array();
1544
  $request_params['query'] = $name_cache;
1545
  $request_params['tree'] = get_current_classification_uuid();
1546
  $request_params['doTaxa'] = 1;
1547
  $request_params['doSynonyms'] = 1;
1548
  $request_params['doTaxaByCommonNames'] = 0;
1549
  $request_params['matchMode'] = "EXACT";
1550
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1551

    
1552
  // Removing the name where we came from.
1553
  foreach ($taxon_pager->records as $k => &$taxon) {
1554
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1555
      unset($taxon_pager->records[$k]);
1556
    }
1557
  }
1558
  // Show the taxa list or go to the singular taxon.
1559
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1560
    $singleTaxon = array_pop($taxon_pager->records);
1561
    if ($singleTaxon->class != "Taxon") {
1562
      // It is a Synonym -> look for the accepted.
1563
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1564
      if (!empty($highlite_synonym_uuid)) {
1565
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1566
      }
1567
      else {
1568
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1569
      }
1570
    }
1571
    else {
1572
      // It is an accepted taxon.
1573
      if (!empty($highlite_synonym_uuid)) {
1574
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1575
      }
1576
      else {
1577
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1578
      }
1579
    }
1580
  }
1581
  else {// More than one taxa case.
1582
    $taxon_name_page = new stdClass();
1583
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1584
    if ($taxon_pager->records) {
1585
      $taxon_name_page->content = compose_list_of_taxa($taxon_pager->records);
1586
    }
1587
    else {
1588
      $taxon_name_page->content = 'This name has no taxa';
1589
    }
1590
    return $taxon_name_page;
1591
  }
1592
}
1593

    
1594
/**
1595
 * Creates a page with the advance search form.
1596
 *
1597
 * NOTE: The advance search form allows searching for taxa.
1598
 */
1599
function cdm_dataportal_view_search_advanced() {
1600
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1601
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1602
}
1603

    
1604
/**
1605
 * Creates a page with the search form for searching by taxon descriptions.
1606
 */
1607
function cdm_dataportal_view_search_taxon_by_description() {
1608
  drupal_set_title(t('Search by factual data'), PASS_THROUGH);
1609
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1610
}
1611

    
1612
/**
1613
 * Executes the search and generates the result list of taxa.
1614
 */
1615
function cdm_dataportal_view_search_results_taxon() {
1616

    
1617
  $taxonPager = cdm_dataportal_search_execute();
1618

    
1619
  $showThumbnails = do_showThumbnails();
1620

    
1621
  $setSessionUri = url('cdm_api/setvalue/session', array(
1622
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1623
  ));
1624

    
1625
  drupal_add_js('jQuery(document).ready(function() {
1626

    
1627
      // init
1628
      if(' . $showThumbnails . ' == 1){
1629
          jQuery(\'.media_gallery\').show(20);
1630
      } else {
1631
          jQuery(\'.media_gallery\').hide(20);
1632
      }
1633

    
1634
      // add change handler
1635
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1636
      function(event){
1637
        var state = 0;
1638
        if(jQuery(this).is(\':checked\')){
1639
          jQuery(\'.media_gallery\').show(20);
1640
          state = 1;
1641
        } else {
1642
          jQuery(\'.media_gallery\').hide(20);
1643
        }
1644
        // store state in session variable
1645
        var uri = \'' . $setSessionUri . '\' + state;
1646
        jQuery.get(uri);
1647
      });
1648
  });',
1649
  array('type' => "inline", 'scope' => JS_DEFAULT));
1650

    
1651
  drupal_set_title(t('Search results'), PASS_THROUGH);
1652

    
1653
  return theme('cdm_search_results', array(
1654
    'pager' => $taxonPager,
1655
    'path' => 'cdm_dataportal/search/results/taxon',
1656
    ));
1657
}
1658

    
1659
/**
1660
 * Provides the standart image wich indicated a loading process
1661
 *
1662
 * @return string
1663
 *  The img html tag
1664
 */
1665
function loading_image_html() {
1666
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1667
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1668
}
1669

    
1670
/**
1671
 * Returns the state of the the showThumbnails flag set in the
1672
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1673
 *
1674
 * @return boolean
1675
 *    returns 1 if the flag is set
1676
 */
1677
function do_showThumbnails() {
1678
  static $showThumbnails = null;
1679

    
1680
  if($showThumbnails == null) {
1681
    $showThumbnails = 0;
1682
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1683
      $showThumbnails = 0;
1684
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1685
      $showThumbnails = is_array($search_gallery_settings)
1686
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1687
        && (
1688
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1689
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1690
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1691
            )
1692
         ? 1 : 0;
1693

    
1694
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1695
    }
1696
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1697
    if (!is_numeric($showThumbnails)) {
1698
      $showThumbnails = 1;
1699
    }
1700
  }
1701

    
1702
  return $showThumbnails;
1703
}
1704

    
1705
/**
1706
 * View which transforms XML output from a given webservice endpoint into JSON.
1707
 */
1708
/*
1709
 function cdm_view_xml2json(){
1710
 $file = arg(2);
1711
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1712
 return  xml2json::transformXmlStringToJson($datastr);
1713
 }
1714
 */
1715

    
1716
/* ====================== other functions ====================== */
1717
/**
1718
 * Creates a URL to the taxon page specified by the $uuid parameter.
1719
 *
1720
 * The URL will be prepended with a path element to a specific taxon page tab.
1721
 *
1722
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1723
 * be set globally in the administrative settings or individually in the user
1724
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1725
 * the last portal will stay on this last tab.
1726
 *
1727
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1728
 * internal mechanism by a specific value.
1729
 *
1730
 * @param string $uuid
1731
 *   The UUID of the taxon.
1732
 * @param string $page_tab
1733
 *   Overwriting the preset mechanism by defining specific value for the
1734
 *   taxon page tab.
1735
 *
1736
 * @return string
1737
 *   The created URL.
1738
 */
1739
function path_to_taxon($uuid, $page_tab = FALSE) {
1740

    
1741
  $tab = get_default_taxon_tab();
1742
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1743

    
1744
  if (!$uuid) {
1745
    return FALSE;
1746
  }
1747

    
1748
  if ($page_tab) {
1749
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1750
  }
1751
  elseif (!$tab || strtolower($tab) == 'general') {
1752
    return 'cdm_dataportal/taxon/' . $uuid;
1753
  }
1754
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1755
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1756
  }
1757
  else {
1758
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1759
  }
1760
}
1761

    
1762
function path_to_specimen($uuid) {
1763

    
1764
    if (!$uuid) {
1765
        return FALSE;
1766
    }
1767
    else {
1768
        return 'cdm_dataportal/specimen/' . $uuid;
1769
    }
1770
}
1771

    
1772
/**
1773
 * Creates a URL to show a synonmy in the according taxon page.
1774
 *
1775
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1776
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1777
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1778
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1779
 * in the page
1780
 *
1781
 * @param string $synonymUuid
1782
 *    The uuid of the synonym
1783
 * @param string $acceptedUuid
1784
 *    The uuid of the according accepted taxon
1785
 * @return string
1786
 *    The URL to show a synonmy in the according taxon page
1787
 */
1788
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1789
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1790
  return url($acceptedPath, array(
1791
      'query' => array(
1792
        // highlite the synony in the synonymy
1793
        'highlite' => $synonymUuid,
1794
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1795
        // see theme_taxon_page_title()
1796
        'acceptedFor' => $synonymUuid
1797
      ),
1798
      'fragment' => $synonymUuid
1799
  ));
1800

    
1801
}
1802

    
1803
/**
1804
 * Compses the drupal path to the key identified by the uuid.
1805
 *
1806
 * @param string $keyType
1807
 *    the key typer corresponds to the specific class of the CDM
1808
 *    IdentificationKey. Possible values are
1809
 *      -PolytomousKey
1810
 *      -MultimediaKey
1811
 *      - ...
1812
 * @param UUID $keyUuid
1813
 *   The UUID of the key
1814
 */
1815
function path_to_key($keyType, $keyUuid) {
1816
  if (!$keyUuid || !$keyType) {
1817
    return FALSE;
1818
  }
1819
  $keyType{0} = strtolower($keyType{0});
1820
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1821
}
1822

    
1823
/**
1824
 * @todo Please document this function.
1825
 * @see http://drupal.org/node/1354
1826
 */
1827
function path_to_reference($uuid) {
1828
  if (!$uuid) {
1829
    return FALSE;
1830
  }
1831
  return 'cdm_dataportal/reference/' . $uuid;
1832
}
1833

    
1834
/**
1835
 * Creates the path to a cdm_dataportal taxon name page.
1836
 *
1837
 * @param UUID $taxon_name_uuid
1838
 *   The uuid of the CDM TaxonNameBase to show a name page for
1839
 * @param UUID $taxon_to_hide_uuid
1840
 *   A taxon which should not be displayed in the taxon list
1841
 * @param UUID $highlite_synonym_uuid
1842
 *   Optinal parameter wich takes another taxon uuid, if given the
1843
 *   target taxon pages will show the syonymy tab where the taxon
1844
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1845
 *   in case it is found on this page.
1846
 *
1847
 * @return a URI path element as string
1848
 */
1849
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1850
  $res = FALSE;
1851
  if ($name_uuid) {
1852
    $res = 'cdm_dataportal/name/' . $name_uuid;
1853
  }
1854
  if($taxon_to_hide_uuid){
1855
    $res .= '/' . $taxon_to_hide_uuid;
1856
    if($synonym_uuid){
1857
      $res .= '/' . $synonym_uuid;
1858
    }
1859
  }
1860
  return $res;
1861
}
1862

    
1863
/**
1864
 * @todo Please document this function.
1865
 * @see http://drupal.org/node/1354
1866
 */
1867
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1868
  if (!$uuid) {
1869
    return FALSE;
1870
  }
1871
  $out = 'cdm_dataportal/media/' . $uuid;
1872
  if ($representaion_uuid) {
1873
    $out .= '/' . $representaion_uuid;
1874
    if ($partId !== FALSE) {
1875
      $out .= '/' . $partId;
1876
    }
1877
  }
1878
  return $out;
1879
}
1880

    
1881
/**
1882
 * Compares thisRank with thatRank.
1883
 *
1884
 * Returns a negative integer, zero, or a positive integer
1885
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1886
 * e.g:
1887
 * <ul>
1888
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1889
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1890
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1891
 * </ul>
1892
 * <p>
1893
 * This compare logic of the underlying webservice is the
1894
 * <b>inverse logic</b> of the the one implemented in
1895
 * java.lang.Comparable#compareTo(java.lang.Object)
1896
 *
1897
 * @param $thisRankUuid
1898
 * @param $thatRankUuid
1899
 *
1900
 * @return int
1901
 *   A negative integer, zero, or a positive integer
1902
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1903
 */
1904
function rank_compare($thisRankUuid, $thatRankUuid) {
1905
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1906
  return $result->Integer;
1907
}
1908

    
1909
/**
1910
 * Composes an HTML element class attribute value composed of
1911
 * the shortname of the cdm class and the uuid of the entity.
1912
 * This class attribute should be used whereever an cdm-entity is rendered.
1913
 *
1914
 * These according class selectors in css must be escaped, eg:
1915
 *    .cdm\:TextData
1916
 *
1917
 * @param $cdmEntity
1918
 */
1919
function html_class_attribute_ref($cdmEntity) {
1920

    
1921
  if (is_cdm_entity($cdmEntity)) {
1922
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1923
  }
1924
}
1925

    
1926

    
1927
/**
1928
 * Creates a short taxonname.
1929
 *
1930
 * The short name is created by using the taggedTitle field of
1931
 * NameSTO or NameTO instances.
1932
 * If the taggedTitle if empty the fullname will be returned.
1933
 *
1934
 * @param unknown_type $name
1935
 *   Name or TreeNode.
1936
 *
1937
 * @return string
1938
 */
1939
function cdm_dataportal_shortname_of($name) {
1940
  $nameStr = '';
1941

    
1942
  normalize_tagged_text($name->taggedTitle);
1943

    
1944
  // Get all tagged text tokens of the scientific name.
1945
  foreach ($name->taggedTitle as $tagtxt) {
1946
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1947
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1948
    }
1949
  }
1950
  $nameStr = trim($nameStr);
1951

    
1952
  if ($nameStr) {
1953

    
1954
    // Do not return short names for these.
1955
    if ($name->unplaced || $name->excluded) {
1956
      return $nameStr;
1957
    }
1958

    
1959
    /*
1960
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1961
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1962
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1963
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1964
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1965
    */
1966
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1967
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1968
      return $matches[1][0] . "." . $matches[3][0];
1969
    }
1970
    else {
1971
      return $nameStr;
1972
    }
1973
  }
1974
  else {
1975
    return $name->titleCache;
1976
  }
1977
}
1978

    
1979
/**
1980
 * Check if a taxon is accepted by the current taxonomic tree.
1981
 *
1982
 * @param mixed $taxon
1983
 *   The Taxon obkect to check.
1984
 *
1985
 * @return bool
1986
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1987
 */
1988
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1989

    
1990
  $defaultTreeUuid = get_current_classification_uuid();
1991

    
1992
  if (isset($taxon->taxonNodes)) {
1993
    $taxonNodes = $taxon->taxonNodes;
1994
  }
1995
  else {
1996
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1997
  }
1998

    
1999
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
2000
    foreach ($taxonNodes as $node) {
2001
      if (isset($node->classification)){
2002
        if(is_object($node->classification)) {
2003
          if ($node->classification->uuid == $defaultTreeUuid) {
2004
            return TRUE;
2005
          }
2006
        }
2007
        else {
2008
          if ($node->classification == $defaultTreeUuid) {
2009
            return TRUE;
2010
          }
2011
        }
2012
      }
2013
    }
2014
  }
2015

    
2016
  return FALSE;
2017
}
2018

    
2019
/**
2020
 * Checks is the source has one of the given types.
2021
 *
2022
 * @param object $source
2023
 *   The original source entity
2024
 * @param array $types
2025
 *   An array of elementd of the OriginalSourceType enumeration
2026
 *   If not set the default will be used which is:
2027
 *    - Lineage
2028
 *    - PrimaryMediaSource
2029
 *    - PrimaryTaxonomicSource
2030
 *    - Unknown
2031
 *    - Other
2032
 * @return boolean
2033
 */
2034
  function _is_original_source_type($source, $types = null) {
2035
    // this is the default
2036
    // maybe this should also be put into the settings
2037
    static $default = array(
2038
      OriginalSourceType::Lineage,
2039
      OriginalSourceType::PrimaryMediaSource,
2040
      OriginalSourceType::PrimaryTaxonomicSource,
2041
      OriginalSourceType::Unknown,
2042
      OriginalSourceType::Other,
2043
    );
2044

    
2045
    if(!$types){
2046
      $types = $default;
2047
    }
2048
    return isset($source->type) && in_array($source->type, $types);
2049
  }
2050

    
2051
/**
2052
 * @todo Please document this function.
2053
 * @see http://drupal.org/node/1354
2054
 */
2055
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2056
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2057
}
2058

    
2059

    
2060
/**
2061
 * Collects all the media from a list of description elements.
2062
 *
2063
 * @param array $descriptionElements
2064
 *   The description elements from which to collect the media.
2065
 *
2066
 * @return array
2067
 *   The output with all the collected media.
2068
 */
2069
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2070

    
2071
  $outArrayOfMedia = array();
2072

    
2073
  // Avoiding a warning box in Drupal for Flora Malesiana.
2074
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2075
    foreach ($descriptionElements as $descriptionElement) {
2076
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2077
        foreach ($descriptionElement->media as $media) {
2078
          if (is_object($media)) {
2079
            $outArrayOfMedia[] = $media;
2080
          }
2081
        }
2082
      }
2083
    }
2084
  }
2085
  return $outArrayOfMedia;
2086
}
2087

    
2088
/**
2089
 * @todo Please document this function.
2090
 * @see http://drupal.org/node/1354
2091
 *
2092
 * @param array $cdm_entities
2093
 *   An array of CdmBase instances or a single instance.
2094
 * @param string $footnote_list_key_suggestion
2095
 *
2096
 * @return unknown
2097
 */
2098
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2099

    
2100
   static $annotations_types_filter = null;
2101
   if(!$annotations_types_filter) {
2102
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2103
   }
2104

    
2105
  $footNoteKeys = array();
2106

    
2107
  // Is argument cdmBase an array?
2108
  if (!is_array($cdm_entities)) {
2109
    $cdmBase_array = array();
2110
    $cdmBase_array[] = $cdm_entities;
2111
  }
2112
  else {
2113
    $cdmBase_array = $cdm_entities;
2114
  }
2115

    
2116
  // Getting the key for the footnotemanager.
2117
  if (isset($footnote_list_key_suggestion)) {
2118
    $footnote_list_key = $footnote_list_key_suggestion;
2119
  }
2120
  else {
2121
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2122
  }
2123

    
2124
  // Adding the footnotes keys.
2125
  foreach ($cdmBase_array as $cdmBase_element) {
2126
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2127
    if (is_array($annotations)) {
2128
      foreach ($annotations as $annotation) {
2129
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2130
      }
2131
    }
2132
  }
2133

    
2134
  return $footNoteKeys;
2135
}
2136

    
2137

    
2138
/**
2139
 * Creates a CDM Dynabox.
2140
 *
2141
 * @param string $dynabox_id
2142
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2143
 * @param string $label
2144
 *   The clickable text to show.
2145
 * @param string $content_url
2146
 *   The cdm REST service request url wich will deliver the content to be shown
2147
 *   once the dynabox toggles open.
2148
 * @param string $theme
2149
 *   The theme to be used for rendering the cdm REST service response with is
2150
 *   returned from the $content_url.
2151
 * @param string $link_alt_text
2152
 *   The value for the alt attribute of the dynabox link.
2153
 * @param array $enclosingtags
2154
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2155
 *   element itself, $enclosingtags[1] is the tag to be used for the
2156
 *   dynabox_content (optional)
2157
 * @param array $attributes
2158
 * @param $content_element_selector
2159
 *   Optional jQuery selector which can be used to reference a dom element which should
2160
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2161
 *  element will be placed in this container.
2162
 *
2163
 * @param string $open_callback
2164
 *   optional javascript call back function to be triggered after toggling the box to
2165
 *   the open state.
2166
 * @param string $close_callback
2167
 *   optional javascript call back function to be triggered after toggling the box to
2168
 *   the closed state.
2169
 * @return string Returns HTML for a dynabox.
2170
 * Returns HTML for a dynabox.
2171
 */
2172
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2173
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2174
                     $content_element_selector = null,
2175
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2176
  $out = '';
2177

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

    
2181
  if(!array_key_exists('class', $attributes)) {
2182
    $attributes['class'] = array();
2183
  }
2184
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2185
  $dynabox_attributes = drupal_attributes($attributes);
2186

    
2187

    
2188
  _add_js_domEvent(); // requires domEvent.js
2189
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2190
  drupal_add_js("
2191
  jQuery(document).ready(
2192
      function() {
2193
        dynabox('". $dynabox_id ."',
2194
          {
2195
            open_callback: " . $open_callback .",
2196
            close_callback: " . $close_callback .
2197
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2198
          }
2199
        );
2200
      }
2201
   );",
2202
   array(
2203
    'type'=>'inline',
2204
    'scope'=>'footer'
2205
    )
2206
  );
2207

    
2208

    
2209
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2210
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2211
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2212
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2213
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2214
  $out .= '    </' . $enclosingtags[1] . '>';
2215
  $out .= '  </' . $enclosingtags[0] . '>';
2216
  $out .= '<!-- dynabox end -->';
2217
  return $out;
2218
}
2219

    
2220
/**
2221
 * Checks whether a feature has any description elements.
2222
 *
2223
 * @param mixed $featureNode
2224
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2225
 *
2226
 * @see _mergeFeatureTreeDescriptions()
2227
 *
2228
 * @return bool
2229
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2230
 *   contains at least one non empty TextData or at least one DescriptionElement
2231
 *   of an other type. A TextData element holding a multilanguageText or a
2232
 *   source reference is considered to be not empty.
2233
 *
2234
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2235
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2236
 *       $feature_block_has_content in compose_feature_block_items_generic
2237
 */
2238
function has_feature_node_description_elements($featureNode) {
2239

    
2240
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2241
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2242
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2243
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2244
          && $descriptionElement->multilanguageText_L10n->text != ''
2245
          || isset($descriptionElement->sources[0])
2246
          || isset($descriptionElement->media[0]) ) {
2247
          return TRUE;
2248
        }
2249
      }
2250
    }
2251
  }
2252
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2253
    foreach ($featureNode->childNodes as $child) {
2254
      if (has_feature_node_description_elements($child)) {
2255
        return TRUE;
2256
      }
2257
    }
2258
  }
2259
  return FALSE;
2260
}
2261

    
2262
/**
2263
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2264
 *
2265
 * @param $chapter
2266
 *   The taxon page chapter or part
2267
 */
2268
function cdm_check_valid_taxon_page($chapter){
2269
  static $taxon_tabs = null;
2270

    
2271
  cdm_check_valid_portal_page();
2272

    
2273
  if($taxon_tabs == null){
2274
    $taxon_tabs = array('all', 'description');
2275
    foreach(get_taxon_tabs_list() as $tab){
2276
      $taxon_tabs[] = strtolower($tab);
2277
    }
2278
  }
2279

    
2280
  if(!in_array($chapter, $taxon_tabs)){
2281
    // oops this is not a valid chapter name
2282
    http_response_code(404); // 404 = Not Found
2283
  }
2284

    
2285
}
2286

    
2287
/**
2288
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2289
 *
2290
 * @param $chapter
2291
 *   The taxon page chapter or part
2292
 */
2293
function cdm_check_valid_portal_page(){
2294
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2295
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2296
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2297
    http_response_code(404); // 404 = Not Found
2298
    exit('HTTP 404');
2299
  }
2300
}
2301

    
2302
/**
2303
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2304
 *
2305
 * @param $text_a
2306
 * @param $text_b
2307
 * @return string
2308
 */
2309
function diff_viewer($text_a, $text_b) {
2310

    
2311
  static $diff_viewer_count = 0;
2312

    
2313
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2314

    
2315
  // http://code.stephenmorley.org/php/diff-implementation/
2316
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2317
  drupal_add_css(drupal_get_path('module',
2318
      'cdm_dataportal') . '/css/diff.css');
2319
  _add_jquery_ui();
2320
  drupal_add_js(
2321
    'jQuery(document).ready( function(){
2322
        jQuery(\'#' . $element_id . '\').accordion({
2323
        collapsible: true,
2324
        active: false,
2325
        fillSpace: true,
2326
        }).children(\'div\').css({ \'height\': \'auto\' });
2327
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2328
     });'
2329
    , array(
2330
    'type' => 'inline',
2331
    'scope' => 'footer'
2332
  ));
2333

    
2334
  $diff = Diff::compare($text_a,
2335
    $text_b);
2336
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2337
    . Diff::toTable($diff, '', '')
2338
    . '</div></div>';
2339
  return $diff_viewer_markup;
2340
}
2341

    
2342

    
(10-10/16)