Project

General

Profile

Download (75 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/pages');
28
  module_load_include('inc', 'cdm_dataportal', 'includes/media');
29
  module_load_include('inc', 'cdm_dataportal', 'includes/maps');
30
  module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
31
  module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
32
  module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
33

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

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

    
49

    
50
  /* ============================ java script functions ============================= */
51

    
52

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

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

    
74
  /**
75
   */
76
  function drupal_add_js_rowToggle($tableId){
77

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

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

    
91
    $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
92

    
93
    drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
94

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

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

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

    
124
  function _add_js_openlayers() {
125

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

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

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

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

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

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

    
173
  }
174

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

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

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

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

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

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

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

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

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

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

    
319

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

    
322
    $font_awesome_css_uri=drupal_get_path('module', 'cdm_dataportal').'/font-awesome/4.2.0/css/font-awesome.min.css';
323
    $font_awesome_css_uri="//maxcdn.bootstrapcdn.com/font-awesome/4.2.0/css/font-awesome.min.css";
324

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

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

    
338
    return '<i ' . drupal_attributes($attributes) . '></i>';
339
  }
340

    
341

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

    
366
/**
367
 * Implements hook_menu().
368
 */
369
function cdm_dataportal_menu() {
370
  $items = array();
371

    
372
  // @see settings.php.
373
  cdm_dataportal_menu_admin($items);
374
  cdm_dataportal_menu_help($items);
375

    
376
  $items['cdm_dataportal/names'] = array(
377
    'page callback' => 'cdm_dataportal_view_names',
378
    'access arguments' => array('access content'),
379
    'type' => MENU_CALLBACK,
380
  );
381

    
382
  // Optional callback arguments: page.
383
  $items['cdm_dataportal/taxon'] = array(
384
    'page callback' => 'cdm_dataportal_taxon_page_view',
385
    'access arguments' => array('access content'),
386
    'type' => MENU_CALLBACK,
387
    // Expected callback arguments: uuid.
388
  );
389

    
390
   // Optional callback arguments: page.
391
    //FIXME point to view/page method in this module
392
    $items['cdm_dataportal/specimen'] = array(
393
        'page callback' => 'cdm_dataportal_specimen_page_view',
394
        'access arguments' => array('access content'),
395
        'type' => MENU_CALLBACK,
396
        // Expected callback arguments: uuid.
397
    );
398

    
399
  $items['cdm_dataportal/name'] = array(
400
    'page callback' => 'cdm_dataportal_name_page_view',
401
      /*
402
    'page arguments' => array(
403
       'taxon_name_uuid',
404
       'taxon_to_hide_uuid',
405
       'synonym_uuid' => NULL
406
      ),
407
      */
408
    'access arguments' => array('access content'),
409
    'type' => MENU_CALLBACK,
410
    // Expected callback arguments: uuid.
411
  );
412

    
413
  $items['cdm_dataportal/reference'] = array(
414
    'page callback' => 'cdm_dataportal_view_reference',
415
    'access arguments' => array('access content'),
416
    'type' => MENU_CALLBACK,
417
    // Expected callback arguments: uuid.
418
  );
419

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

    
427
  $items['cdm_dataportal/media'] = array(
428
    'page callback' => 'cdm_dataportal_view_media',
429
    'access arguments' => array('access content'),
430
    'type' => MENU_CALLBACK,
431
    // Expected callback arguments:
432
    // uuid, mediarepresentation_uuid, part_uuid or part#.
433
  );
434

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

    
442
  $items['cdm_dataportal/search'] = array(
443
    'page callback' => 'cdm_dataportal_view_search_advanced',
444
    'access arguments' => array('access content'),
445
    'type' => MENU_CALLBACK,
446
  );
447

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

    
455
  $items['cdm_dataportal/search/taxon_by_description'] = array(
456
    'title' => 'By description full text',
457
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
458
    'access arguments' => array('access content'),
459
    'type' => MENU_LOCAL_TASK,
460
  );
461

    
462
  $items['cdm_dataportal/search/results/taxon'] = array(
463
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
464
    'access arguments' => array('access content'),
465
    'type' => MENU_CALLBACK,
466
  );
467
  /*
468
   $items['cdm/xml2json'] = array(
469
   'page callback' => 'cdm_view_xml2json',
470
   'access arguments' => array('access content'),
471
   'type' => MENU_CALLBACK,
472
   );
473
   */
474

    
475
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
476
  // User configuration of cdm_dataportal.
477
  $items['user/%/cdm_dataportal'] = array(
478
    'title' => 'cdm_dataportal',
479
    'access arguments' => array('access content'),
480
    'page callback' => 'drupal_get_form',
481
    'page arguments' => array('cdm_dataportal_user_form'),
482
    'type' => MENU_LOCAL_TASK,
483
    'weight' => 10,
484
  );
485
  // }
486

    
487
  // 'May not cache' in D5.
488
  $items['cdm_dataportal/name/%'] = array(
489
    // 'page callback' => 'cdm_dataportal_view_name',
490
    'page callback' => 'cdm_dataportal_name_page_view',
491
    'page arguments' => array(2, 3, 4),
492
    'access arguments' => array('access content'),
493
    'type' => MENU_CALLBACK,
494
  );
495

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

    
509
    $items['cdm_dataportal/taxon/%/all'] = array(
510
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
511
      'page callback' => 'cdm_dataportal_taxon_page_view',
512
      'access arguments' => array('access content'),
513
      'type' => MENU_CALLBACK,
514
      'weight' => 2,
515
      'page arguments' => array(2, "all")
516
      , // Expected callback arguments: taxon_uuid.
517
    );
518

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

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

    
548
    $items['cdm_dataportal/taxon/%/specimens'] = array(
549
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
550
      'page callback' => 'cdm_dataportal_taxon_page_view',
551
      'access arguments' => array('access content'),
552
      'type' => MENU_LOCAL_TASK,
553
      'weight' => 6,
554
      'page arguments' => array(2, "specimens")
555
      , // Expected callback arguments: taxon_uuid.
556
    );
557

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

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

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

    
591
  return $items;
592
}
593

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

    
605
  if(variable_get('cdm_debug_mode', FALSE)){
606
    $file = 'temporary://drupal_debug.txt';
607
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
608
  }
609

    
610
  $bibliography_settings = get_bibliography_settings();
611
  $enclosing_tag = $bibliography_settings['enabled'] == 1 ? 'div' : 'span';
612
  FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', $enclosing_tag, $bibliography_settings['key_format']);
613
}
614

    
615
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
616

    
617
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
618

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

    
628
  $parameters['cacheL2_refresh'] ='1';
629

    
630

    
631
  drupal_goto($base_path, array('query' => $parameters));
632
}
633

    
634
/**
635
 * The function generate form for own user cdm dataportal configurations.
636
 */
637
function cdm_dataportal_user_form($form, &$form_state) {
638
  global $user;
639
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
640

    
641
  $form['taxon_page_tabs'] = array(
642
      '#type' => 'fieldset',
643
      '#title' => t('Taxon page tabs'),
644
  );
645
  $form['taxon_page_tabs']['check'] = array(
646
    '#type' => 'checkbox',
647
    '#title' => t('Activate user default configuration'),
648
    '#default_value' => variable_get($checkbox_value, 0),
649
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
650
  );
651

    
652
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
653
    '#type' => 'select',
654
    '#title' => t('Default tab to display'),
655
    '#default_value' => get_default_taxon_tab(TRUE),
656
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
657
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
658
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
659
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
660
  );
661

    
662
  $form['submit'] = array(
663
    '#type' => 'submit',
664
    '#value' => t('Submit'),
665
  );
666

    
667
  return $form;
668
}
669

    
670
/**
671
 * Form submission handler for user_form().
672
 *
673
 * Submits the user cdm dataportal configurations.
674
 */
675
function cdm_dataportal_user_form_submit($form, &$form_state) {
676
  global $user;
677
  $msg_type = 'status';
678
  $username = $user->name;
679
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
680

    
681
  // If is the right user the variables are setted.
682
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
683
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
684
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
685
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
686
    if ($form_state['values']['check']) {
687
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
688
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
689
        '!tab' => $variable[variable_get($variable_to_use, 0)],
690
        '!user' => $username,
691
      ))), $msg_type);
692
    }
693
    else {
694
      drupal_set_message(check_plain(t('The user default tab wont be used for
695
        the next taxon site, check the box if you want to use the user default configuration.')));
696
    }
697
    // Problem with the user id => variables wont be saved.
698
  }
699
  else {
700
    $msg_type = 'warning';
701
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
702
  }
703
}
704

    
705
/**
706
 * Implements hook_block_info().
707
 */
708
function cdm_dataportal_block_info() {
709

    
710
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
711
    // $block[1]["info"] = t("CDM DataPortal Credits");
712
    $block["2"] = array(
713
        "info" => t("CDM Search Taxa"),
714
        "cache" => DRUPAL_NO_CACHE
715
      );
716
    // $block[3]["info"] = t("CDM Filters");
717
    $block["4"]["info"] = t("CDM Dataportal Print");
718
    $block["keys"]["info"] = t("CDM identification keys");
719
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
720
    $block["classification_breadcrumbs"] =  array(
721
        'info' => t('Classification breadcrumbs'),
722
        'cache' => DRUPAL_CACHE_PER_PAGE
723
      );
724

    
725
    return $block;
726
}
727

    
728
/**
729
 * Implements hook_block_view().
730
 */
731
function cdm_dataportal_block_view($delta) {
732
  // TODO Rename block deltas (e.g. '2') to readable strings.
733
  switch ($delta) {
734
    // case 'delta-1':
735
    // $block['subject'] = t('Credits');
736
    // $block['content'] = theme('cdm_credits');
737
    // return $block;
738
    case '2':
739
      $block['subject'] = t('Search taxa');
740
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
741
      $block['content'] = drupal_render($form);
742

    
743
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
744
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
745
      }
746
      return $block;
747
    case '4':
748
      $block['subject'] = '';
749
      $block['content'] = theme('cdm_print_button');
750
      return $block;
751
    case "keys":
752
      $block['subject'] = t('Identification Keys');
753
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
754
      return $block;
755
    case "fundedByEDIT":
756
      // t('Funded by EDIT');
757
      $text = '<none>';
758
      $block['subject'] = $text;
759
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/powered_by_edit.png' . '" alt="' . $text . '"/>';
760
      $block['content'] = l($img_tag, "http://cybertaxonomy.org/", array(
761
        'attributes' => array("target" => "EDIT"),
762
        'absolute' => TRUE,
763
        'html' => TRUE,
764
      ));
765
      return $block;
766
    case 'classification_breadcrumbs':
767
      if (arg(1) == 'taxon' && is_uuid(arg(2))) {
768
        $block['subject'] = '<none>';
769
        $block['content'] = compose_classification_breadcrumbs(arg(2));
770
        return $block;
771
      }
772
      break;
773
  }
774
}
775

    
776
/*
777
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
778
 $_SESSION['cdm'] = NULL;
779
 if(is_string($cdm_ws_uri_update)){
780
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
781
 }
782
 }
783

    
784
 function cdm_dataportal_session_validate(){
785
 if(!isset($_SESSION['cdm']['ws_uri'])){
786
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
787
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
788
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
789
 }
790
 }
791
 */
792

    
793
/**
794
 * creates a  selector form for taxonomic trees.
795
 *
796
 * @return a drupal form array
797
 */
798
function cdm_taxonomictree_selector() {
799
  _add_js_treeselector();
800

    
801
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
802
  return $form;
803
}
804

    
805
/**
806
 * @todo Please document this function.
807
 * @see http://drupal.org/node/1354
808
 */
809
function cdm_taxonomictree_selector_form($form, &$form_state) {
810

    
811
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
812
  $form['#action'] = $url;
813

    
814
  $form['var'] = array(
815
    '#weight' => -3,
816
    '#type' => 'hidden',
817
    '#value' => '[cdm][taxonomictree_uuid]',
818
  );
819

    
820
  $destination_array = drupal_get_destination();
821
  $destination = $destination_array['destination'];
822

    
823
  $form['destination'] = array(
824
    '#weight' => -3,
825
    '#type' => 'hidden',
826
    '#value' =>  $destination,
827
  );
828

    
829
  $options = cdm_get_taxontrees_as_options();
830
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
831
  if($taxontree_includes){
832
    $filtered_options = array();
833
    foreach($options as $uuid=>$label){
834
      if(!empty($taxontree_includes[$uuid])){
835
        $filtered_options[$uuid] = $label;
836
      }
837
    }
838
    $options = $filtered_options;
839
  }
840

    
841
  $form['val'] = array(
842
    '#type' => 'select',
843
    '#title' => t('Available classifications'),
844
    '#default_value' => get_current_classification_uuid(),
845
    '#options' => $options,
846
    '#attributes' => array('class' => array('highlite-first-child'))
847
  );
848

    
849
  return $form;
850

    
851
}
852

    
853
/* UNREACHABLE since action of form directly links to view.
854
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
855

    
856
 $_SESSION['cdm']['search'] = $form_values;
857
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
858
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
859
 //$paramstr = compose_url_prameterstr($form_values);
860
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
861
 }
862
 */
863
/* ====================== menu callback functions ====================== */
864
/**
865
 * @todo Please document this function.
866
 * @see http://drupal.org/node/1354
867
 */
868
/*
869
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
870
  static $comment_node_disabled =  0;
871
  static $comment_node_read_only =  1;
872
  static $comment_node_read_write =  2;
873

    
874
  if ($form_id == 'node_type_form'
875
   && isset($form['identity']['type'])
876
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
877
  ) {
878
    $form['workflow']['comment'] = array(
879
      '#type' => 'radios',
880
      '#title' => t('Default comment setting'),
881
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
882
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
883
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
884
    );
885
  }
886
}
887
*/
888

    
889
/**
890
 * Displays a list of the known taxonomic names.
891
 *
892
 * When the list of taxonomic names is displayed, long lists are split up into
893
 * multiple pages.
894
 *
895
 * TODO: Parameters are still preliminary.
896
 *
897
 * @param string $beginsWith
898
 * @param string $page
899
 *   Page number to diplay defaults to page 1.
900
 * @param bool $onlyAccepted
901
 */
902
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
903

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

    
906
  /*
907
  // FIXME the filter for accepted names will be a form element, thus this
908
  // widget should be generated via form api preferably as block.
909
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
910
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
911
  $out .= theme('cdm_listof_taxa', $taxonPager);
912
  return $out;
913
  */
914
}
915

    
916
/**
917
 * @todo Please document this function.
918
 * @see http://drupal.org/node/1354
919
 */
920
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
921

    
922
  cdm_check_valid_portal_page();
923

    
924
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
925
  return theme('cdm_reference_page', array('reference' => $reference));
926
}
927

    
928
/**
929
 * Created a view on a all references contained in the portal.
930
 *
931
 * This function is used at the path cdm_dataportal/reference/list
932
 */
933
function cdm_dataportal_view_reference_list($pageNumber) {
934
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
935
  return theme('cdm_reference_pager', array(
936
    'referencePager' => $referencePager,
937
    'path' => 'cdm_dataportal/reference/list/',
938
    ));
939
}
940

    
941
/**
942
 * @todo Please document this function.
943
 * @see http://drupal.org/node/1354
944
 */
945
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
946

    
947
  cdm_check_valid_portal_page();
948

    
949
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
950
  return theme('cdm_media_page', array(
951
    'media' => $media,
952
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
953
    'partId' => $part,
954
    ));
955
}
956

    
957
/**
958
 * @todo Please document this function.
959
 * @see http://drupal.org/node/1354
960
 */
961
function _load_taxonBase(&$taxonBase) {
962
  if (isset($taxonBase->uuid)) {
963
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
964
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
965
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
966
  }
967
}
968

    
969
/**
970
 * Loads the media associated to the given taxon from the cdm server.
971
 * The aggregation settings regarding taxon relathionships and
972
 * taxonnomic childen are taken into account.
973
 *
974
 * The media lists are cached in a static variable.
975
 *
976
 * @param Taxon $taxon
977
 *   A CDM Taxon entitiy
978
 *
979
 * @return array
980
 *   An array of CDM Media entities
981
 *
982
 */
983
function _load_media_for_taxon($taxon) {
984

    
985
  static $media = NULL;
986

    
987
  if(!isset($media)) {
988
    $media = array();
989
  }
990
  if (!isset($media[$taxon->uuid])) {
991

    
992
    // --- GET Images --- //
993
    $mediaQueryParameters = array(
994
        "type" => "ImageFile",
995
    );
996

    
997
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
998
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
999
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1000

    
1001
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1002
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1003
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1004
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1005

    
1006
    $ws_endpoint = NULL;
1007
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1008
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1009
    } else {
1010
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1011
    }
1012

    
1013
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1014
        array(
1015
            $taxon->uuid,
1016
        ),
1017
        queryString($mediaQueryParameters)
1018
       );
1019
  }
1020

    
1021
  return $media[$taxon->uuid];
1022
}
1023

    
1024
/**
1025
 *
1026
 * @param Taxon $taxon
1027
 *   A CDM Taxon entitiy
1028
 *
1029
 * @return array
1030
 *   An array of CDM SpecimenOrObservation entities
1031
 *
1032
function _load_occurences_for_taxon($taxon){
1033

    
1034
  static $occurences = NULL;
1035

    
1036
  if(!isset($occurences)) {
1037
    $occurences = array();
1038
  }
1039

    
1040
  if (!isset($occurences[$taxon->uuid])){
1041

    
1042
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1043
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1044
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1045

    
1046
    $by_associatedtaxon_query = http_build_query(array(
1047
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1048
        'relationships' => implode(',', $relationship_choice['direct']),
1049
        'pageSize' => null // all hits in one page
1050
    )
1051
    );
1052

    
1053
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1054
        null,
1055
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1056
    );
1057

    
1058

    
1059
    if(isset($pager->records[0])){
1060
      $occurences[$taxon->uuid] =  $pager->records;
1061
    }
1062
  }
1063
  return $occurences[$taxon->uuid];
1064
}
1065
 */
1066

    
1067
/**
1068
 * Gets a Drupal variable, string or array and returns it.
1069
 *
1070
 * Similar to the variable_get() function of Drupal, except that this function
1071
 * is able to handle arrays correctly. This function is especially useful
1072
 * when dealing with collections of settings form elements (#tree = TRUE).
1073
 *
1074
 * @param string $variableKey
1075
 *   The Unique key of the Drupal variable in the Drupal variables table.
1076
 * @param string $defaultValueString
1077
 *   A string as for example derived from a CONSTANT.
1078
 *
1079
 * @return mixed
1080
 *   usually an array, depending on the nature of the variable.
1081
 *
1082
 * TODO compare with get_array_variable_merged() duplicate functions?
1083
 * @deprecated rather use get_array_variable_merged() since this function
1084
 * used an array as second parameter
1085
 */
1086
function mixed_variable_get($variableKey, $defaultValueString) {
1087
  $systemDefaults = unserialize($defaultValueString);
1088
  $storedSettings = variable_get($variableKey, array());
1089
  if (is_array($storedSettings)) {
1090
    // TODO better use drupal_array_merge_deep() ?
1091
    $settings = array_merge($systemDefaults, $storedSettings);
1092
  }
1093
  else {
1094
    $settings = $systemDefaults;
1095
  }
1096
  return $settings;
1097
}
1098

    
1099
/**
1100
 * Recursive function to convert an object into an array.
1101
 * also subordinate objects will be converted.
1102
 *
1103
 * @param object $object
1104
 * @return the array
1105
 */
1106
function convert_to_array($object) {
1107
  if(is_object($object) || is_array($object)) {
1108
    $array = (array)$object;
1109
    foreach ($array as $key=>$value){
1110
      $array[$key] = convert_to_array($value);
1111
    }
1112
    return $array;
1113
  } else {
1114
    return $object;
1115
  }
1116
}
1117

    
1118
/**
1119
 * Searches the $collection for the cdm entitiy given as $element.
1120
 *
1121
 * The elements are compared by their UUID.
1122
 *
1123
 * @param $element
1124
 *  the CDM entitiy to search for
1125
 * @param $collection
1126
 *  the list of CDM entities to search in
1127
 *
1128
 * @return boolean TRUE if the $collection contains the $element, otheriwse FALSE
1129
 *
1130
 */
1131
function contains_cdm_entitiy($element, $collection) {
1132
  $result = FALSE;
1133
  foreach ($collection as $a) {
1134
    if ($a->uuid == $element->uuid) {
1135
      $result = TRUE;
1136
    }
1137
  }
1138
  return $result;
1139
}
1140

    
1141
/**
1142
 * Fiters the array $entity_list of CDM entities by the list
1143
 * of $excludes. Any element contained in the $excludes will be removed
1144
 * from included int the retuned list.
1145
 *
1146
 * If the $entity_list is not an array the $excludes will be returned.
1147
 */
1148
function filter_cdm_entity_list($entity_list, $excludes) {
1149
  if (is_array($entity_list)) {
1150
    $result = $entity_list;
1151
    if ($excludes) {
1152
      foreach ($excludes as $exclude) {
1153
        if (!contains_cdm_entitiy($exclude, $entity_list)) {
1154
          $result[] = $exclude;
1155
        }
1156
      }
1157
    }
1158
  }
1159
  else {
1160
    $result = $excludes;
1161
  }
1162
  return $result;
1163
}
1164

    
1165
/**
1166
 * Wraps the given $html string into a render array suitable for drupal_render()
1167
 *
1168
 * @param $html
1169
 *   the html string, see
1170
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1171
 * @param $weight
1172
 *   A positive or negative number (integer or decimal).
1173
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1174
 * @param $prefix
1175
 *   Optional markup for the '#prefix' element of the render array
1176
 * @param $suffix
1177
 *   Optional markup for the '#suffix' element of the render array
1178
 *
1179
 * @return array
1180
 *   A render array
1181
 *
1182
 */
1183
function markup_to_render_array($html, $weight = FALSE, $prefix = NULL, $suffix = NULL) {
1184
  $render_array = array(
1185
    '#markup' => $html
1186
      );
1187
  if (is_numeric($weight)) {
1188
    $render_array['#weight'] = $weight;
1189
  }
1190
  if($prefix){
1191
    $render_array['#prefix'] = $prefix;
1192
  }
1193
  if($suffix) {
1194
    $render_array['#suffix'] = $suffix;
1195
  }
1196
  return $render_array;
1197
}
1198

    
1199
/**
1200
 * Loads the subgraph of a given PolytomousKeyNode.
1201
 *
1202
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1203
 * the CDM REST service.
1204
 *
1205
 * @param mixed $polytomousKeyNode
1206
 *   PolytomousKeyNode passed by reference.
1207
 *
1208
 * @return void
1209
 */
1210
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1211

    
1212
  if (!$polytomousKeyNode) {
1213
    return;
1214
  }
1215
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1216
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1217
    return;
1218
  }
1219
  if (!is_uuid($polytomousKeyNode->uuid)) {
1220
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1221
    return;
1222
  }
1223

    
1224
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1225

    
1226
  if (!$polytomousKeyNode) {
1227
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1228
    return;
1229
  }
1230

    
1231
  // Load children.
1232
  foreach ($polytomousKeyNode->children as &$childNode) {
1233
    _load_polytomousKeySubGraph($childNode);
1234
  }
1235

    
1236
  // Load subkey.
1237
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1238

    
1239
  // Load taxon.
1240
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1241
  _load_taxonBase($polytomousKeyNode->taxon);
1242
  return;
1243
}
1244

    
1245
/**
1246
 * @todo Please document this function.
1247
 * @see http://drupal.org/node/1354
1248
 */
1249
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1250

    
1251
  cdm_check_valid_portal_page();
1252

    
1253
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1254

    
1255
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1256
  if (is_array($sourcePager->records)) {
1257
    $polytomousKey->sources = $sourcePager->records;
1258
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1259
  }
1260

    
1261
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1262
  if (is_array($annotationPager->records)) {
1263
    $polytomousKey->annotations = $annotationPager->records;
1264
  }
1265

    
1266
  _load_polytomousKeySubGraph($polytomousKey->root);
1267
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1268
}
1269

    
1270
/**
1271
 * Creates a taxon page view or a chapter of it.
1272
 *
1273
 * The taxon page gives detailed information on a taxon, it shows:
1274
 *  - Taxon name.
1275
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1276
 *    heterotypic and finally followed by misapplied names.
1277
 *    The list is ordered historically.
1278
 *  - All description associated with the taxon.
1279
 *
1280
 * @param string $uuid
1281
 * @param string $chapter
1282
 *   Name of the part to display, valid values are:
1283
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1284
 *
1285
 * @return unknown_type
1286
 */
1287
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1288

    
1289
  cdm_check_valid_taxon_page($chapter);
1290
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1291
  // show a warning in case the javascript development mode is anabled
1292
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1293
    drupal_set_message(t('The !url1 is enabled.
1294
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1295
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1296
    )),
1297
    'warning'
1298
        );
1299
  }
1300

    
1301
  // Display the page for the taxon defined by $uuid.
1302
  // set_last_taxon_page_tab(arg(3));
1303
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1304
  if (!empty($taxonpage)) {
1305
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1306
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1307
  }
1308
  else {
1309
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1310
    return '';
1311
  }
1312
}
1313

    
1314
/**
1315
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1316
 * which has two fields, one for the page title and one for the content. Later on in the
1317
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1318
 * function as the function parameters $title and $content.
1319
 *
1320
 * @param string $uuid
1321
 *   the uuid of the taxon to show
1322
 * @param string $chapter
1323
 *   Name of the part to display, valid values are:
1324
 *   'description', 'images', 'synonymy', 'all'.
1325
 *
1326
 * @return taxonpage object with the following fields:
1327
 *   - title : the title of the page
1328
 *   - content: the content of the page
1329
 *
1330
 */
1331
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1332
  // Taxon object.
1333
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1334
  if (empty($taxon)) {
1335
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1336
    return FALSE;
1337
  }
1338
  $taxonpage = new stdClass();
1339

    
1340
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1341
    'taxon' => $taxon
1342
  ));
1343

    
1344
  // Check if the taxon id contained in the currently selected tree.
1345
  $taxon_in_current_classification = taxon_in_current_classification($uuid);
1346

    
1347
  if (!$taxon_in_current_classification) {
1348
    $classifications = get_classifications_for_taxon($taxon);
1349
    if (count($classifications) == 0) {
1350
      drupal_set_message(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.',
1351
        array(
1352
        '!taxonname' => render_taxon_or_name($taxon->name),
1353
        )
1354
      ), 'warning');
1355
    }
1356
    else {
1357
      $trees = '';
1358
      foreach ($classifications as $classification) {
1359
        if (isset($classification->titleCache)) {
1360
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1361
        }
1362
      }
1363

    
1364
      drupal_set_message(format_plural(count($trees),
1365
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1366
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1367
          array('!taxonname' => render_taxon_or_name($taxon), '!trees' => $trees)
1368
        ) ,
1369
        'warning');
1370
    }
1371
  }
1372

    
1373
  // Render the taxon page.
1374
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1375
  $taxonpage->content = drupal_render($render_array);
1376

    
1377
  return $taxonpage;
1378
}
1379

    
1380
/**
1381
 * Creates a specimen page view.
1382
 * @param string $uuid the UUID of the specimen
1383
 * @return array|string
1384
 */
1385
function cdm_dataportal_specimen_page_view($uuid) {
1386

    
1387
    //cdm_check_valid_taxon_page($chapter);
1388
    //cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1389
    // show a warning in case the javascript development mode is anabled
1390
    if(variable_get('cdm_js_devel_mode', FALSE)) {
1391
        drupal_set_message(t('The !url1 is enabled.
1392
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1393
            '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1394
        )),
1395
            'warning'
1396
        );
1397
    }
1398

    
1399
    // Display the page for the specimen defined by $uuid.
1400
    $specimenpage = cdm_dataportal_specimen_view($uuid);
1401
    if (!empty($specimenpage)) {
1402
        return cdm_node_show(NODETYPE_TAXON, $uuid, $specimenpage->title, $specimenpage->content);
1403
    }
1404
    else {
1405
        return '';
1406
    }
1407
}
1408

    
1409
/**
1410
 *
1411
 * Creates a specimen view.
1412
 * @param string $uuid the UUID of the specimen
1413
 * @return array|string
1414
 */
1415
function cdm_dataportal_specimen_view($uuid) {
1416
    $specimen = cdm_ws_get(CDM_WS_OCCURRENCE, $uuid);
1417
    if (empty($specimen)) {
1418
        drupal_set_title(t('Specimen does not exist'), PASS_THROUGH);
1419
        return FALSE;
1420
    }
1421
    $specimenpage = new stdClass();
1422

    
1423
    $specimenpage->title = theme('cdm_specimen_page_title', array(
1424
        'specimen' => $specimen
1425
    ));
1426

    
1427
    // Render the specimen page.
1428
    $render_array = compose_cdm_specimen_page($uuid);
1429
    $specimenpage->content = drupal_render($render_array);
1430

    
1431
    return $specimenpage;
1432
}
1433

    
1434
/**
1435
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1436
 *
1437
 * The node page shows the taxon name title and the list of taxon related
1438
 * with such taxon. Name on the tree already in use.
1439
 *
1440
 * @param UUID $taxon_name_uuid
1441
 *   The uuid of the CDM TaxonNameBase to show a name page for
1442
 * @param UUID $taxon_to_hide_uuid
1443
 *   A taxon which should not be displayed in the taxon list
1444
 * @param UUID $highlite_synonym_uuid
1445
 *   Optinal parameter wich takes another taxon uuid, if given the
1446
 *   target taxon pages will show the syonymy tab where the taxon
1447
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1448
 *   in case it is found on this page.
1449
 *
1450
 * @return mixed
1451
 *   The formatted name page as node.
1452
 */
1453
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1454

    
1455
  cdm_check_valid_portal_page();
1456

    
1457
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1458
  if (!empty($taxonname_page)) {
1459
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1460
  }
1461
  else {
1462
    return '';
1463
  }
1464
}
1465

    
1466
/**
1467
 * View function for a TaxonNameBase page.
1468
 *
1469
 * The name page lists all taxa for which the name specified by the
1470
 * $taxon_name_uuid is being used. I case there is only one name the
1471
 * page automatically redirects ti the according taxon page. Otherwise
1472
 * the list of names is displayed.
1473
 *
1474
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1475
 * list of taxa. This is useful for example when referencing from a taxon
1476
 * to the name page and the referring taxon should not be repeaded in the
1477
 * name page.
1478
 *
1479
 *
1480
 * @param UUID $taxon_name_uuid
1481
 *   The uuid of the CDM TaxonNameBase to show a name page for
1482
 * @param UUID $taxon_to_hide_uuid
1483
 *   A taxon which should not be displayed in the taxon list
1484
 * @param UUID $highlite_synonym_uuid
1485
 *   Optinal parameter wich takes another taxon uuid, if given the
1486
 *   target taxon pages will show the syonymy tab where the taxon
1487
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1488
 *   in case it is found on this page.
1489
 *
1490
 * @return object
1491
 *   An object with two fields:
1492
 *     - title: the page title
1493
 *     - content: the page content
1494
 */
1495
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1496
  // Getting the full taxonname object from the server.
1497
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1498
  if (!$taxon_name) {
1499
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1500
    return FALSE;
1501
  }
1502
  // Searching for all the taxa connected with the taxon name on the tree
1503
  // in use.
1504
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1505
  $request_params = array();
1506
  $request_params['query'] = $name_cache;
1507
  $request_params['tree'] = get_current_classification_uuid();
1508
  $request_params['doTaxa'] = 1;
1509
  $request_params['doSynonyms'] = 1;
1510
  $request_params['doTaxaByCommonNames'] = 0;
1511
  $request_params['matchMode'] = "EXACT";
1512
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1513

    
1514
  // Removing the name where we come from.
1515
  foreach ($taxon_pager->records as $k => &$taxon) {
1516
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1517
      unset($taxon_pager->records[$k]);
1518
    }
1519
  }
1520
  // Show the taxa list or go to the singular taxon.
1521
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1522
    $singleTaxon = array_pop($taxon_pager->records);
1523
    if ($singleTaxon->class != "Taxon") {
1524
      // It is a Synonym -> look for the accepted.
1525
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_current_classification_uuid()));
1526
      if (!empty($highlite_synonym_uuid)) {
1527
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1528
      }
1529
      else {
1530
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1531
      }
1532
    }
1533
    else {
1534
      // It is an accepted taxon.
1535
      if (!empty($highlite_synonym_uuid)) {
1536
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1537
      }
1538
      else {
1539
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1540
      }
1541
    }
1542
  }
1543
  else {// More than one taxa case.
1544
    $taxon_name_page = new stdClass();
1545
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1546
    if ($taxon_pager->records) {
1547
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1548
    }
1549
    else {
1550
      $taxon_name_page->content = 'This name has no taxa';
1551
    }
1552
    return $taxon_name_page;
1553
  }
1554
}
1555

    
1556
/**
1557
 * Creates a page with the advance search form.
1558
 *
1559
 * NOTE: The advance search form allows searching for taxa.
1560
 */
1561
function cdm_dataportal_view_search_advanced() {
1562
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1563
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1564
}
1565

    
1566
/**
1567
 * Creates a page with the search form for searching by taxon descriptions.
1568
 */
1569
function cdm_dataportal_view_search_taxon_by_description() {
1570
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1571
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1572
}
1573

    
1574
/**
1575
 * Executes the search and generates the result list of taxa.
1576
 */
1577
function cdm_dataportal_view_search_results_taxon() {
1578

    
1579
  $taxonPager = cdm_dataportal_search_execute();
1580

    
1581
  $showThumbnails = do_showThumbnails();
1582

    
1583
  $setSessionUri = url('cdm_api/setvalue/session', array(
1584
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1585
  ));
1586

    
1587
  drupal_add_js('jQuery(document).ready(function() {
1588

    
1589
      // init
1590
      if(' . $showThumbnails . ' == 1){
1591
          jQuery(\'.media_gallery\').show(20);
1592
      } else {
1593
          jQuery(\'.media_gallery\').hide(20);
1594
      }
1595

    
1596
      // add change handler
1597
      jQuery(\'#showThumbnails input.showThumbnails\').change(
1598
      function(event){
1599
        var state = 0;
1600
        if(jQuery(this).is(\':checked\')){
1601
          jQuery(\'.media_gallery\').show(20);
1602
          state = 1;
1603
        } else {
1604
          jQuery(\'.media_gallery\').hide(20);
1605
        }
1606
        // store state in session variable
1607
        var uri = \'' . $setSessionUri . '\' + state;
1608
        jQuery.get(uri);
1609
      });
1610
  });',
1611
  array('type' => "inline", 'scope' => JS_DEFAULT));
1612

    
1613
  drupal_set_title(t('Search results'), PASS_THROUGH);
1614

    
1615
  return theme('cdm_search_results', array(
1616
    'pager' => $taxonPager,
1617
    'path' => 'cdm_dataportal/search/results/taxon',
1618
    ));
1619
}
1620

    
1621
/**
1622
 * Provides the standart image wich indicated a loading process
1623
 *
1624
 * @return string
1625
 *  The img html tag
1626
 */
1627
function loading_image_html() {
1628
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1629
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1630
}
1631

    
1632
/**
1633
 * Returns the state of the the showThumbnails flag set in the
1634
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1635
 *
1636
 * @return boolean
1637
 *    returns 1 if the flag is set
1638
 */
1639
function do_showThumbnails() {
1640
  static $showThumbnails = null;
1641

    
1642
  if($showThumbnails == null) {
1643
    $showThumbnails = 0;
1644
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1645
      $showThumbnails = 0;
1646
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1647
      $showThumbnails = is_array($search_gallery_settings)
1648
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1649
        && (
1650
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1651
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1652
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1653
            )
1654
         ? 1 : 0;
1655

    
1656
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1657
    }
1658
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1659
    if (!is_numeric($showThumbnails)) {
1660
      $showThumbnails = 1;
1661
    }
1662
  }
1663

    
1664
  return $showThumbnails;
1665
}
1666

    
1667
/**
1668
 * View which transforms XML output from a given webservice endpoint into JSON.
1669
 */
1670
/*
1671
 function cdm_view_xml2json(){
1672
 $file = arg(2);
1673
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1674
 return  xml2json::transformXmlStringToJson($datastr);
1675
 }
1676
 */
1677

    
1678
/* ====================== other functions ====================== */
1679
/**
1680
 * Creates a URL to the taxon page specified by the $uuid parameter.
1681
 *
1682
 * The URL will be prepended with a path element to a specific taxon page tab.
1683
 *
1684
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1685
 * be set globally in the administrative settings or individually in the user
1686
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1687
 * the last portal will stay on this last tab.
1688
 *
1689
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1690
 * internal mechanism by a specific value.
1691
 *
1692
 * @param string $uuid
1693
 *   The UUID of the taxon.
1694
 * @param string $page_tab
1695
 *   Overwriting the preset mechanism by defining specific value for the
1696
 *   taxon page tab.
1697
 *
1698
 * @return string
1699
 *   The created URL.
1700
 */
1701
function path_to_taxon($uuid, $page_tab = FALSE) {
1702

    
1703
  $tab = get_default_taxon_tab();
1704
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1705

    
1706
  if (!$uuid) {
1707
    return FALSE;
1708
  }
1709

    
1710
  if ($page_tab) {
1711
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1712
  }
1713
  elseif (!$tab || strtolower($tab) == 'general') {
1714
    return 'cdm_dataportal/taxon/' . $uuid;
1715
  }
1716
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1717
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1718
  }
1719
  else {
1720
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1721
  }
1722
}
1723

    
1724
function path_to_specimen($uuid) {
1725

    
1726
    if (!$uuid) {
1727
        return FALSE;
1728
    }
1729
    else {
1730
        return 'cdm_dataportal/specimen/' . $uuid;
1731
    }
1732
}
1733

    
1734
/**
1735
 * Creates a URL to show a synonmy in the according taxon page.
1736
 *
1737
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1738
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1739
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1740
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1741
 * in the page
1742
 *
1743
 * @param string $synonymUuid
1744
 *    The uuid of the synonym
1745
 * @param string $acceptedUuid
1746
 *    The uuid of the according accepted taxon
1747
 * @return string
1748
 *    The URL to show a synonmy in the according taxon page
1749
 */
1750
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1751
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1752
  return url($acceptedPath, array(
1753
      'query' => array(
1754
        // highlite the synony in the synonymy
1755
        'highlite' => $synonymUuid,
1756
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1757
        // see theme_taxon_page_title()
1758
        'acceptedFor' => $synonymUuid
1759
      ),
1760
      'fragment' => $synonymUuid
1761
  ));
1762

    
1763
}
1764

    
1765
/**
1766
 * Compses the drupal path to the key identified by the uuid.
1767
 *
1768
 * @param string $keyType
1769
 *    the key typer corresponds to the specific class of the CDM
1770
 *    IdentificationKey. Possible values are
1771
 *      -PolytomousKey
1772
 *      -MultimediaKey
1773
 *      - ...
1774
 * @param UUID $keyUuid
1775
 *   The UUID of the key
1776
 */
1777
function path_to_key($keyType, $keyUuid) {
1778
  if (!$keyUuid || !$keyType) {
1779
    return FALSE;
1780
  }
1781
  $keyType{0} = strtolower($keyType{0});
1782
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1783
}
1784

    
1785
/**
1786
 * @todo Please document this function.
1787
 * @see http://drupal.org/node/1354
1788
 */
1789
function path_to_reference($uuid) {
1790
  if (!$uuid) {
1791
    return FALSE;
1792
  }
1793
  return 'cdm_dataportal/reference/' . $uuid;
1794
}
1795

    
1796
/**
1797
 * Creates the path to a cdm_dataportal taxon name page.
1798
 *
1799
 * @param UUID $taxon_name_uuid
1800
 *   The uuid of the CDM TaxonNameBase to show a name page for
1801
 * @param UUID $taxon_to_hide_uuid
1802
 *   A taxon which should not be displayed in the taxon list
1803
 * @param UUID $highlite_synonym_uuid
1804
 *   Optinal parameter wich takes another taxon uuid, if given the
1805
 *   target taxon pages will show the syonymy tab where the taxon
1806
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1807
 *   in case it is found on this page.
1808
 *
1809
 * @return a URI path element as string
1810
 */
1811
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1812
  $res = FALSE;
1813
  if ($name_uuid) {
1814
    $res = 'cdm_dataportal/name/' . $name_uuid;
1815
  }
1816
  if($taxon_to_hide_uuid){
1817
    $res .= '/' . $taxon_to_hide_uuid;
1818
    if($synonym_uuid){
1819
      $res .= '/' . $synonym_uuid;
1820
    }
1821
  }
1822
  return $res;
1823
}
1824

    
1825
/**
1826
 * @todo Please document this function.
1827
 * @see http://drupal.org/node/1354
1828
 */
1829
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1830
  if (!$uuid) {
1831
    return FALSE;
1832
  }
1833
  $out = 'cdm_dataportal/media/' . $uuid;
1834
  if ($representaion_uuid) {
1835
    $out .= '/' . $representaion_uuid;
1836
    if ($partId !== FALSE) {
1837
      $out .= '/' . $partId;
1838
    }
1839
  }
1840
  return $out;
1841
}
1842

    
1843
/**
1844
 * Compares thisRank with thatRank.
1845
 *
1846
 * Returns a negative integer, zero, or a positive integer
1847
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1848
 * e.g:
1849
 * <ul>
1850
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1851
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1852
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1853
 * </ul>
1854
 * <p>
1855
 * This compare logic of the underlying webservice is the
1856
 * <b>inverse logic</b> of the the one implemented in
1857
 * java.lang.Comparable#compareTo(java.lang.Object)
1858
 *
1859
 * @param $thisRankUuid
1860
 * @param $thatRankUuid
1861
 *
1862
 * @return int
1863
 *   A negative integer, zero, or a positive integer
1864
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1865
 */
1866
function rank_compare($thisRankUuid, $thatRankUuid) {
1867
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1868
  return $result->Integer;
1869
}
1870

    
1871
/**
1872
 * Composes an HTML element class attribute value composed of
1873
 * the shortname of the cdm class and the uuid of the entity.
1874
 * This class attribute should be used whereever an cdm-entity is rendered.
1875
 *
1876
 * These according class selectors in css must be escaped, eg:
1877
 *    .cdm\:TextData
1878
 *
1879
 * @param $cdmEntity
1880
 */
1881
function html_class_attribute_ref($cdmEntity) {
1882

    
1883
  if (is_cdm_entity($cdmEntity)) {
1884
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1885
  }
1886
}
1887

    
1888

    
1889
/**
1890
 * Creates a short taxonname.
1891
 *
1892
 * The short name is created by using the taggedTitle field of
1893
 * NameSTO or NameTO instances.
1894
 * If the taggedTitle if empty the fullname will be returned.
1895
 *
1896
 * @param unknown_type $name
1897
 *   Name or TreeNode.
1898
 *
1899
 * @return string
1900
 */
1901
function cdm_dataportal_shortname_of($name) {
1902
  $nameStr = '';
1903

    
1904
  normalize_tagged_text($name->taggedTitle);
1905

    
1906
  // Get all tagged text tokens of the scientific name.
1907
  foreach ($name->taggedTitle as $tagtxt) {
1908
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1909
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1910
    }
1911
  }
1912
  $nameStr = trim($nameStr);
1913

    
1914
  if ($nameStr) {
1915

    
1916
    // Do not return short names for these.
1917
    if ($name->unplaced || $name->excluded) {
1918
      return $nameStr;
1919
    }
1920

    
1921
    /*
1922
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1923
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1924
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1925
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1926
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1927
    */
1928
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1929
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1930
      return $matches[1][0] . "." . $matches[3][0];
1931
    }
1932
    else {
1933
      return $nameStr;
1934
    }
1935
  }
1936
  else {
1937
    return $name->titleCache;
1938
  }
1939
}
1940

    
1941
/**
1942
 * Check if a taxon is accepted by the current taxonomic tree.
1943
 *
1944
 * @param mixed $taxon
1945
 *   The Taxon obkect to check.
1946
 *
1947
 * @return bool
1948
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1949
 */
1950
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1951

    
1952
  $defaultTreeUuid = get_current_classification_uuid();
1953

    
1954
  if (isset($taxon->taxonNodes)) {
1955
    $taxonNodes = $taxon->taxonNodes;
1956
  }
1957
  else {
1958
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1959
  }
1960

    
1961
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1962
    foreach ($taxonNodes as $node) {
1963
      if (isset($node->classification)){
1964
        if(is_object($node->classification)) {
1965
          if ($node->classification->uuid == $defaultTreeUuid) {
1966
            return TRUE;
1967
          }
1968
        }
1969
        else {
1970
          if ($node->classification == $defaultTreeUuid) {
1971
            return TRUE;
1972
          }
1973
        }
1974
      }
1975
    }
1976
  }
1977

    
1978
  return FALSE;
1979
}
1980

    
1981
/**
1982
 * Checks is the source has one of the given types.
1983
 *
1984
 * @param object $source
1985
 *   The original source entity
1986
 * @param array $types
1987
 *   An array of elementd of the OriginalSourceType enumeration
1988
 *   If not set the default will be used which is:
1989
 *    - Lineage
1990
 *    - PrimaryMediaSource
1991
 *    - PrimaryTaxonomicSource
1992
 *    - Unknown
1993
 *    - Other
1994
 * @return boolean
1995
 */
1996
  function _is_original_source_type($source, $types = null) {
1997
    // this is the default
1998
    // maybe this should also be put into the settings
1999
    static $default = array(
2000
      OriginalSourceType::Lineage,
2001
      OriginalSourceType::PrimaryMediaSource,
2002
      OriginalSourceType::PrimaryTaxonomicSource,
2003
      OriginalSourceType::Unknown,
2004
      OriginalSourceType::Other,
2005
    );
2006

    
2007
    if(!$types){
2008
      $types = $default;
2009
    }
2010
    return isset($source->type) && in_array($source->type, $types);
2011
  }
2012

    
2013
/**
2014
 * @todo Please document this function.
2015
 * @see http://drupal.org/node/1354
2016
 */
2017
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
2018
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
2019
}
2020

    
2021

    
2022
/**
2023
 * Collects all the media from a list of description elements.
2024
 *
2025
 * @param array $descriptionElements
2026
 *   The description elements from which to collect the media.
2027
 *
2028
 * @return array
2029
 *   The output with all the collected media.
2030
 */
2031
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2032

    
2033
  $outArrayOfMedia = array();
2034

    
2035
  // Avoiding a warning box in Drupal for Flora Malesiana.
2036
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2037
    foreach ($descriptionElements as $descriptionElement) {
2038
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2039
        foreach ($descriptionElement->media as $media) {
2040
          if (is_object($media)) {
2041
            $outArrayOfMedia[] = $media;
2042
          }
2043
        }
2044
      }
2045
    }
2046
  }
2047
  return $outArrayOfMedia;
2048
}
2049

    
2050
/**
2051
 * @todo Please document this function.
2052
 * @see http://drupal.org/node/1354
2053
 *
2054
 * @param array $cdm_entities
2055
 *   An array of CdmBase instances or a single instance.
2056
 * @param string $footnote_list_key_suggestion
2057
 *
2058
 * @return unknown
2059
 */
2060
function cdm_annotations_as_footnotekeys($cdm_entities, $footnote_list_key_suggestion = NULL) {
2061

    
2062
   static $annotations_types_filter = null;
2063
   if(!$annotations_types_filter) {
2064
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2065
   }
2066

    
2067
  $footNoteKeys = array();
2068

    
2069
  // Is argument cdmBase an array?
2070
  if (!is_array($cdm_entities)) {
2071
    $cdmBase_array = array();
2072
    $cdmBase_array[] = $cdm_entities;
2073
  }
2074
  else {
2075
    $cdmBase_array = $cdm_entities;
2076
  }
2077

    
2078
  // Getting the key for the footnotemanager.
2079
  if (isset($footnote_list_key_suggestion)) {
2080
    $footnote_list_key = $footnote_list_key_suggestion;
2081
  }
2082
  else {
2083
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2084
  }
2085

    
2086
  // Adding the footnotes keys.
2087
  foreach ($cdmBase_array as $cdmBase_element) {
2088
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2089
    if (is_array($annotations)) {
2090
      foreach ($annotations as $annotation) {
2091
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2092
      }
2093
    }
2094
  }
2095

    
2096
  return $footNoteKeys;
2097
}
2098

    
2099

    
2100
/**
2101
 * Creates a CDM Dynabox.
2102
 *
2103
 * @param string $dynabox_id
2104
 *   a uninque name for tha dynabox, using a cdm entity uuid as id is good practice.
2105
 * @param string $label
2106
 *   The clickable text to show.
2107
 * @param string $content_url
2108
 *   The cdm REST service request url wich will deliver the content to be shown
2109
 *   once the dynabox toggles open.
2110
 * @param string $theme
2111
 *   The theme to be used for rendering the cdm REST service response with is
2112
 *   returned from the $content_url.
2113
 * @param string $link_alt_text
2114
 *   The value for the alt attribute of the dynabox link.
2115
 * @param array $enclosingtags
2116
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2117
 *   element itself, $enclosingtags[1] is the tag to be used for the
2118
 *   dynabox_content (optional)
2119
 * @param array $attributes
2120
 * @param $content_element_selector
2121
 *   Optional jQuery selector which can be used to reference a dom element which should
2122
 *   be used as container for the content to be shown. The dynabox-<dynabox id>-content
2123
 *  element will be placed in this container.
2124
 *
2125
 * @param string $open_callback
2126
 *   optional javascript call back function to be triggered after toggling the box to
2127
 *   the open state.
2128
 * @param string $close_callback
2129
 *   optional javascript call back function to be triggered after toggling the box to
2130
 *   the closed state.
2131
 * @return string Returns HTML for a dynabox.
2132
 * Returns HTML for a dynabox.
2133
 */
2134
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text,
2135
                     $enclosingtags = array('li', 'ul'), $attributes = array(),
2136
                     $content_element_selector = null,
2137
                     $open_callback = 'function(){}', $close_callback = 'function(){}' ) {
2138
  $out = '';
2139

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

    
2143
  if(!array_key_exists('class', $attributes)) {
2144
    $attributes['class'] = array();
2145
  }
2146
  $attributes['id'][] = 'dynabox-' . $dynabox_id;
2147
  $dynabox_attributes = drupal_attributes($attributes);
2148

    
2149

    
2150
  _add_js_domEvent(); // requires domEvent.js
2151
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2152
  drupal_add_js("
2153
  jQuery(document).ready(
2154
      function() {
2155
        dynabox('". $dynabox_id ."',
2156
          {
2157
            open_callback: " . $open_callback .",
2158
            close_callback: " . $close_callback .
2159
            ($content_element_selector ? ",\n content_container_selector: '" . $content_element_selector . "'" : "") . "
2160
          }
2161
        );
2162
      }
2163
   );",
2164
   array(
2165
    'type'=>'inline',
2166
    'scope'=>'footer'
2167
    )
2168
  );
2169

    
2170

    
2171
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2172
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2173
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2174
  $out .= '  <' . $enclosingtags[1] . ' id="dynabox-' . $dynabox_id . '-content">';
2175
  $out .= '    <' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2176
  $out .= '    </' . $enclosingtags[1] . '>';
2177
  $out .= '  </' . $enclosingtags[0] . '>';
2178
  $out .= '<!-- dynabox end -->';
2179
  return $out;
2180
}
2181

    
2182
/**
2183
 * Checks whether a feature has any description elements.
2184
 *
2185
 * @param mixed $featureNode
2186
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2187
 *
2188
 * @see _mergeFeatureTreeDescriptions()
2189
 *
2190
 * @return bool
2191
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2192
 *   contains at least one non empty TextData or at least one DescriptionElement
2193
 *   of an other type. A TextData element holding a multilanguageText or a
2194
 *   source reference is considered to be not empty.
2195
 *
2196
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2197
 *       see $block_content_is_not_empty in compose_feature_blocks() and
2198
 *       $feature_block_has_content in compose_feature_block_items_generic
2199
 */
2200
function has_feature_node_description_elements($featureNode) {
2201

    
2202
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2203
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2204
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2205
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2206
          && $descriptionElement->multilanguageText_L10n->text != ''
2207
          || isset($descriptionElement->sources[0])
2208
          || isset($descriptionElement->media[0]) ) {
2209
          return TRUE;
2210
        }
2211
      }
2212
    }
2213
  }
2214
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2215
    foreach ($featureNode->childNodes as $child) {
2216
      if (has_feature_node_description_elements($child)) {
2217
        return TRUE;
2218
      }
2219
    }
2220
  }
2221
  return FALSE;
2222
}
2223

    
2224
/**
2225
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2226
 *
2227
 * @param $chapter
2228
 *   The taxon page chapter or part
2229
 */
2230
function cdm_check_valid_taxon_page($chapter){
2231
  static $taxon_tabs = null;
2232

    
2233
  cdm_check_valid_portal_page();
2234

    
2235
  if($taxon_tabs == null){
2236
    $taxon_tabs = array('all', 'description');
2237
    foreach(get_taxon_tabs_list() as $tab){
2238
      $taxon_tabs[] = strtolower($tab);
2239
    }
2240
  }
2241

    
2242
  if(!in_array($chapter, $taxon_tabs)){
2243
    // oops this is not a valid chapter name
2244
    http_send_status(404); // 404 = Not Found
2245
  }
2246

    
2247
}
2248

    
2249
/**
2250
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2251
 *
2252
 * @param $chapter
2253
 *   The taxon page chapter or part
2254
 */
2255
function cdm_check_valid_portal_page(){
2256
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2257
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2258
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2259
    http_send_status(404); // 404 = Not Found
2260
    exit('HTTP 404');
2261
  }
2262
}
2263

    
2264
/**
2265
 * Generates the diff of the texts and presents it in a HTML diff viewer.
2266
 *
2267
 * @param $text_a
2268
 * @param $text_b
2269
 * @return string
2270
 */
2271
function diff_viewer($text_a, $text_b) {
2272

    
2273
  static $diff_viewer_count = 0;
2274

    
2275
  $element_id = 'part_definitions_diff_' . $diff_viewer_count++;
2276

    
2277
  // http://code.stephenmorley.org/php/diff-implementation/
2278
  module_load_include('php', 'cdm_dataportal', 'lib/class.Diff');
2279
  drupal_add_css(drupal_get_path('module',
2280
      'cdm_dataportal') . '/css/diff.css');
2281
  _add_jquery_ui();
2282
  drupal_add_js(
2283
    'jQuery(document).ready( function(){
2284
        jQuery(\'#' . $element_id . '\').accordion({
2285
        collapsible: true,
2286
        active: false,
2287
        fillSpace: true,
2288
        }).children(\'div\').css({ \'height\': \'auto\' });
2289
        jQuery(\'#' . $element_id . ' table.diff\').prepend(\'<thead><tr><th>Default</th><th>User defined<th></th><tr></thead>\');
2290
     });'
2291
    , array(
2292
    'type' => 'inline',
2293
    'scope' => 'footer'
2294
  ));
2295

    
2296
  $diff = Diff::compare($text_a,
2297
    $text_b);
2298
  $diff_viewer_markup = '<div id="' . $element_id . '"><h3>View Diff</h3><div>'
2299
    . Diff::toTable($diff, '', '')
2300
    . '</div></div>';
2301
  return $diff_viewer_markup;
2302
}
2303

    
2304

    
(9-9/15)