Project

General

Profile

Download (71.7 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

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

    
48

    
49
/* ============================ java script functions ============================= */
50

    
51

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

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

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

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

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

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

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

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

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

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

    
123
function _add_js_openlayers() {
124

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

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

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

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

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

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

    
172
}
173

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

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

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

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

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

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

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

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

    
284

    
285
/* ====================== hook implementations ====================== */
286
/**
287
 * Implements hook_permission().
288
 *
289
 * Valid permissions for this module.
290
 *
291
 * @return array
292
 *   An array of valid permissions for the portfolio module.
293
 */
294
function cdm_dataportal_permission() {
295
  return array(
296
    'administer cdm_dataportal' => array(
297
      'title' => t('administer cdm_dataportal'),
298
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
299
    ),
300
    'cdm_dataportal view notes' => array(
301
      'title' => t('cdm_dataportal view notes'),
302
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
303
    ),
304
    // TODO Which other permissions are required?
305
    // -> check the WP6 requirements document.
306
  );
307
}
308

    
309
/**
310
 * Implements hook_menu().
311
 */
312
function cdm_dataportal_menu() {
313
  $items = array();
314

    
315
  // @see settings.php.
316
  cdm_dataportal_menu_admin($items);
317
  cdm_dataportal_menu_help($items);
318

    
319
  $items['cdm_dataportal/names'] = array(
320
    'page callback' => 'cdm_dataportal_view_names',
321
    'access arguments' => array('access content'),
322
    'type' => MENU_CALLBACK,
323
  );
324

    
325
  // Optional callback arguments: page.
326
  $items['cdm_dataportal/taxon'] = array(
327
    'page callback' => 'cdm_dataportal_taxon_page_view',
328
    'access arguments' => array('access content'),
329
    'type' => MENU_CALLBACK,
330
    // Expected callback arguments: uuid.
331
  );
332

    
333
  $items['cdm_dataportal/name'] = array(
334
    'page callback' => 'cdm_dataportal_name_page_view',
335
      /*
336
    'page arguments' => array(
337
       'taxon_name_uuid',
338
       'taxon_to_hide_uuid',
339
       'synonym_uuid' => NULL
340
      ),
341
      */
342
    'access arguments' => array('access content'),
343
    'type' => MENU_CALLBACK,
344
    // Expected callback arguments: uuid.
345
  );
346

    
347
  $items['cdm_dataportal/reference'] = array(
348
    'page callback' => 'cdm_dataportal_view_reference',
349
    'access arguments' => array('access content'),
350
    'type' => MENU_CALLBACK,
351
    // Expected callback arguments: uuid.
352
  );
353

    
354
  $items['cdm_dataportal/reference/list'] = array(
355
    'page callback' => 'cdm_dataportal_view_reference_list',
356
    'access arguments' => array('access content'),
357
    'type' => MENU_CALLBACK,
358
    // Expected callback arguments: uuid.
359
  );
360

    
361
  $items['cdm_dataportal/media'] = array(
362
    'page callback' => 'cdm_dataportal_view_media',
363
    'access arguments' => array('access content'),
364
    'type' => MENU_CALLBACK,
365
    // Expected callback arguments:
366
    // uuid, mediarepresentation_uuid, part_uuid or part#.
367
  );
368

    
369
  $items['cdm_dataportal/polytomousKey'] = array(
370
    'page callback' => 'cdm_dataportal_view_polytomousKey',
371
    'access arguments' => array('access content'),
372
    'type' => MENU_CALLBACK,
373
    // Expected callback arguments: polytomousKey->uuid.
374
  );
375

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

    
382
  $items['cdm_dataportal/search/advanced'] = array(
383
    'title' => 'Advanced',
384
    'page callback' => 'cdm_dataportal_view_search_advanced',
385
    'access arguments' => array('access content'),
386
    'type' => MENU_DEFAULT_LOCAL_TASK,
387
  );
388

    
389
  $items['cdm_dataportal/search/taxon_by_description'] = array(
390
    'title' => 'By description full text',
391
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
392
    'access arguments' => array('access content'),
393
    'type' => MENU_LOCAL_TASK,
394
  );
395

    
396
  $items['cdm_dataportal/search/results/taxon'] = array(
397
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
398
    'access arguments' => array('access content'),
399
    'type' => MENU_CALLBACK,
400
  );
401
  /*
402
   $items['cdm/xml2json'] = array(
403
   'page callback' => 'cdm_view_xml2json',
404
   'access arguments' => array('access content'),
405
   'type' => MENU_CALLBACK,
406
   );
407
   */
408

    
409
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
410
  // User configuration of cdm_dataportal.
411
  $items['user/%/cdm_dataportal'] = array(
412
    'title' => 'cdm_dataportal',
413
    'access arguments' => array('access content'),
414
    'page callback' => 'drupal_get_form',
415
    'page arguments' => array('cdm_dataportal_user_form'),
416
    'type' => MENU_LOCAL_TASK,
417
    'weight' => 10,
418
  );
419
  // }
420

    
421
  // 'May not cache' in D5.
422
  $items['cdm_dataportal/name/%'] = array(
423
    // 'page callback' => 'cdm_dataportal_view_name',
424
    'page callback' => 'cdm_dataportal_name_page_view',
425
    'page arguments' => array(2, 3, 4),
426
    'access arguments' => array('access content'),
427
    'type' => MENU_CALLBACK,
428
  );
429

    
430
  // --- Local tasks for Taxon.
431
  // --- tabbed taxon page
432
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
433
    $items['cdm_dataportal/taxon/%'] = 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' => 1,
439
      'page arguments' => array(2, "description")
440
      , // Expected callback arguments: name_uuid.
441
    );
442

    
443
    $items['cdm_dataportal/taxon/%/all'] = 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_CALLBACK,
448
      'weight' => 2,
449
      'page arguments' => array(2, "all")
450
      , // Expected callback arguments: name_uuid.
451
    );
452

    
453
    $items['cdm_dataportal/taxon/%/description'] = array(
454
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
455
      'page callback' => 'cdm_dataportal_taxon_page_view',
456
      'access arguments' => array('access content'),
457
      'type' => MENU_DEFAULT_LOCAL_TASK,
458
      'weight' => 2,
459
      'page arguments' => array(2, "description")
460
      , // Expected callback arguments: name_uuid.
461
    );
462

    
463
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
464
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
465
      'page callback' => 'cdm_dataportal_taxon_page_view',
466
      'access arguments' => array('access content'),
467
      'type' => MENU_LOCAL_TASK,
468
      'weight' => 4,
469
      'page arguments' => array(2, "synonymy", 4)
470
      , // Expected callback arguments: name_uuid.
471
    );
472
    $items['cdm_dataportal/taxon/%/images'] = array(
473
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
474
      'page callback' => 'cdm_dataportal_taxon_page_view',
475
      'access arguments' => array('access content'),
476
      'type' => MENU_LOCAL_TASK,
477
      'weight' => 5,
478
      'page arguments' => array(2, "images")
479
      , // Expected callback arguments: name_uuid.
480
    );
481

    
482
    $items['cdm_dataportal/taxon/%/specimens'] = array(
483
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
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, "specimens")
489
      , // Expected callback arguments: name_uuid.
490
    );
491

    
492
    $items['cdm_dataportal/taxon/%/keys'] = array(
493
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
494
      'page callback' => 'cdm_dataportal_taxon_page_view',
495
      'access arguments' => array('access content'),
496
      'type' => MENU_LOCAL_TASK,
497
      'weight' => 6,
498
      'page arguments' => array(2, "keys")
499
      , // Expected callback arguments: name_uuid.
500
    );
501
  }
502

    
503
  // --- refresh link for all cdmnode types
504
  foreach (cdm_get_nodetypes() as $type=>$name) {
505
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
506
        'title' => t('Refresh'),
507
        'page callback' => 'cdm_dataportal_refresh_node',
508
        'access arguments' => array('administer cdm_dataportal'),
509
        'type' => MENU_LOCAL_TASK,
510
        'weight' => 100,
511
        'page arguments' => array($name, 2)
512
    );
513
  }
514

    
515
  return $items;
516
}
517

    
518
/**
519
 * Implements hook_init().
520
 *
521
 */
522
function cdm_dataportal_init() {
523
  //FIXME To add CSS or JS that should be present on all pages, modules
524
  //      should not implement this hook, but declare these files in their .info file.
525
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
526
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
527
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
528

    
529
  if(variable_get('cdm_debug_mode', FALSE)){
530
    $file = 'temporary://drupal_debug.txt';
531
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
532
  }
533

    
534
  $bibliography_settings = get_bibliography_settings();
535
  if($bibliography_settings['enabled'] == 1){
536
    FootnoteManager::registerFootnoteSet('BIBLIOGRAPHY', 'div', $bibliography_settings['key_format']);
537
  }
538
}
539

    
540
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
541

    
542
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
543

    
544
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
545
    // force reloading of all and notify user about this special loading
546
    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: ')
547
        . l('Back to tabbed taxon page', $base_path));
548
    $base_path .= '/all';
549
  } else {
550
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
551
  }
552

    
553
  $parameters['cacheL2_refresh'] ='1';
554

    
555

    
556
  drupal_goto($base_path, array('query' => $parameters));
557
}
558

    
559
/**
560
 * The function generate form for own user cdm dataportal configurations.
561
 */
562
function cdm_dataportal_user_form($form, &$form_state) {
563
  global $user;
564
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
565

    
566
  $form['taxon_page_tabs'] = array(
567
      '#type' => 'fieldset',
568
      '#title' => t('Taxon page tabs'),
569
  );
570
  $form['taxon_page_tabs']['check'] = array(
571
    '#type' => 'checkbox',
572
    '#title' => t('Activate user default configuration'),
573
    '#default_value' => variable_get($checkbox_value, 0),
574
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
575
  );
576

    
577
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
578
    '#type' => 'select',
579
    '#title' => t('Default tab to display'),
580
    '#default_value' => get_default_taxon_tab(TRUE),
581
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
582
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
583
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
584
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
585
  );
586

    
587
  $form['submit'] = array(
588
    '#type' => 'submit',
589
    '#value' => t('Submit'),
590
  );
591

    
592
  return $form;
593
}
594

    
595
/**
596
 * Form submission handler for user_form().
597
 *
598
 * Submits the user cdm dataportal configurations.
599
 */
600
function cdm_dataportal_user_form_submit($form, &$form_state) {
601
  global $user;
602
  $msg_type = 'status';
603
  $username = $user->name;
604
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
605

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

    
630
/**
631
 * Implements hook_block_info().
632
 */
633
function cdm_dataportal_block_info() {
634

    
635
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
636
    // $block[1]["info"] = t("CDM DataPortal Credits");
637
    $block["2"] = array(
638
        "info" => t("CDM Search Taxa"),
639
        "cache" => DRUPAL_NO_CACHE
640
      );
641
    // $block[3]["info"] = t("CDM Filters");
642
    $block["4"]["info"] = t("CDM Dataportal Print");
643
    $block["keys"]["info"] = t("CDM identification keys");
644
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
645

    
646
    return $block;
647
}
648

    
649
/**
650
 * Implements hook_block_view().
651
 */
652
function cdm_dataportal_block_view($delta) {
653
  // TODO Rename block deltas (e.g. '2') to readable strings.
654
  switch ($delta) {
655
    // case 'delta-1':
656
    // $block['subject'] = t('Credits');
657
    // $block['content'] = theme('cdm_credits');
658
    // return $block;
659
    case '2':
660
      $block['subject'] = t('Search taxa');
661
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
662
      $block['content'] = drupal_render($form);
663

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

    
690
/*
691
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
692
 $_SESSION['cdm'] = NULL;
693
 if(is_string($cdm_ws_uri_update)){
694
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
695
 }
696
 }
697

    
698
 function cdm_dataportal_session_validate(){
699
 if(!isset($_SESSION['cdm']['ws_uri'])){
700
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
701
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
702
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
703
 }
704
 }
705
 */
706

    
707
/**
708
 * creates a  selector form for taxonomic trees.
709
 *
710
 * @return a drupal form array
711
 */
712
function cdm_taxonomictree_selector() {
713
  _add_js_treeselector();
714

    
715
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
716
  return $form;
717
}
718

    
719
/**
720
 * @todo Please document this function.
721
 * @see http://drupal.org/node/1354
722
 */
723
function cdm_taxonomictree_selector_form($form, &$form_state) {
724

    
725
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
726
  $form['#action'] = $url;
727

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

    
734
  $destination_array = drupal_get_destination();
735
  $destination = $destination_array['destination'];
736

    
737
  $form['destination'] = array(
738
    '#weight' => -3,
739
    '#type' => 'hidden',
740
    '#value' =>  $destination,
741
  );
742

    
743
  $options = cdm_get_taxontrees_as_options();
744
  $taxontree_includes = variable_get(CDM_TAXONTREE_INCLUDES, null);
745
  if($taxontree_includes){
746
    $filtered_options = array();
747
    foreach($options as $uuid=>$label){
748
      if(!empty($taxontree_includes[$uuid])){
749
        $filtered_options[$uuid] = $label;
750
      }
751
    }
752
    $options = $filtered_options;
753
  }
754

    
755
  $form['val'] = array(
756
    '#type' => 'select',
757
    '#title' => t('Available classifications'),
758
    '#default_value' => get_taxonomictree_uuid_selected(),
759
    '#options' => $options,
760
    '#attributes' => array('class' => array('highlite-first-child'))
761
  );
762

    
763
  return $form;
764

    
765
}
766

    
767
/* UNREACHABLE since action of form directly links to view.
768
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
769

    
770
 $_SESSION['cdm']['search'] = $form_values;
771
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
772
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
773
 //$paramstr = compose_url_prameterstr($form_values);
774
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
775
 }
776
 */
777
/* ====================== menu callback functions ====================== */
778
/**
779
 * @todo Please document this function.
780
 * @see http://drupal.org/node/1354
781
 */
782
/*
783
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
784
  static $comment_node_disabled =  0;
785
  static $comment_node_read_only =  1;
786
  static $comment_node_read_write =  2;
787

    
788
  if ($form_id == 'node_type_form'
789
   && isset($form['identity']['type'])
790
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
791
  ) {
792
    $form['workflow']['comment'] = array(
793
      '#type' => 'radios',
794
      '#title' => t('Default comment setting'),
795
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
796
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
797
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
798
    );
799
  }
800
}
801
*/
802

    
803
/**
804
 * Displays a list of the known taxonomic names.
805
 *
806
 * When the list of taxonomic names is displayed, long lists are split up into
807
 * multiple pages.
808
 *
809
 * TODO: Parameters are still preliminary.
810
 *
811
 * @param string $beginsWith
812
 * @param string $page
813
 *   Page number to diplay defaults to page 1.
814
 * @param bool $onlyAccepted
815
 */
816
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
817

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

    
820
  /*
821
  // FIXME the filter for accepted names will be a form element, thus this
822
  // widget should be generated via form api preferably as block.
823
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
824
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
825
  $out .= theme('cdm_listof_taxa', $taxonPager);
826
  return $out;
827
  */
828
}
829

    
830
/**
831
 * @todo Please document this function.
832
 * @see http://drupal.org/node/1354
833
 */
834
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
835

    
836
  cdm_check_valid_portal_page();
837

    
838
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
839
  return theme('cdm_reference_page', array('reference' => $reference));
840
}
841

    
842
/**
843
 * Created a view on a all references contained in the portal.
844
 *
845
 * This function is used at the path cdm_dataportal/reference/list
846
 */
847
function cdm_dataportal_view_reference_list($pageNumber) {
848
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
849
  return theme('cdm_reference_pager', array(
850
    'referencePager' => $referencePager,
851
    'path' => 'cdm_dataportal/reference/list/',
852
    ));
853
}
854

    
855
/**
856
 * @todo Please document this function.
857
 * @see http://drupal.org/node/1354
858
 */
859
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
860

    
861
  cdm_check_valid_portal_page();
862

    
863
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
864
  return theme('cdm_media_page', array(
865
    'media' => $media,
866
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
867
    'partId' => $part,
868
    ));
869
}
870

    
871
/**
872
 * @todo Please document this function.
873
 * @see http://drupal.org/node/1354
874
 */
875
function _load_taxonBase(&$taxonBase) {
876
  if (isset($taxonBase->uuid)) {
877
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
878
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
879
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
880
  }
881
}
882

    
883
/**
884
 * Loads the media associated to the given taxon from the cdm server.
885
 * The aggregation settings regarding taxon relathionships and
886
 * taxonnomic childen are taken into account.
887
 *
888
 * The media lists are cached in a static variable.
889
 *
890
 * @param Taxon $taxon
891
 *   A CDM Taxon entitiy
892
 *
893
 * @return array
894
 *   An array of CDM Media entities
895
 *
896
 */
897
function _load_media_for_taxon($taxon) {
898

    
899
  static $media = NULL;
900

    
901
  if(!isset($media)) {
902
    $media = array();
903
  }
904
  if (!isset($media[$taxon->uuid])) {
905

    
906
    // --- GET Images --- //
907
    $mediaQueryParameters = array(
908
        "type" => "ImageFile",
909
    );
910

    
911
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
912
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
913
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
914

    
915
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
916
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
917
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
918
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
919

    
920
    $ws_endpoint = NULL;
921
    if ( variable_get('cdm_images_include_children', 0) == 0) {
922
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
923
    } else {
924
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
925
    }
926

    
927
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
928
        array(
929
            $taxon->uuid,
930
        ),
931
        queryString($mediaQueryParameters)
932
       );
933
  }
934

    
935
  return $media[$taxon->uuid];
936
}
937

    
938
/**
939
 *
940
 * @param Taxon $taxon
941
 *   A CDM Taxon entitiy
942
 *
943
 * @return array
944
 *   An array of CDM SpecimenOrObservation entities
945
 *
946
function _load_occurences_for_taxon($taxon){
947

    
948
  static $occurences = NULL;
949

    
950
  if(!isset($occurences)) {
951
    $occurences = array();
952
  }
953

    
954
  if (!isset($occurences[$taxon->uuid])){
955

    
956
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
957
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
958
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
959

    
960
    $by_associatedtaxon_query = http_build_query(array(
961
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
962
        'relationships' => implode(',', $relationship_choice['direct']),
963
        'pageSize' => null // all hits in one page
964
    )
965
    );
966

    
967
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
968
        null,
969
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
970
    );
971

    
972

    
973
    if(isset($pager->records[0])){
974
      $occurences[$taxon->uuid] =  $pager->records;
975
    }
976
  }
977
  return $occurences[$taxon->uuid];
978
}
979
 */
980

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

    
1008
/**
1009
 * Recusive funciton to convert an object into an array.
1010
 * also subordinate objects will be converted.
1011
 *
1012
 * @param object $object
1013
 * @return the array
1014
 */
1015
function convert_to_array($object) {
1016
  if(is_object($object) || is_array($object)) {
1017
    $array = (array)$object;
1018
    foreach ($array as $key=>$value){
1019
      $array[$key] = convert_to_array($value);
1020
    }
1021
    return $array;
1022
  } else {
1023
    return $object;
1024
  }
1025
}
1026

    
1027
/**
1028
 * Wraps the given $html string into a render array suitable for drupal_render()
1029
 *
1030
 * @param string $html
1031
 *   the html string, see
1032
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1033
 * @param number $weight
1034
 *   A positive or negative number (integer or decimal).
1035
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1036
 *
1037
 * @return
1038
 *   A render array
1039
 *
1040
 */
1041
function markup_to_render_array($html, $weight = FALSE) {
1042
  $render_array = array(
1043
    '#markup' => $html
1044
      );
1045
  if (is_numeric($weight)) {
1046
    $render_array['#weight'] = $weight;
1047
}
1048
  return $render_array;
1049
}
1050

    
1051
/**
1052
 * Loads the subgraph of a given PolytomousKeyNode.
1053
 *
1054
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1055
 * the CDM REST service.
1056
 *
1057
 * @param mixed $polytomousKeyNode
1058
 *   PolytomousKeyNode passed by reference.
1059
 *
1060
 * @return void
1061
 */
1062
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1063

    
1064
  if (!$polytomousKeyNode) {
1065
    return;
1066
  }
1067
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1068
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1069
    return;
1070
  }
1071
  if (!is_uuid($polytomousKeyNode->uuid)) {
1072
    drupal_set_message('_load_polytomousKeySubGraph(): ' . t('invalid type given.'), 'error');
1073
    return;
1074
  }
1075

    
1076
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1077

    
1078
  if (!$polytomousKeyNode) {
1079
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1080
    return;
1081
  }
1082

    
1083
  // Load children.
1084
  foreach ($polytomousKeyNode->children as &$childNode) {
1085
    _load_polytomousKeySubGraph($childNode);
1086
  }
1087

    
1088
  // Load subkey.
1089
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1090

    
1091
  // Load taxon.
1092
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1093
  _load_taxonBase($polytomousKeyNode->taxon);
1094
  return;
1095
}
1096

    
1097
/**
1098
 * @todo Please document this function.
1099
 * @see http://drupal.org/node/1354
1100
 */
1101
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1102

    
1103
  cdm_check_valid_portal_page();
1104

    
1105
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1106

    
1107
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1108
  if (is_array($sourcePager->records)) {
1109
    $polytomousKey->sources = $sourcePager->records;
1110
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1111
  }
1112

    
1113
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1114
  if (is_array($annotationPager->records)) {
1115
    $polytomousKey->annotations = $annotationPager->records;
1116
  }
1117

    
1118
  _load_polytomousKeySubGraph($polytomousKey->root);
1119
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1120
}
1121

    
1122
/**
1123
 * Creates a taxon page view or a chapter of it.
1124
 *
1125
 * The taxon page gives detailed information on a taxon, it shows:
1126
 *  - Taxon name.
1127
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1128
 *    heterotypic and finally followed by misapplied names.
1129
 *    The list is ordered historically.
1130
 *  - All description associated with the taxon.
1131
 *
1132
 * @param string $uuid
1133
 * @param string $chapter
1134
 *   Name of the part to display, valid values are:
1135
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1136
 *
1137
 * @return unknown_type
1138
 */
1139
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1140

    
1141
  cdm_check_valid_taxon_page($chapter);
1142
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1143
  // show a warning in case the javascript development mode is anabled
1144
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1145
    drupal_set_message(t('The !url1 is enabled.
1146
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1147
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1148
    )),
1149
    'warning'
1150
        );
1151
  }
1152

    
1153
  // Display the page for the taxon defined by $uuid.
1154
  // set_last_taxon_page_tab(arg(3));
1155
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1156
  if (!empty($taxonpage)) {
1157
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1158
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1159
  }
1160
  else {
1161
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1162
    return '';
1163
  }
1164
}
1165

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

    
1192
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1193
    'taxon' => $taxon
1194
  ));
1195

    
1196
  // Check if the taxon id contained in the currently selected tree.
1197
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1198

    
1199
  if (!$taxon_in_current_tree) {
1200
    $classifications = get_classifications_for_taxon($taxon);
1201
    if (count($classifications) == 0) {
1202
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1203
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1204
      ))), 'warning');
1205
    }
1206
    else {
1207
      $trees = '';
1208
      foreach ($classifications as $classification) {
1209
        if (isset($classification->titleCache)) {
1210
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1211
        }
1212
      }
1213

    
1214
      drupal_set_message(format_plural(count($trees),
1215
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1216
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1217
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1218
    }
1219
  }
1220

    
1221
  // Render the taxon page.
1222
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1223
  $taxonpage->content = drupal_render($render_array);
1224

    
1225
  return $taxonpage;
1226
}
1227

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

    
1249
  cdm_check_valid_portal_page();
1250

    
1251
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1252
  if (!empty($taxonname_page)) {
1253
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1254
  }
1255
  else {
1256
    return '';
1257
  }
1258
}
1259

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

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

    
1350
/**
1351
 * @todo Please document this function.
1352
 * @see http://drupal.org/node/1354
1353
 */
1354
function cdm_dataportal_view_search_advanced() {
1355

    
1356
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1357
  $form = array();
1358
  $form_state = array();
1359
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1360

    
1361
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1362

    
1363
}
1364

    
1365
/**
1366
 * @todo Please document this function.
1367
 * @see http://drupal.org/node/1354
1368
 */
1369
function cdm_dataportal_view_search_taxon_by_description() {
1370
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1371
  // $form_state = false;
1372
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1373
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1374

    
1375
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1376
}
1377

    
1378
/**
1379
 * Executes the search and generates the result list of taxa.
1380
 */
1381
function cdm_dataportal_view_search_results_taxon() {
1382

    
1383
  $taxonPager = cdm_dataportal_search_execute();
1384

    
1385
  $showThumbnails = do_showThumbnails();
1386

    
1387
  $setSessionUri = url('cdm_api/setvalue/session', array(
1388
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1389
  ));
1390

    
1391
  drupal_add_js('jQuery(document).ready(function() {
1392

    
1393
      // init
1394
      if(' . $showThumbnails . ' == 1){
1395
      jQuery(\'.media_gallery\').show(20);
1396
  } else {
1397
      jQuery(\'.media_gallery\').hide(20);
1398
  }
1399
      // add change hander
1400
      jQuery(\'#showThumbnails\').change(
1401
      function(event){
1402
      var state = 0;
1403
      if(jQuery(this).is(\':checked\')){
1404
      jQuery(\'.media_gallery\').show(20);
1405
      state = 1;
1406
  } else {
1407
      jQuery(\'.media_gallery\').hide(20);
1408
  }
1409
      // store state in session variable
1410
      var uri = \'' . $setSessionUri . '\' + state;
1411
      jQuery.get(uri);
1412
  });
1413
  });',
1414
  array('type' => "inline", 'scope' => JS_DEFAULT));
1415

    
1416
  drupal_set_title(t('Search results'), PASS_THROUGH);
1417

    
1418
  return theme('cdm_search_results', array(
1419
    'pager' => $taxonPager,
1420
    'path' => 'cdm_dataportal/search/results/taxon',
1421
    ));
1422
}
1423

    
1424
/**
1425
 * Provides the standart image wich indicated a loading process
1426
 *
1427
 * @return string
1428
 *  The img html tag
1429
 */
1430
function loading_image_html() {
1431
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1432
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1433
}
1434

    
1435
/**
1436
 * Returns the state of the the showThumbnails flag set in the
1437
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1438
 *
1439
 * @return boolean
1440
 *    returns 1 if the flag is set
1441
 */
1442
function do_showThumbnails() {
1443
  static $showThumbnails = null;
1444

    
1445
  if($showThumbnails == null) {
1446
    $showThumbnails = 0;
1447
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1448
      $showThumbnails = 0;
1449
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1450
      $showThumbnails = is_array($search_gallery_settings)
1451
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1452
        && (
1453
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1454
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1455
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1456
            )
1457
         ? 1 : 0;
1458

    
1459
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1460
    }
1461
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1462
    if (!is_numeric($showThumbnails)) {
1463
      $showThumbnails = 1;
1464
    }
1465
  }
1466

    
1467
  return $showThumbnails;
1468
}
1469

    
1470
/**
1471
 * View which transforms XML output from a given webservice endpoint into JSON.
1472
 */
1473
/*
1474
 function cdm_view_xml2json(){
1475
 $file = arg(2);
1476
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1477
 return  xml2json::transformXmlStringToJson($datastr);
1478
 }
1479
 */
1480

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

    
1506
  $tab = get_default_taxon_tab();
1507
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1508

    
1509
  if (!$uuid) {
1510
    return FALSE;
1511
  }
1512

    
1513
  if ($page_tab) {
1514
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1515
  }
1516
  elseif (!$tab || strtolower($tab) == 'general') {
1517
    return 'cdm_dataportal/taxon/' . $uuid;
1518
  }
1519
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1520
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1521
  }
1522
  else {
1523
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1524
  }
1525
}
1526

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

    
1556
}
1557

    
1558
/**
1559
 * Compses the drupal path to the key identified by the uuid.
1560
 *
1561
 * @param string $keyType
1562
 *    the key typer corresponds to the specific class of the CDM
1563
 *    IdentificationKey. Possible values are
1564
 *      -PolytomousKey
1565
 *      -MultimediaKey
1566
 *      - ...
1567
 * @param UUID $keyUuid
1568
 *   The UUID of the key
1569
 */
1570
function path_to_key($keyType, $keyUuid) {
1571
  if (!$keyUuid || !$keyType) {
1572
    return FALSE;
1573
  }
1574
  $keyType{0} = strtolower($keyType{0});
1575
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1576
}
1577

    
1578
/**
1579
 * @todo Please document this function.
1580
 * @see http://drupal.org/node/1354
1581
 */
1582
function path_to_reference($uuid) {
1583
  if (!$uuid) {
1584
    return FALSE;
1585
  }
1586
  return 'cdm_dataportal/reference/' . $uuid;
1587
}
1588

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

    
1618
/**
1619
 * @todo Please document this function.
1620
 * @see http://drupal.org/node/1354
1621
 */
1622
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1623
  if (!$uuid) {
1624
    return FALSE;
1625
  }
1626
  $out = 'cdm_dataportal/media/' . $uuid;
1627
  if ($representaion_uuid) {
1628
    $out .= '/' . $representaion_uuid;
1629
    if ($partId !== FALSE) {
1630
      $out .= '/' . $partId;
1631
    }
1632
  }
1633
  return $out;
1634
}
1635

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

    
1664
/**
1665
 * Composes an HTML element class attribute value composed of
1666
 * the shortname of the cdm class and the uuid of the entity.
1667
 * This class attribute should be used whereever an cdm-entity is rendered.
1668
 *
1669
 * These according class selectors in css must be escaped, eg:
1670
 *    .cdm\:TextData
1671
 *
1672
 * @param $cdmEntity
1673
 */
1674
function html_class_attribute_ref($cdmEntity) {
1675

    
1676
  if (is_cdm_entity($cdmEntity)) {
1677
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1678
  }
1679
}
1680

    
1681
/**
1682
 * Preprocess the taggedName to normalize newly introduced
1683
 * tagtypes like hybridSign, separator, .. more?
1684
 *
1685
 * @param unknown_type $taggedTextList
1686
 */
1687
function normalize_TaggedName(&$taggedTextList) {
1688

    
1689
  if (is_array($taggedTextList)) {
1690

    
1691
    // First pass: rename.
1692
    for ($i = 0; $i < count($taggedTextList); $i++) {
1693

    
1694
      if ($taggedTextList[$i]->type == "hybridSign") {
1695
        $taggedTextList[$i]->type = "name";
1696
      }
1697
    }
1698

    
1699
    // Second pass: resolve separators.
1700
    $taggedNameListNew = array();
1701
    for ($i = 0; $i < count($taggedTextList); $i++) {
1702

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

    
1705
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1706
          $taggedName = $taggedTextList[$i];
1707
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1708
          $taggedNameListNew[] = $taggedName;
1709
          ++$i;
1710
          ++$i;
1711
        }
1712
      }
1713
      else {
1714
        $taggedNameListNew[] = $taggedTextList[$i];
1715
      }
1716
    }
1717
    $taggedTextList = $taggedNameListNew;
1718
  }
1719
}
1720

    
1721
/**
1722
 * Creates a short taxonname.
1723
 *
1724
 * The short name is created by using the taggename field of
1725
 * NameSTO or NameTO instances.
1726
 * If the taggename if empty the fullname will be returned.
1727
 *
1728
 * @param unknown_type $name
1729
 *   Name or TreeNode.
1730
 *
1731
 * @return string
1732
 */
1733
function cdm_dataportal_shortname_of($name) {
1734
  $nameStr = '';
1735

    
1736
  normalize_TaggedName($name->taggedTitle);
1737

    
1738
  // Get all tagged text tokens of the scientific name.
1739
  foreach ($name->taggedTitle as $tagtxt) {
1740
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1741
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1742
    }
1743
  }
1744
  $nameStr = trim($nameStr);
1745

    
1746
  if ($nameStr) {
1747

    
1748
    // Do not return short names for these.
1749
    if ($name->unplaced || $name->excluded) {
1750
      return $nameStr;
1751
    }
1752

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

    
1773
/**
1774
 * Check if a taxon is accepted by the current taxonomic tree.
1775
 *
1776
 * @param mixed $taxon
1777
 *   The Taxon obkect to check.
1778
 *
1779
 * @return bool
1780
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1781
 */
1782
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1783

    
1784
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1785

    
1786
  if (isset($taxon->taxonNodes)) {
1787
    $taxonNodes = $taxon->taxonNodes;
1788
  }
1789
  else {
1790
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1791
  }
1792

    
1793
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1794
    foreach ($taxonNodes as $node) {
1795
      if (isset($node->classification)){
1796
        if(is_object($node->classification)) {
1797
          if ($node->classification->uuid == $defaultTreeUuid) {
1798
            return TRUE;
1799
          }
1800
        }
1801
        else {
1802
          if ($node->classification == $defaultTreeUuid) {
1803
            return TRUE;
1804
          }
1805
        }
1806
      }
1807
    }
1808
  }
1809

    
1810
  return FALSE;
1811
}
1812

    
1813
/**
1814
 * Workaround for missing original source type.
1815
 *
1816
 * idNamespace is always set in these cases.
1817
 * @todo improve documentation of this function.
1818
 *
1819
 * @param unknown_type $source
1820
 *
1821
 * @return unknown_type
1822
 */
1823
function _is_original_source_type($source) {
1824
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1825
}
1826

    
1827
/**
1828
 * @todo Please document this function.
1829
 * @see http://drupal.org/node/1354
1830
 */
1831
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1832
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1833
}
1834

    
1835
/**
1836
 * Gets the metadata info such as title or artist of a media file.
1837
 *
1838
 * The function tries at first to get all the info from the file metadata
1839
 * and if it is not avaible look at the media file info stored at the database.
1840
 *
1841
 * @param mixed $media
1842
 *   The media file object for which to get the metadata.
1843
 *
1844
 * @return array
1845
 *   The array with the available specified metadata info.
1846
 * TODO rename to read_media_metadata() and move to *.module.
1847
 */
1848
function cdm_read_media_metadata($media) {
1849

    
1850
  $metadata_caption = array(
1851
    'title' => '',// Media_metadata and media.
1852
    'artist' => '',// Media_metadata and media.
1853
    'rights',// Media_metadata and media.
1854
    'location',// Media_metadata.
1855
    'filename' => '',// Media.
1856
    'mediacreated' => '',// Media.
1857
    'description' => '',
1858
  );// Media.
1859

    
1860
  // Getting the media metadata.
1861
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1862
  $media_metadata_aux = (array) $media_metadata;
1863

    
1864
  // Filename.
1865
  if (!empty($media->representations[0]->parts[0]->uri)) {
1866
    $fileUri = $media->representations[0]->parts[0]->uri;
1867
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1868
    $metadata_caption['filename'] = $filename;
1869
  }
1870
  else {
1871
    $metadata_caption['filename'] = '';
1872
  }
1873

    
1874
  // Title.
1875
  if (!empty($media_metadata->ObjectName)) {
1876
    $metadata_caption['title'] = $media_metadata->ObjectName;
1877
  }
1878
  elseif (!empty($media_metadata_aux['Object Name'])) {
1879
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1880
  }
1881
  elseif (!empty($media->title_L10n)) {
1882
    $metadata_caption['title'] = $media->title_L10n;
1883
  }
1884
  elseif (!empty($media->titleCache)) {
1885
    $metadata_caption['title'] = $media->titleCache;
1886
  }
1887

    
1888
  // Append description to title.
1889
  if (!empty($media->description_L10n)) {
1890
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1891
  }
1892

    
1893
  // Artist.
1894
  if (!empty($media_metadata->Artist)) {
1895
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1896
  }
1897
  elseif (!empty($media->artist->titleCache)) {
1898
    $metadata_caption['artist'] = $media->artist->titleCache;
1899
  }
1900

    
1901
  // Copyright.
1902
  $metadata_caption['rights'] = array(
1903
    'copyright' => array('agentNames' => array()),
1904
    'license' => array(
1905
      'agentNames' => array(),
1906
      'types' => array(),
1907
      'abbreviatedTexts' => array(),
1908
      'uris' => array(),
1909
    ),
1910
  );
1911
  if (!empty($media_metadata->Copyright)) {
1912
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1913
  }
1914
  elseif (isset($media->rights) && is_array($media->rights)) {
1915
    foreach ($media->rights as $right) {
1916
      if(isset($right->term)){
1917
        switch ($right->type->uuid) {
1918
          case UUID_RIGHTS_LICENCE:
1919
            $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1920
            $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1921
            $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1922
            $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1923
            break;
1924
          case UUID_RIGHTS_COPYRIGHT:
1925
            $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1926
            break;
1927
        }
1928
      }
1929
    }
1930
  }
1931
  else {
1932
    $metadata_caption['rights']['agentNames'][] = '';
1933
  }
1934

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

    
1938
  // Location.
1939
  $metadata_caption['location'] = array();
1940
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1941
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1942
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1943
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1944

    
1945
  /*
1946
   // Creation date.
1947
   if($media_metadata["Modify Date"])
1948
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1949
   else
1950
   $metadata_caption['mediacreated'] = $media->created;
1951
   */
1952

    
1953
  // Returned value.
1954
  return $metadata_caption;
1955
}
1956

    
1957
/**
1958
 * Collects all the media from a list of description elements.
1959
 *
1960
 * @param array $descriptionElements
1961
 *   The description elements from which to collect the media.
1962
 *
1963
 * @return array
1964
 *   The output with all the collected media.
1965
 */
1966
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1967

    
1968
  $outArrayOfMedia = array();
1969

    
1970
  // Avoiding a warning box in Drupal for Flora Malesiana.
1971
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1972
    foreach ($descriptionElements as $descriptionElement) {
1973
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1974
        foreach ($descriptionElement->media as $media) {
1975
          if (is_object($media)) {
1976
            $outArrayOfMedia[] = $media;
1977
          }
1978
        }
1979
      }
1980
    }
1981
  }
1982
  return $outArrayOfMedia;
1983
}
1984

    
1985
/**
1986
 * @todo Please document this function.
1987
 * @see http://drupal.org/node/1354
1988
 *
1989
 * @param array $cdmBase_list
1990
 *   An array of CdmBase instances or a single instance.
1991
 * @param string $footnote_list_key_suggestion
1992
 *
1993
 * @return unknown
1994
 */
1995
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key_suggestion = NULL) {
1996

    
1997
   static $annotations_types_filter = null;
1998
   if(!$annotations_types_filter) {
1999
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2000
   }
2001

    
2002
  $footNoteKeys = array();
2003

    
2004
  // Is argument cdmBase an array?
2005
  if (!is_array($cdmBase_list)) {
2006
    $cdmBase_array = array();
2007
    $cdmBase_array[] = $cdmBase_list;
2008
  }
2009
  else {
2010
    $cdmBase_array = $cdmBase_list;
2011
  }
2012

    
2013
  // Getting the key for the footnotemanager.
2014
  if (isset($footnote_list_key_suggestion)) {
2015
    $footnote_list_key = $footnote_list_key_suggestion;
2016
  }
2017
  else {
2018
    $footnote_list_key = RenderHints::getFootnoteListKey() . '-annotations';
2019
  }
2020

    
2021
  // Adding the footnotes keys.
2022
  foreach ($cdmBase_array as $cdmBase_element) {
2023
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2024
    if (is_array($annotations)) {
2025
      foreach ($annotations as $annotation) {
2026
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnote_list_key, $annotation->text);
2027
      }
2028
    }
2029
  }
2030

    
2031
  return $footNoteKeys;
2032
}
2033

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

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

    
2069
  if(!array_key_exists('class', $attributes)) {
2070
    $attributes['class'] = array();
2071
  }
2072
  $attributes['class'][] = 'dynabox-' . $dynabox_id;
2073
  $dynabox_attributes = drupal_attributes($attributes);
2074

    
2075

    
2076
  _add_js_domEvent(); // requires domEvent.js
2077
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2078
  drupal_add_js("
2079
  jQuery(document).ready(
2080
      function() {
2081
        dynabox('". $dynabox_id ."',
2082
          {
2083
            open_callback: " . $open_callback .",
2084
            close_callback: " . $close_callback ."
2085
          }
2086
        );
2087
      }
2088
   );",
2089
   array(
2090
    'type'=>'inline',
2091
    'scope'=>'footer'
2092
    )
2093
  );
2094

    
2095

    
2096
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2097
  $out .= '<!-- dynabox for ' . $content_url . ' -->';
2098
  $out .= '<' . $enclosingtags[0] . ' ' .  $dynabox_attributes. '><a href="' . $cdm_proxy_url . '" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2099
  // TODO stop using the title attribute, the label href now contains the same url!
2100
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '">';
2101
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-content-inner">' . loading_image_html() . '</' . $enclosingtags[0] . '>';
2102
  $out .= '</' . $enclosingtags[1] . '>';
2103
  $out .= '</' . $enclosingtags[0] . '>';
2104
  $out .= '<!-- dynabox end -->';
2105
  return $out;
2106
}
2107

    
2108
/**
2109
 * Checks whether a feature has any description elements.
2110
 *
2111
 * @param mixed $featureNode
2112
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2113
 *
2114
 * @see _mergeFeatureTreeDescriptions()
2115
 *
2116
 * @return bool
2117
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2118
 *   contains at least one non empty TextData or at least one DescriptionElement
2119
 *   of an other type. A TextData element holding a multilanguageText or a
2120
 *   source reference is considered to be not empty.
2121
 *
2122
 * @TODO this function may have become obsolete by the new method of detecting empty blocks,
2123
 *       see $block_content_is_not_empty in compose_cdm_feature_nodes() and
2124
 *       $feature_block_has_content in compose_cdm_descriptionElements
2125
 */
2126
function has_feature_node_description_elements($featureNode) {
2127

    
2128
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2129
    if(!isset($featureNode->descriptionElements['#type'])){ // #type is used to identify e.g. DTO elements: '#type' => 'DTO'
2130
      foreach ($featureNode->descriptionElements as $descriptionElement) {
2131
        if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text)
2132
          && $descriptionElement->multilanguageText_L10n->text != ''
2133
          || isset($descriptionElement->sources[0])
2134
          || isset($descriptionElement->media[0]) ) {
2135
          return TRUE;
2136
        }
2137
      }
2138
    }
2139
  }
2140
  else if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2141
    foreach ($featureNode->childNodes as $child) {
2142
      if (has_feature_node_description_elements($child)) {
2143
        return TRUE;
2144
      }
2145
    }
2146
  }
2147
  return FALSE;
2148
}
2149

    
2150
/**
2151
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2152
 *
2153
 * @param $chapter
2154
 *   The taxon page chapter or part
2155
 */
2156
function cdm_check_valid_taxon_page($chapter){
2157
  static $taxon_tabs = null;
2158

    
2159
  cdm_check_valid_portal_page();
2160

    
2161
  if($taxon_tabs == null){
2162
    $taxon_tabs = array('all', 'description');
2163
    foreach(get_taxon_tabs_list() as $tab){
2164
      $taxon_tabs[] = strtolower($tab);
2165
    }
2166
  }
2167

    
2168
  if(!in_array($chapter, $taxon_tabs)){
2169
    // oops this is not a valid chapter name
2170
    http_send_status(404); // 404 = Not Found
2171
  }
2172

    
2173
}
2174

    
2175
/**
2176
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2177
 *
2178
 * @param $chapter
2179
 *   The taxon page chapter or part
2180
 */
2181
function cdm_check_valid_portal_page(){
2182
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2183
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2184
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2185
    http_send_status(404); // 404 = Not Found
2186
    exit('HTTP 404');
2187
  }
2188
}
(7-7/14)