Project

General

Profile

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

    
126
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers,
127
    array(
128
      'type' => 'file',
129
      'weight' => JS_LIBRARY,
130
      'cache' => FALSE,
131
    )
132
  );
133
// TODO remove if not needed (Andreas Kohlbecker 30.07.2013)
134
//   drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $proj4js,
135
//     array(
136
//       'type' => 'file',
137
//       'weight' => JS_LIBRARY,
138
//       'cache' => FALSE,
139
//     )
140
//   );
141
}
142

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

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

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

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

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

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

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

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

    
253

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

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

    
284
  // @see settings.php.
285
  cdm_dataportal_menu_admin($items);
286
  cdm_dataportal_menu_help($items);
287

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
484
  return $items;
485
}
486

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

    
500
function cdm_dataportal_refresh_node($cdm_node_name, $uuid, $parameters = array()){
501

    
502
  $base_path = 'cdm_dataportal/' . $cdm_node_name . '/' . $uuid;
503

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

    
513
  $parameters['cacheL2_refresh'] ='1';
514

    
515

    
516
  drupal_goto($base_path, array('query' => $parameters));
517
}
518

    
519
/**
520
 * The function generate form for own user cdm dataportal configurations.
521
 */
522
function cdm_dataportal_user_form($form, &$form_state) {
523
  global $user;
524
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
525

    
526
  $form['taxon_page_tabs'] = array(
527
      '#type' => 'fieldset',
528
      '#title' => t('Taxon page tabs'),
529
  );
530
  $form['taxon_page_tabs']['check'] = array(
531
    '#type' => 'checkbox',
532
    '#title' => t('Activate user default configuration'),
533
    '#default_value' => variable_get($checkbox_value, 0),
534
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
535
  );
536

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

    
547
  $form['submit'] = array(
548
    '#type' => 'submit',
549
    '#value' => t('Submit'),
550
  );
551

    
552
  return $form;
553
}
554

    
555
/**
556
 * Form submission handler for user_form().
557
 *
558
 * Submits the user cdm dataportal configurations.
559
 */
560
function cdm_dataportal_user_form_submit($form, &$form_state) {
561
  global $user;
562
  $msg_type = 'status';
563
  $username = $user->name;
564
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
565

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

    
590
/**
591
 * Implements hook_block_info().
592
 */
593
function cdm_dataportal_block_info() {
594

    
595
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
596
    // $block[1]["info"] = t("CDM DataPortal Credits");
597
    $block["2"] = array(
598
        "info" => t("CDM Search Taxa"),
599
        "cache" => DRUPAL_NO_CACHE
600
      );
601
    // $block[3]["info"] = t("CDM Filters");
602
    $block["4"]["info"] = t("CDM Dataportal Print");
603
    $block["keys"]["info"] = t("CDM identification keys");
604
    $block["uses"]["info"] = t("CDM Uses");
605
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
606

    
607
    return $block;
608
}
609

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

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

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

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

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

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

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

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

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

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

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

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

    
716
  return $form;
717

    
718
}
719

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

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

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

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

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

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

    
783
/**
784
 * @todo Please document this function.
785
 * @see http://drupal.org/node/1354
786
 */
787
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
788
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
789
  return theme('cdm_reference_page', array('reference' => $reference));
790
}
791

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

    
805
/**
806
 * @todo Please document this function.
807
 * @see http://drupal.org/node/1354
808
 */
809
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
810
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
811
  return theme('cdm_media_page', array(
812
    'media' => $media,
813
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
814
    'partId' => $part,
815
    ));
816
}
817

    
818
/**
819
 * @todo Please document this function.
820
 * @see http://drupal.org/node/1354
821
 */
822
function _load_taxonBase(&$taxonBase) {
823
  if (isset($taxonBase->uuid)) {
824
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
825
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
826
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
827
  }
828
}
829

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

    
846
  static $media = NULL;
847

    
848
  if(!isset($media)) {
849
    $media = array();
850
  }
851
  if (!isset($media[$taxon->uuid])) {
852

    
853
    // --- GET Images --- //
854
    $mediaQueryParameters = array(
855
        "type" => "ImageFile",
856
    );
857

    
858
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
859
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
860
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
861

    
862
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
863
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
864
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
865
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
866

    
867
    $ws_endpoint = NULL;
868
    if ( variable_get('cdm_images_include_children', 0) == 0) {
869
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
870
    } else {
871
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
872
    }
873

    
874
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
875
        array(
876
            $taxon->uuid,
877
        ),
878
        queryString($mediaQueryParameters)
879
       );
880
  }
881

    
882
  return $media[$taxon->uuid];
883
}
884

    
885
/**
886
 *
887
 * @param Taxon $taxon
888
 *   A CDM Taxon entitiy
889
 *
890
 * @return array
891
 *   An array of CDM SpecimenOrObservation entities
892
 *
893
function _load_occurences_for_taxon($taxon){
894

    
895
  static $occurences = NULL;
896

    
897
  if(!isset($occurences)) {
898
    $occurences = array();
899
  }
900

    
901
  if (!isset($occurences[$taxon->uuid])){
902

    
903
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
904
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
905
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
906

    
907
    $by_associatedtaxon_query = http_build_query(array(
908
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
909
        'relationships' => implode(',', $relationship_choice['direct']),
910
        'pageSize' => null // all hits in one page
911
    )
912
    );
913

    
914
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
915
        null,
916
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
917
    );
918

    
919

    
920
    if(isset($pager->records[0])){
921
      $occurences[$taxon->uuid] =  $pager->records;
922
    }
923
  }
924
  return $occurences[$taxon->uuid];
925
}
926
 */
927

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

    
955
/**
956
 * Recusive funciton to convert an object into an array.
957
 * also subordinate objects will be converted.
958
 *
959
 * @param object $object
960
 * @return the array
961
 */
962
function convert_to_array($object) {
963
  if(is_object($object) || is_array($object)) {
964
    $array = (array)$object;
965
    foreach ($array as $key=>$value){
966
      $array[$key] = convert_to_array($value);
967
    }
968
    return $array;
969
  } else {
970
    return $object;
971
  }
972
}
973

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

    
995
/**
996
 * Loads the subgraph of a given PolytomousKeyNode.
997
 *
998
 * Loads the subgraph of the given PolytomousKeyNode recursively from
999
 * the CDM REST service.
1000
 *
1001
 * @param mixed $polytomousKeyNode
1002
 *   PolytomousKeyNode passed by reference.
1003
 *
1004
 * @return void
1005
 */
1006
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1007

    
1008
  if (!$polytomousKeyNode) {
1009
    return;
1010
  }
1011
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1012
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1013
    return;
1014
  }
1015
  if (!is_uuid($polytomousKeyNode->uuid)) {
1016
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1017
    return;
1018
  }
1019

    
1020
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1021

    
1022
  if (!$polytomousKeyNode) {
1023
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1024
    return;
1025
  }
1026

    
1027
  // Load children.
1028
  foreach ($polytomousKeyNode->children as &$childNode) {
1029
    _load_polytomousKeySubGraph($childNode);
1030
  }
1031

    
1032
  // Load subkey.
1033
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1034

    
1035
  // Load taxon.
1036
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1037
  _load_taxonBase($polytomousKeyNode->taxon);
1038
  return;
1039
}
1040

    
1041
/**
1042
 * @todo Please document this function.
1043
 * @see http://drupal.org/node/1354
1044
 */
1045
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1046
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1047

    
1048
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1049
  if (is_array($sourcePager->records)) {
1050
    $polytomousKey->sources = $sourcePager->records;
1051
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1052
  }
1053

    
1054
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1055
  if (is_array($annotationPager->records)) {
1056
    $polytomousKey->annotations = $annotationPager->records;
1057
  }
1058

    
1059
  _load_polytomousKeySubGraph($polytomousKey->root);
1060
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1061
}
1062

    
1063
/**
1064
 * Creates a taxon page view or a chapter of it.
1065
 *
1066
 * The taxon page gives detailed information on a taxon, it shows:
1067
 *  - Taxon name.
1068
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1069
 *    heterotypic and finally followed by misapplied names.
1070
 *    The list is ordered historically.
1071
 *  - All description associated with the taxon.
1072
 *
1073
 * @param string $uuid
1074
 * @param string $chapter
1075
 *   Name of the part to display, valid values are:
1076
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1077
 *
1078
 * @return unknown_type
1079
 */
1080
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1081

    
1082
  // show a warning in case the javascript development mode is anabled
1083
  if(variable_get('cdm_js_devel_mode', FALSE)) {
1084
    drupal_set_message(t('The !url1 is enabled.
1085
        WARNING: this is a performance penalty and must be turned off on production websites.', array(
1086
          '!url1' => l('java-script development mode', 'admin/config/cdm_dataportal/settings', array('fragment' => 'edit-cdm-js-devel-mode'))
1087
    )),
1088
    'warning'
1089
        );
1090
  }
1091

    
1092
  // Display the page for the taxon defined by $uuid.
1093
  // set_last_taxon_page_tab(arg(3));
1094
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1095
  if (!empty($taxonpage)) {
1096
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1097
  }
1098
  else {
1099
    return '';
1100
  }
1101
}
1102

    
1103
/**
1104
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1105
 * which has two fields, one for the page title and one for the content. Later on in the
1106
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1107
 * function as the function parameters $title and $content.
1108
 *
1109
 * @param string $uuid
1110
 *   the uuid of the taxon to show
1111
 * @param string $chapter
1112
 *   Name of the part to display, valid values are:
1113
 *   'description', 'images', 'synonymy', 'all'.
1114
 *
1115
 * @return taxonpage object with the following fields:
1116
 *   - title : the title of the page
1117
 *   - content: the content of the page
1118
 *
1119
 */
1120
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1121
  // Taxon object.
1122
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1123
  if (empty($taxon)) {
1124
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1125
    return FALSE;
1126
  }
1127
  $taxonpage = new stdClass();
1128

    
1129
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1130
    'taxon' => $taxon
1131
  ));
1132

    
1133
  // Check if the taxon id contained in the currently selected tree.
1134
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1135

    
1136
  if (!$taxon_in_current_tree) {
1137
    $classifications = get_classifications_for_taxon($taxon);
1138
    if (count($classifications) == 0) {
1139
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1140
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1141
      ))), 'warning');
1142
    }
1143
    else {
1144
      $trees = '';
1145
      foreach ($classifications as $classification) {
1146
        if (isset($classification->titleCache)) {
1147
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1148
        }
1149
      }
1150

    
1151
      drupal_set_message(format_plural(count($trees),
1152
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1153
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1154
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1155
    }
1156
  }
1157

    
1158
  // Render the taxon page.
1159
  $taxonpage->content = theme('cdm_taxon_page', array(
1160
    'taxon' => $taxon,
1161
    'page_part' => $chapter,
1162
  ));
1163

    
1164
  return $taxonpage;
1165
}
1166

    
1167
/**
1168
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1169
 *
1170
 * The node page shows the taxon name title and the list of taxon related
1171
 * with such taxon. Name on the tree already in use.
1172
 *
1173
 * @param string $taxon_name_uuid
1174
 *   A taxon name UUID.
1175
 *
1176
 * @return mixed
1177
 *   The formatted name page as node.
1178
 */
1179
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1180

    
1181
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1182
  if (!empty($taxonname_page)) {
1183
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1184
  }
1185
  else {
1186
    return '';
1187
  }
1188
}
1189

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

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

    
1280
/**
1281
 * @todo Please document this function.
1282
 * @see http://drupal.org/node/1354
1283
 */
1284
function cdm_dataportal_view_search_advanced() {
1285

    
1286
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1287
  $form = array();
1288
  $form_state = array();
1289
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1290

    
1291
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1292

    
1293
}
1294

    
1295
/**
1296
 * @todo Please document this function.
1297
 * @see http://drupal.org/node/1354
1298
 */
1299
function cdm_dataportal_view_search_taxon_by_description() {
1300
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1301
  // $form_state = false;
1302
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1303
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1304

    
1305
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1306
}
1307

    
1308
/**
1309
 * Executes the search and generates the result list of taxa.
1310
 */
1311
function cdm_dataportal_view_search_results_taxon() {
1312

    
1313
  $taxonPager = cdm_dataportal_search_execute();
1314

    
1315
  $showThumbnails = do_showThumbnails();
1316

    
1317
  $setSessionUri = url('cdm_api/setvalue/session', array(
1318
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1319
  ));
1320

    
1321
  drupal_add_js('jQuery(document).ready(function() {
1322

    
1323
      // init
1324
      if(' . $showThumbnails . ' == 1){
1325
      jQuery(\'.media_gallery\').show(20);
1326
  } else {
1327
      jQuery(\'.media_gallery\').hide(20);
1328
  }
1329
      // add change hander
1330
      jQuery(\'#showThumbnails\').change(
1331
      function(event){
1332
      var state = 0;
1333
      if(jQuery(this).is(\':checked\')){
1334
      jQuery(\'.media_gallery\').show(20);
1335
      state = 1;
1336
  } else {
1337
      jQuery(\'.media_gallery\').hide(20);
1338
  }
1339
      // store state in session variable
1340
      var uri = \'' . $setSessionUri . '\' + state;
1341
      jQuery.get(uri);
1342
  });
1343
  });',
1344
  array('type' => "inline", 'scope' => JS_DEFAULT));
1345

    
1346
  drupal_set_title(t('Search results'), PASS_THROUGH);
1347

    
1348
  return theme('cdm_search_results', array(
1349
    'pager' => $taxonPager,
1350
    'path' => 'cdm_dataportal/search/results/taxon',
1351
    ));
1352
}
1353

    
1354
/**
1355
 * Provides the standart image wich indicated a loading process
1356
 *
1357
 * @return string
1358
 *  The img html tag
1359
 */
1360
function loading_image_html() {
1361
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1362
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1363
}
1364

    
1365
/**
1366
 * Returns the state of the the showThumbnails flag set in the
1367
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1368
 *
1369
 * @return boolean
1370
 *    returns 1 if the flag is set
1371
 */
1372
function do_showThumbnails() {
1373
  static $showThumbnails = null;
1374

    
1375
  if($showThumbnails == null) {
1376
    $showThumbnails = 0;
1377
    if (!isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1378
      $showThumbnails = 0;
1379
      $search_gallery_settings = variable_get(CDM_DATAPORTAL_SEARCH_GALLERY_NAME, null);
1380
      $showThumbnails = is_array($search_gallery_settings)
1381
        && isset($search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'])
1382
        && (
1383
            $search_gallery_settings['cdm_dataportal_show_taxon_thumbnails'] +
1384
            $search_gallery_settings['cdm_dataportal_show_synonym_thumbnails'] +
1385
            $search_gallery_settings['cdm_dataportal_show_thumbnail_captions'] > 0
1386
            )
1387
         ? 1 : 0;
1388

    
1389
       drupal_array_set_nested_value($_SESSION, array('pageoption', 'searchtaxa', 'showThumbnails'), $showThumbnails);
1390
    }
1391
    $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1392
    if (!is_numeric($showThumbnails)) {
1393
      $showThumbnails = 1;
1394
    }
1395
  }
1396

    
1397
  return $showThumbnails;
1398
}
1399

    
1400
/**
1401
 * View which transforms XML output from a given webservice endpoint into JSON.
1402
 */
1403
/*
1404
 function cdm_view_xml2json(){
1405
 $file = arg(2);
1406
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1407
 return  xml2json::transformXmlStringToJson($datastr);
1408
 }
1409
 */
1410

    
1411
/* ====================== other functions ====================== */
1412
/**
1413
 * Creates a URL to the taxon page specified by the $uuid parameter.
1414
 *
1415
 * The URL will be prepended with a path element to a specific taxon page tab.
1416
 *
1417
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1418
 * be set globally in the administrative settings or individually in the user
1419
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1420
 * the last portal will stay on this last tab.
1421
 *
1422
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1423
 * internal mechanism by a specific value.
1424
 *
1425
 * @param string $uuid
1426
 *   The UUID of the taxon.
1427
 * @param string $page_tab
1428
 *   Overwriting the preset mechanism by defining specific value for the
1429
 *   taxon page tab.
1430
 *
1431
 * @return string
1432
 *   The created URL.
1433
 */
1434
function path_to_taxon($uuid, $page_tab = FALSE) {
1435

    
1436
  $tab = get_default_taxon_tab();
1437
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1438

    
1439
  if (!$uuid) {
1440
    return FALSE;
1441
  }
1442

    
1443
  if ($page_tab) {
1444
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1445
  }
1446
  elseif (!$tab || strtolower($tab) == 'general') {
1447
    return 'cdm_dataportal/taxon/' . $uuid;
1448
  }
1449
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1450
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1451
  }
1452
  else {
1453
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1454
  }
1455
}
1456

    
1457
/**
1458
 * Creates a URL to show a synonmy in the according taxon page.
1459
 *
1460
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1461
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1462
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1463
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1464
 * in the page
1465
 *
1466
 * @param string $synonymUuid
1467
 *    The uuid of the synonym
1468
 * @param string $acceptedUuid
1469
 *    The uuid of the according accepted taxon
1470
 * @return string
1471
 *    The URL to show a synonmy in the according taxon page
1472
 */
1473
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1474
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1475
  return url($acceptedPath, array(
1476
      'query' => array(
1477
        // highlite the synony in the synonymy
1478
        'highlite' => $synonymUuid,
1479
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1480
        // see theme_taxon_page_title()
1481
        'acceptedFor' => $synonymUuid
1482
      ),
1483
      'fragment' => $synonymUuid
1484
  ));
1485

    
1486
}
1487

    
1488
/**
1489
 * Compses the drupal path to the key identified by the uuid.
1490
 *
1491
 * @param string $keyType
1492
 *    the key typer corresponds to the specific class of the CDM
1493
 *    IdentificationKey. Possible values are
1494
 *      -PolytomousKey
1495
 *      -MultimediaKey
1496
 *      - ...
1497
 * @param UUID $keyUuid
1498
 *   The UUID of the key
1499
 */
1500
function path_to_key($keyType, $keyUuid) {
1501
  if (!$keyUuid || !$keyType) {
1502
    return FALSE;
1503
  }
1504
  $keyType{0} = strtolower($keyType{0});
1505
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1506
}
1507

    
1508
/**
1509
 * @todo Please document this function.
1510
 * @see http://drupal.org/node/1354
1511
 */
1512
function path_to_reference($uuid) {
1513
  if (!$uuid) {
1514
    return FALSE;
1515
  }
1516
  return 'cdm_dataportal/reference/' . $uuid;
1517
}
1518

    
1519
/**
1520
 * @todo Please document this function.
1521
 * @see http://drupal.org/node/1354
1522
 */
1523
function path_to_name($name_uuid) {
1524
  $res = FALSE;
1525
  if ($name_uuid) {
1526
    $res = 'cdm_dataportal/name/' . $name_uuid;
1527
  }
1528
  return $res;
1529
}
1530

    
1531
/**
1532
 * @todo Please document this function.
1533
 * @see http://drupal.org/node/1354
1534
 */
1535
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1536
  if (!$uuid) {
1537
    return FALSE;
1538
  }
1539
  $out = 'cdm_dataportal/media/' . $uuid;
1540
  if ($representaion_uuid) {
1541
    $out .= '/' . $representaion_uuid;
1542
    if ($partId !== FALSE) {
1543
      $out .= '/' . $partId;
1544
    }
1545
  }
1546
  return $out;
1547
}
1548

    
1549
/**
1550
 * Compares thisRank with thatRank.
1551
 *
1552
 * Returns a negative integer, zero, or a positive integer
1553
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1554
 * e.g:
1555
 * <ul>
1556
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1557
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1558
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1559
 * </ul>
1560
 * <p>
1561
 * This compare logic of the underlying webservice is the
1562
 * <b>inverse logic</b> of the the one implemented in
1563
 * java.lang.Comparable#compareTo(java.lang.Object)
1564
 *
1565
 * @param $thisRankUuid
1566
 * @param $thatRankUuid
1567
 *
1568
 * @return int
1569
 *   A negative integer, zero, or a positive integer
1570
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1571
 */
1572
function rank_compare($thisRankUuid, $thatRankUuid) {
1573
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1574
  return $result->Integer;
1575
}
1576

    
1577
/**
1578
 * Composes an HTML element class attribute value composed of
1579
 * the shortname of the cdm class and the uuid of the entity.
1580
 * This class attribute should be used whereever an cdm-entity is rendered.
1581
 *
1582
 * These according class selectors in css must be escaped, eg:
1583
 *    .cdm\:TextData
1584
 *
1585
 * @param $cdmEntity
1586
 */
1587
function html_class_atttibute_ref($cdmEntity) {
1588

    
1589
  if (is_cdm_entity($cdmEntity)) {
1590
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1591
  }
1592
}
1593

    
1594
/**
1595
 * Preprocess the taggedName to normalize newly introduced
1596
 * tagtypes like hybridSign, separator, .. more?
1597
 *
1598
 * @param unknown_type $taggedTextList
1599
 */
1600
function normalize_TaggedName(&$taggedTextList) {
1601

    
1602
  if (is_array($taggedTextList)) {
1603

    
1604
    // First pass: rename.
1605
    for ($i = 0; $i < count($taggedTextList); $i++) {
1606

    
1607
      if ($taggedTextList[$i]->type == "hybridSign") {
1608
        $taggedTextList[$i]->type = "name";
1609
      }
1610
    }
1611

    
1612
    // Second pass: resolve separators.
1613
    $taggedNameListNew = array();
1614
    for ($i = 0; $i < count($taggedTextList); $i++) {
1615

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

    
1618
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1619
          $taggedName = $taggedTextList[$i];
1620
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1621
          $taggedNameListNew[] = $taggedName;
1622
          ++$i;
1623
          ++$i;
1624
        }
1625
      }
1626
      else {
1627
        $taggedNameListNew[] = $taggedTextList[$i];
1628
      }
1629
    }
1630
    $taggedTextList = $taggedNameListNew;
1631
  }
1632
}
1633

    
1634
/**
1635
 * Creates a short taxonname.
1636
 *
1637
 * The short name is created by using the taggename field of
1638
 * NameSTO or NameTO instances.
1639
 * If the taggename if empty the fullname will be returned.
1640
 *
1641
 * @param unknown_type $name
1642
 *   Name or TreeNode.
1643
 *
1644
 * @return string
1645
 */
1646
function cdm_dataportal_shortname_of($name) {
1647
  $nameStr = '';
1648

    
1649
  normalize_TaggedName($name->taggedTitle);
1650

    
1651
  // Get all tagged text tokens of the scientific name.
1652
  foreach ($name->taggedTitle as $tagtxt) {
1653
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1654
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1655
    }
1656
  }
1657
  $nameStr = trim($nameStr);
1658

    
1659
  if ($nameStr) {
1660

    
1661
    // Do not return short names for these.
1662
    if ($name->unplaced || $name->excluded) {
1663
      return $nameStr;
1664
    }
1665

    
1666
    /*
1667
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1668
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1669
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1670
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1671
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1672
    */
1673
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1674
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1675
      return $matches[1][0] . "." . $matches[3][0];
1676
    }
1677
    else {
1678
      return $nameStr;
1679
    }
1680
  }
1681
  else {
1682
    return $name->titleCache;
1683
  }
1684
}
1685

    
1686
/**
1687
 * Check if a taxon is accepted by the current taxonomic tree.
1688
 *
1689
 * @param mixed $taxon
1690
 *   The Taxon obkect to check.
1691
 *
1692
 * @return bool
1693
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1694
 */
1695
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1696

    
1697
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1698

    
1699
  if (isset($taxon->taxonNodes)) {
1700
    $taxonNodes = $taxon->taxonNodes;
1701
  }
1702
  else {
1703
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1704
  }
1705

    
1706
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1707
    foreach ($taxonNodes as $node) {
1708
      if (is_object($node->classification)) {
1709
        if ($node->classification->uuid == $defaultTreeUuid) {
1710
          return TRUE;
1711
        }
1712
      }
1713
      else {
1714
        if ($node->classification == $defaultTreeUuid) {
1715
          return TRUE;
1716
        }
1717
      }
1718
    }
1719
  }
1720

    
1721
  return FALSE;
1722
}
1723

    
1724
/**
1725
 * Workaround for missing original source type.
1726
 *
1727
 * idNamespace is always set in these cases.
1728
 * @todo improve documentation of this function.
1729
 *
1730
 * @param unknown_type $source
1731
 *
1732
 * @return unknown_type
1733
 */
1734
function _is_original_source_type($source) {
1735
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1736
}
1737

    
1738
/**
1739
 * @todo Please document this function.
1740
 * @see http://drupal.org/node/1354
1741
 */
1742
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1743
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1744
}
1745

    
1746
/**
1747
 * Gets the metadata info such as title or artist of a media file.
1748
 *
1749
 * The function tries at first to get all the info from the file metadata
1750
 * and if it is not avaible look at the media file info stored at the database.
1751
 *
1752
 * @param mixed $media
1753
 *   The media file object for which to get the metadata.
1754
 *
1755
 * @return array
1756
 *   The array with the available specified metadata info.
1757
 * TODO rename to read_media_metadata() and move to *.module.
1758
 */
1759
function cdm_read_media_metadata($media) {
1760

    
1761
  $metadata_caption = array(
1762
    'title' => '',// Media_metadata and media.
1763
    'artist' => '',// Media_metadata and media.
1764
    'rights',// Media_metadata and media.
1765
    'location',// Media_metadata.
1766
    'filename' => '',// Media.
1767
    'mediacreated' => '',// Media.
1768
    'description' => '',
1769
  );// Media.
1770

    
1771
  // Getting the media metadata.
1772
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1773
  $media_metadata_aux = (array) $media_metadata;
1774

    
1775
  // Filename.
1776
  if (!empty($media->representations[0]->parts[0]->uri)) {
1777
    $fileUri = $media->representations[0]->parts[0]->uri;
1778
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1779
    $metadata_caption['filename'] = $filename;
1780
  }
1781
  else {
1782
    $metadata_caption['filename'] = '';
1783
  }
1784

    
1785
  // Title.
1786
  if (!empty($media_metadata->ObjectName)) {
1787
    $metadata_caption['title'] = $media_metadata->ObjectName;
1788
  }
1789
  elseif (!empty($media_metadata_aux['Object Name'])) {
1790
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1791
  }
1792
  elseif (!empty($media->title_L10n)) {
1793
    $metadata_caption['title'] = $media->title_L10n;
1794
  }
1795
  elseif (!empty($media->titleCache)) {
1796
    $metadata_caption['title'] = $media->titleCache;
1797
  }
1798

    
1799
  // Append description to title.
1800
  if (!empty($media->description_L10n)) {
1801
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1802
  }
1803

    
1804
  // Artist.
1805
  if (!empty($media_metadata->Artist)) {
1806
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1807
  }
1808
  elseif (!empty($media->artist->titleCache)) {
1809
    $metadata_caption['artist'] = $media->artist->titleCache;
1810
  }
1811

    
1812
  // Copyright.
1813
  $metadata_caption['rights'] = array(
1814
    'copyright' => array('agentNames' => array()),
1815
    'license' => array(
1816
      'agentNames' => array(),
1817
      'types' => array(),
1818
      'abbreviatedTexts' => array(),
1819
      'uris' => array(),
1820
    ),
1821
  );
1822
  if (!empty($media_metadata->Copyright)) {
1823
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1824
  }
1825
  elseif (isset($media->rights) && is_array($media->rights)) {
1826
    foreach ($media->rights as $right) {
1827
      switch ($right->term->uuid) {
1828
        case UUID_RIGHTS_LICENCE:
1829
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1830
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1831
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1832
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1833
          break;
1834
        case UUID_RIGHTS_COPYRIGHT:
1835
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1836
          break;
1837
      }
1838
    }
1839
  }
1840
  else {
1841
    $metadata_caption['rights']['agentNames'][] = '';
1842
  }
1843

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

    
1847
  // Location.
1848
  $metadata_caption['location'] = array();
1849
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1850
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1851
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1852
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1853

    
1854
  /*
1855
   // Creation date.
1856
   if($media_metadata["Modify Date"])
1857
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1858
   else
1859
   $metadata_caption['mediacreated'] = $media->created;
1860
   */
1861

    
1862
  // Returned value.
1863
  return $metadata_caption;
1864
}
1865

    
1866
/**
1867
 * Collects all the media from a list of description elements.
1868
 *
1869
 * @param array $descriptionElements
1870
 *   The description elements from which to collect the media.
1871
 *
1872
 * @return array
1873
 *   The output with all the collected media.
1874
 */
1875
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1876

    
1877
  $outArrayOfMedia = array();
1878

    
1879
  // Avoiding a warning box in Drupal for Flora Malesiana.
1880
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1881
    foreach ($descriptionElements as $descriptionElement) {
1882
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1883
        foreach ($descriptionElement->media as $media) {
1884
          if (is_object($media)) {
1885
            $outArrayOfMedia[] = $media;
1886
          }
1887
        }
1888
      }
1889
    }
1890
  }
1891
  return $outArrayOfMedia;
1892
}
1893

    
1894
/**
1895
 * @todo Please document this function.
1896
 * @see http://drupal.org/node/1354
1897
 *
1898
 * @param array $cdmBase_list
1899
 *   An array of CdmBase instances or a single instance.
1900
 * @param string $footnote_list_key
1901
 *
1902
 * @return unknown
1903
 */
1904
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1905

    
1906
   static $annotations_types_filter = null;
1907
   if(!$annotations_types_filter) {
1908
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1909
   }
1910

    
1911
  $footNoteKeys = array();
1912

    
1913
  // Is argument cdmBase an array?
1914
  if (!is_array($cdmBase_list)) {
1915
    $cdmBase_array = array();
1916
    $cdmBase_array[] = $cdmBase_list;
1917
  }
1918
  else {
1919
    $cdmBase_array = $cdmBase_list;
1920
  }
1921

    
1922
  // Getting the key for the footnotemanager.
1923
  if (isset($footnote_list_key)) {
1924
    $footnoteListKey = $footnote_list_key;
1925
  }
1926
  else {
1927
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1928
  }
1929

    
1930
  // Adding the footnotes keys.
1931
  foreach ($cdmBase_array as $cdmBase_element) {
1932
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1933
    if (is_array($annotations)) {
1934
      foreach ($annotations as $annotation) {
1935
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1936
      }
1937
    }
1938
  }
1939

    
1940
  return $footNoteKeys;
1941
}
1942

    
1943
// @WA Comment: should this not be a theme function?
1944
/**
1945
 *  Creates a CDM Dynabox.
1946
 * @param string $dynabox_id
1947
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
1948
 * @param string $label
1949
 *   The clickable text to show.
1950
 * @param string $content_url
1951
 *   The cdm REST service request url wich will deliver the content to be shown
1952
 *   once the dynabox toggles open.
1953
 * @param string $theme
1954
 *   The theme to be used for rendering the cdm REST service reponse with is
1955
 *   returned from the $content_url.
1956
 * @param string $link_alt_text
1957
 *   The value for the alt attribute of the dynabox link.
1958
 * @param array $enclosingtags
1959
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
1960
 *   element itself, $enclosingtags[1] is the tag to be used for the
1961
 *   dynabox_content (optional)
1962
 * @param string $open_callback
1963
 *   optional javascript call back function to be triggered after toggeling the box to
1964
 *   the open state.
1965
 * @param string $close_callback
1966
 *   optional javascript call back function to be triggered after toggeling the box to
1967
 *   the closed state.
1968
 *
1969
 * @return string
1970
 *   Returns HTML for a dynabox.
1971
 */
1972
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
1973
  $out = '';
1974

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

    
1978
  _add_js_domEvent(); // requires domEvent.js
1979
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
1980
  drupal_add_js("
1981
  jQuery(document).ready(
1982
      function() {
1983
        dynabox('". $dynabox_id ."',
1984
          {
1985
            open_callback: " . $open_callback .",
1986
            close_callback: " . $close_callback ."
1987
          }
1988
        );
1989
      }
1990
   );",
1991
   array(
1992
    'type'=>'inline',
1993
    'scope'=>'footer'
1994
    )
1995
  );
1996

    
1997
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
1998
  $out .= '<!-- ' . $content_url . ' -->';
1999
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2000
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '>' . loading_image_html() . '</' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2001
  $out .= '</' . $enclosingtags[0] . '>';
2002
  return $out;
2003
}
2004

    
2005
/**
2006
 * Checks whether a feature has any description elements.
2007
 *
2008
 * @param mixed $featureNode
2009
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2010
 *
2011
 * @see _mergeFeatureTreeDescriptions()
2012
 *
2013
 * @return bool
2014
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2015
 *   contains at least one non empty TextData or at least one DescriptionElement
2016
 *   of an other type. A TextData element holding a multilanguageText or a
2017
 *   source reference is considered to be not empty.
2018
 */
2019
function hasFeatureNodeDescriptionElements($featureNode) {
2020

    
2021
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2022
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2023
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2024
        return TRUE;
2025
      }
2026
    }
2027
  }
2028
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2029
    foreach ($featureNode->children as $child) {
2030
      if (hasFeatureNodeDescriptionElements($child)) {
2031
        return TRUE;
2032
      }
2033
    }
2034
  }
2035
  return FALSE;
2036
}
(7-7/14)