Project

General

Profile

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

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

    
25
module_load_include('inc', 'cdm_dataportal', 'includes/common');
26
module_load_include('inc', 'cdm_dataportal', 'includes/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
  );
747

    
748
  return $form;
749

    
750
}
751

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

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

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

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

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

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

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

    
821
  cdm_check_valid_portal_page();
822

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

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

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

    
846
  cdm_check_valid_portal_page();
847

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

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

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

    
884
  static $media = NULL;
885

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

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

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

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

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

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

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

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

    
933
  static $occurences = NULL;
934

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

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

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

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

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

    
957

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

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

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

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

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

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

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

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

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

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

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

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

    
1085
  cdm_check_valid_portal_page();
1086

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1207
  return $taxonpage;
1208
}
1209

    
1210
/**
1211
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1212
 *
1213
 * The node page shows the taxon name title and the list of taxon related
1214
 * with such taxon. Name on the tree already in use.
1215
 *
1216
 * @param string $taxon_name_uuid
1217
 *   A taxon name UUID.
1218
 *
1219
 * @return mixed
1220
 *   The formatted name page as node.
1221
 */
1222
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1223

    
1224
  cdm_check_valid_portal_page();
1225

    
1226
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1227
  if (!empty($taxonname_page)) {
1228
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1229
  }
1230
  else {
1231
    return '';
1232
  }
1233
}
1234

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

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

    
1325
/**
1326
 * @todo Please document this function.
1327
 * @see http://drupal.org/node/1354
1328
 */
1329
function cdm_dataportal_view_search_advanced() {
1330

    
1331
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1332
  $form = array();
1333
  $form_state = array();
1334
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1335

    
1336
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1337

    
1338
}
1339

    
1340
/**
1341
 * @todo Please document this function.
1342
 * @see http://drupal.org/node/1354
1343
 */
1344
function cdm_dataportal_view_search_taxon_by_description() {
1345
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1346
  // $form_state = false;
1347
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1348
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1349

    
1350
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1351
}
1352

    
1353
/**
1354
 * Executes the search and generates the result list of taxa.
1355
 */
1356
function cdm_dataportal_view_search_results_taxon() {
1357

    
1358
  $taxonPager = cdm_dataportal_search_execute();
1359

    
1360
  $showThumbnails = do_showThumbnails();
1361

    
1362
  $setSessionUri = url('cdm_api/setvalue/session', array(
1363
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1364
  ));
1365

    
1366
  drupal_add_js('jQuery(document).ready(function() {
1367

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

    
1391
  drupal_set_title(t('Search results'), PASS_THROUGH);
1392

    
1393
  return theme('cdm_search_results', array(
1394
    'pager' => $taxonPager,
1395
    'path' => 'cdm_dataportal/search/results/taxon',
1396
    ));
1397
}
1398

    
1399
/**
1400
 * Provides the standart image wich indicated a loading process
1401
 *
1402
 * @return string
1403
 *  The img html tag
1404
 */
1405
function loading_image_html() {
1406
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1407
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1408
}
1409

    
1410
/**
1411
 * Returns the state of the the showThumbnails flag set in the
1412
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1413
 *
1414
 * @return boolean
1415
 *    returns 1 if the flag is set
1416
 */
1417
function do_showThumbnails() {
1418
  static $showThumbnails = null;
1419

    
1420
  if($showThumbnails == null) {
1421
    $showThumbnails = 0;
1422
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1423
      $showThumbnails = 0;
1424
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1425
      $showThumbnails = is_array($search_gallery_settings)
1426
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1427
        && (
1428
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1429
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1430
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1431
            )
1432
         ? 1 : 0;
1433

    
1434
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1435
    }
1436
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1437
    if (!is_numeric($showThumbnails)) {
1438
      $showThumbnails = 1;
1439
    }
1440
  }
1441

    
1442
  return $showThumbnails;
1443
}
1444

    
1445
/**
1446
 * View which transforms XML output from a given webservice endpoint into JSON.
1447
 */
1448
/*
1449
 function cdm_view_xml2json(){
1450
 $file = arg(2);
1451
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1452
 return  xml2json::transformXmlStringToJson($datastr);
1453
 }
1454
 */
1455

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

    
1481
  $tab = get_default_taxon_tab();
1482
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1483

    
1484
  if (!$uuid) {
1485
    return FALSE;
1486
  }
1487

    
1488
  if ($page_tab) {
1489
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1490
  }
1491
  elseif (!$tab || strtolower($tab) == 'general') {
1492
    return 'cdm_dataportal/taxon/' . $uuid;
1493
  }
1494
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1495
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1496
  }
1497
  else {
1498
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1499
  }
1500
}
1501

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

    
1531
}
1532

    
1533
/**
1534
 * Compses the drupal path to the key identified by the uuid.
1535
 *
1536
 * @param string $keyType
1537
 *    the key typer corresponds to the specific class of the CDM
1538
 *    IdentificationKey. Possible values are
1539
 *      -PolytomousKey
1540
 *      -MultimediaKey
1541
 *      - ...
1542
 * @param UUID $keyUuid
1543
 *   The UUID of the key
1544
 */
1545
function path_to_key($keyType, $keyUuid) {
1546
  if (!$keyUuid || !$keyType) {
1547
    return FALSE;
1548
  }
1549
  $keyType{0} = strtolower($keyType{0});
1550
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1551
}
1552

    
1553
/**
1554
 * @todo Please document this function.
1555
 * @see http://drupal.org/node/1354
1556
 */
1557
function path_to_reference($uuid) {
1558
  if (!$uuid) {
1559
    return FALSE;
1560
  }
1561
  return 'cdm_dataportal/reference/' . $uuid;
1562
}
1563

    
1564
/**
1565
 * @todo Please document this function.
1566
 * @see http://drupal.org/node/1354
1567
 */
1568
function path_to_name($name_uuid) {
1569
  $res = FALSE;
1570
  if ($name_uuid) {
1571
    $res = 'cdm_dataportal/name/' . $name_uuid;
1572
  }
1573
  return $res;
1574
}
1575

    
1576
/**
1577
 * @todo Please document this function.
1578
 * @see http://drupal.org/node/1354
1579
 */
1580
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1581
  if (!$uuid) {
1582
    return FALSE;
1583
  }
1584
  $out = 'cdm_dataportal/media/' . $uuid;
1585
  if ($representaion_uuid) {
1586
    $out .= '/' . $representaion_uuid;
1587
    if ($partId !== FALSE) {
1588
      $out .= '/' . $partId;
1589
    }
1590
  }
1591
  return $out;
1592
}
1593

    
1594
/**
1595
 * Compares thisRank with thatRank.
1596
 *
1597
 * Returns a negative integer, zero, or a positive integer
1598
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1599
 * e.g:
1600
 * <ul>
1601
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1602
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1603
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1604
 * </ul>
1605
 * <p>
1606
 * This compare logic of the underlying webservice is the
1607
 * <b>inverse logic</b> of the the one implemented in
1608
 * java.lang.Comparable#compareTo(java.lang.Object)
1609
 *
1610
 * @param $thisRankUuid
1611
 * @param $thatRankUuid
1612
 *
1613
 * @return int
1614
 *   A negative integer, zero, or a positive integer
1615
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1616
 */
1617
function rank_compare($thisRankUuid, $thatRankUuid) {
1618
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1619
  return $result->Integer;
1620
}
1621

    
1622
/**
1623
 * Composes an HTML element class attribute value composed of
1624
 * the shortname of the cdm class and the uuid of the entity.
1625
 * This class attribute should be used whereever an cdm-entity is rendered.
1626
 *
1627
 * These according class selectors in css must be escaped, eg:
1628
 *    .cdm\:TextData
1629
 *
1630
 * @param $cdmEntity
1631
 */
1632
function html_class_atttibute_ref($cdmEntity) {
1633

    
1634
  if (is_cdm_entity($cdmEntity)) {
1635
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1636
  }
1637
}
1638

    
1639
/**
1640
 * Preprocess the taggedName to normalize newly introduced
1641
 * tagtypes like hybridSign, separator, .. more?
1642
 *
1643
 * @param unknown_type $taggedTextList
1644
 */
1645
function normalize_TaggedName(&$taggedTextList) {
1646

    
1647
  if (is_array($taggedTextList)) {
1648

    
1649
    // First pass: rename.
1650
    for ($i = 0; $i < count($taggedTextList); $i++) {
1651

    
1652
      if ($taggedTextList[$i]->type == "hybridSign") {
1653
        $taggedTextList[$i]->type = "name";
1654
      }
1655
    }
1656

    
1657
    // Second pass: resolve separators.
1658
    $taggedNameListNew = array();
1659
    for ($i = 0; $i < count($taggedTextList); $i++) {
1660

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

    
1663
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1664
          $taggedName = $taggedTextList[$i];
1665
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1666
          $taggedNameListNew[] = $taggedName;
1667
          ++$i;
1668
          ++$i;
1669
        }
1670
      }
1671
      else {
1672
        $taggedNameListNew[] = $taggedTextList[$i];
1673
      }
1674
    }
1675
    $taggedTextList = $taggedNameListNew;
1676
  }
1677
}
1678

    
1679
/**
1680
 * Creates a short taxonname.
1681
 *
1682
 * The short name is created by using the taggename field of
1683
 * NameSTO or NameTO instances.
1684
 * If the taggename if empty the fullname will be returned.
1685
 *
1686
 * @param unknown_type $name
1687
 *   Name or TreeNode.
1688
 *
1689
 * @return string
1690
 */
1691
function cdm_dataportal_shortname_of($name) {
1692
  $nameStr = '';
1693

    
1694
  normalize_TaggedName($name->taggedTitle);
1695

    
1696
  // Get all tagged text tokens of the scientific name.
1697
  foreach ($name->taggedTitle as $tagtxt) {
1698
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1699
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1700
    }
1701
  }
1702
  $nameStr = trim($nameStr);
1703

    
1704
  if ($nameStr) {
1705

    
1706
    // Do not return short names for these.
1707
    if ($name->unplaced || $name->excluded) {
1708
      return $nameStr;
1709
    }
1710

    
1711
    /*
1712
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1713
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1714
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1715
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1716
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1717
    */
1718
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1719
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1720
      return $matches[1][0] . "." . $matches[3][0];
1721
    }
1722
    else {
1723
      return $nameStr;
1724
    }
1725
  }
1726
  else {
1727
    return $name->titleCache;
1728
  }
1729
}
1730

    
1731
/**
1732
 * Check if a taxon is accepted by the current taxonomic tree.
1733
 *
1734
 * @param mixed $taxon
1735
 *   The Taxon obkect to check.
1736
 *
1737
 * @return bool
1738
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1739
 */
1740
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1741

    
1742
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1743

    
1744
  if (isset($taxon->taxonNodes)) {
1745
    $taxonNodes = $taxon->taxonNodes;
1746
  }
1747
  else {
1748
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1749
  }
1750

    
1751
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1752
    foreach ($taxonNodes as $node) {
1753
      if (isset($node->classification)){
1754
        if(is_object($node->classification)) {
1755
          if ($node->classification->uuid == $defaultTreeUuid) {
1756
            return TRUE;
1757
          }
1758
        }
1759
        else {
1760
          if ($node->classification == $defaultTreeUuid) {
1761
            return TRUE;
1762
          }
1763
        }
1764
      }
1765
    }
1766
  }
1767

    
1768
  return FALSE;
1769
}
1770

    
1771
/**
1772
 * Workaround for missing original source type.
1773
 *
1774
 * idNamespace is always set in these cases.
1775
 * @todo improve documentation of this function.
1776
 *
1777
 * @param unknown_type $source
1778
 *
1779
 * @return unknown_type
1780
 */
1781
function _is_original_source_type($source) {
1782
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1783
}
1784

    
1785
/**
1786
 * @todo Please document this function.
1787
 * @see http://drupal.org/node/1354
1788
 */
1789
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1790
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1791
}
1792

    
1793
/**
1794
 * Gets the metadata info such as title or artist of a media file.
1795
 *
1796
 * The function tries at first to get all the info from the file metadata
1797
 * and if it is not avaible look at the media file info stored at the database.
1798
 *
1799
 * @param mixed $media
1800
 *   The media file object for which to get the metadata.
1801
 *
1802
 * @return array
1803
 *   The array with the available specified metadata info.
1804
 * TODO rename to read_media_metadata() and move to *.module.
1805
 */
1806
function cdm_read_media_metadata($media) {
1807

    
1808
  $metadata_caption = array(
1809
    'title' => '',// Media_metadata and media.
1810
    'artist' => '',// Media_metadata and media.
1811
    'rights',// Media_metadata and media.
1812
    'location',// Media_metadata.
1813
    'filename' => '',// Media.
1814
    'mediacreated' => '',// Media.
1815
    'description' => '',
1816
  );// Media.
1817

    
1818
  // Getting the media metadata.
1819
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1820
  $media_metadata_aux = (array) $media_metadata;
1821

    
1822
  // Filename.
1823
  if (!empty($media->representations[0]->parts[0]->uri)) {
1824
    $fileUri = $media->representations[0]->parts[0]->uri;
1825
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1826
    $metadata_caption['filename'] = $filename;
1827
  }
1828
  else {
1829
    $metadata_caption['filename'] = '';
1830
  }
1831

    
1832
  // Title.
1833
  if (!empty($media_metadata->ObjectName)) {
1834
    $metadata_caption['title'] = $media_metadata->ObjectName;
1835
  }
1836
  elseif (!empty($media_metadata_aux['Object Name'])) {
1837
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1838
  }
1839
  elseif (!empty($media->title_L10n)) {
1840
    $metadata_caption['title'] = $media->title_L10n;
1841
  }
1842
  elseif (!empty($media->titleCache)) {
1843
    $metadata_caption['title'] = $media->titleCache;
1844
  }
1845

    
1846
  // Append description to title.
1847
  if (!empty($media->description_L10n)) {
1848
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1849
  }
1850

    
1851
  // Artist.
1852
  if (!empty($media_metadata->Artist)) {
1853
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1854
  }
1855
  elseif (!empty($media->artist->titleCache)) {
1856
    $metadata_caption['artist'] = $media->artist->titleCache;
1857
  }
1858

    
1859
  // Copyright.
1860
  $metadata_caption['rights'] = array(
1861
    'copyright' => array('agentNames' => array()),
1862
    'license' => array(
1863
      'agentNames' => array(),
1864
      'types' => array(),
1865
      'abbreviatedTexts' => array(),
1866
      'uris' => array(),
1867
    ),
1868
  );
1869
  if (!empty($media_metadata->Copyright)) {
1870
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1871
  }
1872
  elseif (isset($media->rights) && is_array($media->rights)) {
1873
    foreach ($media->rights as $right) {
1874
      switch ($right->term->uuid) {
1875
        case UUID_RIGHTS_LICENCE:
1876
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1877
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1878
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1879
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1880
          break;
1881
        case UUID_RIGHTS_COPYRIGHT:
1882
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1883
          break;
1884
      }
1885
    }
1886
  }
1887
  else {
1888
    $metadata_caption['rights']['agentNames'][] = '';
1889
  }
1890

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

    
1894
  // Location.
1895
  $metadata_caption['location'] = array();
1896
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1897
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1898
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1899
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1900

    
1901
  /*
1902
   // Creation date.
1903
   if($media_metadata["Modify Date"])
1904
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1905
   else
1906
   $metadata_caption['mediacreated'] = $media->created;
1907
   */
1908

    
1909
  // Returned value.
1910
  return $metadata_caption;
1911
}
1912

    
1913
/**
1914
 * Collects all the media from a list of description elements.
1915
 *
1916
 * @param array $descriptionElements
1917
 *   The description elements from which to collect the media.
1918
 *
1919
 * @return array
1920
 *   The output with all the collected media.
1921
 */
1922
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1923

    
1924
  $outArrayOfMedia = array();
1925

    
1926
  // Avoiding a warning box in Drupal for Flora Malesiana.
1927
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1928
    foreach ($descriptionElements as $descriptionElement) {
1929
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1930
        foreach ($descriptionElement->media as $media) {
1931
          if (is_object($media)) {
1932
            $outArrayOfMedia[] = $media;
1933
          }
1934
        }
1935
      }
1936
    }
1937
  }
1938
  return $outArrayOfMedia;
1939
}
1940

    
1941
/**
1942
 * @todo Please document this function.
1943
 * @see http://drupal.org/node/1354
1944
 *
1945
 * @param array $cdmBase_list
1946
 *   An array of CdmBase instances or a single instance.
1947
 * @param string $footnote_list_key
1948
 *
1949
 * @return unknown
1950
 */
1951
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1952

    
1953
   static $annotations_types_filter = null;
1954
   if(!$annotations_types_filter) {
1955
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1956
   }
1957

    
1958
  $footNoteKeys = array();
1959

    
1960
  // Is argument cdmBase an array?
1961
  if (!is_array($cdmBase_list)) {
1962
    $cdmBase_array = array();
1963
    $cdmBase_array[] = $cdmBase_list;
1964
  }
1965
  else {
1966
    $cdmBase_array = $cdmBase_list;
1967
  }
1968

    
1969
  // Getting the key for the footnotemanager.
1970
  if (isset($footnote_list_key)) {
1971
    $footnoteListKey = $footnote_list_key;
1972
  }
1973
  else {
1974
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1975
  }
1976

    
1977
  // Adding the footnotes keys.
1978
  foreach ($cdmBase_array as $cdmBase_element) {
1979
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1980
    if (is_array($annotations)) {
1981
      foreach ($annotations as $annotation) {
1982
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1983
      }
1984
    }
1985
  }
1986

    
1987
  return $footNoteKeys;
1988
}
1989

    
1990
// @WA Comment: should this not be a theme function?
1991
/**
1992
 *  Creates a CDM Dynabox.
1993
 * @param string $dynabox_id
1994
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
1995
 * @param string $label
1996
 *   The clickable text to show.
1997
 * @param string $content_url
1998
 *   The cdm REST service request url wich will deliver the content to be shown
1999
 *   once the dynabox toggles open.
2000
 * @param string $theme
2001
 *   The theme to be used for rendering the cdm REST service reponse with is
2002
 *   returned from the $content_url.
2003
 * @param string $link_alt_text
2004
 *   The value for the alt attribute of the dynabox link.
2005
 * @param array $enclosingtags
2006
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2007
 *   element itself, $enclosingtags[1] is the tag to be used for the
2008
 *   dynabox_content (optional)
2009
 * @param string $open_callback
2010
 *   optional javascript call back function to be triggered after toggeling the box to
2011
 *   the open state.
2012
 * @param string $close_callback
2013
 *   optional javascript call back function to be triggered after toggeling the box to
2014
 *   the closed state.
2015
 *
2016
 * @return string
2017
 *   Returns HTML for a dynabox.
2018
 */
2019
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
2020
  $out = '';
2021

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

    
2025
  _add_js_domEvent(); // requires domEvent.js
2026
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2027
  drupal_add_js("
2028
  jQuery(document).ready(
2029
      function() {
2030
        dynabox('". $dynabox_id ."',
2031
          {
2032
            open_callback: " . $open_callback .",
2033
            close_callback: " . $close_callback ."
2034
          }
2035
        );
2036
      }
2037
   );",
2038
   array(
2039
    'type'=>'inline',
2040
    'scope'=>'footer'
2041
    )
2042
  );
2043

    
2044
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2045
  $out .= '<!-- ' . $content_url . ' -->';
2046
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2047
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '>' . loading_image_html() . '</' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2048
  $out .= '</' . $enclosingtags[0] . '>';
2049
  return $out;
2050
}
2051

    
2052
/**
2053
 * Checks whether a feature has any description elements.
2054
 *
2055
 * @param mixed $featureNode
2056
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2057
 *
2058
 * @see _mergeFeatureTreeDescriptions()
2059
 *
2060
 * @return bool
2061
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2062
 *   contains at least one non empty TextData or at least one DescriptionElement
2063
 *   of an other type. A TextData element holding a multilanguageText or a
2064
 *   source reference is considered to be not empty.
2065
 */
2066
function hasFeatureNodeDescriptionElements($featureNode) {
2067

    
2068
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2069
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2070
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2071
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2072
          return TRUE;
2073
        }
2074
      }
2075
    }
2076
  }
2077
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2078
    foreach ($featureNode->childNodes as $child) {
2079
      if (hasFeatureNodeDescriptionElements($child)) {
2080
        return TRUE;
2081
      }
2082
    }
2083
  }
2084
  return FALSE;
2085
}
2086

    
2087
/**
2088
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2089
 *
2090
 * @param $chapter
2091
 *   The taxon page chapter or part
2092
 */
2093
function cdm_check_valid_taxon_page($chapter){
2094
  static $taxon_tabs = null;
2095

    
2096
  cdm_check_valid_portal_page();
2097

    
2098
  if($taxon_tabs == null){
2099
    $taxon_tabs = array('all', 'description');
2100
    foreach(get_taxon_tabs_list() as $tab){
2101
      $taxon_tabs[] = strtolower($tab);
2102
    }
2103
  }
2104

    
2105
  if(!in_array($chapter, $taxon_tabs)){
2106
    // oops this is not a valid chapter name
2107
    http_send_status(404); // 404 = Not Found
2108
  }
2109

    
2110
}
2111

    
2112
/**
2113
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2114
 *
2115
 * @param $chapter
2116
 *   The taxon page chapter or part
2117
 */
2118
function cdm_check_valid_portal_page(){
2119
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2120
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2121
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2122
    http_send_status(404); // 404 = Not Found
2123
    exit('HTTP 404');
2124
  }
2125
}
(7-7/14)