Project

General

Profile

Download (76.2 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', // will be passed through t()
456
    'page callback' => 'cdm_dataportal_view_search_advanced',
457
    'access arguments' => array('access content'),
458
    'type' => MENU_DEFAULT_LOCAL_TASK,
459
  );
460

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

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

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

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

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

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

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

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

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

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

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

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

    
597
  return $items;
598
}
599

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

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

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

    
621
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
622

    
623
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
624

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

    
634
  $parameters['cacheL2_refresh'] ='1';
635

    
636

    
637
  drupal_goto($base_path, array('query' => $parameters));
638
}
639

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

    
645
  global $user;
646
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
647

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

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

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

    
671

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

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

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

    
697
  return $form;
698
}
699

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

    
711
  // FIXME: this is completely wrong, see user_profile_form_submit()
712

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

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

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

    
740
/**
741
 * Implements hook_block_info().
742
 */
743
function cdm_dataportal_block_info() {
744

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

    
760
    return $block;
761
}
762

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

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

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

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

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

    
836
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
837
  return $form;
838
}
839

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

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

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

    
855
  $destination_array = drupal_get_destination();
856
  $destination = $destination_array['destination'];
857

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

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

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

    
884
  return $form;
885

    
886
}
887

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

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

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

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

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

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

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

    
957
  cdm_check_valid_portal_page();
958

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

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

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

    
979
  cdm_check_valid_portal_page();
980

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

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

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

    
1017
  static $media = NULL;
1018

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

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

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

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

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

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

    
1053
  return $media[$taxon->uuid];
1054
}
1055

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

    
1066
  static $occurences = NULL;
1067

    
1068
  if(!isset($occurences)) {
1069
    $occurences = array();
1070
  }
1071

    
1072
  if (!isset($occurences[$taxon->uuid])){
1073

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

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

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

    
1090

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

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

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

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

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

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

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

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

    
1256
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1257

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

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

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

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

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

    
1283
  cdm_check_valid_portal_page();
1284

    
1285
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1286

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1413
  return $taxonpage;
1414
}
1415

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

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

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

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

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

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

    
1467
    return $specimenpage;
1468
}
1469

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

    
1491
  cdm_check_valid_portal_page();
1492

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

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

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

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

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

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

    
1615
  $taxonPager = cdm_dataportal_search_execute();
1616

    
1617
  $showThumbnails = do_showThumbnails();
1618

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

    
1623
  drupal_add_js('jQuery(document).ready(function() {
1624

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

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

    
1649
  drupal_set_title(t('Search results'), PASS_THROUGH);
1650

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

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

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

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

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

    
1700
  return $showThumbnails;
1701
}
1702

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

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

    
1739
  $tab = get_default_taxon_tab();
1740
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1741

    
1742
  if (!$uuid) {
1743
    return FALSE;
1744
  }
1745

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

    
1760
function path_to_specimen($uuid) {
1761

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

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

    
1799
}
1800

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

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

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

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

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

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

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

    
1924

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

    
1940
  normalize_tagged_text($name->taggedTitle);
1941

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

    
1950
  if ($nameStr) {
1951

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

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

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

    
1988
  $defaultTreeUuid = get_current_classification_uuid();
1989

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

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

    
2014
  return FALSE;
2015
}
2016

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

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

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

    
2057

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

    
2069
  $outArrayOfMedia = array();
2070

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

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

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

    
2103
  $footNoteKeys = array();
2104

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

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

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

    
2132
  return $footNoteKeys;
2133
}
2134

    
2135

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

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

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

    
2185

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

    
2206

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

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

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

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

    
2269
  cdm_check_valid_portal_page();
2270

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

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

    
2283
}
2284

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

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

    
2309
  static $diff_viewer_count = 0;
2310

    
2311
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2312

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

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

    
2340

    
(10-10/16)