Project

General

Profile

Download (71 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
 * can be removed after fixing the FIXME below
512
 */
513
function cdm_dataportal_init() {
514
  //FIXME To add CSS or JS that should be present on all pages, modules
515
  //      should not implement this hook, but declare these files in their .info file.
516
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
517
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
518
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
519

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

    
526
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
527

    
528
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
529

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

    
539
  $parameters['cacheL2_refresh'] ='1';
540

    
541

    
542
  drupal_goto($base_path, array('query' => $parameters));
543
}
544

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

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

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

    
573
  $form['submit'] = array(
574
    '#type' => 'submit',
575
    '#value' => t('Submit'),
576
  );
577

    
578
  return $form;
579
}
580

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

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

    
616
/**
617
 * Implements hook_block_info().
618
 */
619
function cdm_dataportal_block_info() {
620

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

    
632
    return $block;
633
}
634

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

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

    
676
/*
677
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
678
 $_SESSION['cdm'] = NULL;
679
 if(is_string($cdm_ws_uri_update)){
680
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
681
 }
682
 }
683

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

    
693
/**
694
 * creates a  selector form for taxonomic trees.
695
 *
696
 * @return a drupal form array
697
 */
698
function cdm_taxonomictree_selector() {
699
  _add_js_treeselector();
700

    
701
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
702
  return $form;
703
}
704

    
705
/**
706
 * @todo Please document this function.
707
 * @see http://drupal.org/node/1354
708
 */
709
function cdm_taxonomictree_selector_form($form, &$form_state) {
710

    
711
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
712
  $form['#action'] = $url;
713

    
714
  $form['var'] = array(
715
    '#weight' => -3,
716
    '#type' => 'hidden',
717
    '#value' => '[cdm][taxonomictree_uuid]',
718
  );
719

    
720
  $destination_array = drupal_get_destination();
721
  $destination = $destination_array['destination'];
722

    
723
  $form['destination'] = array(
724
    '#weight' => -3,
725
    '#type' => 'hidden',
726
    '#value' =>  $destination,
727
  );
728

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

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

    
749
  return $form;
750

    
751
}
752

    
753
/* UNREACHABLE since action of form directly links to view.
754
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
755

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

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

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

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

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

    
816
/**
817
 * @todo Please document this function.
818
 * @see http://drupal.org/node/1354
819
 */
820
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
821

    
822
  cdm_check_valid_portal_page();
823

    
824
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
825
  return theme('cdm_reference_page', array('reference' => $reference));
826
}
827

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

    
841
/**
842
 * @todo Please document this function.
843
 * @see http://drupal.org/node/1354
844
 */
845
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
846

    
847
  cdm_check_valid_portal_page();
848

    
849
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
850
  return theme('cdm_media_page', array(
851
    'media' => $media,
852
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
853
    'partId' => $part,
854
    ));
855
}
856

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

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

    
885
  static $media = NULL;
886

    
887
  if(!isset($media)) {
888
    $media = array();
889
  }
890
  if (!isset($media[$taxon->uuid])) {
891

    
892
    // --- GET Images --- //
893
    $mediaQueryParameters = array(
894
        "type" => "ImageFile",
895
    );
896

    
897
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
898
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
899
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
900

    
901
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
902
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
903
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
904
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
905

    
906
    $ws_endpoint = NULL;
907
    if ( variable_get('cdm_images_include_children', 0) == 0) {
908
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
909
    } else {
910
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
911
    }
912

    
913
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
914
        array(
915
            $taxon->uuid,
916
        ),
917
        queryString($mediaQueryParameters)
918
       );
919
  }
920

    
921
  return $media[$taxon->uuid];
922
}
923

    
924
/**
925
 *
926
 * @param Taxon $taxon
927
 *   A CDM Taxon entitiy
928
 *
929
 * @return array
930
 *   An array of CDM SpecimenOrObservation entities
931
 *
932
function _load_occurences_for_taxon($taxon){
933

    
934
  static $occurences = NULL;
935

    
936
  if(!isset($occurences)) {
937
    $occurences = array();
938
  }
939

    
940
  if (!isset($occurences[$taxon->uuid])){
941

    
942
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
943
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
944
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
945

    
946
    $by_associatedtaxon_query = http_build_query(array(
947
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
948
        'relationships' => implode(',', $relationship_choice['direct']),
949
        'pageSize' => null // all hits in one page
950
    )
951
    );
952

    
953
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
954
        null,
955
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
956
    );
957

    
958

    
959
    if(isset($pager->records[0])){
960
      $occurences[$taxon->uuid] =  $pager->records;
961
    }
962
  }
963
  return $occurences[$taxon->uuid];
964
}
965
 */
966

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

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

    
1013
/**
1014
 * Wrapps the given $html string into a reder array suitable for drupal_render()
1015
 *
1016
 * @param string $html
1017
 *   the html string, see
1018
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1019
 * @param number $weight
1020
 *   A positive or negative number (integer or decimal).
1021
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1022
 *
1023
 * @return
1024
 *   A render array
1025
 *
1026
 */
1027
function markup_to_render_array($html, $weight = 0) {
1028
  return array(
1029
          '#markup' => $html,
1030
          '#weight' => $weight,
1031
      );
1032
}
1033

    
1034
/**
1035
 * Loads the subgraph of a given PolytomousKeyNode.
1036
 *
1037
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1038
 * the CDM REST service.
1039
 *
1040
 * @param mixed $polytomousKeyNode
1041
 *   PolytomousKeyNode passed by reference.
1042
 *
1043
 * @return void
1044
 */
1045
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1046

    
1047
  if (!$polytomousKeyNode) {
1048
    return;
1049
  }
1050
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1051
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1052
    return;
1053
  }
1054
  if (!is_uuid($polytomousKeyNode->uuid)) {
1055
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1056
    return;
1057
  }
1058

    
1059
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1060

    
1061
  if (!$polytomousKeyNode) {
1062
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1063
    return;
1064
  }
1065

    
1066
  // Load children.
1067
  foreach ($polytomousKeyNode->children as &$childNode) {
1068
    _load_polytomousKeySubGraph($childNode);
1069
  }
1070

    
1071
  // Load subkey.
1072
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1073

    
1074
  // Load taxon.
1075
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1076
  _load_taxonBase($polytomousKeyNode->taxon);
1077
  return;
1078
}
1079

    
1080
/**
1081
 * @todo Please document this function.
1082
 * @see http://drupal.org/node/1354
1083
 */
1084
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1085

    
1086
  cdm_check_valid_portal_page();
1087

    
1088
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1089

    
1090
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1091
  if (is_array($sourcePager->records)) {
1092
    $polytomousKey->sources = $sourcePager->records;
1093
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1094
  }
1095

    
1096
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1097
  if (is_array($annotationPager->records)) {
1098
    $polytomousKey->annotations = $annotationPager->records;
1099
  }
1100

    
1101
  _load_polytomousKeySubGraph($polytomousKey->root);
1102
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1103
}
1104

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

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

    
1136
  // Display the page for the taxon defined by $uuid.
1137
  // set_last_taxon_page_tab(arg(3));
1138
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1139
  if (!empty($taxonpage)) {
1140
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1141
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1142
  }
1143
  else {
1144
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1145
    return '';
1146
  }
1147
}
1148

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

    
1175
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1176
    'taxon' => $taxon
1177
  ));
1178

    
1179
  // Check if the taxon id contained in the currently selected tree.
1180
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1181

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

    
1197
      drupal_set_message(format_plural(count($trees),
1198
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1199
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1200
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1201
    }
1202
  }
1203

    
1204
  // Render the taxon page.
1205
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1206
  $taxonpage->content = drupal_render($render_array);
1207

    
1208
  return $taxonpage;
1209
}
1210

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

    
1232
  cdm_check_valid_portal_page();
1233

    
1234
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1235
  if (!empty($taxonname_page)) {
1236
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1237
  }
1238
  else {
1239
    return '';
1240
  }
1241
}
1242

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

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

    
1333
/**
1334
 * @todo Please document this function.
1335
 * @see http://drupal.org/node/1354
1336
 */
1337
function cdm_dataportal_view_search_advanced() {
1338

    
1339
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1340
  $form = array();
1341
  $form_state = array();
1342
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1343

    
1344
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1345

    
1346
}
1347

    
1348
/**
1349
 * @todo Please document this function.
1350
 * @see http://drupal.org/node/1354
1351
 */
1352
function cdm_dataportal_view_search_taxon_by_description() {
1353
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1354
  // $form_state = false;
1355
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1356
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1357

    
1358
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1359
}
1360

    
1361
/**
1362
 * Executes the search and generates the result list of taxa.
1363
 */
1364
function cdm_dataportal_view_search_results_taxon() {
1365

    
1366
  $taxonPager = cdm_dataportal_search_execute();
1367

    
1368
  $showThumbnails = do_showThumbnails();
1369

    
1370
  $setSessionUri = url('cdm_api/setvalue/session', array(
1371
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1372
  ));
1373

    
1374
  drupal_add_js('jQuery(document).ready(function() {
1375

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

    
1399
  drupal_set_title(t('Search results'), PASS_THROUGH);
1400

    
1401
  return theme('cdm_search_results', array(
1402
    'pager' => $taxonPager,
1403
    'path' => 'cdm_dataportal/search/results/taxon',
1404
    ));
1405
}
1406

    
1407
/**
1408
 * Provides the standart image wich indicated a loading process
1409
 *
1410
 * @return string
1411
 *  The img html tag
1412
 */
1413
function loading_image_html() {
1414
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1415
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1416
}
1417

    
1418
/**
1419
 * Returns the state of the the showThumbnails flag set in the
1420
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1421
 *
1422
 * @return boolean
1423
 *    returns 1 if the flag is set
1424
 */
1425
function do_showThumbnails() {
1426
  static $showThumbnails = null;
1427

    
1428
  if($showThumbnails == null) {
1429
    $showThumbnails = 0;
1430
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1431
      $showThumbnails = 0;
1432
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1433
      $showThumbnails = is_array($search_gallery_settings)
1434
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1435
        && (
1436
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1437
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1438
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1439
            )
1440
         ? 1 : 0;
1441

    
1442
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1443
    }
1444
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1445
    if (!is_numeric($showThumbnails)) {
1446
      $showThumbnails = 1;
1447
    }
1448
  }
1449

    
1450
  return $showThumbnails;
1451
}
1452

    
1453
/**
1454
 * View which transforms XML output from a given webservice endpoint into JSON.
1455
 */
1456
/*
1457
 function cdm_view_xml2json(){
1458
 $file = arg(2);
1459
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1460
 return  xml2json::transformXmlStringToJson($datastr);
1461
 }
1462
 */
1463

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

    
1489
  $tab = get_default_taxon_tab();
1490
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1491

    
1492
  if (!$uuid) {
1493
    return FALSE;
1494
  }
1495

    
1496
  if ($page_tab) {
1497
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1498
  }
1499
  elseif (!$tab || strtolower($tab) == 'general') {
1500
    return 'cdm_dataportal/taxon/' . $uuid;
1501
  }
1502
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1503
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1504
  }
1505
  else {
1506
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1507
  }
1508
}
1509

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

    
1539
}
1540

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

    
1561
/**
1562
 * @todo Please document this function.
1563
 * @see http://drupal.org/node/1354
1564
 */
1565
function path_to_reference($uuid) {
1566
  if (!$uuid) {
1567
    return FALSE;
1568
  }
1569
  return 'cdm_dataportal/reference/' . $uuid;
1570
}
1571

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

    
1601
/**
1602
 * @todo Please document this function.
1603
 * @see http://drupal.org/node/1354
1604
 */
1605
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1606
  if (!$uuid) {
1607
    return FALSE;
1608
  }
1609
  $out = 'cdm_dataportal/media/' . $uuid;
1610
  if ($representaion_uuid) {
1611
    $out .= '/' . $representaion_uuid;
1612
    if ($partId !== FALSE) {
1613
      $out .= '/' . $partId;
1614
    }
1615
  }
1616
  return $out;
1617
}
1618

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

    
1647
/**
1648
 * Composes an HTML element class attribute value composed of
1649
 * the shortname of the cdm class and the uuid of the entity.
1650
 * This class attribute should be used whereever an cdm-entity is rendered.
1651
 *
1652
 * These according class selectors in css must be escaped, eg:
1653
 *    .cdm\:TextData
1654
 *
1655
 * @param $cdmEntity
1656
 */
1657
function html_class_attribute_ref($cdmEntity) {
1658

    
1659
  if (is_cdm_entity($cdmEntity)) {
1660
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1661
  }
1662
}
1663

    
1664
/**
1665
 * Preprocess the taggedName to normalize newly introduced
1666
 * tagtypes like hybridSign, separator, .. more?
1667
 *
1668
 * @param unknown_type $taggedTextList
1669
 */
1670
function normalize_TaggedName(&$taggedTextList) {
1671

    
1672
  if (is_array($taggedTextList)) {
1673

    
1674
    // First pass: rename.
1675
    for ($i = 0; $i < count($taggedTextList); $i++) {
1676

    
1677
      if ($taggedTextList[$i]->type == "hybridSign") {
1678
        $taggedTextList[$i]->type = "name";
1679
      }
1680
    }
1681

    
1682
    // Second pass: resolve separators.
1683
    $taggedNameListNew = array();
1684
    for ($i = 0; $i < count($taggedTextList); $i++) {
1685

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

    
1688
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1689
          $taggedName = $taggedTextList[$i];
1690
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1691
          $taggedNameListNew[] = $taggedName;
1692
          ++$i;
1693
          ++$i;
1694
        }
1695
      }
1696
      else {
1697
        $taggedNameListNew[] = $taggedTextList[$i];
1698
      }
1699
    }
1700
    $taggedTextList = $taggedNameListNew;
1701
  }
1702
}
1703

    
1704
/**
1705
 * Creates a short taxonname.
1706
 *
1707
 * The short name is created by using the taggename field of
1708
 * NameSTO or NameTO instances.
1709
 * If the taggename if empty the fullname will be returned.
1710
 *
1711
 * @param unknown_type $name
1712
 *   Name or TreeNode.
1713
 *
1714
 * @return string
1715
 */
1716
function cdm_dataportal_shortname_of($name) {
1717
  $nameStr = '';
1718

    
1719
  normalize_TaggedName($name->taggedTitle);
1720

    
1721
  // Get all tagged text tokens of the scientific name.
1722
  foreach ($name->taggedTitle as $tagtxt) {
1723
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1724
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1725
    }
1726
  }
1727
  $nameStr = trim($nameStr);
1728

    
1729
  if ($nameStr) {
1730

    
1731
    // Do not return short names for these.
1732
    if ($name->unplaced || $name->excluded) {
1733
      return $nameStr;
1734
    }
1735

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

    
1756
/**
1757
 * Check if a taxon is accepted by the current taxonomic tree.
1758
 *
1759
 * @param mixed $taxon
1760
 *   The Taxon obkect to check.
1761
 *
1762
 * @return bool
1763
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1764
 */
1765
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1766

    
1767
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1768

    
1769
  if (isset($taxon->taxonNodes)) {
1770
    $taxonNodes = $taxon->taxonNodes;
1771
  }
1772
  else {
1773
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1774
  }
1775

    
1776
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1777
    foreach ($taxonNodes as $node) {
1778
      if (isset($node->classification)){
1779
        if(is_object($node->classification)) {
1780
          if ($node->classification->uuid == $defaultTreeUuid) {
1781
            return TRUE;
1782
          }
1783
        }
1784
        else {
1785
          if ($node->classification == $defaultTreeUuid) {
1786
            return TRUE;
1787
          }
1788
        }
1789
      }
1790
    }
1791
  }
1792

    
1793
  return FALSE;
1794
}
1795

    
1796
/**
1797
 * Workaround for missing original source type.
1798
 *
1799
 * idNamespace is always set in these cases.
1800
 * @todo improve documentation of this function.
1801
 *
1802
 * @param unknown_type $source
1803
 *
1804
 * @return unknown_type
1805
 */
1806
function _is_original_source_type($source) {
1807
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1808
}
1809

    
1810
/**
1811
 * @todo Please document this function.
1812
 * @see http://drupal.org/node/1354
1813
 */
1814
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1815
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1816
}
1817

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

    
1833
  $metadata_caption = array(
1834
    'title' => '',// Media_metadata and media.
1835
    'artist' => '',// Media_metadata and media.
1836
    'rights',// Media_metadata and media.
1837
    'location',// Media_metadata.
1838
    'filename' => '',// Media.
1839
    'mediacreated' => '',// Media.
1840
    'description' => '',
1841
  );// Media.
1842

    
1843
  // Getting the media metadata.
1844
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1845
  $media_metadata_aux = (array) $media_metadata;
1846

    
1847
  // Filename.
1848
  if (!empty($media->representations[0]->parts[0]->uri)) {
1849
    $fileUri = $media->representations[0]->parts[0]->uri;
1850
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1851
    $metadata_caption['filename'] = $filename;
1852
  }
1853
  else {
1854
    $metadata_caption['filename'] = '';
1855
  }
1856

    
1857
  // Title.
1858
  if (!empty($media_metadata->ObjectName)) {
1859
    $metadata_caption['title'] = $media_metadata->ObjectName;
1860
  }
1861
  elseif (!empty($media_metadata_aux['Object Name'])) {
1862
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1863
  }
1864
  elseif (!empty($media->title_L10n)) {
1865
    $metadata_caption['title'] = $media->title_L10n;
1866
  }
1867
  elseif (!empty($media->titleCache)) {
1868
    $metadata_caption['title'] = $media->titleCache;
1869
  }
1870

    
1871
  // Append description to title.
1872
  if (!empty($media->description_L10n)) {
1873
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1874
  }
1875

    
1876
  // Artist.
1877
  if (!empty($media_metadata->Artist)) {
1878
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1879
  }
1880
  elseif (!empty($media->artist->titleCache)) {
1881
    $metadata_caption['artist'] = $media->artist->titleCache;
1882
  }
1883

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

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

    
1921
  // Location.
1922
  $metadata_caption['location'] = array();
1923
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1924
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1925
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1926
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1927

    
1928
  /*
1929
   // Creation date.
1930
   if($media_metadata["Modify Date"])
1931
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1932
   else
1933
   $metadata_caption['mediacreated'] = $media->created;
1934
   */
1935

    
1936
  // Returned value.
1937
  return $metadata_caption;
1938
}
1939

    
1940
/**
1941
 * Collects all the media from a list of description elements.
1942
 *
1943
 * @param array $descriptionElements
1944
 *   The description elements from which to collect the media.
1945
 *
1946
 * @return array
1947
 *   The output with all the collected media.
1948
 */
1949
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1950

    
1951
  $outArrayOfMedia = array();
1952

    
1953
  // Avoiding a warning box in Drupal for Flora Malesiana.
1954
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1955
    foreach ($descriptionElements as $descriptionElement) {
1956
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1957
        foreach ($descriptionElement->media as $media) {
1958
          if (is_object($media)) {
1959
            $outArrayOfMedia[] = $media;
1960
          }
1961
        }
1962
      }
1963
    }
1964
  }
1965
  return $outArrayOfMedia;
1966
}
1967

    
1968
/**
1969
 * @todo Please document this function.
1970
 * @see http://drupal.org/node/1354
1971
 *
1972
 * @param array $cdmBase_list
1973
 *   An array of CdmBase instances or a single instance.
1974
 * @param string $footnote_list_key
1975
 *
1976
 * @return unknown
1977
 */
1978
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1979

    
1980
   static $annotations_types_filter = null;
1981
   if(!$annotations_types_filter) {
1982
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1983
   }
1984

    
1985
  $footNoteKeys = array();
1986

    
1987
  // Is argument cdmBase an array?
1988
  if (!is_array($cdmBase_list)) {
1989
    $cdmBase_array = array();
1990
    $cdmBase_array[] = $cdmBase_list;
1991
  }
1992
  else {
1993
    $cdmBase_array = $cdmBase_list;
1994
  }
1995

    
1996
  // Getting the key for the footnotemanager.
1997
  if (isset($footnote_list_key)) {
1998
    $footnoteListKey = $footnote_list_key;
1999
  }
2000
  else {
2001
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2002
  }
2003

    
2004
  // Adding the footnotes keys.
2005
  foreach ($cdmBase_array as $cdmBase_element) {
2006
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2007
    if (is_array($annotations)) {
2008
      foreach ($annotations as $annotation) {
2009
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2010
      }
2011
    }
2012
  }
2013

    
2014
  return $footNoteKeys;
2015
}
2016

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

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

    
2052
  if(!array_key_exists('class', $attributes)) {
2053
    $attributes['class'] = array();
2054
  }
2055
  $attributes['class'][] = 'dynabox-' . $dynabox_id;
2056
  $dynabox_attributes = drupal_attributes($attributes);
2057

    
2058

    
2059
  _add_js_domEvent(); // requires domEvent.js
2060
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2061
  drupal_add_js("
2062
  jQuery(document).ready(
2063
      function() {
2064
        dynabox('". $dynabox_id ."',
2065
          {
2066
            open_callback: " . $open_callback .",
2067
            close_callback: " . $close_callback ."
2068
          }
2069
        );
2070
      }
2071
   );",
2072
   array(
2073
    'type'=>'inline',
2074
    'scope'=>'footer'
2075
    )
2076
  );
2077

    
2078

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

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

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

    
2126
/**
2127
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2128
 *
2129
 * @param $chapter
2130
 *   The taxon page chapter or part
2131
 */
2132
function cdm_check_valid_taxon_page($chapter){
2133
  static $taxon_tabs = null;
2134

    
2135
  cdm_check_valid_portal_page();
2136

    
2137
  if($taxon_tabs == null){
2138
    $taxon_tabs = array('all', 'description');
2139
    foreach(get_taxon_tabs_list() as $tab){
2140
      $taxon_tabs[] = strtolower($tab);
2141
    }
2142
  }
2143

    
2144
  if(!in_array($chapter, $taxon_tabs)){
2145
    // oops this is not a valid chapter name
2146
    http_send_status(404); // 404 = Not Found
2147
  }
2148

    
2149
}
2150

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