Project

General

Profile

Download (68.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
    )
131
  );
132

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

    
143
}
144

    
145
/**
146
 * @todo Please document this function.
147
 * @see http://drupal.org/node/1354
148
 */
149
function _add_js_thickbox() {
150
  // ---- jQuery thickbox:
151
  /*
152
  * bug: compat-1.0.js && thickbox.js line 237 .trigger("unload") -> event is
153
  * not triggered because of problems with compat-1.0.js' see INSTALL.txt
154
  */
155
  // drupal_add_js(drupal_get_path('module',
156
  // 'cdm_dataportal').'/js/jquery.imagetool.min.js');
157
  //
158
  // Add a setting for the path to cdm_dataportal module, used to find the path
159
  // for the loading animation image in thickbox.
160
  drupal_add_js(array(
161
  'cdm_dataportal' => array(
162
  'cdm_dataportal_path' => base_path() . drupal_get_path('module', 'cdm_dataportal'),
163
  )
164
  ),
165
  'setting'
166
      );
167
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/thickbox.js');
168
      drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/thickbox/cdm_thickbox.css');
169
}
170

    
171
/**
172
 * @todo Please document this function.
173
 * @see http://drupal.org/node/1354
174
 */
175
function _add_js_lightbox($galleryID) {
176
  /*
177
   * Important Notice: The jquery.lightbox-0.5.js has been modified in order to
178
  * allow using the "alt" attribute for captions instead of the "title"
179
  * attribute
180
  */
181
  $lightbox_base_path =  drupal_get_path('module', 'cdm_dataportal') . '/js/jquery-lightbox-0.5';
182
  $lightbox_image_path = base_path() . $lightbox_base_path . '/images/';
183
  drupal_add_js($lightbox_base_path . '/js/jquery.lightbox-0.5.js');
184
  drupal_add_css($lightbox_base_path . '/css/jquery.lightbox-0.5.css');
185
  drupal_add_js('jQuery(document).ready(function() {
186
      jQuery(\'#' . $galleryID . ' a.lightbox\').lightBox({
187
        fixedNavigation:  true,
188
        imageLoading:     \'' . $lightbox_image_path . 'lightbox-ico-loading.gif\',
189
        imageBtnPrev:     \'' . $lightbox_image_path . 'lightbox-btn-prev.gif\',
190
        imageBtnNext:     \'' . $lightbox_image_path . 'lightbox-btn-next.gif\',
191
        imageBtnClose:    \'' . $lightbox_image_path . 'lightbox-btn-close.gif\',
192
        imageBlank:       \'' . $lightbox_image_path . 'lightbox-blank.gif\',
193
        adjustToWindow: true
194
      });
195
    });
196
    ', array('type' => 'inline'));
197
}
198

    
199
/**
200
 * @todo Please document this function.
201
 * @see http://drupal.org/node/1354
202
 */
203
function _add_js_footnotes() {
204
  _add_js_domEvent();
205
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
206
}
207

    
208
/**
209
 * @todo Please document this function.
210
 * @see http://drupal.org/node/1354
211
 */
212
function _add_js_cluetip() {
213

    
214
  // TODO replace by
215
  // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
216
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.min.js');
217
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
218
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
219
  if(variable_get('cdm_js_devel_mode', FALSE)){
220
    drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
221
  }
222
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
223
  drupal_add_js("jQuery(document).ready(function(){
224
      jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
225
        splitTitle: '|',
226
        showTitle: true,
227
        activation: 'hover',
228
        sicky: true,
229
        arrows: true,
230
        dropShadow: false,
231
        cluetipClass: 'rounded'
232
      });
233
    });", array('type' => 'inline'));
234
}
235

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

    
242
  _add_js_domEvent(); // requires domEvent.js
243
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
244
}
245

    
246
/**
247
 * Adds the external javascript file for domEvent.js.
248
 *
249
 * @see drupal_add_js()
250
 */
251
function _add_js_domEvent() {
252
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
253
}
254

    
255

    
256
/* ====================== hook implementations ====================== */
257
/**
258
 * Implements hook_permission().
259
 *
260
 * Valid permissions for this module.
261
 *
262
 * @return array
263
 *   An array of valid permissions for the portfolio module.
264
 */
265
function cdm_dataportal_permission() {
266
  return array(
267
    'administer cdm_dataportal' => array(
268
      'title' => t('administer cdm_dataportal'),
269
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
270
    ),
271
    'cdm_dataportal view notes' => array(
272
      'title' => t('cdm_dataportal view notes'),
273
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
274
    ),
275
    // TODO Which other permissions are required?
276
    // -> check the WP6 requirements document.
277
  );
278
}
279

    
280
/**
281
 * Implements hook_menu().
282
 */
283
function cdm_dataportal_menu() {
284
  $items = array();
285

    
286
  // @see settings.php.
287
  cdm_dataportal_menu_admin($items);
288
  cdm_dataportal_menu_help($items);
289

    
290
  $items['cdm_dataportal/names'] = array(
291
    'page callback' => 'cdm_dataportal_view_names',
292
    'access arguments' => array('access content'),
293
    'type' => MENU_CALLBACK,
294
  );
295

    
296
  // Optional callback arguments: page.
297
  $items['cdm_dataportal/taxon'] = array(
298
    'page callback' => 'cdm_dataportal_taxon_page_view',
299
    'access arguments' => array('access content'),
300
    'type' => MENU_CALLBACK,
301
    // Expected callback arguments: uuid.
302
  );
303

    
304
  $items['cdm_dataportal/name'] = array(
305
    'page callback' => 'cdm_dataportal_name_page_view',
306
      /*
307
    'page arguments' => array(
308
       'taxon_name_uuid',
309
       'taxon_to_hide_uuid',
310
       'synonym_uuid' => NULL
311
      ),
312
      */
313
    'access arguments' => array('access content'),
314
    'type' => MENU_CALLBACK,
315
    // Expected callback arguments: uuid.
316
  );
317

    
318
  $items['cdm_dataportal/reference'] = array(
319
    'page callback' => 'cdm_dataportal_view_reference',
320
    'access arguments' => array('access content'),
321
    'type' => MENU_CALLBACK,
322
    // Expected callback arguments: uuid.
323
  );
324

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

    
332
  $items['cdm_dataportal/media'] = array(
333
    'page callback' => 'cdm_dataportal_view_media',
334
    'access arguments' => array('access content'),
335
    'type' => MENU_CALLBACK,
336
    // Expected callback arguments:
337
    // uuid, mediarepresentation_uuid, part_uuid or part#.
338
  );
339

    
340
  $items['cdm_dataportal/polytomousKey'] = array(
341
    'page callback' => 'cdm_dataportal_view_polytomousKey',
342
    'access arguments' => array('access content'),
343
    'type' => MENU_CALLBACK,
344
    // Expected callback arguments: polytomousKey->uuid.
345
  );
346

    
347
  $items['cdm_dataportal/search'] = array(
348
    'page callback' => 'cdm_dataportal_view_search_advanced',
349
    'access arguments' => array('access content'),
350
    'type' => MENU_CALLBACK,
351
  );
352

    
353
  $items['cdm_dataportal/search/advanced'] = array(
354
    'title' => 'Advanced',
355
    'page callback' => 'cdm_dataportal_view_search_advanced',
356
    'access arguments' => array('access content'),
357
    'type' => MENU_DEFAULT_LOCAL_TASK,
358
  );
359

    
360
  $items['cdm_dataportal/search/taxon_by_description'] = array(
361
    'title' => 'By description full text',
362
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
363
    'access arguments' => array('access content'),
364
    'type' => MENU_LOCAL_TASK,
365
  );
366

    
367
  $items['cdm_dataportal/search/results/taxon'] = array(
368
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
369
    'access arguments' => array('access content'),
370
    'type' => MENU_CALLBACK,
371
  );
372
  /*
373
   $items['cdm/xml2json'] = array(
374
   'page callback' => 'cdm_view_xml2json',
375
   'access arguments' => array('access content'),
376
   'type' => MENU_CALLBACK,
377
   );
378
   */
379

    
380
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
381
  // User configuration of cdm_dataportal.
382
  $items['user/%/cdm_dataportal'] = array(
383
    'title' => 'cdm_dataportal',
384
    'access arguments' => array('access content'),
385
    'page callback' => 'drupal_get_form',
386
    'page arguments' => array('cdm_dataportal_user_form'),
387
    'type' => MENU_LOCAL_TASK,
388
    'weight' => 10,
389
  );
390
  // }
391

    
392
  // 'May not cache' in D5.
393
  $items['cdm_dataportal/name/%'] = array(
394
    // 'page callback' => 'cdm_dataportal_view_name',
395
    'page callback' => 'cdm_dataportal_name_page_view',
396
    'page arguments' => array(2, 3, 4),
397
    'access arguments' => array('access content'),
398
    'type' => MENU_CALLBACK,
399
  );
400

    
401
  // --- Local tasks for Taxon.
402
  // --- tabbed taxon page
403
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
404
    $items['cdm_dataportal/taxon/%'] = array(
405
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
406
      'page callback' => 'cdm_dataportal_taxon_page_view',
407
      'access arguments' => array('access content'),
408
      'type' => MENU_CALLBACK,
409
      'weight' => 1,
410
      'page arguments' => array(2, "description")
411
      , // Expected callback arguments: name_uuid.
412
    );
413

    
414
    $items['cdm_dataportal/taxon/%/all'] = array(
415
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
416
      'page callback' => 'cdm_dataportal_taxon_page_view',
417
      'access arguments' => array('access content'),
418
      'type' => MENU_CALLBACK,
419
      'weight' => 2,
420
      'page arguments' => array(2, "all")
421
      , // Expected callback arguments: name_uuid.
422
    );
423

    
424
    $items['cdm_dataportal/taxon/%/description'] = array(
425
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
426
      'page callback' => 'cdm_dataportal_taxon_page_view',
427
      'access arguments' => array('access content'),
428
      'type' => MENU_DEFAULT_LOCAL_TASK,
429
      'weight' => 2,
430
      'page arguments' => array(2, "description")
431
      , // Expected callback arguments: name_uuid.
432
    );
433

    
434
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
435
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
436
      'page callback' => 'cdm_dataportal_taxon_page_view',
437
      'access arguments' => array('access content'),
438
      'type' => MENU_LOCAL_TASK,
439
      'weight' => 4,
440
      'page arguments' => array(2, "synonymy", 4)
441
      , // Expected callback arguments: name_uuid.
442
    );
443
    $items['cdm_dataportal/taxon/%/images'] = array(
444
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
445
      'page callback' => 'cdm_dataportal_taxon_page_view',
446
      'access arguments' => array('access content'),
447
      'type' => MENU_LOCAL_TASK,
448
      'weight' => 5,
449
      'page arguments' => array(2, "images")
450
      , // Expected callback arguments: name_uuid.
451
    );
452

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

    
463
    $items['cdm_dataportal/taxon/%/keys'] = array(
464
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
465
      'page callback' => 'cdm_dataportal_taxon_page_view',
466
      'access arguments' => array('access content'),
467
      'type' => MENU_LOCAL_TASK,
468
      'weight' => 6,
469
      'page arguments' => array(2, "keys")
470
      , // Expected callback arguments: name_uuid.
471
    );
472
  }
473

    
474
  // --- refresh link for all cdmnode types
475
  foreach (cdm_get_nodetypes() as $type=>$name) {
476
    $items['cdm_dataportal/' . $name . '/%/refresh'] = array(
477
        'title' => t('Refresh'),
478
        'page callback' => 'cdm_dataportal_refresh_node',
479
        'access arguments' => array('administer cdm_dataportal'),
480
        'type' => MENU_LOCAL_TASK,
481
        'weight' => 100,
482
        'page arguments' => array($name, 2)
483
    );
484
  }
485

    
486
  return $items;
487
}
488

    
489
/**
490
 * Implements hook_init().
491
 *
492
 * can be removed after fixing the FIXME below
493
 */
494
function cdm_dataportal_init() {
495
  //FIXME To add CSS or JS that should be present on all pages, modules
496
  //      should not implement this hook, but declare these files in their .info file.
497
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
498
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
499
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
500

    
501
  if(variable_get('cdm_debug_mode', FALSE)){
502
    $file = 'temporary://drupal_debug.txt';
503
    file_put_contents($file, 'CDM DEBUG LOG for ' . $_GET['q']. "\n"); // will overwrite the file
504
  }
505
}
506

    
507
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
508

    
509
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
510

    
511
  if($cdm_node_name == 'taxon' && variable_get('cdm_dataportal_taxonpage_tabs', 1)){
512
    // force reloading of all and notify user about this special loading
513
    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: ')
514
        . l('Back to tabbed taxon page', $base_path));
515
    $base_path .= '/all';
516
  } else {
517
    drupal_set_message(t('The level 2 cache has been cleared for this page'));
518
  }
519

    
520
  $parameters['cacheL2_refresh'] ='1';
521

    
522

    
523
  drupal_goto($base_path, array('query' => $parameters));
524
}
525

    
526
/**
527
 * The function generate form for own user cdm dataportal configurations.
528
 */
529
function cdm_dataportal_user_form($form, &$form_state) {
530
  global $user;
531
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
532

    
533
  $form['taxon_page_tabs'] = array(
534
      '#type' => 'fieldset',
535
      '#title' => t('Taxon page tabs'),
536
  );
537
  $form['taxon_page_tabs']['check'] = array(
538
    '#type' => 'checkbox',
539
    '#title' => t('Activate user default configuration'),
540
    '#default_value' => variable_get($checkbox_value, 0),
541
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
542
  );
543

    
544
  $form['taxon_page_tabs']['cdm_dataportal_user_form'] = array(
545
    '#type' => 'select',
546
    '#title' => t('Default tab to display'),
547
    '#default_value' => get_default_taxon_tab(TRUE),
548
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
549
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
550
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
551
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
552
  );
553

    
554
  $form['submit'] = array(
555
    '#type' => 'submit',
556
    '#value' => t('Submit'),
557
  );
558

    
559
  return $form;
560
}
561

    
562
/**
563
 * Form submission handler for user_form().
564
 *
565
 * Submits the user cdm dataportal configurations.
566
 */
567
function cdm_dataportal_user_form_submit($form, &$form_state) {
568
  global $user;
569
  $msg_type = 'status';
570
  $username = $user->name;
571
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
572

    
573
  // If is the right user the variables are setted.
574
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
575
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
576
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
577
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
578
    if ($form_state['values']['check']) {
579
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
580
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
581
        '!tab' => $variable[variable_get($variable_to_use, 0)],
582
        '!user' => $username,
583
      ))), $msg_type);
584
    }
585
    else {
586
      drupal_set_message(check_plain(t('The user default tab wont be used for
587
        the next taxon site, check the box if you want to use the user default configuration.')));
588
    }
589
    // Problem with the user id => variables wont be saved.
590
  }
591
  else {
592
    $msg_type = 'warning';
593
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
594
  }
595
}
596

    
597
/**
598
 * Implements hook_block_info().
599
 */
600
function cdm_dataportal_block_info() {
601

    
602
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
603
    // $block[1]["info"] = t("CDM DataPortal Credits");
604
    $block["2"] = array(
605
        "info" => t("CDM Search Taxa"),
606
        "cache" => DRUPAL_NO_CACHE
607
      );
608
    // $block[3]["info"] = t("CDM Filters");
609
    $block["4"]["info"] = t("CDM Dataportal Print");
610
    $block["keys"]["info"] = t("CDM identification keys");
611
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
612

    
613
    return $block;
614
}
615

    
616
/**
617
 * Implements hook_block_view().
618
 */
619
function cdm_dataportal_block_view($delta) {
620
  // TODO Rename block deltas (e.g. '2') to readable strings.
621
  switch ($delta) {
622
    // case 'delta-1':
623
    // $block['subject'] = t('Credits');
624
    // $block['content'] = theme('cdm_credits');
625
    // return $block;
626
    case '2':
627
      $block['subject'] = t('Search taxa');
628
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
629
      $block['content'] = drupal_render($form);
630

    
631
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
632
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
633
      }
634
      return $block;
635
    case '4':
636
      $block['subject'] = '';
637
      $block['content'] = theme('cdm_print_button');
638
      return $block;
639
    case "keys":
640
      $block['subject'] = t('Identification Keys');
641
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
642
      return $block;
643
    case "fundedByEDIT":
644
      // t('Funded by EDIT');
645
      $text = '<none>';
646
      $block['subject'] = $text;
647
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
648
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
649
        'attributes' => array("target" => "EDIT"),
650
        'absolute' => TRUE,
651
        'html' => TRUE,
652
      ));
653
      return $block;
654
  }
655
}
656

    
657
/*
658
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
659
 $_SESSION['cdm'] = NULL;
660
 if(is_string($cdm_ws_uri_update)){
661
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
662
 }
663
 }
664

    
665
 function cdm_dataportal_session_validate(){
666
 if(!isset($_SESSION['cdm']['ws_uri'])){
667
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
668
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
669
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
670
 }
671
 }
672
 */
673

    
674
/**
675
 * @todo Please document this function.
676
 * @see http://drupal.org/node/1354
677
 */
678
function cdm_taxonomictree_selector() {
679
  _add_js_treeselector();
680

    
681
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
682
  $out = drupal_render($form);
683
  return $out;
684
}
685

    
686
/**
687
 * @todo Please document this function.
688
 * @see http://drupal.org/node/1354
689
 */
690
function cdm_taxonomictree_selector_form($form, &$form_state) {
691

    
692
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
693
  $form['#action'] = $url;
694

    
695
  $form['var'] = array(
696
    '#weight' => -3,
697
    '#type' => 'hidden',
698
    '#value' => '[cdm][taxonomictree_uuid]',
699
  );
700

    
701
  $destination_array = drupal_get_destination();
702
  $destination = $destination_array['destination'];
703

    
704
  $form['destination'] = array(
705
    '#weight' => -3,
706
    '#type' => 'hidden',
707
    '#value' =>  $destination,
708
  );
709

    
710
  $form['val'] = array(
711
    '#type' => 'select',
712
    '#title' => t('Available classifications'),
713
    '#default_value' => get_taxonomictree_uuid_selected(),
714
    '#options' => cdm_get_taxontrees_as_options(),
715
  );
716

    
717
  return $form;
718

    
719
}
720

    
721
/* UNREACHABLE since action of form directly links to view.
722
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
723

    
724
 $_SESSION['cdm']['search'] = $form_values;
725
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
726
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
727
 //$paramstr = compose_url_prameterstr($form_values);
728
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
729
 }
730
 */
731
/* ====================== menu callback functions ====================== */
732
/**
733
 * @todo Please document this function.
734
 * @see http://drupal.org/node/1354
735
 */
736
/*
737
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
738
  static $comment_node_disabled =  0;
739
  static $comment_node_read_only =  1;
740
  static $comment_node_read_write =  2;
741

    
742
  if ($form_id == 'node_type_form'
743
   && isset($form['identity']['type'])
744
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
745
  ) {
746
    $form['workflow']['comment'] = array(
747
      '#type' => 'radios',
748
      '#title' => t('Default comment setting'),
749
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
750
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
751
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
752
    );
753
  }
754
}
755
*/
756

    
757
/**
758
 * Displays a list of the known taxonomic names.
759
 *
760
 * When the list of taxonomic names is displayed, long lists are split up into
761
 * multiple pages.
762
 *
763
 * TODO: Parameters are still preliminary.
764
 *
765
 * @param string $beginsWith
766
 * @param string $page
767
 *   Page number to diplay defaults to page 1.
768
 * @param bool $onlyAccepted
769
 */
770
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
771

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

    
774
  /*
775
  // FIXME the filter for accepted names will be a form element, thus this
776
  // widget should be generated via form api preferably as block.
777
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
778
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
779
  $out .= theme('cdm_listof_taxa', $taxonPager);
780
  return $out;
781
  */
782
}
783

    
784
/**
785
 * @todo Please document this function.
786
 * @see http://drupal.org/node/1354
787
 */
788
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
789

    
790
  cdm_check_valid_portal_page();
791

    
792
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
793
  return theme('cdm_reference_page', array('reference' => $reference));
794
}
795

    
796
/**
797
 * Created a view on a all references contained in the portal.
798
 *
799
 * This function is used at the path cdm_dataportal/reference/list
800
 */
801
function cdm_dataportal_view_reference_list($pageNumber) {
802
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
803
  return theme('cdm_reference_pager', array(
804
    'referencePager' => $referencePager,
805
    'path' => 'cdm_dataportal/reference/list/',
806
    ));
807
}
808

    
809
/**
810
 * @todo Please document this function.
811
 * @see http://drupal.org/node/1354
812
 */
813
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
814

    
815
  cdm_check_valid_portal_page();
816

    
817
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
818
  return theme('cdm_media_page', array(
819
    'media' => $media,
820
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
821
    'partId' => $part,
822
    ));
823
}
824

    
825
/**
826
 * @todo Please document this function.
827
 * @see http://drupal.org/node/1354
828
 */
829
function _load_taxonBase(&$taxonBase) {
830
  if (isset($taxonBase->uuid)) {
831
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
832
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
833
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
834
  }
835
}
836

    
837
/**
838
 * Loads the media associated to the given taxon from the cdm server.
839
 * The aggregation settings regarding taxon relathionships and
840
 * taxonnomic childen are taken into account.
841
 *
842
 * The media lists are cached in a static variable.
843
 *
844
 * @param Taxon $taxon
845
 *   A CDM Taxon entitiy
846
 *
847
 * @return array
848
 *   An array of CDM Media entities
849
 *
850
 */
851
function _load_media_for_taxon($taxon) {
852

    
853
  static $media = NULL;
854

    
855
  if(!isset($media)) {
856
    $media = array();
857
  }
858
  if (!isset($media[$taxon->uuid])) {
859

    
860
    // --- GET Images --- //
861
    $mediaQueryParameters = array(
862
        "type" => "ImageFile",
863
    );
864

    
865
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
866
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
867
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
868

    
869
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
870
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
871
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
872
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
873

    
874
    $ws_endpoint = NULL;
875
    if ( variable_get('cdm_images_include_children', 0) == 0) {
876
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
877
    } else {
878
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
879
    }
880

    
881
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
882
        array(
883
            $taxon->uuid,
884
        ),
885
        queryString($mediaQueryParameters)
886
       );
887
  }
888

    
889
  return $media[$taxon->uuid];
890
}
891

    
892
/**
893
 *
894
 * @param Taxon $taxon
895
 *   A CDM Taxon entitiy
896
 *
897
 * @return array
898
 *   An array of CDM SpecimenOrObservation entities
899
 *
900
function _load_occurences_for_taxon($taxon){
901

    
902
  static $occurences = NULL;
903

    
904
  if(!isset($occurences)) {
905
    $occurences = array();
906
  }
907

    
908
  if (!isset($occurences[$taxon->uuid])){
909

    
910
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
911
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
912
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
913

    
914
    $by_associatedtaxon_query = http_build_query(array(
915
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
916
        'relationships' => implode(',', $relationship_choice['direct']),
917
        'pageSize' => null // all hits in one page
918
    )
919
    );
920

    
921
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
922
        null,
923
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
924
    );
925

    
926

    
927
    if(isset($pager->records[0])){
928
      $occurences[$taxon->uuid] =  $pager->records;
929
    }
930
  }
931
  return $occurences[$taxon->uuid];
932
}
933
 */
934

    
935
/**
936
 * Gets a Drupal variable, string or array and returns it.
937
 *
938
 * Similar to the variable_get() function of Drupal, except that this function
939
 * is able to handle arrays correctly. This function is especially useful
940
 * when dealing with collections of setting form elements (#tree = TRUE).
941
 *
942
 * @param string $variableKey
943
 *   The Unique key of the Drupal variable in the Drupal variables table.
944
 * @param string $defaultValueString
945
 *   A string as for example derived from a CONSTANT.
946
 *
947
 * @return mixed
948
 *   Returns usally an array, depending on the nature of the variable.
949
 */
950
function mixed_variable_get($variableKey, $defaultValueString) {
951
  $systemDefaults = unserialize($defaultValueString);
952
  $storedSettings = variable_get($variableKey, array());
953
  if (is_array($storedSettings)) {
954
    $settings = array_merge($systemDefaults, $storedSettings);
955
  }
956
  else {
957
    $settings = $systemDefaults;
958
  }
959
  return $settings;
960
}
961

    
962
/**
963
 * Recusive funciton to convert an object into an array.
964
 * also subordinate objects will be converted.
965
 *
966
 * @param object $object
967
 * @return the array
968
 */
969
function convert_to_array($object) {
970
  if(is_object($object) || is_array($object)) {
971
    $array = (array)$object;
972
    foreach ($array as $key=>$value){
973
      $array[$key] = convert_to_array($value);
974
    }
975
    return $array;
976
  } else {
977
    return $object;
978
  }
979
}
980

    
981
/**
982
 * Wrapps the given $html string into a reder array suitable for drupal_render()
983
 *
984
 * @param string $html
985
 *   the html string, see
986
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
987
 * @param number $weight
988
 *   A positive or negative number (integer or decimal).
989
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
990
 *
991
 * @return
992
 *   A render array
993
 *
994
 */
995
function markup_to_render_array($html, $weight = 0) {
996
  return array(
997
          '#markup' => $html,
998
          '#weight' => $weight,
999
      );
1000
}
1001

    
1002
/**
1003
 * Loads the subgraph of a given PolytomousKeyNode.
1004
 *
1005
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1006
 * the CDM REST service.
1007
 *
1008
 * @param mixed $polytomousKeyNode
1009
 *   PolytomousKeyNode passed by reference.
1010
 *
1011
 * @return void
1012
 */
1013
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1014

    
1015
  if (!$polytomousKeyNode) {
1016
    return;
1017
  }
1018
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1019
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1020
    return;
1021
  }
1022
  if (!is_uuid($polytomousKeyNode->uuid)) {
1023
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1024
    return;
1025
  }
1026

    
1027
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1028

    
1029
  if (!$polytomousKeyNode) {
1030
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1031
    return;
1032
  }
1033

    
1034
  // Load children.
1035
  foreach ($polytomousKeyNode->children as &$childNode) {
1036
    _load_polytomousKeySubGraph($childNode);
1037
  }
1038

    
1039
  // Load subkey.
1040
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1041

    
1042
  // Load taxon.
1043
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1044
  _load_taxonBase($polytomousKeyNode->taxon);
1045
  return;
1046
}
1047

    
1048
/**
1049
 * @todo Please document this function.
1050
 * @see http://drupal.org/node/1354
1051
 */
1052
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1053

    
1054
  cdm_check_valid_portal_page();
1055

    
1056
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1057

    
1058
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1059
  if (is_array($sourcePager->records)) {
1060
    $polytomousKey->sources = $sourcePager->records;
1061
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1062
  }
1063

    
1064
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1065
  if (is_array($annotationPager->records)) {
1066
    $polytomousKey->annotations = $annotationPager->records;
1067
  }
1068

    
1069
  _load_polytomousKeySubGraph($polytomousKey->root);
1070
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1071
}
1072

    
1073
/**
1074
 * Creates a taxon page view or a chapter of it.
1075
 *
1076
 * The taxon page gives detailed information on a taxon, it shows:
1077
 *  - Taxon name.
1078
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1079
 *    heterotypic and finally followed by misapplied names.
1080
 *    The list is ordered historically.
1081
 *  - All description associated with the taxon.
1082
 *
1083
 * @param string $uuid
1084
 * @param string $chapter
1085
 *   Name of the part to display, valid values are:
1086
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1087
 *
1088
 * @return unknown_type
1089
 */
1090
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1091

    
1092
  cdm_check_valid_taxon_page($chapter);
1093
  cdm_dd("START OF TAXON PAGE [" . $chapter . "] " . $uuid . ' for ' . $_GET['q']);
1094
  // show a warning in case the javascript development mode is anabled
1095
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1096
    drupal_set_message(t('The !url1 is enabled.
1097
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1098
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1099
    )),
1100
    'warning'
1101
        );
1102
  }
1103

    
1104
  // Display the page for the taxon defined by $uuid.
1105
  // set_last_taxon_page_tab(arg(3));
1106
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1107
  if (!empty($taxonpage)) {
1108
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid);
1109
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1110
  }
1111
  else {
1112
    cdm_dd("END OF TAXON PAGE [" . $chapter . "] " . $uuid . ' !!! PAGE IS EMPTY !!!');
1113
    return '';
1114
  }
1115
}
1116

    
1117
/**
1118
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1119
 * which has two fields, one for the page title and one for the content. Later on in the
1120
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1121
 * function as the function parameters $title and $content.
1122
 *
1123
 * @param string $uuid
1124
 *   the uuid of the taxon to show
1125
 * @param string $chapter
1126
 *   Name of the part to display, valid values are:
1127
 *   'description', 'images', 'synonymy', 'all'.
1128
 *
1129
 * @return taxonpage object with the following fields:
1130
 *   - title : the title of the page
1131
 *   - content: the content of the page
1132
 *
1133
 */
1134
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1135
  // Taxon object.
1136
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1137
  if (empty($taxon)) {
1138
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1139
    return FALSE;
1140
  }
1141
  $taxonpage = new stdClass();
1142

    
1143
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1144
    'taxon' => $taxon
1145
  ));
1146

    
1147
  // Check if the taxon id contained in the currently selected tree.
1148
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1149

    
1150
  if (!$taxon_in_current_tree) {
1151
    $classifications = get_classifications_for_taxon($taxon);
1152
    if (count($classifications) == 0) {
1153
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1154
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1155
      ))), 'warning');
1156
    }
1157
    else {
1158
      $trees = '';
1159
      foreach ($classifications as $classification) {
1160
        if (isset($classification->titleCache)) {
1161
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1162
        }
1163
      }
1164

    
1165
      drupal_set_message(format_plural(count($trees),
1166
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1167
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1168
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1169
    }
1170
  }
1171

    
1172
  // Render the taxon page.
1173
  $render_array = compose_cdm_taxon_page($taxon, $chapter);
1174
  $taxonpage->content = drupal_render($render_array);
1175

    
1176
  return $taxonpage;
1177
}
1178

    
1179
/**
1180
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1181
 *
1182
 * The node page shows the taxon name title and the list of taxon related
1183
 * with such taxon. Name on the tree already in use.
1184
 *
1185
 * @param string $taxon_name_uuid
1186
 *   A taxon name UUID.
1187
 *
1188
 * @return mixed
1189
 *   The formatted name page as node.
1190
 */
1191
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1192

    
1193
  cdm_check_valid_portal_page();
1194

    
1195
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1196
  if (!empty($taxonname_page)) {
1197
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1198
  }
1199
  else {
1200
    return '';
1201
  }
1202
}
1203

    
1204
/**
1205
 * View function for a TaxonNameBase page.
1206
 *
1207
 * The name page lists all taxa for which the name specified by the
1208
 * $taxon_name_uuid is being used. I case there is only one name the
1209
 * page automatically redirects ti the according taxon page. Otherwise
1210
 * the list of names is displayed.
1211
 *
1212
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1213
 * list of taxa. This is useful for example when referencing from a taxon
1214
 * to the name page and the referring taxon should not be repeaded in the
1215
 * name page.
1216
 *
1217
 *
1218
 * @param UUID $taxon_name_uuid
1219
 *   The uuid of the CDM TaxonNameBase to show a name page for
1220
 * @param UUID $taxon_to_hide_uuid
1221
 *   A taxon which should not be displayed in the taxon list
1222
 * @param UUID $highlite_synonym_uuid
1223
 *   Optinal parameter wich takes another taxon uuid, if given the
1224
 *   target taxon pages will show the syonymy tab where the taxon
1225
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1226
 *   in case it is found on this page.
1227
 *
1228
 * @return object
1229
 *   An object with two fields:
1230
 *     - title: the page title
1231
 *     - content: the page content
1232
 */
1233
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1234
  // Getting the full taxonname object from the server.
1235
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1236
  if (!$taxon_name) {
1237
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1238
    return FALSE;
1239
  }
1240
  // Searching for all the taxa connected with the taxon name on the tree
1241
  // in use.
1242
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1243
  $request_params = array();
1244
  $request_params['query'] = $name_cache;
1245
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1246
  $request_params['doTaxa'] = 1;
1247
  $request_params['doSynonyms'] = 1;
1248
  $request_params['doTaxaByCommonNames'] = 0;
1249
  $request_params['matchMode'] = "EXACT";
1250
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1251

    
1252
  // Removing the name where we come from.
1253
  foreach ($taxon_pager->records as $k => &$taxon) {
1254
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1255
      unset($taxon_pager->records[$k]);
1256
    }
1257
  }
1258
  // Show the taxa list or go to the singular taxon.
1259
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1260
    $singleTaxon = array_pop($taxon_pager->records);
1261
    if ($singleTaxon->class != "Taxon") {
1262
      // It is a Synonym -> look for the accepted.
1263
      $accepted_taxa = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1264
      if (!empty($highlite_synonym_uuid)) {
1265
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1266
      }
1267
      else {
1268
        drupal_goto('cdm_dataportal/taxon/' . $accepted_taxa[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1269
      }
1270
    }
1271
    else {
1272
      // It is an accepted taxon.
1273
      if (!empty($highlite_synonym_uuid)) {
1274
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1275
      }
1276
      else {
1277
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1278
      }
1279
    }
1280
  }
1281
  else {// More than one taxa case.
1282
    $taxon_name_page = new stdClass();
1283
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1284
    if ($taxon_pager->records) {
1285
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1286
    }
1287
    else {
1288
      $taxon_name_page->content = 'This name has no taxa';
1289
    }
1290
    return $taxon_name_page;
1291
  }
1292
}
1293

    
1294
/**
1295
 * @todo Please document this function.
1296
 * @see http://drupal.org/node/1354
1297
 */
1298
function cdm_dataportal_view_search_advanced() {
1299

    
1300
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1301
  $form = array();
1302
  $form_state = array();
1303
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1304

    
1305
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1306

    
1307
}
1308

    
1309
/**
1310
 * @todo Please document this function.
1311
 * @see http://drupal.org/node/1354
1312
 */
1313
function cdm_dataportal_view_search_taxon_by_description() {
1314
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1315
  // $form_state = false;
1316
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1317
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1318

    
1319
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1320
}
1321

    
1322
/**
1323
 * Executes the search and generates the result list of taxa.
1324
 */
1325
function cdm_dataportal_view_search_results_taxon() {
1326

    
1327
  $taxonPager = cdm_dataportal_search_execute();
1328

    
1329
  $showThumbnails = do_showThumbnails();
1330

    
1331
  $setSessionUri = url('cdm_api/setvalue/session', array(
1332
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1333
  ));
1334

    
1335
  drupal_add_js('jQuery(document).ready(function() {
1336

    
1337
      // init
1338
      if(' . $showThumbnails . ' == 1){
1339
      jQuery(\'.media_gallery\').show(20);
1340
  } else {
1341
      jQuery(\'.media_gallery\').hide(20);
1342
  }
1343
      // add change hander
1344
      jQuery(\'#showThumbnails\').change(
1345
      function(event){
1346
      var state = 0;
1347
      if(jQuery(this).is(\':checked\')){
1348
      jQuery(\'.media_gallery\').show(20);
1349
      state = 1;
1350
  } else {
1351
      jQuery(\'.media_gallery\').hide(20);
1352
  }
1353
      // store state in session variable
1354
      var uri = \'' . $setSessionUri . '\' + state;
1355
      jQuery.get(uri);
1356
  });
1357
  });',
1358
  array('type' => "inline", 'scope' => JS_DEFAULT));
1359

    
1360
  drupal_set_title(t('Search results'), PASS_THROUGH);
1361

    
1362
  return theme('cdm_search_results', array(
1363
    'pager' => $taxonPager,
1364
    'path' => 'cdm_dataportal/search/results/taxon',
1365
    ));
1366
}
1367

    
1368
/**
1369
 * Provides the standart image wich indicated a loading process
1370
 *
1371
 * @return string
1372
 *  The img html tag
1373
 */
1374
function loading_image_html() {
1375
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1376
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1377
}
1378

    
1379
/**
1380
 * Returns the state of the the showThumbnails flag set in the
1381
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1382
 *
1383
 * @return boolean
1384
 *    returns 1 if the flag is set
1385
 */
1386
function do_showThumbnails() {
1387
  static $showThumbnails = null;
1388

    
1389
  if($showThumbnails == null) {
1390
    $showThumbnails = 0;
1391
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1392
      $showThumbnails = 0;
1393
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1394
      $showThumbnails = is_array($search_gallery_settings)
1395
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1396
        && (
1397
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1398
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1399
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1400
            )
1401
         ? 1 : 0;
1402

    
1403
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1404
    }
1405
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1406
    if (!is_numeric($showThumbnails)) {
1407
      $showThumbnails = 1;
1408
    }
1409
  }
1410

    
1411
  return $showThumbnails;
1412
}
1413

    
1414
/**
1415
 * View which transforms XML output from a given webservice endpoint into JSON.
1416
 */
1417
/*
1418
 function cdm_view_xml2json(){
1419
 $file = arg(2);
1420
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1421
 return  xml2json::transformXmlStringToJson($datastr);
1422
 }
1423
 */
1424

    
1425
/* ====================== other functions ====================== */
1426
/**
1427
 * Creates a URL to the taxon page specified by the $uuid parameter.
1428
 *
1429
 * The URL will be prepended with a path element to a specific taxon page tab.
1430
 *
1431
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1432
 * be set globally in the administrative settings or individually in the user
1433
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1434
 * the last portal will stay on this last tab.
1435
 *
1436
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1437
 * internal mechanism by a specific value.
1438
 *
1439
 * @param string $uuid
1440
 *   The UUID of the taxon.
1441
 * @param string $page_tab
1442
 *   Overwriting the preset mechanism by defining specific value for the
1443
 *   taxon page tab.
1444
 *
1445
 * @return string
1446
 *   The created URL.
1447
 */
1448
function path_to_taxon($uuid, $page_tab = FALSE) {
1449

    
1450
  $tab = get_default_taxon_tab();
1451
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1452

    
1453
  if (!$uuid) {
1454
    return FALSE;
1455
  }
1456

    
1457
  if ($page_tab) {
1458
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1459
  }
1460
  elseif (!$tab || strtolower($tab) == 'general') {
1461
    return 'cdm_dataportal/taxon/' . $uuid;
1462
  }
1463
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1464
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1465
  }
1466
  else {
1467
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1468
  }
1469
}
1470

    
1471
/**
1472
 * Creates a URL to show a synonmy in the according taxon page.
1473
 *
1474
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1475
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1476
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1477
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1478
 * in the page
1479
 *
1480
 * @param string $synonymUuid
1481
 *    The uuid of the synonym
1482
 * @param string $acceptedUuid
1483
 *    The uuid of the according accepted taxon
1484
 * @return string
1485
 *    The URL to show a synonmy in the according taxon page
1486
 */
1487
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1488
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1489
  return url($acceptedPath, array(
1490
      'query' => array(
1491
        // highlite the synony in the synonymy
1492
        'highlite' => $synonymUuid,
1493
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1494
        // see theme_taxon_page_title()
1495
        'acceptedFor' => $synonymUuid
1496
      ),
1497
      'fragment' => $synonymUuid
1498
  ));
1499

    
1500
}
1501

    
1502
/**
1503
 * Compses the drupal path to the key identified by the uuid.
1504
 *
1505
 * @param string $keyType
1506
 *    the key typer corresponds to the specific class of the CDM
1507
 *    IdentificationKey. Possible values are
1508
 *      -PolytomousKey
1509
 *      -MultimediaKey
1510
 *      - ...
1511
 * @param UUID $keyUuid
1512
 *   The UUID of the key
1513
 */
1514
function path_to_key($keyType, $keyUuid) {
1515
  if (!$keyUuid || !$keyType) {
1516
    return FALSE;
1517
  }
1518
  $keyType{0} = strtolower($keyType{0});
1519
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1520
}
1521

    
1522
/**
1523
 * @todo Please document this function.
1524
 * @see http://drupal.org/node/1354
1525
 */
1526
function path_to_reference($uuid) {
1527
  if (!$uuid) {
1528
    return FALSE;
1529
  }
1530
  return 'cdm_dataportal/reference/' . $uuid;
1531
}
1532

    
1533
/**
1534
 * @todo Please document this function.
1535
 * @see http://drupal.org/node/1354
1536
 */
1537
function path_to_name($name_uuid) {
1538
  $res = FALSE;
1539
  if ($name_uuid) {
1540
    $res = 'cdm_dataportal/name/' . $name_uuid;
1541
  }
1542
  return $res;
1543
}
1544

    
1545
/**
1546
 * @todo Please document this function.
1547
 * @see http://drupal.org/node/1354
1548
 */
1549
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1550
  if (!$uuid) {
1551
    return FALSE;
1552
  }
1553
  $out = 'cdm_dataportal/media/' . $uuid;
1554
  if ($representaion_uuid) {
1555
    $out .= '/' . $representaion_uuid;
1556
    if ($partId !== FALSE) {
1557
      $out .= '/' . $partId;
1558
    }
1559
  }
1560
  return $out;
1561
}
1562

    
1563
/**
1564
 * Compares thisRank with thatRank.
1565
 *
1566
 * Returns a negative integer, zero, or a positive integer
1567
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1568
 * e.g:
1569
 * <ul>
1570
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1571
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1572
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1573
 * </ul>
1574
 * <p>
1575
 * This compare logic of the underlying webservice is the
1576
 * <b>inverse logic</b> of the the one implemented in
1577
 * java.lang.Comparable#compareTo(java.lang.Object)
1578
 *
1579
 * @param $thisRankUuid
1580
 * @param $thatRankUuid
1581
 *
1582
 * @return int
1583
 *   A negative integer, zero, or a positive integer
1584
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1585
 */
1586
function rank_compare($thisRankUuid, $thatRankUuid) {
1587
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1588
  return $result->Integer;
1589
}
1590

    
1591
/**
1592
 * Composes an HTML element class attribute value composed of
1593
 * the shortname of the cdm class and the uuid of the entity.
1594
 * This class attribute should be used whereever an cdm-entity is rendered.
1595
 *
1596
 * These according class selectors in css must be escaped, eg:
1597
 *    .cdm\:TextData
1598
 *
1599
 * @param $cdmEntity
1600
 */
1601
function html_class_atttibute_ref($cdmEntity) {
1602

    
1603
  if (is_cdm_entity($cdmEntity)) {
1604
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1605
  }
1606
}
1607

    
1608
/**
1609
 * Preprocess the taggedName to normalize newly introduced
1610
 * tagtypes like hybridSign, separator, .. more?
1611
 *
1612
 * @param unknown_type $taggedTextList
1613
 */
1614
function normalize_TaggedName(&$taggedTextList) {
1615

    
1616
  if (is_array($taggedTextList)) {
1617

    
1618
    // First pass: rename.
1619
    for ($i = 0; $i < count($taggedTextList); $i++) {
1620

    
1621
      if ($taggedTextList[$i]->type == "hybridSign") {
1622
        $taggedTextList[$i]->type = "name";
1623
      }
1624
    }
1625

    
1626
    // Second pass: resolve separators.
1627
    $taggedNameListNew = array();
1628
    for ($i = 0; $i < count($taggedTextList); $i++) {
1629

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

    
1632
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1633
          $taggedName = $taggedTextList[$i];
1634
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1635
          $taggedNameListNew[] = $taggedName;
1636
          ++$i;
1637
          ++$i;
1638
        }
1639
      }
1640
      else {
1641
        $taggedNameListNew[] = $taggedTextList[$i];
1642
      }
1643
    }
1644
    $taggedTextList = $taggedNameListNew;
1645
  }
1646
}
1647

    
1648
/**
1649
 * Creates a short taxonname.
1650
 *
1651
 * The short name is created by using the taggename field of
1652
 * NameSTO or NameTO instances.
1653
 * If the taggename if empty the fullname will be returned.
1654
 *
1655
 * @param unknown_type $name
1656
 *   Name or TreeNode.
1657
 *
1658
 * @return string
1659
 */
1660
function cdm_dataportal_shortname_of($name) {
1661
  $nameStr = '';
1662

    
1663
  normalize_TaggedName($name->taggedTitle);
1664

    
1665
  // Get all tagged text tokens of the scientific name.
1666
  foreach ($name->taggedTitle as $tagtxt) {
1667
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1668
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1669
    }
1670
  }
1671
  $nameStr = trim($nameStr);
1672

    
1673
  if ($nameStr) {
1674

    
1675
    // Do not return short names for these.
1676
    if ($name->unplaced || $name->excluded) {
1677
      return $nameStr;
1678
    }
1679

    
1680
    /*
1681
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1682
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1683
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1684
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1685
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1686
    */
1687
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1688
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1689
      return $matches[1][0] . "." . $matches[3][0];
1690
    }
1691
    else {
1692
      return $nameStr;
1693
    }
1694
  }
1695
  else {
1696
    return $name->titleCache;
1697
  }
1698
}
1699

    
1700
/**
1701
 * Check if a taxon is accepted by the current taxonomic tree.
1702
 *
1703
 * @param mixed $taxon
1704
 *   The Taxon obkect to check.
1705
 *
1706
 * @return bool
1707
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1708
 */
1709
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1710

    
1711
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1712

    
1713
  if (isset($taxon->taxonNodes)) {
1714
    $taxonNodes = $taxon->taxonNodes;
1715
  }
1716
  else {
1717
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1718
  }
1719

    
1720
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1721
    foreach ($taxonNodes as $node) {
1722
      if (isset($node->classification)){
1723
        if(is_object($node->classification)) {
1724
          if ($node->classification->uuid == $defaultTreeUuid) {
1725
            return TRUE;
1726
          }
1727
        }
1728
        else {
1729
          if ($node->classification == $defaultTreeUuid) {
1730
            return TRUE;
1731
          }
1732
        }
1733
      }
1734
    }
1735
  }
1736

    
1737
  return FALSE;
1738
}
1739

    
1740
/**
1741
 * Workaround for missing original source type.
1742
 *
1743
 * idNamespace is always set in these cases.
1744
 * @todo improve documentation of this function.
1745
 *
1746
 * @param unknown_type $source
1747
 *
1748
 * @return unknown_type
1749
 */
1750
function _is_original_source_type($source) {
1751
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1752
}
1753

    
1754
/**
1755
 * @todo Please document this function.
1756
 * @see http://drupal.org/node/1354
1757
 */
1758
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1759
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1760
}
1761

    
1762
/**
1763
 * Gets the metadata info such as title or artist of a media file.
1764
 *
1765
 * The function tries at first to get all the info from the file metadata
1766
 * and if it is not avaible look at the media file info stored at the database.
1767
 *
1768
 * @param mixed $media
1769
 *   The media file object for which to get the metadata.
1770
 *
1771
 * @return array
1772
 *   The array with the available specified metadata info.
1773
 * TODO rename to read_media_metadata() and move to *.module.
1774
 */
1775
function cdm_read_media_metadata($media) {
1776

    
1777
  $metadata_caption = array(
1778
    'title' => '',// Media_metadata and media.
1779
    'artist' => '',// Media_metadata and media.
1780
    'rights',// Media_metadata and media.
1781
    'location',// Media_metadata.
1782
    'filename' => '',// Media.
1783
    'mediacreated' => '',// Media.
1784
    'description' => '',
1785
  );// Media.
1786

    
1787
  // Getting the media metadata.
1788
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1789
  $media_metadata_aux = (array) $media_metadata;
1790

    
1791
  // Filename.
1792
  if (!empty($media->representations[0]->parts[0]->uri)) {
1793
    $fileUri = $media->representations[0]->parts[0]->uri;
1794
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1795
    $metadata_caption['filename'] = $filename;
1796
  }
1797
  else {
1798
    $metadata_caption['filename'] = '';
1799
  }
1800

    
1801
  // Title.
1802
  if (!empty($media_metadata->ObjectName)) {
1803
    $metadata_caption['title'] = $media_metadata->ObjectName;
1804
  }
1805
  elseif (!empty($media_metadata_aux['Object Name'])) {
1806
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1807
  }
1808
  elseif (!empty($media->title_L10n)) {
1809
    $metadata_caption['title'] = $media->title_L10n;
1810
  }
1811
  elseif (!empty($media->titleCache)) {
1812
    $metadata_caption['title'] = $media->titleCache;
1813
  }
1814

    
1815
  // Append description to title.
1816
  if (!empty($media->description_L10n)) {
1817
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1818
  }
1819

    
1820
  // Artist.
1821
  if (!empty($media_metadata->Artist)) {
1822
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1823
  }
1824
  elseif (!empty($media->artist->titleCache)) {
1825
    $metadata_caption['artist'] = $media->artist->titleCache;
1826
  }
1827

    
1828
  // Copyright.
1829
  $metadata_caption['rights'] = array(
1830
    'copyright' => array('agentNames' => array()),
1831
    'license' => array(
1832
      'agentNames' => array(),
1833
      'types' => array(),
1834
      'abbreviatedTexts' => array(),
1835
      'uris' => array(),
1836
    ),
1837
  );
1838
  if (!empty($media_metadata->Copyright)) {
1839
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1840
  }
1841
  elseif (isset($media->rights) && is_array($media->rights)) {
1842
    foreach ($media->rights as $right) {
1843
      switch ($right->term->uuid) {
1844
        case UUID_RIGHTS_LICENCE:
1845
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1846
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1847
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1848
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1849
          break;
1850
        case UUID_RIGHTS_COPYRIGHT:
1851
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1852
          break;
1853
      }
1854
    }
1855
  }
1856
  else {
1857
    $metadata_caption['rights']['agentNames'][] = '';
1858
  }
1859

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

    
1863
  // Location.
1864
  $metadata_caption['location'] = array();
1865
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1866
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1867
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1868
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1869

    
1870
  /*
1871
   // Creation date.
1872
   if($media_metadata["Modify Date"])
1873
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1874
   else
1875
   $metadata_caption['mediacreated'] = $media->created;
1876
   */
1877

    
1878
  // Returned value.
1879
  return $metadata_caption;
1880
}
1881

    
1882
/**
1883
 * Collects all the media from a list of description elements.
1884
 *
1885
 * @param array $descriptionElements
1886
 *   The description elements from which to collect the media.
1887
 *
1888
 * @return array
1889
 *   The output with all the collected media.
1890
 */
1891
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1892

    
1893
  $outArrayOfMedia = array();
1894

    
1895
  // Avoiding a warning box in Drupal for Flora Malesiana.
1896
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1897
    foreach ($descriptionElements as $descriptionElement) {
1898
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1899
        foreach ($descriptionElement->media as $media) {
1900
          if (is_object($media)) {
1901
            $outArrayOfMedia[] = $media;
1902
          }
1903
        }
1904
      }
1905
    }
1906
  }
1907
  return $outArrayOfMedia;
1908
}
1909

    
1910
/**
1911
 * @todo Please document this function.
1912
 * @see http://drupal.org/node/1354
1913
 *
1914
 * @param array $cdmBase_list
1915
 *   An array of CdmBase instances or a single instance.
1916
 * @param string $footnote_list_key
1917
 *
1918
 * @return unknown
1919
 */
1920
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1921

    
1922
   static $annotations_types_filter = null;
1923
   if(!$annotations_types_filter) {
1924
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1925
   }
1926

    
1927
  $footNoteKeys = array();
1928

    
1929
  // Is argument cdmBase an array?
1930
  if (!is_array($cdmBase_list)) {
1931
    $cdmBase_array = array();
1932
    $cdmBase_array[] = $cdmBase_list;
1933
  }
1934
  else {
1935
    $cdmBase_array = $cdmBase_list;
1936
  }
1937

    
1938
  // Getting the key for the footnotemanager.
1939
  if (isset($footnote_list_key)) {
1940
    $footnoteListKey = $footnote_list_key;
1941
  }
1942
  else {
1943
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1944
  }
1945

    
1946
  // Adding the footnotes keys.
1947
  foreach ($cdmBase_array as $cdmBase_element) {
1948
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1949
    if (is_array($annotations)) {
1950
      foreach ($annotations as $annotation) {
1951
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1952
      }
1953
    }
1954
  }
1955

    
1956
  return $footNoteKeys;
1957
}
1958

    
1959
// @WA Comment: should this not be a theme function?
1960
/**
1961
 *  Creates a CDM Dynabox.
1962
 * @param string $dynabox_id
1963
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
1964
 * @param string $label
1965
 *   The clickable text to show.
1966
 * @param string $content_url
1967
 *   The cdm REST service request url wich will deliver the content to be shown
1968
 *   once the dynabox toggles open.
1969
 * @param string $theme
1970
 *   The theme to be used for rendering the cdm REST service reponse with is
1971
 *   returned from the $content_url.
1972
 * @param string $link_alt_text
1973
 *   The value for the alt attribute of the dynabox link.
1974
 * @param array $enclosingtags
1975
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
1976
 *   element itself, $enclosingtags[1] is the tag to be used for the
1977
 *   dynabox_content (optional)
1978
 * @param string $open_callback
1979
 *   optional javascript call back function to be triggered after toggeling the box to
1980
 *   the open state.
1981
 * @param string $close_callback
1982
 *   optional javascript call back function to be triggered after toggeling the box to
1983
 *   the closed state.
1984
 *
1985
 * @return string
1986
 *   Returns HTML for a dynabox.
1987
 */
1988
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
1989
  $out = '';
1990

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

    
1994
  _add_js_domEvent(); // requires domEvent.js
1995
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
1996
  drupal_add_js("
1997
  jQuery(document).ready(
1998
      function() {
1999
        dynabox('". $dynabox_id ."',
2000
          {
2001
            open_callback: " . $open_callback .",
2002
            close_callback: " . $close_callback ."
2003
          }
2004
        );
2005
      }
2006
   );",
2007
   array(
2008
    'type'=>'inline',
2009
    'scope'=>'footer'
2010
    )
2011
  );
2012

    
2013
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2014
  $out .= '<!-- ' . $content_url . ' -->';
2015
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2016
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '>' . loading_image_html() . '</' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2017
  $out .= '</' . $enclosingtags[0] . '>';
2018
  return $out;
2019
}
2020

    
2021
/**
2022
 * Checks whether a feature has any description elements.
2023
 *
2024
 * @param mixed $featureNode
2025
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2026
 *
2027
 * @see _mergeFeatureTreeDescriptions()
2028
 *
2029
 * @return bool
2030
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2031
 *   contains at least one non empty TextData or at least one DescriptionElement
2032
 *   of an other type. A TextData element holding a multilanguageText or a
2033
 *   source reference is considered to be not empty.
2034
 */
2035
function hasFeatureNodeDescriptionElements($featureNode) {
2036

    
2037
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2038
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2039
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2040
        return TRUE;
2041
      }
2042
    }
2043
  }
2044
  elseif (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2045
    foreach ($featureNode->childNodes as $child) {
2046
      if (hasFeatureNodeDescriptionElements($child)) {
2047
        return TRUE;
2048
      }
2049
    }
2050
  }
2051
  return FALSE;
2052
}
2053

    
2054
/**
2055
 * Checks if the current page is a valid taxon portal page and responds with HTTP status 404 (not found) otherwise
2056
 *
2057
 * @param $chapter
2058
 *   The taxon page chapter or part
2059
 */
2060
function cdm_check_valid_taxon_page($chapter){
2061
  static $taxon_tabs = null;
2062

    
2063
  cdm_check_valid_portal_page();
2064

    
2065
  if($taxon_tabs == null){
2066
    $taxon_tabs = array('all', 'description');
2067
    foreach(get_taxon_tabs_list() as $tab){
2068
      $taxon_tabs[] = strtolower($tab);
2069
    }
2070
  }
2071

    
2072
  if(!in_array($chapter, $taxon_tabs)){
2073
    // oops this is not a valid chapter name
2074
    http_send_status(404); // 404 = Not Found
2075
  }
2076

    
2077
}
2078

    
2079
/**
2080
 * Checks if the current page is a valid portal page and responds with HTTP status 404 (not found) otherwise
2081
 *
2082
 * @param $chapter
2083
 *   The taxon page chapter or part
2084
 */
2085
function cdm_check_valid_portal_page(){
2086
  $ends_with_file_suffix_pattern = '/\/[^\.\/]*[\.][^\.\/]*$/';
2087
  if(preg_match($ends_with_file_suffix_pattern, $_GET['q'])){
2088
    // oops this urls ends with a file_suffix and thus does not refer to a portal page
2089
    http_send_status(404); // 404 = Not Found
2090
    exit('HTTP 404');
2091
  }
2092
}
(7-7/14)