Project

General

Profile

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

    
33
module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
34
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
35
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
36
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
37
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
38
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
39
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
40
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
41
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
42
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.bibliography');
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
 * @param unknown_type $link_element_selector
76
 * @param unknown_type $progress_element_selector
77
 */
78
function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
79

    
80
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
81

    
82
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
83

    
84
  //   drupal_add_js("
85
  //   	  if (Drupal.jsEnabled) {
86
  //         $(document).ready(function() {
87
  //       		$('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');
88
  //         });
89
  //       }", 'inline');
90
  }
91

    
92
/**
93
 * @todo Please document this function.
94
 * @see http://drupal.org/node/1354
95
 */
96
function _add_js_treeselector() {
97
  // drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
98
  drupal_add_js("
99
      jQuery(document).ready(function() {
100
         jQuery('#cdm-taxonomictree-selector-form #edit-val').change(function () {
101
              jQuery('#cdm-taxonomictree-selector-form').submit();
102
          });
103

    
104
      });
105
    ",
106
    array(
107
      'type' => 'inline',
108
      'scope' => 'footer'
109
    )
110
  );
111
}
112

    
113
function _add_js_openlayers() {
114

    
115
  $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.js';
116
  $proj4js = '/js/map/proj4js-1.1.0/proj4js-compressed.js';
117

    
118
  if(variable_get('cdm_js_devel_mode', FALSE)){
119
    // develooper mode libs
120
//     $openlayers = '/js/map/OpenLayers-2.13.1/lib/OpenLayers.js';
121
    $openlayers = '/js/map/OpenLayers-2.13.1/OpenLayers.debug.js';
122
    $proj4js = '/js/map/proj4js-1.1.0/proj4js-combined.js';
123
  }
124

    
125
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
126
    array(
127
      'type' => 'file',
128
      'weight' => JS_LIBRARY,
129
      'cache' => TRUE,
130
      'preprocess' => FALSE
131
    )
132
  );
133

    
134
  // see https://github.com/proj4js/proj4js
135
  // http://openlayers.org/dev/examples/using-proj4js.html
136
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
137
    array(
138
      'type' => 'file',
139
      'weight' => JS_LIBRARY,
140
      'cache' => TRUE,
141
    )
142
  );
143

    
144
  // configure the theme
145
  $openlayers_theme_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/OpenLayers-2.13.1/theme/default/';
146
  $openlayers_imp_path = drupal_get_path('module', 'cdm_dataportal') . '/js/map/img/dark/';
147
  drupal_add_js('OpenLayers.ImgPath="' . base_path() . $openlayers_imp_path . '";', array(
148
      'type' => 'inline',
149
      'weight' => JS_LIBRARY,
150
      'cache' => TRUE,
151
      'preprocess' => FALSE
152
    ));
153

    
154
  drupal_add_css($openlayers_theme_path . 'style.tidy.css',
155
    array(
156
      'type' => 'file',
157
      'cache' => TRUE,
158
      'preprocess' => FALSE
159
    )
160
  );
161

    
162
}
163

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

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

    
218
/**
219
 * @todo Please document this function.
220
 * @see http://drupal.org/node/1354
221
 */
222
function _add_js_footnotes() {
223
  _add_js_domEvent();
224
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
225
}
226

    
227
/**
228
 * @todo Please document this function.
229
 * @see http://drupal.org/node/1354
230
 */
231
function _add_js_cluetip() {
232

    
233
  // TODO replace by
234
  // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
235
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
236
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
237
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
238
  if(variable_get('cdm_js_devel_mode', FALSE)){
239
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
240
  }
241
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
242
  drupal_add_js("jQuery(document).ready(function(){
243
      jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
244
        splitTitle: '|',
245
        showTitle: true,
246
        activation: 'hover',
247
        sicky: true,
248
        arrows: true,
249
        dropShadow: false,
250
        cluetipClass: 'rounded'
251
      });
252
    });", array('type' => 'inline'));
253
}
254

    
255
/**
256
 * @todo Please document this function.
257
 * @see http://drupal.org/node/1354
258
 */
259
function _add_js_ahah() {
260

    
261
  _add_js_domEvent(); // requires domEvent.js
262
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
263
}
264

    
265
/**
266
 * Adds the external javascript file for domEvent.js.
267
 *
268
 * @see drupal_add_js()
269
 */
270
function _add_js_domEvent() {
271
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
272
}
273

    
274

    
275
/* ====================== hook implementations ====================== */
276
/**
277
 * Implements hook_permission().
278
 *
279
 * Valid permissions for this module.
280
 *
281
 * @return array
282
 *   An array of valid permissions for the portfolio module.
283
 */
284
function cdm_dataportal_permission() {
285
  return array(
286
    'administer cdm_dataportal' => array(
287
      'title' => t('administer cdm_dataportal'),
288
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
289
    ),
290
    'cdm_dataportal view notes' => array(
291
      'title' => t('cdm_dataportal view notes'),
292
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
293
    ),
294
    // TODO Which other permissions are required?
295
    // -> check the WP6 requirements document.
296
  );
297
}
298

    
299
/**
300
 * Implements hook_menu().
301
 */
302
function cdm_dataportal_menu() {
303
  $items = array();
304

    
305
  // @see settings.php.
306
  cdm_dataportal_menu_admin($items);
307
  cdm_dataportal_menu_help($items);
308

    
309
  $items['cdm_dataportal/names'] = array(
310
    'page callback' => 'cdm_dataportal_view_names',
311
    'access arguments' => array('access content'),
312
    'type' => MENU_CALLBACK,
313
  );
314

    
315
  // Optional callback arguments: page.
316
  $items['cdm_dataportal/taxon'] = array(
317
    'page callback' => 'cdm_dataportal_taxon_page_view',
318
    'access arguments' => array('access content'),
319
    'type' => MENU_CALLBACK,
320
    // Expected callback arguments: uuid.
321
  );
322

    
323
  $items['cdm_dataportal/name'] = array(
324
    'page callback' => 'cdm_dataportal_name_page_view',
325
      /*
326
    'page arguments' => array(
327
       'taxon_name_uuid',
328
       'taxon_to_hide_uuid',
329
       'synonym_uuid' => NULL
330
      ),
331
      */
332
    'access arguments' => array('access content'),
333
    'type' => MENU_CALLBACK,
334
    // Expected callback arguments: uuid.
335
  );
336

    
337
  $items['cdm_dataportal/reference'] = array(
338
    'page callback' => 'cdm_dataportal_view_reference',
339
    'access arguments' => array('access content'),
340
    'type' => MENU_CALLBACK,
341
    // Expected callback arguments: uuid.
342
  );
343

    
344
  $items['cdm_dataportal/reference/list'] = array(
345
    'page callback' => 'cdm_dataportal_view_reference_list',
346
    'access arguments' => array('access content'),
347
    'type' => MENU_CALLBACK,
348
    // Expected callback arguments: uuid.
349
  );
350

    
351
  $items['cdm_dataportal/media'] = array(
352
    'page callback' => 'cdm_dataportal_view_media',
353
    'access arguments' => array('access content'),
354
    'type' => MENU_CALLBACK,
355
    // Expected callback arguments:
356
    // uuid, mediarepresentation_uuid, part_uuid or part#.
357
  );
358

    
359
  $items['cdm_dataportal/polytomousKey'] = array(
360
    'page callback' => 'cdm_dataportal_view_polytomousKey',
361
    'access arguments' => array('access content'),
362
    'type' => MENU_CALLBACK,
363
    // Expected callback arguments: polytomousKey->uuid.
364
  );
365

    
366
  $items['cdm_dataportal/search'] = array(
367
    'page callback' => 'cdm_dataportal_view_search_advanced',
368
    'access arguments' => array('access content'),
369
    'type' => MENU_CALLBACK,
370
  );
371

    
372
  $items['cdm_dataportal/search/advanced'] = array(
373
    'title' => 'Advanced',
374
    'page callback' => 'cdm_dataportal_view_search_advanced',
375
    'access arguments' => array('access content'),
376
    'type' => MENU_DEFAULT_LOCAL_TASK,
377
  );
378

    
379
  $items['cdm_dataportal/search/taxon_by_description'] = array(
380
    'title' => 'By description full text',
381
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
382
    'access arguments' => array('access content'),
383
    'type' => MENU_LOCAL_TASK,
384
  );
385

    
386
  $items['cdm_dataportal/search/results/taxon'] = array(
387
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
388
    'access arguments' => array('access content'),
389
    'type' => MENU_CALLBACK,
390
  );
391
  /*
392
   $items['cdm/xml2json'] = array(
393
   'page callback' => 'cdm_view_xml2json',
394
   'access arguments' => array('access content'),
395
   'type' => MENU_CALLBACK,
396
   );
397
   */
398

    
399
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
400
  // User configuration of cdm_dataportal.
401
  $items['user/%/cdm_dataportal'] = array(
402
    'title' => 'cdm_dataportal',
403
    'access arguments' => array('access content'),
404
    'page callback' => 'drupal_get_form',
405
    'page arguments' => array('cdm_dataportal_user_form'),
406
    'type' => MENU_LOCAL_TASK,
407
    'weight' => 10,
408
  );
409
  // }
410

    
411
  // 'May not cache' in D5.
412
  $items['cdm_dataportal/name/%'] = array(
413
    // 'page callback' => 'cdm_dataportal_view_name',
414
    'page callback' => 'cdm_dataportal_name_page_view',
415
    'page arguments' => array(2, 3, 4),
416
    'access arguments' => array('access content'),
417
    'type' => MENU_CALLBACK,
418
  );
419

    
420
  // --- Local tasks for Taxon.
421
  // --- tabbed taxon page
422
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
423
    $items['cdm_dataportal/taxon/%'] = array(
424
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
425
      'page callback' => 'cdm_dataportal_taxon_page_view',
426
      'access arguments' => array('access content'),
427
      'type' => MENU_CALLBACK,
428
      'weight' => 1,
429
      'page arguments' => array(2, "description")
430
      , // Expected callback arguments: name_uuid.
431
    );
432

    
433
    $items['cdm_dataportal/taxon/%/all'] = array(
434
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
435
      'page callback' => 'cdm_dataportal_taxon_page_view',
436
      'access arguments' => array('access content'),
437
      'type' => MENU_CALLBACK,
438
      'weight' => 2,
439
      'page arguments' => array(2, "all")
440
      , // Expected callback arguments: name_uuid.
441
    );
442

    
443
    $items['cdm_dataportal/taxon/%/description'] = array(
444
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
445
      'page callback' => 'cdm_dataportal_taxon_page_view',
446
      'access arguments' => array('access content'),
447
      'type' => MENU_DEFAULT_LOCAL_TASK,
448
      'weight' => 2,
449
      'page arguments' => array(2, "description")
450
      , // Expected callback arguments: name_uuid.
451
    );
452

    
453
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
454
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
455
      'page callback' => 'cdm_dataportal_taxon_page_view',
456
      'access arguments' => array('access content'),
457
      'type' => MENU_LOCAL_TASK,
458
      'weight' => 4,
459
      'page arguments' => array(2, "synonymy", 4)
460
      , // Expected callback arguments: name_uuid.
461
    );
462
    $items['cdm_dataportal/taxon/%/images'] = array(
463
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
464
      'page callback' => 'cdm_dataportal_taxon_page_view',
465
      'access arguments' => array('access content'),
466
      'type' => MENU_LOCAL_TASK,
467
      'weight' => 5,
468
      'page arguments' => array(2, "images")
469
      , // Expected callback arguments: name_uuid.
470
    );
471

    
472
    $items['cdm_dataportal/taxon/%/specimens'] = array(
473
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
474
      'page callback' => 'cdm_dataportal_taxon_page_view',
475
      'access arguments' => array('access content'),
476
      'type' => MENU_LOCAL_TASK,
477
      'weight' => 6,
478
      'page arguments' => array(2, "specimens")
479
      , // Expected callback arguments: name_uuid.
480
    );
481

    
482
    $items['cdm_dataportal/taxon/%/keys'] = array(
483
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
484
      'page callback' => 'cdm_dataportal_taxon_page_view',
485
      'access arguments' => array('access content'),
486
      'type' => MENU_LOCAL_TASK,
487
      'weight' => 6,
488
      'page arguments' => array(2, "keys")
489
      , // Expected callback arguments: name_uuid.
490
    );
491
  }
492

    
493
  // --- refresh link for all cdmnode types
494
  foreach (cdm_get_nodetypes() as $type=>$name) {
495
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
496
        'title' => t('Refresh'),
497
        'page callback' => 'cdm_dataportal_refresh_node',
498
        'access arguments' => array('administer cdm_dataportal'),
499
        'type' => MENU_LOCAL_TASK,
500
        'weight' => 100,
501
        'page arguments' => array($name, 2)
502
    );
503
  }
504

    
505
  return $items;
506
}
507

    
508
/**
509
 * Implements hook_init().
510
 *
511
 */
512
function cdm_dataportal_init() {
513
  //FIXME To add CSS or JS that should be present on all pages, modules
514
  //      should not implement this hook, but declare these files in their .info file.
515
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
516
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
517
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
518

    
519
  if(variable_get('cdm_debug_mode', FALSE)){
520
    $file = 'temporary://drupal_debug.txt';
521
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
522
  }
523

    
524
  $bibliography_settings = get_bibliography_settings();
525
  if($bibliography_settings['enabled'] == 1){
526
    FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', 'div', $bibliography_settings['key_format']);
527
  }
528
}
529

    
530
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
531

    
532
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
533

    
534
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
535
    // force reloading of all and notify user about this special loading
536
    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: ')
537
        . l('Back to tabbed taxon page', $base_path));
538
    $base_path .= '/all';
539
  } else {
540
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
541
  }
542

    
543
  $parameters['cacheL2_refresh'] ='1';
544

    
545

    
546
  drupal_goto($base_path, array('query' => $parameters));
547
}
548

    
549
/**
550
 * The function generate form for own user cdm dataportal configurations.
551
 */
552
function cdm_dataportal_user_form($form, &$form_state) {
553
  global $user;
554
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
555

    
556
  $form['taxon_page_tabs'] = array(
557
      '#type' => 'fieldset',
558
      '#title' => t('Taxon page tabs'),
559
  );
560
  $form['taxon_page_tabs']['check'] = array(
561
    '#type' => 'checkbox',
562
    '#title' => t('Activate user default configuration'),
563
    '#default_value' => variable_get($checkbox_value, 0),
564
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
565
  );
566

    
567
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
568
    '#type' => 'select',
569
    '#title' => t('Default tab to display'),
570
    '#default_value' => get_default_taxon_tab(TRUE),
571
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
572
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
573
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
574
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
575
  );
576

    
577
  $form['submit'] = array(
578
    '#type' => 'submit',
579
    '#value' => t('Submit'),
580
  );
581

    
582
  return $form;
583
}
584

    
585
/**
586
 * Form submission handler for user_form().
587
 *
588
 * Submits the user cdm dataportal configurations.
589
 */
590
function cdm_dataportal_user_form_submit($form, &$form_state) {
591
  global $user;
592
  $msg_type = 'status';
593
  $username = $user->name;
594
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
595

    
596
  // If is the right user the variables are setted.
597
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
598
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
599
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
600
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
601
    if ($form_state['values']['check']) {
602
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
603
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
604
        '!tab' => $variable[variable_get($variable_to_use, 0)],
605
        '!user' => $username,
606
      ))), $msg_type);
607
    }
608
    else {
609
      drupal_set_message(check_plain(t('The user default tab wont be used for
610
        the next taxon site, check the box if you want to use the user default configuration.')));
611
    }
612
    // Problem with the user id => variables wont be saved.
613
  }
614
  else {
615
    $msg_type = 'warning';
616
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
617
  }
618
}
619

    
620
/**
621
 * Implements hook_block_info().
622
 */
623
function cdm_dataportal_block_info() {
624

    
625
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
626
    // $block[1]["info"] = t("CDM DataPortal Credits");
627
    $block["2"] = array(
628
        "info" => t("CDM Search Taxa"),
629
        "cache" => DRUPAL_NO_CACHE
630
      );
631
    // $block[3]["info"] = t("CDM Filters");
632
    $block["4"]["info"] = t("CDM Dataportal Print");
633
    $block["keys"]["info"] = t("CDM identification keys");
634
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
635

    
636
    return $block;
637
}
638

    
639
/**
640
 * Implements hook_block_view().
641
 */
642
function cdm_dataportal_block_view($delta) {
643
  // TODO Rename block deltas (e.g. '2') to readable strings.
644
  switch ($delta) {
645
    // case 'delta-1':
646
    // $block['subject'] = t('Credits');
647
    // $block['content'] = theme('cdm_credits');
648
    // return $block;
649
    case '2':
650
      $block['subject'] = t('Search taxa');
651
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
652
      $block['content'] = drupal_render($form);
653

    
654
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
655
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
656
      }
657
      return $block;
658
    case '4':
659
      $block['subject'] = '';
660
      $block['content'] = theme('cdm_print_button');
661
      return $block;
662
    case "keys":
663
      $block['subject'] = t('Identification Keys');
664
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
665
      return $block;
666
    case "fundedByEDIT":
667
      // t('Funded by EDIT');
668
      $text = '<none>';
669
      $block['subject'] = $text;
670
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
671
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
672
        'attributes' => array("target" => "EDIT"),
673
        'absolute' => TRUE,
674
        'html' => TRUE,
675
      ));
676
      return $block;
677
  }
678
}
679

    
680
/*
681
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
682
 $_SESSION['cdm'] = NULL;
683
 if(is_string($cdm_ws_uri_update)){
684
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
685
 }
686
 }
687

    
688
 function cdm_dataportal_session_validate(){
689
 if(!isset($_SESSION['cdm']['ws_uri'])){
690
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
691
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
692
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
693
 }
694
 }
695
 */
696

    
697
/**
698
 * creates a  selector form for taxonomic trees.
699
 *
700
 * @return a drupal form array
701
 */
702
function cdm_taxonomictree_selector() {
703
  _add_js_treeselector();
704

    
705
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
706
  return $form;
707
}
708

    
709
/**
710
 * @todo Please document this function.
711
 * @see http://drupal.org/node/1354
712
 */
713
function cdm_taxonomictree_selector_form($form, &$form_state) {
714

    
715
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
716
  $form['#action'] = $url;
717

    
718
  $form['var'] = array(
719
    '#weight' => -3,
720
    '#type' => 'hidden',
721
    '#value' => '[cdm][taxonomictree_uuid]',
722
  );
723

    
724
  $destination_array = drupal_get_destination();
725
  $destination = $destination_array['destination'];
726

    
727
  $form['destination'] = array(
728
    '#weight' => -3,
729
    '#type' => 'hidden',
730
    '#value' =>  $destination,
731
  );
732

    
733
  $options = cdm_get_taxontrees_as_options();
734
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
735
  if($taxontree_includes){
736
    $filtered_options = array();
737
    foreach($options as $uuid=>$label){
738
      if(!empty($taxontree_includes[$uuid])){
739
        $filtered_options[$uuid] = $label;
740
      }
741
    }
742
    $options = $filtered_options;
743
  }
744

    
745
  $form['val'] = array(
746
    '#type' => 'select',
747
    '#title' => t('Available classifications'),
748
    '#default_value' => get_taxonomictree_uuid_selected(),
749
    '#options' => $options,
750
    '#attributes' => array('class' => array('highlite-first-child'))
751
  );
752

    
753
  return $form;
754

    
755
}
756

    
757
/* UNREACHABLE since action of form directly links to view.
758
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
759

    
760
 $_SESSION['cdm']['search'] = $form_values;
761
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
762
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
763
 //$paramstr = compose_url_prameterstr($form_values);
764
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
765
 }
766
 */
767
/* ====================== menu callback functions ====================== */
768
/**
769
 * @todo Please document this function.
770
 * @see http://drupal.org/node/1354
771
 */
772
/*
773
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
774
  static $comment_node_disabled =  0;
775
  static $comment_node_read_only =  1;
776
  static $comment_node_read_write =  2;
777

    
778
  if ($form_id == 'node_type_form'
779
   && isset($form['identity']['type'])
780
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
781
  ) {
782
    $form['workflow']['comment'] = array(
783
      '#type' => 'radios',
784
      '#title' => t('Default comment setting'),
785
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
786
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
787
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
788
    );
789
  }
790
}
791
*/
792

    
793
/**
794
 * Displays a list of the known taxonomic names.
795
 *
796
 * When the list of taxonomic names is displayed, long lists are split up into
797
 * multiple pages.
798
 *
799
 * TODO: Parameters are still preliminary.
800
 *
801
 * @param string $beginsWith
802
 * @param string $page
803
 *   Page number to diplay defaults to page 1.
804
 * @param bool $onlyAccepted
805
 */
806
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
807

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

    
810
  /*
811
  // FIXME the filter for accepted names will be a form element, thus this
812
  // widget should be generated via form api preferably as block.
813
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
814
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
815
  $out .= theme('cdm_listof_taxa', $taxonPager);
816
  return $out;
817
  */
818
}
819

    
820
/**
821
 * @todo Please document this function.
822
 * @see http://drupal.org/node/1354
823
 */
824
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
825

    
826
  cdm_check_valid_portal_page();
827

    
828
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
829
  return theme('cdm_reference_page', array('reference' => $reference));
830
}
831

    
832
/**
833
 * Created a view on a all references contained in the portal.
834
 *
835
 * This function is used at the path cdm_dataportal/reference/list
836
 */
837
function cdm_dataportal_view_reference_list($pageNumber) {
838
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
839
  return theme('cdm_reference_pager', array(
840
    'referencePager' => $referencePager,
841
    'path' => 'cdm_dataportal/reference/list/',
842
    ));
843
}
844

    
845
/**
846
 * @todo Please document this function.
847
 * @see http://drupal.org/node/1354
848
 */
849
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
850

    
851
  cdm_check_valid_portal_page();
852

    
853
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
854
  return theme('cdm_media_page', array(
855
    'media' => $media,
856
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
857
    'partId' => $part,
858
    ));
859
}
860

    
861
/**
862
 * @todo Please document this function.
863
 * @see http://drupal.org/node/1354
864
 */
865
function _load_taxonBase(&$taxonBase) {
866
  if (isset($taxonBase->uuid)) {
867
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
868
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
869
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
870
  }
871
}
872

    
873
/**
874
 * Loads the media associated to the given taxon from the cdm server.
875
 * The aggregation settings regarding taxon relathionships and
876
 * taxonnomic childen are taken into account.
877
 *
878
 * The media lists are cached in a static variable.
879
 *
880
 * @param Taxon $taxon
881
 *   A CDM Taxon entitiy
882
 *
883
 * @return array
884
 *   An array of CDM Media entities
885
 *
886
 */
887
function _load_media_for_taxon($taxon) {
888

    
889
  static $media = NULL;
890

    
891
  if(!isset($media)) {
892
    $media = array();
893
  }
894
  if (!isset($media[$taxon->uuid])) {
895

    
896
    // --- GET Images --- //
897
    $mediaQueryParameters = array(
898
        "type" => "ImageFile",
899
    );
900

    
901
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
902
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
903
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
904

    
905
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
906
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
907
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
908
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
909

    
910
    $ws_endpoint = NULL;
911
    if ( variable_get('cdm_images_include_children', 0) == 0) {
912
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
913
    } else {
914
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
915
    }
916

    
917
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
918
        array(
919
            $taxon->uuid,
920
        ),
921
        queryString($mediaQueryParameters)
922
       );
923
  }
924

    
925
  return $media[$taxon->uuid];
926
}
927

    
928
/**
929
 *
930
 * @param Taxon $taxon
931
 *   A CDM Taxon entitiy
932
 *
933
 * @return array
934
 *   An array of CDM SpecimenOrObservation entities
935
 *
936
function _load_occurences_for_taxon($taxon){
937

    
938
  static $occurences = NULL;
939

    
940
  if(!isset($occurences)) {
941
    $occurences = array();
942
  }
943

    
944
  if (!isset($occurences[$taxon->uuid])){
945

    
946
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
947
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
948
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
949

    
950
    $by_associatedtaxon_query = http_build_query(array(
951
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
952
        'relationships' => implode(',', $relationship_choice['direct']),
953
        'pageSize' => null // all hits in one page
954
    )
955
    );
956

    
957
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
958
        null,
959
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
960
    );
961

    
962

    
963
    if(isset($pager->records[0])){
964
      $occurences[$taxon->uuid] =  $pager->records;
965
    }
966
  }
967
  return $occurences[$taxon->uuid];
968
}
969
 */
970

    
971
/**
972
 * Gets a Drupal variable, string or array and returns it.
973
 *
974
 * Similar to the variable_get() function of Drupal, except that this function
975
 * is able to handle arrays correctly. This function is especially useful
976
 * when dealing with collections of setting form elements (#tree = TRUE).
977
 *
978
 * @param string $variableKey
979
 *   The Unique key of the Drupal variable in the Drupal variables table.
980
 * @param string $defaultValueString
981
 *   A string as for example derived from a CONSTANT.
982
 *
983
 * @return mixed
984
 *   Returns usally an array, depending on the nature of the variable.
985
 */
986
function mixed_variable_get($variableKey, $defaultValueString) {
987
  $systemDefaults = unserialize($defaultValueString);
988
  $storedSettings = variable_get($variableKey, array());
989
  if (is_array($storedSettings)) {
990
    $settings = array_merge($systemDefaults, $storedSettings);
991
  }
992
  else {
993
    $settings = $systemDefaults;
994
  }
995
  return $settings;
996
}
997

    
998
/**
999
 * Recusive funciton to convert an object into an array.
1000
 * also subordinate objects will be converted.
1001
 *
1002
 * @param object $object
1003
 * @return the array
1004
 */
1005
function convert_to_array($object) {
1006
  if(is_object($object) || is_array($object)) {
1007
    $array = (array)$object;
1008
    foreach ($array as $key=>$value){
1009
      $array[$key] = convert_to_array($value);
1010
    }
1011
    return $array;
1012
  } else {
1013
    return $object;
1014
  }
1015
}
1016

    
1017
/**
1018
 * Wraps the given $html string into a render array suitable for drupal_render()
1019
 *
1020
 * @param string $html
1021
 *   the html string, see
1022
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1023
 * @param number $weight
1024
 *   A positive or negative number (integer or decimal).
1025
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1026
 *
1027
 * @return
1028
 *   A render array
1029
 *
1030
 */
1031
function markup_to_render_array($html, $weight = FALSE) {
1032
  $render_array = array(
1033
    '#markup' => $html
1034
  );
1035
  if (is_numeric($weight)) {
1036
    $render_array['#weight'] = $weight;
1037
  }
1038
  return $render_array;
1039
}
1040

    
1041
/**
1042
 * Loads the subgraph of a given PolytomousKeyNode.
1043
 *
1044
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1045
 * the CDM REST service.
1046
 *
1047
 * @param mixed $polytomousKeyNode
1048
 *   PolytomousKeyNode passed by reference.
1049
 *
1050
 * @return void
1051
 */
1052
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1053

    
1054
  if (!$polytomousKeyNode) {
1055
    return;
1056
  }
1057
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1058
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1059
    return;
1060
  }
1061
  if (!is_uuid($polytomousKeyNode->uuid)) {
1062
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1063
    return;
1064
  }
1065

    
1066
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1067

    
1068
  if (!$polytomousKeyNode) {
1069
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1070
    return;
1071
  }
1072

    
1073
  // Load children.
1074
  foreach ($polytomousKeyNode->children as &$childNode) {
1075
    _load_polytomousKeySubGraph($childNode);
1076
  }
1077

    
1078
  // Load subkey.
1079
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1080

    
1081
  // Load taxon.
1082
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1083
  _load_taxonBase($polytomousKeyNode->taxon);
1084
  return;
1085
}
1086

    
1087
/**
1088
 * @todo Please document this function.
1089
 * @see http://drupal.org/node/1354
1090
 */
1091
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1092

    
1093
  cdm_check_valid_portal_page();
1094

    
1095
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1096

    
1097
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1098
  if (is_array($sourcePager->records)) {
1099
    $polytomousKey->sources = $sourcePager->records;
1100
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1101
  }
1102

    
1103
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1104
  if (is_array($annotationPager->records)) {
1105
    $polytomousKey->annotations = $annotationPager->records;
1106
  }
1107

    
1108
  _load_polytomousKeySubGraph($polytomousKey->root);
1109
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1110
}
1111

    
1112
/**
1113
 * Creates a taxon page view or a chapter of it.
1114
 *
1115
 * The taxon page gives detailed information on a taxon, it shows:
1116
 *  - Taxon name.
1117
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1118
 *    heterotypic and finally followed by misapplied names.
1119
 *    The list is ordered historically.
1120
 *  - All description associated with the taxon.
1121
 *
1122
 * @param string $uuid
1123
 * @param string $chapter
1124
 *   Name of the part to display, valid values are:
1125
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1126
 *
1127
 * @return unknown_type
1128
 */
1129
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1130

    
1131
  cdm_check_valid_taxon_page($chapter);
1132
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1133
  // show a warning in case the javascript development mode is anabled
1134
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1135
    drupal_set_message(t('The !url1 is enabled.
1136
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1137
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1138
    )),
1139
    'warning'
1140
        );
1141
  }
1142

    
1143
  // Display the page for the taxon defined by $uuid.
1144
  // set_last_taxon_page_tab(arg(3));
1145
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1146
  if (!empty($taxonpage)) {
1147
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1148
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1149
  }
1150
  else {
1151
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1152
    return '';
1153
  }
1154
}
1155

    
1156
/**
1157
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1158
 * which has two fields, one for the page title and one for the content. Later on in the
1159
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1160
 * function as the function parameters $title and $content.
1161
 *
1162
 * @param string $uuid
1163
 *   the uuid of the taxon to show
1164
 * @param string $chapter
1165
 *   Name of the part to display, valid values are:
1166
 *   'description', 'images', 'synonymy', 'all'.
1167
 *
1168
 * @return taxonpage object with the following fields:
1169
 *   - title : the title of the page
1170
 *   - content: the content of the page
1171
 *
1172
 */
1173
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1174
  // Taxon object.
1175
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1176
  if (empty($taxon)) {
1177
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1178
    return FALSE;
1179
  }
1180
  $taxonpage = new stdClass();
1181

    
1182
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1183
    'taxon' => $taxon
1184
  ));
1185

    
1186
  // Check if the taxon id contained in the currently selected tree.
1187
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1188

    
1189
  if (!$taxon_in_current_tree) {
1190
    $classifications = get_classifications_for_taxon($taxon);
1191
    if (count($classifications) == 0) {
1192
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1193
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1194
      ))), 'warning');
1195
    }
1196
    else {
1197
      $trees = '';
1198
      foreach ($classifications as $classification) {
1199
        if (isset($classification->titleCache)) {
1200
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1201
        }
1202
      }
1203

    
1204
      drupal_set_message(format_plural(count($trees),
1205
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1206
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1207
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1208
    }
1209
  }
1210

    
1211
  // Render the taxon page.
1212
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1213
  $taxonpage->content = drupal_render($render_array);
1214

    
1215
  return $taxonpage;
1216
}
1217

    
1218
/**
1219
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1220
 *
1221
 * The node page shows the taxon name title and the list of taxon related
1222
 * with such taxon. Name on the tree already in use.
1223
 *
1224
 * @param UUID $taxon_name_uuid
1225
 *   The uuid of the CDM TaxonNameBase to show a name page for
1226
 * @param UUID $taxon_to_hide_uuid
1227
 *   A taxon which should not be displayed in the taxon list
1228
 * @param UUID $highlite_synonym_uuid
1229
 *   Optinal parameter wich takes another taxon uuid, if given the
1230
 *   target taxon pages will show the syonymy tab where the taxon
1231
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1232
 *   in case it is found on this page.
1233
 *
1234
 * @return mixed
1235
 *   The formatted name page as node.
1236
 */
1237
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1238

    
1239
  cdm_check_valid_portal_page();
1240

    
1241
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1242
  if (!empty($taxonname_page)) {
1243
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1244
  }
1245
  else {
1246
    return '';
1247
  }
1248
}
1249

    
1250
/**
1251
 * View function for a TaxonNameBase page.
1252
 *
1253
 * The name page lists all taxa for which the name specified by the
1254
 * $taxon_name_uuid is being used. I case there is only one name the
1255
 * page automatically redirects ti the according taxon page. Otherwise
1256
 * the list of names is displayed.
1257
 *
1258
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1259
 * list of taxa. This is useful for example when referencing from a taxon
1260
 * to the name page and the referring taxon should not be repeaded in the
1261
 * name page.
1262
 *
1263
 *
1264
 * @param UUID $taxon_name_uuid
1265
 *   The uuid of the CDM TaxonNameBase to show a name page for
1266
 * @param UUID $taxon_to_hide_uuid
1267
 *   A taxon which should not be displayed in the taxon list
1268
 * @param UUID $highlite_synonym_uuid
1269
 *   Optinal parameter wich takes another taxon uuid, if given the
1270
 *   target taxon pages will show the syonymy tab where the taxon
1271
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1272
 *   in case it is found on this page.
1273
 *
1274
 * @return object
1275
 *   An object with two fields:
1276
 *     - title: the page title
1277
 *     - content: the page content
1278
 */
1279
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1280
  // Getting the full taxonname object from the server.
1281
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1282
  if (!$taxon_name) {
1283
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1284
    return FALSE;
1285
  }
1286
  // Searching for all the taxa connected with the taxon name on the tree
1287
  // in use.
1288
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1289
  $request_params = array();
1290
  $request_params['query'] = $name_cache;
1291
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1292
  $request_params['doTaxa'] = 1;
1293
  $request_params['doSynonyms'] = 1;
1294
  $request_params['doTaxaByCommonNames'] = 0;
1295
  $request_params['matchMode'] = "EXACT";
1296
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1297

    
1298
  // Removing the name where we come from.
1299
  foreach ($taxon_pager->records as $k => &$taxon) {
1300
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1301
      unset($taxon_pager->records[$k]);
1302
    }
1303
  }
1304
  // Show the taxa list or go to the singular taxon.
1305
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1306
    $singleTaxon = array_pop($taxon_pager->records);
1307
    if ($singleTaxon->class != "Taxon") {
1308
      // It is a Synonym -> look for the accepted.
1309
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1310
      if (!empty($highlite_synonym_uuid)) {
1311
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1312
      }
1313
      else {
1314
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1315
      }
1316
    }
1317
    else {
1318
      // It is an accepted taxon.
1319
      if (!empty($highlite_synonym_uuid)) {
1320
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1321
      }
1322
      else {
1323
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1324
      }
1325
    }
1326
  }
1327
  else {// More than one taxa case.
1328
    $taxon_name_page = new stdClass();
1329
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1330
    if ($taxon_pager->records) {
1331
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1332
    }
1333
    else {
1334
      $taxon_name_page->content = 'This name has no taxa';
1335
    }
1336
    return $taxon_name_page;
1337
  }
1338
}
1339

    
1340
/**
1341
 * @todo Please document this function.
1342
 * @see http://drupal.org/node/1354
1343
 */
1344
function cdm_dataportal_view_search_advanced() {
1345

    
1346
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1347
  $form = array();
1348
  $form_state = array();
1349
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1350

    
1351
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1352

    
1353
}
1354

    
1355
/**
1356
 * @todo Please document this function.
1357
 * @see http://drupal.org/node/1354
1358
 */
1359
function cdm_dataportal_view_search_taxon_by_description() {
1360
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1361
  // $form_state = false;
1362
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1363
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1364

    
1365
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1366
}
1367

    
1368
/**
1369
 * Executes the search and generates the result list of taxa.
1370
 */
1371
function cdm_dataportal_view_search_results_taxon() {
1372

    
1373
  $taxonPager = cdm_dataportal_search_execute();
1374

    
1375
  $showThumbnails = do_showThumbnails();
1376

    
1377
  $setSessionUri = url('cdm_api/setvalue/session', array(
1378
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1379
  ));
1380

    
1381
  drupal_add_js('jQuery(document).ready(function() {
1382

    
1383
      // init
1384
      if(' . $showThumbnails . ' == 1){
1385
      jQuery(\'.media_gallery\').show(20);
1386
  } else {
1387
      jQuery(\'.media_gallery\').hide(20);
1388
  }
1389
      // add change hander
1390
      jQuery(\'#showThumbnails\').change(
1391
      function(event){
1392
      var state = 0;
1393
      if(jQuery(this).is(\':checked\')){
1394
      jQuery(\'.media_gallery\').show(20);
1395
      state = 1;
1396
  } else {
1397
      jQuery(\'.media_gallery\').hide(20);
1398
  }
1399
      // store state in session variable
1400
      var uri = \'' . $setSessionUri . '\' + state;
1401
      jQuery.get(uri);
1402
  });
1403
  });',
1404
  array('type' => "inline", 'scope' => JS_DEFAULT));
1405

    
1406
  drupal_set_title(t('Search results'), PASS_THROUGH);
1407

    
1408
  return theme('cdm_search_results', array(
1409
    'pager' => $taxonPager,
1410
    'path' => 'cdm_dataportal/search/results/taxon',
1411
    ));
1412
}
1413

    
1414
/**
1415
 * Provides the standart image wich indicated a loading process
1416
 *
1417
 * @return string
1418
 *  The img html tag
1419
 */
1420
function loading_image_html() {
1421
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1422
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1423
}
1424

    
1425
/**
1426
 * Returns the state of the the showThumbnails flag set in the
1427
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1428
 *
1429
 * @return boolean
1430
 *    returns 1 if the flag is set
1431
 */
1432
function do_showThumbnails() {
1433
  static $showThumbnails = null;
1434

    
1435
  if($showThumbnails == null) {
1436
    $showThumbnails = 0;
1437
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1438
      $showThumbnails = 0;
1439
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1440
      $showThumbnails = is_array($search_gallery_settings)
1441
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1442
        && (
1443
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1444
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1445
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1446
            )
1447
         ? 1 : 0;
1448

    
1449
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1450
    }
1451
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1452
    if (!is_numeric($showThumbnails)) {
1453
      $showThumbnails = 1;
1454
    }
1455
  }
1456

    
1457
  return $showThumbnails;
1458
}
1459

    
1460
/**
1461
 * View which transforms XML output from a given webservice endpoint into JSON.
1462
 */
1463
/*
1464
 function cdm_view_xml2json(){
1465
 $file = arg(2);
1466
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1467
 return  xml2json::transformXmlStringToJson($datastr);
1468
 }
1469
 */
1470

    
1471
/* ====================== other functions ====================== */
1472
/**
1473
 * Creates a URL to the taxon page specified by the $uuid parameter.
1474
 *
1475
 * The URL will be prepended with a path element to a specific taxon page tab.
1476
 *
1477
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1478
 * be set globally in the administrative settings or individually in the user
1479
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1480
 * the last portal will stay on this last tab.
1481
 *
1482
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1483
 * internal mechanism by a specific value.
1484
 *
1485
 * @param string $uuid
1486
 *   The UUID of the taxon.
1487
 * @param string $page_tab
1488
 *   Overwriting the preset mechanism by defining specific value for the
1489
 *   taxon page tab.
1490
 *
1491
 * @return string
1492
 *   The created URL.
1493
 */
1494
function path_to_taxon($uuid, $page_tab = FALSE) {
1495

    
1496
  $tab = get_default_taxon_tab();
1497
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1498

    
1499
  if (!$uuid) {
1500
    return FALSE;
1501
  }
1502

    
1503
  if ($page_tab) {
1504
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1505
  }
1506
  elseif (!$tab || strtolower($tab) == 'general') {
1507
    return 'cdm_dataportal/taxon/' . $uuid;
1508
  }
1509
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1510
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1511
  }
1512
  else {
1513
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1514
  }
1515
}
1516

    
1517
/**
1518
 * Creates a URL to show a synonmy in the according taxon page.
1519
 *
1520
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1521
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1522
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1523
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1524
 * in the page
1525
 *
1526
 * @param string $synonymUuid
1527
 *    The uuid of the synonym
1528
 * @param string $acceptedUuid
1529
 *    The uuid of the according accepted taxon
1530
 * @return string
1531
 *    The URL to show a synonmy in the according taxon page
1532
 */
1533
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1534
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1535
  return url($acceptedPath, array(
1536
      'query' => array(
1537
        // highlite the synony in the synonymy
1538
        'highlite' => $synonymUuid,
1539
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1540
        // see theme_taxon_page_title()
1541
        'acceptedFor' => $synonymUuid
1542
      ),
1543
      'fragment' => $synonymUuid
1544
  ));
1545

    
1546
}
1547

    
1548
/**
1549
 * Compses the drupal path to the key identified by the uuid.
1550
 *
1551
 * @param string $keyType
1552
 *    the key typer corresponds to the specific class of the CDM
1553
 *    IdentificationKey. Possible values are
1554
 *      -PolytomousKey
1555
 *      -MultimediaKey
1556
 *      - ...
1557
 * @param UUID $keyUuid
1558
 *   The UUID of the key
1559
 */
1560
function path_to_key($keyType, $keyUuid) {
1561
  if (!$keyUuid || !$keyType) {
1562
    return FALSE;
1563
  }
1564
  $keyType{0} = strtolower($keyType{0});
1565
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1566
}
1567

    
1568
/**
1569
 * @todo Please document this function.
1570
 * @see http://drupal.org/node/1354
1571
 */
1572
function path_to_reference($uuid) {
1573
  if (!$uuid) {
1574
    return FALSE;
1575
  }
1576
  return 'cdm_dataportal/reference/' . $uuid;
1577
}
1578

    
1579
/**
1580
 * Creates the path to a cdm_dataportal taxon name page.
1581
 *
1582
 * @param UUID $taxon_name_uuid
1583
 *   The uuid of the CDM TaxonNameBase to show a name page for
1584
 * @param UUID $taxon_to_hide_uuid
1585
 *   A taxon which should not be displayed in the taxon list
1586
 * @param UUID $highlite_synonym_uuid
1587
 *   Optinal parameter wich takes another taxon uuid, if given the
1588
 *   target taxon pages will show the syonymy tab where the taxon
1589
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1590
 *   in case it is found on this page.
1591
 *
1592
 * @return a URI path element as string
1593
 */
1594
function path_to_name($name_uuid, $taxon_to_hide_uuid = NULL, $synonym_uuid  = NULL) {
1595
  $res = FALSE;
1596
  if ($name_uuid) {
1597
    $res = 'cdm_dataportal/name/' . $name_uuid;
1598
  }
1599
  if($taxon_to_hide_uuid){
1600
    $res .= '/' . $taxon_to_hide_uuid;
1601
    if($synonym_uuid){
1602
      $res .= '/' . $synonym_uuid;
1603
    }
1604
  }
1605
  return $res;
1606
}
1607

    
1608
/**
1609
 * @todo Please document this function.
1610
 * @see http://drupal.org/node/1354
1611
 */
1612
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1613
  if (!$uuid) {
1614
    return FALSE;
1615
  }
1616
  $out = 'cdm_dataportal/media/' . $uuid;
1617
  if ($representaion_uuid) {
1618
    $out .= '/' . $representaion_uuid;
1619
    if ($partId !== FALSE) {
1620
      $out .= '/' . $partId;
1621
    }
1622
  }
1623
  return $out;
1624
}
1625

    
1626
/**
1627
 * Compares thisRank with thatRank.
1628
 *
1629
 * Returns a negative integer, zero, or a positive integer
1630
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1631
 * e.g:
1632
 * <ul>
1633
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1634
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1635
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1636
 * </ul>
1637
 * <p>
1638
 * This compare logic of the underlying webservice is the
1639
 * <b>inverse logic</b> of the the one implemented in
1640
 * java.lang.Comparable#compareTo(java.lang.Object)
1641
 *
1642
 * @param $thisRankUuid
1643
 * @param $thatRankUuid
1644
 *
1645
 * @return int
1646
 *   A negative integer, zero, or a positive integer
1647
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1648
 */
1649
function rank_compare($thisRankUuid, $thatRankUuid) {
1650
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1651
  return $result->Integer;
1652
}
1653

    
1654
/**
1655
 * Composes an HTML element class attribute value composed of
1656
 * the shortname of the cdm class and the uuid of the entity.
1657
 * This class attribute should be used whereever an cdm-entity is rendered.
1658
 *
1659
 * These according class selectors in css must be escaped, eg:
1660
 *    .cdm\:TextData
1661
 *
1662
 * @param $cdmEntity
1663
 */
1664
function html_class_attribute_ref($cdmEntity) {
1665

    
1666
  if (is_cdm_entity($cdmEntity)) {
1667
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1668
  }
1669
}
1670

    
1671
/**
1672
 * Preprocess the taggedName to normalize newly introduced
1673
 * tagtypes like hybridSign, separator, .. more?
1674
 *
1675
 * @param unknown_type $taggedTextList
1676
 */
1677
function normalize_TaggedName(&$taggedTextList) {
1678

    
1679
  if (is_array($taggedTextList)) {
1680

    
1681
    // First pass: rename.
1682
    for ($i = 0; $i < count($taggedTextList); $i++) {
1683

    
1684
      if ($taggedTextList[$i]->type == "hybridSign") {
1685
        $taggedTextList[$i]->type = "name";
1686
      }
1687
    }
1688

    
1689
    // Second pass: resolve separators.
1690
    $taggedNameListNew = array();
1691
    for ($i = 0; $i < count($taggedTextList); $i++) {
1692

    
1693
      if ($i + 1 < count($taggedTextList) && $taggedTextList[$i + 1]->type == "separator") {
1694

    
1695
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1696
          $taggedName = $taggedTextList[$i];
1697
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1698
          $taggedNameListNew[] = $taggedName;
1699
          ++$i;
1700
          ++$i;
1701
        }
1702
      }
1703
      else {
1704
        $taggedNameListNew[] = $taggedTextList[$i];
1705
      }
1706
    }
1707
    $taggedTextList = $taggedNameListNew;
1708
  }
1709
}
1710

    
1711
/**
1712
 * Creates a short taxonname.
1713
 *
1714
 * The short name is created by using the taggename field of
1715
 * NameSTO or NameTO instances.
1716
 * If the taggename if empty the fullname will be returned.
1717
 *
1718
 * @param unknown_type $name
1719
 *   Name or TreeNode.
1720
 *
1721
 * @return string
1722
 */
1723
function cdm_dataportal_shortname_of($name) {
1724
  $nameStr = '';
1725

    
1726
  normalize_TaggedName($name->taggedTitle);
1727

    
1728
  // Get all tagged text tokens of the scientific name.
1729
  foreach ($name->taggedTitle as $tagtxt) {
1730
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1731
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1732
    }
1733
  }
1734
  $nameStr = trim($nameStr);
1735

    
1736
  if ($nameStr) {
1737

    
1738
    // Do not return short names for these.
1739
    if ($name->unplaced || $name->excluded) {
1740
      return $nameStr;
1741
    }
1742

    
1743
    /*
1744
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1745
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1746
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1747
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1748
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1749
    */
1750
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1751
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1752
      return $matches[1][0] . "." . $matches[3][0];
1753
    }
1754
    else {
1755
      return $nameStr;
1756
    }
1757
  }
1758
  else {
1759
    return $name->titleCache;
1760
  }
1761
}
1762

    
1763
/**
1764
 * Check if a taxon is accepted by the current taxonomic tree.
1765
 *
1766
 * @param mixed $taxon
1767
 *   The Taxon obkect to check.
1768
 *
1769
 * @return bool
1770
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1771
 */
1772
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1773

    
1774
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1775

    
1776
  if (isset($taxon->taxonNodes)) {
1777
    $taxonNodes = $taxon->taxonNodes;
1778
  }
1779
  else {
1780
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1781
  }
1782

    
1783
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1784
    foreach ($taxonNodes as $node) {
1785
      if (isset($node->classification)){
1786
        if(is_object($node->classification)) {
1787
          if ($node->classification->uuid == $defaultTreeUuid) {
1788
            return TRUE;
1789
          }
1790
        }
1791
        else {
1792
          if ($node->classification == $defaultTreeUuid) {
1793
            return TRUE;
1794
          }
1795
        }
1796
      }
1797
    }
1798
  }
1799

    
1800
  return FALSE;
1801
}
1802

    
1803
/**
1804
 * Workaround for missing original source type.
1805
 *
1806
 * idNamespace is always set in these cases.
1807
 * @todo improve documentation of this function.
1808
 *
1809
 * @param unknown_type $source
1810
 *
1811
 * @return unknown_type
1812
 */
1813
function _is_original_source_type($source) {
1814
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1815
}
1816

    
1817
/**
1818
 * @todo Please document this function.
1819
 * @see http://drupal.org/node/1354
1820
 */
1821
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1822
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1823
}
1824

    
1825
/**
1826
 * Gets the metadata info such as title or artist of a media file.
1827
 *
1828
 * The function tries at first to get all the info from the file metadata
1829
 * and if it is not avaible look at the media file info stored at the database.
1830
 *
1831
 * @param mixed $media
1832
 *   The media file object for which to get the metadata.
1833
 *
1834
 * @return array
1835
 *   The array with the available specified metadata info.
1836
 * TODO rename to read_media_metadata() and move to *.module.
1837
 */
1838
function cdm_read_media_metadata($media) {
1839

    
1840
  $metadata_caption = array(
1841
    'title' => '',// Media_metadata and media.
1842
    'artist' => '',// Media_metadata and media.
1843
    'rights',// Media_metadata and media.
1844
    'location',// Media_metadata.
1845
    'filename' => '',// Media.
1846
    'mediacreated' => '',// Media.
1847
    'description' => '',
1848
  );// Media.
1849

    
1850
  // Getting the media metadata.
1851
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1852
  $media_metadata_aux = (array) $media_metadata;
1853

    
1854
  // Filename.
1855
  if (!empty($media->representations[0]->parts[0]->uri)) {
1856
    $fileUri = $media->representations[0]->parts[0]->uri;
1857
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1858
    $metadata_caption['filename'] = $filename;
1859
  }
1860
  else {
1861
    $metadata_caption['filename'] = '';
1862
  }
1863

    
1864
  // Title.
1865
  if (!empty($media_metadata->ObjectName)) {
1866
    $metadata_caption['title'] = $media_metadata->ObjectName;
1867
  }
1868
  elseif (!empty($media_metadata_aux['Object Name'])) {
1869
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1870
  }
1871
  elseif (!empty($media->title_L10n)) {
1872
    $metadata_caption['title'] = $media->title_L10n;
1873
  }
1874
  elseif (!empty($media->titleCache)) {
1875
    $metadata_caption['title'] = $media->titleCache;
1876
  }
1877

    
1878
  // Append description to title.
1879
  if (!empty($media->description_L10n)) {
1880
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1881
  }
1882

    
1883
  // Artist.
1884
  if (!empty($media_metadata->Artist)) {
1885
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1886
  }
1887
  elseif (!empty($media->artist->titleCache)) {
1888
    $metadata_caption['artist'] = $media->artist->titleCache;
1889
  }
1890

    
1891
  // Copyright.
1892
  $metadata_caption['rights'] = array(
1893
    'copyright' => array('agentNames' => array()),
1894
    'license' => array(
1895
      'agentNames' => array(),
1896
      'types' => array(),
1897
      'abbreviatedTexts' => array(),
1898
      'uris' => array(),
1899
    ),
1900
  );
1901
  if (!empty($media_metadata->Copyright)) {
1902
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1903
  }
1904
  elseif (isset($media->rights) && is_array($media->rights)) {
1905
    foreach ($media->rights as $right) {
1906
      if(isset($right->term)){
1907
        switch ($right->type->uuid) {
1908
          case UUID_RIGHTS_LICENCE:
1909
            $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1910
            $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1911
            $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1912
            $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1913
            break;
1914
          case UUID_RIGHTS_COPYRIGHT:
1915
            $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1916
            break;
1917
        }
1918
      }
1919
    }
1920
  }
1921
  else {
1922
    $metadata_caption['rights']['agentNames'][] = '';
1923
  }
1924

    
1925
  // Filling the description (though there is no description in the db???).
1926
  // $metadata_caption['description'] = $media->description_L10n;
1927

    
1928
  // Location.
1929
  $metadata_caption['location'] = array();
1930
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1931
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1932
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1933
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1934

    
1935
  /*
1936
   // Creation date.
1937
   if($media_metadata["Modify Date"])
1938
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1939
   else
1940
   $metadata_caption['mediacreated'] = $media->created;
1941
   */
1942

    
1943
  // Returned value.
1944
  return $metadata_caption;
1945
}
1946

    
1947
/**
1948
 * Collects all the media from a list of description elements.
1949
 *
1950
 * @param array $descriptionElements
1951
 *   The description elements from which to collect the media.
1952
 *
1953
 * @return array
1954
 *   The output with all the collected media.
1955
 */
1956
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1957

    
1958
  $outArrayOfMedia = array();
1959

    
1960
  // Avoiding a warning box in Drupal for Flora Malesiana.
1961
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1962
    foreach ($descriptionElements as $descriptionElement) {
1963
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1964
        foreach ($descriptionElement->media as $media) {
1965
          if (is_object($media)) {
1966
            $outArrayOfMedia[] = $media;
1967
          }
1968
        }
1969
      }
1970
    }
1971
  }
1972
  return $outArrayOfMedia;
1973
}
1974

    
1975
/**
1976
 * @todo Please document this function.
1977
 * @see http://drupal.org/node/1354
1978
 *
1979
 * @param array $cdmBase_list
1980
 *   An array of CdmBase instances or a single instance.
1981
 * @param string $footnote_list_key_suggestion
1982
 *
1983
 * @return unknown
1984
 */
1985
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key_suggestion = NULL) {
1986

    
1987
   static $annotations_types_filter = null;
1988
   if(!$annotations_types_filter) {
1989
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1990
   }
1991

    
1992
  $footNoteKeys = array();
1993

    
1994
  // Is argument cdmBase an array?
1995
  if (!is_array($cdmBase_list)) {
1996
    $cdmBase_array = array();
1997
    $cdmBase_array[] = $cdmBase_list;
1998
  }
1999
  else {
2000
    $cdmBase_array = $cdmBase_list;
2001
  }
2002

    
2003
  // Getting the key for the footnotemanager.
2004
  if (isset($footnote_list_key_suggestion)) {
2005
    $footnote_list_key = $footnote_list_key_suggestion;
2006
  }
2007
  else {
2008
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2009
  }
2010

    
2011
  // Adding the footnotes keys.
2012
  foreach ($cdmBase_array as $cdmBase_element) {
2013
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2014
    if (is_array($annotations)) {
2015
      foreach ($annotations as $annotation) {
2016
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2017
      }
2018
    }
2019
  }
2020

    
2021
  return $footNoteKeys;
2022
}
2023

    
2024
// @WA Comment: should this not be a theme function?
2025
/**
2026
 *  Creates a CDM Dynabox.
2027
 * @param string $dynabox_id
2028
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice.
2029
 * @param string $label
2030
 *   The clickable text to show.
2031
 * @param string $content_url
2032
 *   The cdm REST service request url wich will deliver the content to be shown
2033
 *   once the dynabox toggles open.
2034
 * @param string $theme
2035
 *   The theme to be used for rendering the cdm REST service reponse with is
2036
 *   returned from the $content_url.
2037
 * @param string $link_alt_text
2038
 *   The value for the alt attribute of the dynabox link.
2039
 * @param array $enclosingtags
2040
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2041
 *   element itself, $enclosingtags[1] is the tag to be used for the
2042
 *   dynabox_content (optional)
2043
 * @param string $open_callback
2044
 *   optional javascript call back function to be triggered after toggeling the box to
2045
 *   the open state.
2046
 * @param string $close_callback
2047
 *   optional javascript call back function to be triggered after toggeling the box to
2048
 *   the closed state.
2049
 *
2050
 * @return string
2051
 *   Returns HTML for a dynabox.
2052
 */
2053
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $attributes = array(), $open_callback = 'function(){}', $close_callback = 'function(){}') {
2054
  $out = '';
2055

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

    
2059
  if(!array_key_exists('class', $attributes)) {
2060
    $attributes['class'] = array();
2061
  }
2062
  $attributes['class'][] = 'dynabox-' . $dynabox_id;
2063
  $dynabox_attributes = drupal_attributes($attributes);
2064

    
2065

    
2066
  _add_js_domEvent(); // requires domEvent.js
2067
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2068
  drupal_add_js("
2069
  jQuery(document).ready(
2070
      function() {
2071
        dynabox('". $dynabox_id ."',
2072
          {
2073
            open_callback: " . $open_callback .",
2074
            close_callback: " . $close_callback ."
2075
          }
2076
        );
2077
      }
2078
   );",
2079
   array(
2080
    'type'=>'inline',
2081
    'scope'=>'footer'
2082
    )
2083
  );
2084

    
2085

    
2086
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2087
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2088
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2089
  // TODO stop using the title attribute, the label href now contains the same url!
2090
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '">';
2091
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2092
  $out .= '</' . $enclosingtags[1] . '>';
2093
  $out .= '</' . $enclosingtags[0] . '>';
2094
  $out .= '<!-- dynabox end -->';
2095
  return $out;
2096
}
2097

    
2098
/**
2099
 * Checks whether a feature has any description elements.
2100
 *
2101
 * @param mixed $featureNode
2102
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2103
 *
2104
 * @see _mergeFeatureTreeDescriptions()
2105
 *
2106
 * @return bool
2107
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2108
 *   contains at least one non empty TextData or at least one DescriptionElement
2109
 *   of an other type. A TextData element holding a multilanguageText or a
2110
 *   source reference is considered to be not empty.
2111
 */
2112
function has_feature_node_description_elements($featureNode) {
2113

    
2114
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2115
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2116
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2117
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2118
          return TRUE;
2119
        }
2120
      }
2121
    }
2122
  }
2123
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2124
    foreach ($featureNode->childNodes as $child) {
2125
      if (has_feature_node_description_elements($child)) {
2126
        return TRUE;
2127
      }
2128
    }
2129
  }
2130
  return FALSE;
2131
}
2132

    
2133
/**
2134
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2135
 *
2136
 * @param $chapter
2137
 *   The taxon page chapter or part
2138
 */
2139
function cdm_check_valid_taxon_page($chapter){
2140
  static $taxon_tabs = null;
2141

    
2142
  cdm_check_valid_portal_page();
2143

    
2144
  if($taxon_tabs == null){
2145
    $taxon_tabs = array('all', 'description');
2146
    foreach(get_taxon_tabs_list() as $tab){
2147
      $taxon_tabs[] = strtolower($tab);
2148
    }
2149
  }
2150

    
2151
  if(!in_array($chapter, $taxon_tabs)){
2152
    // oops this is not a valid chapter name
2153
    http_send_status(404); // 404 = Not Found
2154
  }
2155

    
2156
}
2157

    
2158
/**
2159
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2160
 *
2161
 * @param $chapter
2162
 *   The taxon page chapter or part
2163
 */
2164
function cdm_check_valid_portal_page(){
2165
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2166
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2167
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2168
    http_send_status(404); // 404 = Not Found
2169
    exit('HTTP 404');
2170
  }
2171
}
(7-7/14)