Project

General

Profile

Download (72.6 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/occurrences');
29
module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
30
module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
31

    
32
module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
33
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
34
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
35
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
36
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
37
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
38
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
39
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
40
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
41
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.bibliography');
42

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

    
48

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

    
51

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

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

    
73
/**
74
 * @param unknown_type $link_element_selector
75
 * @param unknown_type $progress_element_selector
76
 */
77
function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
78

    
79
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
80

    
81
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
82

    
83
  //   drupal_add_js("
84
  //   	  if (Drupal.jsEnabled) {
85
  //         $(document).ready(function() {
86
  //       		$('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');
87
  //         });
88
  //       }", 'inline');
89
  }
90

    
91
/**
92
 * @todo Please document this function.
93
 * @see http://drupal.org/node/1354
94
 */
95
function _add_js_treeselector() {
96
  // drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
97
  drupal_add_js("
98
      jQuery(document).ready(function() {
99
         jQuery('#cdm-taxonomictree-selector-form #edit-val').change(function () {
100
              jQuery('#cdm-taxonomictree-selector-form').submit();
101
          });
102

    
103
      });
104
    ",
105
    array(
106
      'type' => 'inline',
107
      'scope' => 'footer'
108
    )
109
  );
110
}
111

    
112
function _add_js_openlayers() {
113
  $openlayers = '/js/OpenLayers-2.11/OpenLayers.js';
114

    
115
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers, array(
116
      'type' => 'file',
117
      'weight' => JS_LIBRARY,
118
      'cache' => FALSE,
119
  ));
120
}
121

    
122
/**
123
 * @todo Please document this function.
124
 * @see http://drupal.org/node/1354
125
 */
126
function _add_js_openlayers_map() {
127

    
128
  _add_js_openlayers();
129

    
130
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
131

    
132
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
133

    
134
  $baseLayers = variable_get('baselayers', array());
135
  if (!is_array($baseLayers) || count($baseLayers) == 0) {
136
    $baseLayers = array(
137
      'metacarta_vmap0' => 'Metacarta Vmap0',
138
      'PREFERRED' => 'metacarta_vmap0',
139
    );
140
  }
141
  $layerNames = '';
142
  foreach ($baseLayers as $layerName => $layerLabel) {
143
    if ($layerName == 'PREFERRED') {
144
      $preferredLayer = $baseLayers['PREFERRED'];
145
    }
146
    else {
147
      $layerNames .= ($layerNames ? ', ' : '') . "'$layerName'";
148
    }
149
  }
150

    
151
  if (isset($baseLayers['gmap']) || isset($baseLayers['gsat']) || isset($baseLayers['ghyb'])) {
152
    drupal_add_html_head('<script src=http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=' . $gmap_api_key . '" type="text/javascript"></script>', $key = NULL /* TODO Set this variable. */);
153
    drupal_add_js('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1', array('type' => 'external'));
154
  }
155

    
156
  $edit_map_service = get_edit_map_service_settings();
157
  // window.onload - is executed when the document and images etc is fully loaded
158
  // Query(document).ready - is executed much earlier, when the DOM is loaded
159
  drupal_add_js("
160
          jQuery(document).ready(function() {
161

    
162
                window.onload = function () {
163
            // ---
164
                  jQuery('#openlayers_map').cdm_openlayers_map(
165
                   '" . $edit_map_service['base_uri'] . "',
166
                   '" . $edit_map_service['version'] . "',
167
                   {
168
                    legendPosition: 3,
169
                    displayWidth: '" . variable_get('cdm_dataportal_geoservice_display_width', FALSE) . "',
170
                    boundingBox: '" . variable_get('cdm_dataportal_geoservice_bounding_box', FALSE) . "',
171
                    distributionOpacity: '" . variable_get('cdm_dataportal_geoservice_distributionOpacity', '0.5') . "',
172
                    legendOpacity: '" . variable_get('cdm_dataportal_geoservice_legendOpacity', '0.5') . "',
173
                    showLayerSwitcher: " . (variable_get('cdm_dataportal_geoservice_showLayerSwitcher', TRUE) ? 'true' : 'false') . ",
174
                    baseLayerNames: [" . $layerNames . "],
175
                    defaultBaseLayerName: '" . $preferredLayer . "'
176
                   }
177
                );
178
                 // ---
179
        };
180
      });
181
    ", array('type' => 'inline'));
182

    
183
}
184

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

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

    
239
/**
240
 * @todo Please document this function.
241
 * @see http://drupal.org/node/1354
242
 */
243
function _add_js_footnotes() {
244
  _add_js_domEvent();
245
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/footnotes.js');
246
}
247

    
248
/**
249
 * @todo Please document this function.
250
 * @see http://drupal.org/node/1354
251
 */
252
function _add_js_cluetip() {
253

    
254
  // TODO replace by
255
  // @see http://www.socialembedded.com/labs/jQuery-Tooltip-Plugin/jQuery-Tooltip-Plugin.html
256
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.js');
257
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/jquery.dimensions.js');
258
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.hoverIntent.js');
259
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/cluetip/jquery.cluetip.css');
260
  drupal_add_js("jQuery(document).ready(function(){
261
      jQuery('.cluetip').css({color: '#0062C2'}).cluetip({
262
        splitTitle: '|',
263
        showTitle: true,
264
        activation: 'hover',
265
        sicky: true,
266
        arrows: true,
267
        dropShadow: false,
268
        cluetipClass: 'rounded'
269
      });
270
    });", array('type' => 'inline'));
271
}
272

    
273
/**
274
 * @todo Please document this function.
275
 * @see http://drupal.org/node/1354
276
 */
277
function _add_js_ahah() {
278

    
279
  _add_js_domEvent(); // requires domEvent.js
280
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ahah-content.js');
281
}
282

    
283
/**
284
 * Adds the external javascript file for domEvent.js.
285
 *
286
 * @see drupal_add_js()
287
 */
288
function _add_js_domEvent() {
289
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/domEvent.js');
290
}
291

    
292

    
293
/**
294
 * @todo Enter description here ...
295
 *
296
 * @param unknown_type $width
297
 * @param unknown_type $bounding_box
298
 * @param unknown_type $occurrenceQuery
299
 * @param unknown_type $distributionQuery
300
 * @param unknown_type $legendFormatQuery
301
 * @param unknown_type $map_caption
302
 *
303
 * @return unknown
304
 */
305
function get_image_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
306

    
307
  // Additional query parameters as set in the data portal admin section.
308
  $labels_on = variable_get('cdm_dataportal_geoservice_labels_on', 0);
309

    
310
  $query_string = '&image=true&recalculate=false&legend=1&ms=' . $width
311
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
312
    . ($labels_on ? '&label=' . $labels_on : '');
313

    
314
  if ($map_caption) {
315
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
316
  }
317

    
318
  if (get_edit_map_service_version_number() >= 1.1) {
319

    
320
    // Either occurrence or distribution - combined maps will be possible
321
    // in the future.
322
    if ($occurrenceQuery) {
323
      // @todo Fix $occurrenceQuery.
324
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
325
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
326
      // Will be replaced below.. HACK!!!
327
      $occurrenceQuery .= '&l=tdwg4&as=';
328

    
329
      $query_string .= "&" . $occurrenceQuery;
330
    }
331
    elseif ($distributionQuery) {
332
      $query_string .= "&" . $distributionQuery;
333
    }
334

    
335
    // Apply Plain Image map settings special for version >= 1.1.
336
    /*
337
    example : title=a:Naturalized++non-invasive
338
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
339
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
340
    &mc_s=Georgia,15,blue&mc=&recalculate=false
341

    
342
    http://edit.br.fgov.be/edit_wp5/v1/rest_gen.php?
343
    l=background_gis:b,cyprusdivs&ad=cyprusdivs%3Abdcode%3Aa%3A8%2C4
344
    &as=a%3A339966%2C%2C0.1%2C|b:0000ff,,
345
    &bbox=32%2C34%2C35%2C36&img=true&legend=1&mc=&mc_s=Georgia%2C15%2Cblue
346
    &mlp=3&ms=500&recalculate=false&title=a%3Aindigenous
347
    */
348

    
349
    $map_service_script_name = "rest_gen.php";
350

    
351
    $bgcolor_areaStyleId = "y";
352
    $baselayer_areaStyleId = "z";
353
    $bgcolor_layer = '';
354
    $additional_area_styles = array();
355

    
356
    // Background color:
357
    if (variable_get('map_bg_color', '')) {
358
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
359
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
360
    }
361

    
362
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
363
    // only needed for distribution maps.
364
    if (strpos($query_string, "?l=") !== FALSE) {
365
      $layer_param_token = "?l=";
366
    }
367
    else {
368
      $layer_param_token = "&l=";
369
    }
370
    if (strpos($query_string, "?as=") !== FALSE) {
371
      $areystyle_param_token = "?as=";
372
    }
373
    else {
374
      $areystyle_param_token = "&as=";
375
    }
376
    if (variable_get('map_base_layer', '')) {
377
      $query_string = str_replace($layer_param_token . "tdwg4", "$layer_param_token" . variable_get('map_base_layer', '') . ":" . $baselayer_areaStyleId, $query_string);
378
    }
379
    else {
380
      $query_string = str_replace($layer_param_token . "tdwg4", $layer_param_token . "tdwg4:" . $baselayer_areaStyleId . ",", $query_string);
381
    }
382

    
383
    if ($bgcolor_layer) {
384
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
385
    }
386

    
387
    if (variable_get('map_base_layer_style', '')) {
388
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
389
    }
390

    
391
    foreach ($additional_area_styles as $as) {
392
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
393
    }
394

    
395
  }
396
  else {
397
    // Pre 1.1. version of map service.
398
    if ($occurrenceQuery) {
399

    
400
      $map_service_script_name = "point.php";
401

    
402
      // Fix $occurrenceQuery.
403
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
404
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
405
      $occurrenceQuery .= '&l=v:e_w_0';
406
      $query_string .= "&" . $occurrenceQuery;
407
    }
408
    elseif ($distributionQuery) {
409
      $query_string .= "&" . $distributionQuery;
410
      $map_service_script_name = "areas.php";
411
    }
412
  }
413

    
414
  $mapUri = url(get_edit_map_service_full_uri() . '/' . $map_service_script_name . '?' .  $query_string);
415
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
416
  // Showing map caption.
417
  if ($map_caption) {
418
    // FIXME: replace <br> by according css style.
419
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
420
    $out .= '</div>';
421
  }
422

    
423
  return $out;
424
}
425

    
426
/**
427
 * @todo Enter description here ...
428
 *
429
 * @param unknown_type $width
430
 * @param unknown_type $bounding_box
431
 * @param unknown_type $occurrenceQuery
432
 * @param unknown_type $distributionQuery
433
 * @param unknown_type $legendFormatQuery
434
 * @param unknown_type $map_caption
435
 *
436
 * @return unknown
437
 */
438
function get_openlayers_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
439

    
440
  _add_js_openlayers_map();
441

    
442
  $out = '<div id="openlayers">';
443
  $out .= '<div id="openlayers_map" class="smallmap"';
444
  if($width) {
445
    $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
446
  }
447

    
448
  // Additional query parameters as set in the data portal admin section.
449
  $labels_on = variable_get('cdm_dataportal_geoservice_labels_on', 0);
450

    
451
  $openlayers_map_query_string = '&img=false&ms=' . $width
452
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
453
    . ($labels_on ? '&label=' . $labels_on : '');
454

    
455
  if ($occurrenceQuery) {
456
    // @todo Fix $occurrenceQuery.
457
//     $occurrenceQuery .= '&bbox=-180,-90,180,90';
458
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
459
    // $occurrenceQuery .= '&l=v:e_w_0';
460
    // TODO add to cdm service?
461
    $occurrenceQuery .= '&legend=0';
462

    
463
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
464
  }
465

    
466
  if ($distributionQuery) {
467
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
468
  }
469

    
470
  if ($legendFormatQuery) {
471
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
472
  }
473

    
474
  $out .= '></div></div>';
475

    
476
  // Showing map caption.
477
  if ($map_caption) {
478
    // FIXME: replace <br> by according css style.
479
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
480
    $out .= '</div>';
481
  }
482
  return $out;
483
}
484

    
485
/* ====================== hook implementations ====================== */
486
/**
487
 * Implements hook_permission().
488
 *
489
 * Valid permissions for this module.
490
 *
491
 * @return array
492
 *   An array of valid permissions for the portfolio module.
493
 */
494
function cdm_dataportal_permission() {
495
  return array(
496
    'administer cdm_dataportal' => array(
497
      'title' => t('administer cdm_dataportal'),
498
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
499
    ),
500
    'cdm_dataportal view notes' => array(
501
      'title' => t('cdm_dataportal view notes'),
502
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
503
    ),
504
    // TODO Which other permissions are required?
505
    // -> check the WP6 requirements document.
506
  );
507
}
508

    
509
/**
510
 * Implements hook_menu().
511
 */
512
function cdm_dataportal_menu() {
513
  $items = array();
514

    
515
  // @see settings.php.
516
  cdm_dataportal_menu_admin($items);
517
  cdm_dataportal_menu_help($items);
518

    
519
  $items['cdm_dataportal/names'] = array(
520
    'page callback' => 'cdm_dataportal_view_names',
521
    'access arguments' => array('access content'),
522
    'type' => MENU_CALLBACK,
523
  );
524

    
525
  // Optional callback arguments: page.
526
  $items['cdm_dataportal/taxon'] = array(
527
    'page callback' => 'cdm_dataportal_taxon_page_view',
528
    'access arguments' => array('access content'),
529
    'type' => MENU_CALLBACK,
530
    // Expected callback arguments: uuid.
531
  );
532

    
533
  $items['cdm_dataportal/name'] = array(
534
    'page callback' => 'cdm_dataportal_name_page_view',
535
      /*
536
    'page arguments' => array(
537
       'taxon_name_uuid',
538
       'taxon_to_hide_uuid',
539
       'synonym_uuid' => NULL
540
      ),
541
      */
542
    'access arguments' => array('access content'),
543
    'type' => MENU_CALLBACK,
544
    // Expected callback arguments: uuid.
545
  );
546

    
547
  $items['cdm_dataportal/reference'] = array(
548
    'page callback' => 'cdm_dataportal_view_reference',
549
    'access arguments' => array('access content'),
550
    'type' => MENU_CALLBACK,
551
    // Expected callback arguments: uuid.
552
  );
553

    
554
  $items['cdm_dataportal/reference/list'] = array(
555
    'page callback' => 'cdm_dataportal_view_reference_list',
556
    'access arguments' => array('access content'),
557
    'type' => MENU_CALLBACK,
558
    // Expected callback arguments: uuid.
559
  );
560

    
561
  $items['cdm_dataportal/media'] = array(
562
    'page callback' => 'cdm_dataportal_view_media',
563
    'access arguments' => array('access content'),
564
    'type' => MENU_CALLBACK,
565
    // Expected callback arguments:
566
    // uuid, mediarepresentation_uuid, part_uuid or part#.
567
  );
568

    
569
  $items['cdm_dataportal/polytomousKey'] = array(
570
    'page callback' => 'cdm_dataportal_view_polytomousKey',
571
    'access arguments' => array('access content'),
572
    'type' => MENU_CALLBACK,
573
    // Expected callback arguments: polytomousKey->uuid.
574
  );
575

    
576
  $items['cdm_dataportal/search'] = array(
577
    'page callback' => 'cdm_dataportal_view_search_advanced',
578
    'access arguments' => array('access content'),
579
    'type' => MENU_CALLBACK,
580
  );
581

    
582
  $items['cdm_dataportal/search/advanced'] = array(
583
    'title' => 'Advanced',
584
    'page callback' => 'cdm_dataportal_view_search_advanced',
585
    'access arguments' => array('access content'),
586
    'type' => MENU_DEFAULT_LOCAL_TASK,
587
  );
588

    
589
  $items['cdm_dataportal/search/taxon_by_description'] = array(
590
    'title' => 'By description full text',
591
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
592
    'access arguments' => array('access content'),
593
    'type' => MENU_LOCAL_TASK,
594
  );
595

    
596
  $items['cdm_dataportal/search/results/taxon'] = array(
597
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
598
    'access arguments' => array('access content'),
599
    'type' => MENU_CALLBACK,
600
  );
601
  /*
602
   $items['cdm/xml2json'] = array(
603
   'page callback' => 'cdm_view_xml2json',
604
   'access arguments' => array('access content'),
605
   'type' => MENU_CALLBACK,
606
   );
607
   */
608

    
609
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
610
  // User configuration of cdm_dataportal.
611
  $items['user/%/cdm_dataportal'] = array(
612
    'title' => 'cdm_dataportal',
613
    'access arguments' => array('access content'),
614
    'page callback' => 'drupal_get_form',
615
    'page arguments' => array('cdm_dataportal_user_form'),
616
    'type' => MENU_LOCAL_TASK,
617
    'weight' => 10,
618
  );
619
  // }
620

    
621
  // 'May not cache' in D5.
622
  // --- Local tasks for Taxon.
623
  $items['cdm_dataportal/name/%'] = array(
624
    // 'page callback' => 'cdm_dataportal_view_name',
625
    'page callback' => 'cdm_dataportal_name_page_view',
626
    'page arguments' => array(2, 3, 4),
627
    'access arguments' => array('access content'),
628
    'type' => MENU_CALLBACK,
629
  );
630

    
631
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
632
    $items['cdm_dataportal/taxon/%'] = array(
633
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
634
      'page callback' => 'cdm_dataportal_taxon_page_view',
635
      'access arguments' => array('access content'),
636
      'type' => MENU_CALLBACK,
637
      'weight' => 1,
638
      'page arguments' => array(2, "description")
639
      , // Expected callback arguments: name_uuid.
640
    );
641

    
642
    $items['cdm_dataportal/taxon/%/all'] = array(
643
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
644
      'page callback' => 'cdm_dataportal_taxon_page_view',
645
      'access arguments' => array('access content'),
646
      'type' => MENU_CALLBACK,
647
      'weight' => 2,
648
      'page arguments' => array(2, "all")
649
      , // Expected callback arguments: name_uuid.
650
    );
651

    
652
    $items['cdm_dataportal/taxon/%/description'] = array(
653
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
654
      'page callback' => 'cdm_dataportal_taxon_page_view',
655
      'access arguments' => array('access content'),
656
      'type' => MENU_DEFAULT_LOCAL_TASK,
657
      'weight' => 2,
658
      'page arguments' => array(2, "description")
659
      , // Expected callback arguments: name_uuid.
660
    );
661

    
662
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
663
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
664
      'page callback' => 'cdm_dataportal_taxon_page_view',
665
      'access arguments' => array('access content'),
666
      'type' => MENU_LOCAL_TASK,
667
      'weight' => 4,
668
      'page arguments' => array(2, "synonymy", 4)
669
      , // Expected callback arguments: name_uuid.
670
    );
671
    $items['cdm_dataportal/taxon/%/images'] = array(
672
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
673
      'page callback' => 'cdm_dataportal_taxon_page_view',
674
      'access arguments' => array('access content'),
675
      'type' => MENU_LOCAL_TASK,
676
      'weight' => 5,
677
      'page arguments' => array(2, "images")
678
      , // Expected callback arguments: name_uuid.
679
    );
680

    
681
    $items['cdm_dataportal/taxon/%/specimens'] = array(
682
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
683
      'page callback' => 'cdm_dataportal_taxon_page_view',
684
      'access arguments' => array('access content'),
685
      'type' => MENU_LOCAL_TASK,
686
      'weight' => 6,
687
      'page arguments' => array(2, "specimens")
688
      , // Expected callback arguments: name_uuid.
689
    );
690

    
691
    $items['cdm_dataportal/taxon/%/keys'] = array(
692
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
693
      'page callback' => 'cdm_dataportal_taxon_page_view',
694
      'access arguments' => array('access content'),
695
      'type' => MENU_LOCAL_TASK,
696
      'weight' => 6,
697
      'page arguments' => array(2, "keys")
698
      , // Expected callback arguments: name_uuid.
699
    );
700
  }
701

    
702
  return $items;
703
}
704

    
705
/**
706
 * Implements hook_init().
707
 *
708
 * can be removed after fixing the FIXME below
709
 */
710
function cdm_dataportal_init() {
711
  //FIXME To add CSS or JS that should be present on all pages, modules should not implement this hook, but declare these files in their .info file.
712
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
713
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
714
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
715
}
716

    
717
/**
718
 * The function generate form for own user cdm dataportal configurations.
719
 */
720
function cdm_dataportal_user_form($form, &$form_state) {
721
  global $user;
722
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
723

    
724
  $form['check'] = array(
725
    '#type' => 'checkbox',
726
    '#title' => t('Activate user default configuration'),
727
    '#default_value' => variable_get($checkbox_value, 0),
728
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
729
  );
730

    
731
  $form['cdm_dataportal_user_form'] = array(
732
    '#type' => 'select',
733
    '#title' => t('Default tab to display'),
734
    '#default_value' => get_default_taxon_tab(TRUE),
735
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
736
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
737
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
738
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
739
  );
740

    
741
  $form['submit'] = array(
742
    '#type' => 'submit',
743
    '#value' => t('Submit'),
744
  );
745

    
746
  return $form;
747
}
748

    
749
/**
750
 * Form submission handler for user_form().
751
 *
752
 * Submits the user cdm dataportal configurations.
753
 */
754
function cdm_dataportal_user_form_submit($form, &$form_state) {
755
  global $user;
756
  $msg_type = 'status';
757
  $username = $user->name;
758
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
759

    
760
  // If is the right user the variables are setted.
761
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
762
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
763
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
764
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
765
    if ($form_state['values']['check']) {
766
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
767
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
768
        '!tab' => $variable[variable_get($variable_to_use, 0)],
769
        '!user' => $username,
770
      ))), $msg_type);
771
    }
772
    else {
773
      drupal_set_message(check_plain(t('The user default tab wont be used for
774
        the next taxon site, check the box if you want to use the user default configuration.')));
775
    }
776
    // Problem with the user id => variables wont be saved.
777
  }
778
  else {
779
    $msg_type = 'warning';
780
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
781
  }
782
}
783

    
784
/**
785
 * Implements hook_block_info().
786
 */
787
function cdm_dataportal_block_info() {
788

    
789
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
790
    // $block[1]["info"] = t("CDM DataPortal Credits");
791
    $block["2"] = array(
792
        "info" => t("CDM Search Taxa"),
793
        "cache" => DRUPAL_NO_CACHE
794
      );
795
    // $block[3]["info"] = t("CDM Filters");
796
    $block["4"]["info"] = t("CDM Dataportal Print");
797
    $block["keys"]["info"] = t("CDM identification keys");
798
    $block["uses"]["info"] = t("CDM Uses");
799
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
800

    
801
    return $block;
802
}
803

    
804
/**
805
 * Implements hook_block_view().
806
 */
807
function cdm_dataportal_block_view($delta) {
808
  // TODO Rename block deltas (e.g. '2') to readable strings.
809
  switch ($delta) {
810
    // case 'delta-1':
811
    // $block['subject'] = t('Credits');
812
    // $block['content'] = theme('cdm_credits');
813
    // return $block;
814
    case '2':
815
      $block['subject'] = t('Search taxa');
816
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
817
      $block['content'] = drupal_render($form);
818

    
819
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
820
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
821
      }
822
      return $block;
823
    case '4':
824
      $block['subject'] = '';
825
      $block['content'] = theme('cdm_print_button');
826
      return $block;
827
    case "keys":
828
      $block['subject'] = t('Identification Keys');
829
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
830
      return $block;
831
      // Creating a block specific for the Use Interface.
832
    case "uses":
833
      $block['subject'] = t('Uses');
834
      $block['content'] = theme('cdm_block_uses', array('taxonUuid' => NULL));
835
      return $block;
836
    case "fundedByEDIT":
837
      // t('Funded by EDIT');
838
      $text = '<none>';
839
      $block['subject'] = $text;
840
      $img_tag = '<img src="' . base_path() . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
841
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
842
        'attributes' => array("target" => "EDIT"),
843
        'absolute' => TRUE,
844
        'html' => TRUE,
845
      ));
846
      return $block;
847
  }
848
}
849

    
850
/*
851
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
852
 $_SESSION['cdm'] = NULL;
853
 if(is_string($cdm_ws_uri_update)){
854
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
855
 }
856
 }
857

    
858
 function cdm_dataportal_session_validate(){
859
 if(!isset($_SESSION['cdm']['ws_uri'])){
860
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
861
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
862
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
863
 }
864
 }
865
 */
866

    
867
/**
868
 * @todo Please document this function.
869
 * @see http://drupal.org/node/1354
870
 */
871
function cdm_taxonomictree_selector() {
872
  _add_js_treeselector();
873

    
874
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
875
  $out = drupal_render($form);
876
  return $out;
877
}
878

    
879
/**
880
 * @todo Please document this function.
881
 * @see http://drupal.org/node/1354
882
 */
883
function cdm_taxonomictree_selector_form($form, &$form_state) {
884

    
885
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
886
  $form['#action'] = $url;
887

    
888
  $form['var'] = array(
889
    '#weight' => -3,
890
    '#type' => 'hidden',
891
    '#value' => '[cdm][taxonomictree_uuid]',
892
  );
893

    
894
  $destination_array = drupal_get_destination();
895
  $destination = $destination_array['destination'];
896

    
897
  $form['destination'] = array(
898
    '#weight' => -3,
899
    '#type' => 'hidden',
900
    '#value' =>  $destination,
901
  );
902

    
903
  $form['val'] = array(
904
    '#type' => 'select',
905
    '#title' => t('Available classifications'),
906
    '#default_value' => get_taxonomictree_uuid_selected(),
907
    '#options' => cdm_get_taxontrees_as_options(),
908
  );
909

    
910
  return $form;
911

    
912
}
913

    
914
/* UNREACHABLE since action of form directly links to view.
915
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
916

    
917
 $_SESSION['cdm']['search'] = $form_values;
918
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
919
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
920
 //$paramstr = compose_url_prameterstr($form_values);
921
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
922
 }
923
 */
924
/* ====================== menu callback functions ====================== */
925
/**
926
 * @todo Please document this function.
927
 * @see http://drupal.org/node/1354
928
 */
929
/*
930
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
931
  static $comment_node_disabled =  0;
932
  static $comment_node_read_only =  1;
933
  static $comment_node_read_write =  2;
934

    
935
  if ($form_id == 'node_type_form'
936
   && isset($form['identity']['type'])
937
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
938
  ) {
939
    $form['workflow']['comment'] = array(
940
      '#type' => 'radios',
941
      '#title' => t('Default comment setting'),
942
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
943
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
944
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
945
    );
946
  }
947
}
948
*/
949

    
950
/**
951
 * Displays a list of the known taxonomic names.
952
 *
953
 * When the list of taxonomic names is displayed, long lists are split up into
954
 * multiple pages.
955
 *
956
 * TODO: Parameters are still preliminary.
957
 *
958
 * @param string $beginsWith
959
 * @param string $page
960
 *   Page number to diplay defaults to page 1.
961
 * @param bool $onlyAccepted
962
 */
963
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
964

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

    
967
  /*
968
  // FIXME the filter for accepted names will be a form element, thus this
969
  // widget should be generated via form api preferably as block.
970
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
971
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
972
  $out .= theme('cdm_listof_taxa', $taxonPager);
973
  return $out;
974
  */
975
}
976

    
977
/**
978
 * @todo Please document this function.
979
 * @see http://drupal.org/node/1354
980
 */
981
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
982
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
983
  return theme('cdm_reference_page', array('reference' => $reference));
984
}
985

    
986
/**
987
 * @todo Please document this function.
988
 * @see http://drupal.org/node/1354
989
 */
990
function cdm_dataportal_view_reference_list($pageNumber) {
991
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
992
  return theme('cdm_reference_pager', array(
993
    'referencePager' => $referencePager,
994
    'path' => 'cdm_dataportal/reference/list/',
995
    ));
996
}
997

    
998
/**
999
 * @todo Please document this function.
1000
 * @see http://drupal.org/node/1354
1001
 */
1002
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1003
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1004
  return theme('cdm_media_page', array(
1005
    'media' => $media,
1006
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1007
    'partId' => $part,
1008
    ));
1009
}
1010

    
1011
/**
1012
 * @todo Please document this function.
1013
 * @see http://drupal.org/node/1354
1014
 */
1015
function _load_taxonBase(&$taxonBase) {
1016
  if (isset($taxonBase->uuid)) {
1017
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1018
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1019
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1020
  }
1021
}
1022

    
1023
/**
1024
 * Loads the media associated to the given taxon from the cdm server.
1025
 * The aggregation settings regarding taxon relathionships and
1026
 * taxonnomic childen are taken into account.
1027
 *
1028
 * The media lists are cached in a static variable.
1029
 *
1030
 * @param Taxon $taxon
1031
 *   A CDM Taxon entitiy
1032
 *
1033
 * @return array
1034
 *   An array of CDM Media entities
1035
 *
1036
 */
1037
function _load_media_for_taxon($taxon) {
1038

    
1039
  static $media = NULL;
1040

    
1041
  if(!isset($media)) {
1042
    $media = array();
1043
  }
1044
  if (!isset($media[$taxon->uuid])) {
1045

    
1046
    // --- GET Images --- //
1047
    $mediaQueryParameters = array(
1048
        "type" => "ImageFile",
1049
    );
1050

    
1051
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1052
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
1053
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
1054

    
1055
    $taxon_media_filter_choice = variable_get(CDM_TAXON_MEDIA_FILTER, unserialize(CDM_TAXON_MEDIA_FILTER_DEFAULT));
1056
    $mediaQueryParameters['includeTaxonDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonDescriptions'] != 0;
1057
    $mediaQueryParameters['includeOccurrences'] = (boolean) $taxon_media_filter_choice['includeOccurrences'] != 0;
1058
    $mediaQueryParameters['includeTaxonNameDescriptions'] = (boolean) $taxon_media_filter_choice['includeTaxonNameDescriptions'] != 0;
1059

    
1060
    $ws_endpoint = NULL;
1061
    if ( variable_get('cdm_images_include_children', 0) == 0) {
1062
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
1063
    } else {
1064
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
1065
    }
1066

    
1067
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
1068
        array(
1069
            $taxon->uuid,
1070
        ),
1071
        queryString($mediaQueryParameters)
1072
       );
1073
  }
1074

    
1075
  return $media[$taxon->uuid];
1076
}
1077

    
1078
/**
1079
 *
1080
 * @param Taxon $taxon
1081
 *   A CDM Taxon entitiy
1082
 *
1083
 * @return array
1084
 *   An array of CDM SpecimenOrObservation entities
1085
 *
1086
function _load_occurences_for_taxon($taxon){
1087

    
1088
  static $occurences = NULL;
1089

    
1090
  if(!isset($occurences)) {
1091
    $occurences = array();
1092
  }
1093

    
1094
  if (!isset($occurences[$taxon->uuid])){
1095

    
1096
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
1097
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
1098
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
1099

    
1100
    $by_associatedtaxon_query = http_build_query(array(
1101
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
1102
        'relationships' => implode(',', $relationship_choice['direct']),
1103
        'pageSize' => null // all hits in one page
1104
    )
1105
    );
1106

    
1107
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
1108
        null,
1109
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
1110
    );
1111

    
1112

    
1113
    if(isset($pager->records[0])){
1114
      $occurences[$taxon->uuid] =  $pager->records;
1115
    }
1116
  }
1117
  return $occurences[$taxon->uuid];
1118
}
1119
 */
1120

    
1121
/**
1122
 * Gets a Drupal variable, string or array and returns it.
1123
 *
1124
 * Similar to the variable_get() function of Drupal, except that this function
1125
 * is able to handle arrays correctly. This function is especially useful
1126
 * when dealing with collections of setting form elements (#tree = TRUE).
1127
 *
1128
 * @param string $variableKey
1129
 *   The Unique key of the Drupal variable in the Drupal variables table.
1130
 * @param string $defaultValueString
1131
 *   A string as for example derived from a CONSTANT.
1132
 *
1133
 * @return mixed
1134
 *   Returns usally an array, depending on the nature of the variable.
1135
 */
1136
function mixed_variable_get($variableKey, $defaultValueString) {
1137
  $systemDefaults = unserialize($defaultValueString);
1138
  $storedSettings = variable_get($variableKey, array());
1139
  if (is_array($storedSettings)) {
1140
    $settings = array_merge($systemDefaults, $storedSettings);
1141
  }
1142
  else {
1143
    $settings = $systemDefaults;
1144
  }
1145
  return $settings;
1146
}
1147

    
1148
/**
1149
 * Recusive funciton to convert an object into an array.
1150
 * also subordinate objects will be converted.
1151
 *
1152
 * @param object $object
1153
 * @return the array
1154
 */
1155
function convert_to_array($object) {
1156
  if(is_object($object) || is_array($object)) {
1157
    $array = (array)$object;
1158
    foreach ($array as $key=>$value){
1159
      $array[$key] = convert_to_array($value);
1160
    }
1161
    return $array;
1162
  } else {
1163
    return $object;
1164
  }
1165
}
1166

    
1167
/**
1168
 * Wrapps the given $html string into a reder array suitable for drupal_render()
1169
 *
1170
 * @param string $html
1171
 *   the html string, see
1172
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1173
 * @param number $weight
1174
 *   A positive or negative number (integer or decimal).
1175
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1176
 *
1177
 * @return
1178
 *   A render array
1179
 *
1180
 */
1181
function markup_to_render_array($html, $weight = 0) {
1182
  return array(
1183
          '#markup' => $html,
1184
          '#weight' => $weight,
1185
      );
1186
}
1187

    
1188
/**
1189
 * Loads the subgraph of a given PolytomousKeyNode.
1190
 *
1191
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1192
 * the CDM REST service.
1193
 *
1194
 * @param mixed $polytomousKeyNode
1195
 *   PolytomousKeyNode passed by reference.
1196
 *
1197
 * @return void
1198
 */
1199
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1200

    
1201
  if (!$polytomousKeyNode) {
1202
    return;
1203
  }
1204
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1205
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1206
    return;
1207
  }
1208
  if (!is_uuid($polytomousKeyNode->uuid)) {
1209
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1210
    return;
1211
  }
1212

    
1213
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1214

    
1215
  if (!$polytomousKeyNode) {
1216
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1217
    return;
1218
  }
1219

    
1220
  // Load children.
1221
  foreach ($polytomousKeyNode->children as &$childNode) {
1222
    _load_polytomousKeySubGraph($childNode);
1223
  }
1224

    
1225
  // Load subkey.
1226
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1227

    
1228
  // Load taxon.
1229
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1230
  _load_taxonBase($polytomousKeyNode->taxon);
1231
  return;
1232
}
1233

    
1234
/**
1235
 * @todo Please document this function.
1236
 * @see http://drupal.org/node/1354
1237
 */
1238
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1239
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1240

    
1241
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1242
  if (is_array($sourcePager->records)) {
1243
    $polytomousKey->sources = $sourcePager->records;
1244
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1245
  }
1246

    
1247
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1248
  if (is_array($annotationPager->records)) {
1249
    $polytomousKey->annotations = $annotationPager->records;
1250
  }
1251

    
1252
  _load_polytomousKeySubGraph($polytomousKey->root);
1253
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1254
}
1255

    
1256
/**
1257
 * Creates a taxon page view or a chapter of it.
1258
 *
1259
 * The taxon page gives detailed information on a taxon, it shows:
1260
 *  - Taxon name.
1261
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1262
 *    heterotypic and finally followed by misapplied names.
1263
 *    The list is ordered historically.
1264
 *  - All description associated with the taxon.
1265
 *
1266
 * @param string $uuid
1267
 * @param string $chapter
1268
 *   Name of the part to display, valid values are:
1269
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1270
 *
1271
 * @return unknown_type
1272
 */
1273
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1274
  // Display the page for the taxon defined by $uuid.
1275
  // set_last_taxon_page_tab(arg(3));
1276
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1277
  if (!empty($taxonpage)) {
1278
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1279
  }
1280
  else {
1281
    return '';
1282
  }
1283
}
1284

    
1285
/**
1286
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1287
 * which has two fields, one for the page title and one for the content. Later on in the
1288
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1289
 * function as the function parameters $title and $content.
1290
 *
1291
 * @param string $uuid
1292
 *   the uuid of the taxon to show
1293
 * @param string $chapter
1294
 *   Name of the part to display, valid values are:
1295
 *   'description', 'images', 'synonymy', 'all'.
1296
 *
1297
 * @return taxonpage object with the following fields:
1298
 *   - title : the title of the page
1299
 *   - content: the content of the page
1300
 *
1301
 */
1302
function cdm_dataportal_taxon_view($uuid, $chapter = 'all') {
1303
  // Taxon object.
1304
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1305
  if (empty($taxon)) {
1306
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1307
    return FALSE;
1308
  }
1309
  $taxonpage = new stdClass();
1310

    
1311
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1312
    'taxon' => $taxon
1313
  ));
1314

    
1315
  // Check if the taxon id contained in the currently selected tree.
1316
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1317

    
1318
  if (!$taxon_in_current_tree) {
1319
    $classifications = get_classifications_for_taxon($taxon);
1320
    if (count($classifications) == 0) {
1321
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1322
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1323
      ))), 'warning');
1324
    }
1325
    else {
1326
      $trees = '';
1327
      foreach ($classifications as $classification) {
1328
        if (isset($classification->titleCache)) {
1329
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1330
        }
1331
      }
1332

    
1333
      drupal_set_message(format_plural(count($trees),
1334
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1335
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1336
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1337
    }
1338
  }
1339

    
1340
  // Render the taxon page.
1341
  $taxonpage->content = theme('cdm_taxon_page', array(
1342
    'taxon' => $taxon,
1343
    'page_part' => $chapter,
1344
  ));
1345

    
1346
  return $taxonpage;
1347
}
1348

    
1349
/**
1350
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1351
 *
1352
 * The node page shows the taxon name title and the list of taxon related
1353
 * with such taxon. Name on the tree already in use.
1354
 *
1355
 * @param string $taxon_name_uuid
1356
 *   A taxon name UUID.
1357
 *
1358
 * @return mixed
1359
 *   The formatted name page as node.
1360
 */
1361
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1362

    
1363
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1364
  if (!empty($taxonname_page)) {
1365
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1366
  }
1367
  else {
1368
    return '';
1369
  }
1370
}
1371

    
1372
/**
1373
 * View function for a TaxonNameBase page.
1374
 *
1375
 * The name page lists all taxa for which the name specified by the
1376
 * $taxon_name_uuid is being used. I case there is only one name the
1377
 * page automatically redirects ti the according taxon page. Otherwise
1378
 * the list of names is displayed.
1379
 *
1380
 * The parameter $taxon_to_hide_uuid allows to exclude a taxon from the
1381
 * list of taxa. This is useful for example when referencing from a taxon
1382
 * to the name page and the referring taxon should not be repeaded in the
1383
 * name page.
1384
 *
1385
 *
1386
 * @param UUID $taxon_name_uuid
1387
 *   The uuid of the CDM TaxonNameBase to show a name page for
1388
 * @param UUID $taxon_to_hide_uuid
1389
 *   A taxon which should not be displayed in the taxon list
1390
 * @param UUID $highlite_synonym_uuid
1391
 *   Optinal parameter wich takes another taxon uuid, if given the
1392
 *   target taxon pages will show the syonymy tab where the taxon
1393
 *   refenrenced by the $highlite_synonym_uuid will be highlighted
1394
 *   in case it is found on this page.
1395
 *
1396
 * @return object
1397
 *   An object with two fields:
1398
 *     - title: the page title
1399
 *     - content: the page content
1400
 */
1401
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $highlite_synonym_uuid = NULL) {
1402
  // Getting the full taxonname object from the server.
1403
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1404
  if (!$taxon_name) {
1405
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1406
    return FALSE;
1407
  }
1408
  // Searching for all the taxa connected with the taxon name on the tree
1409
  // in use.
1410
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1411
  $request_params = array();
1412
  $request_params['query'] = $name_cache;
1413
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1414
  $request_params['doTaxa'] = 1;
1415
  $request_params['doSynonyms'] = 1;
1416
  $request_params['doTaxaByCommonNames'] = 0;
1417
  $request_params['matchMode'] = "EXACT";
1418
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1419

    
1420
  // Removing the name where we come from.
1421
  foreach ($taxon_pager->records as $k => &$taxon) {
1422
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1423
      unset($taxon_pager->records[$k]);
1424
    }
1425
  }
1426
  // Show the taxa list or go to the singular taxon.
1427
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1428
    $singleTaxon = array_pop($taxon_pager->records);
1429
    if ($singleTaxon->class != "Taxon") {
1430
      // It is a Synonym -> look for the accepted.
1431
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1432
      if (!empty($highlite_synonym_uuid)) {
1433
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1434
      }
1435
      else {
1436
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1437
      }
1438
    }
1439
    else {
1440
      // It is an accepted taxon.
1441
      if (!empty($highlite_synonym_uuid)) {
1442
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $highlite_synonym_uuid)));
1443
      }
1444
      else {
1445
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1446
      }
1447
    }
1448
  }
1449
  else {// More than one taxa case.
1450
    $taxon_name_page = new stdClass();
1451
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1452
    if ($taxon_pager->records) {
1453
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1454
    }
1455
    else {
1456
      $taxon_name_page->content = 'This name has no taxa';
1457
    }
1458
    return $taxon_name_page;
1459
  }
1460
}
1461

    
1462
/**
1463
 * @todo Please document this function.
1464
 * @see http://drupal.org/node/1354
1465
 */
1466
function cdm_dataportal_view_search_advanced() {
1467

    
1468
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1469
  $form = array();
1470
  $form_state = array();
1471
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1472

    
1473
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1474

    
1475
}
1476

    
1477
/**
1478
 * @todo Please document this function.
1479
 * @see http://drupal.org/node/1354
1480
 */
1481
function cdm_dataportal_view_search_taxon_by_description() {
1482
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1483
  // $form_state = false;
1484
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1485
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1486

    
1487
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1488
}
1489

    
1490
/**
1491
 * Executes the search and generates the result list of taxa.
1492
 */
1493
function cdm_dataportal_view_search_results_taxon() {
1494

    
1495
  $taxonPager = cdm_dataportal_search_execute();
1496

    
1497
  $showThumbnails = do_showThumbnails();
1498

    
1499
  $setSessionUri = url('cdm_api/setvalue/session', array(
1500
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1501
  ));
1502

    
1503
  drupal_add_js('jQuery(document).ready(function() {
1504

    
1505
      // init
1506
      if(' . $showThumbnails . ' == 1){
1507
      jQuery(\'.media_gallery\').show(20);
1508
  } else {
1509
      jQuery(\'.media_gallery\').hide(20);
1510
  }
1511
      // add change hander
1512
      jQuery(\'#showThumbnails\').change(
1513
      function(event){
1514
      var state = 0;
1515
      if(jQuery(this).is(\':checked\')){
1516
      jQuery(\'.media_gallery\').show(20);
1517
      state = 1;
1518
  } else {
1519
      jQuery(\'.media_gallery\').hide(20);
1520
  }
1521
      // store state in session variable
1522
      var uri = \'' . $setSessionUri . '\' + state;
1523
      jQuery.get(uri);
1524
  });
1525
  });',
1526
  array('type' => "inline", 'scope' => JS_DEFAULT));
1527

    
1528
  drupal_set_title(t('Search results'), PASS_THROUGH);
1529

    
1530
  return theme('cdm_search_results', array(
1531
    'pager' => $taxonPager,
1532
    'path' => 'cdm_dataportal/search/results/taxon',
1533
    ));
1534
}
1535

    
1536
/**
1537
 * Provides the standart image wich indicated a loading process
1538
 *
1539
 * @return string
1540
 *  The img html tag
1541
 */
1542
function loading_image_html() {
1543
  return '<img class="loading" src="' . base_path() . drupal_get_path('module', 'cdm_dataportal')
1544
    . '/images/loading_circle_grey_16.gif" style="display:none;">';
1545
}
1546

    
1547
/**
1548
 * Returns the state of the the showThumbnails flag set in the
1549
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1550
 *
1551
 * @return Ambigous <boolean, number>
1552
 *    returns 1 if the flag is set
1553
 */
1554
function do_showThumbnails() {
1555
  static $showThumbnails = null;
1556

    
1557
  if($showThumbnails == null) {
1558
    $showThumbnails = FALSE;
1559
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1560
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1561
    }
1562
    if (!is_numeric($showThumbnails)) {
1563
      $showThumbnails = 1;
1564
    }
1565
  }
1566

    
1567
  return $showThumbnails;
1568
}
1569

    
1570
/**
1571
 * View which transforms XML output from a given webservice endpoint into JSON.
1572
 */
1573
/*
1574
 function cdm_view_xml2json(){
1575
 $file = arg(2);
1576
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1577
 return  xml2json::transformXmlStringToJson($datastr);
1578
 }
1579
 */
1580

    
1581
/* ====================== other functions ====================== */
1582
/**
1583
 * Creates a URL to the taxon page specified by the $uuid parameter.
1584
 *
1585
 * The URL will be prepended with a path element to a specific taxon page tab.
1586
 *
1587
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1588
 * be set globally in the administrative settings or individually in the user
1589
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1590
 * the last portal will stay on this last tab.
1591
 *
1592
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1593
 * internal mechanism by a specific value.
1594
 *
1595
 * @param string $uuid
1596
 *   The UUID of the taxon.
1597
 * @param string $page_tab
1598
 *   Overwriting the preset mechanism by defining specific value for the
1599
 *   taxon page tab.
1600
 *
1601
 * @return string
1602
 *   The created URL.
1603
 */
1604
function path_to_taxon($uuid, $page_tab = FALSE) {
1605

    
1606
  $tab = get_default_taxon_tab();
1607
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1608

    
1609
  if (!$uuid) {
1610
    return FALSE;
1611
  }
1612

    
1613
  if ($page_tab) {
1614
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1615
  }
1616
  elseif (!$tab || strtolower($tab) == 'general') {
1617
    return 'cdm_dataportal/taxon/' . $uuid;
1618
  }
1619
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1620
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1621
  }
1622
  else {
1623
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1624
  }
1625
}
1626

    
1627
/**
1628
 * Creates a URL to show a synonmy in the according taxon page.
1629
 *
1630
 * The URL will point to the synonymy tab of the taxon page of the accepted taxon given as parameter $acceptedUuid.
1631
 * The resulting URI will include query parameters to highlight the synonym, and to optionally display
1632
 * the accepted taxons name in aform like "Foo bar is accepted taxon for Ree doo". The URI will also
1633
 * include the sysnonym uuid as fragment in order to let the browser scroll to the according location
1634
 * in the page
1635
 *
1636
 * @param string $synonymUuid
1637
 *    The uuid of the synonym
1638
 * @param string $acceptedUuid
1639
 *    The uuid of the according accepted taxon
1640
 * @return string
1641
 *    The URL to show a synonmy in the according taxon page
1642
 */
1643
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1644
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1645
  return url($acceptedPath, array(
1646
      'query' => array(
1647
        // highlite the synony in the synonymy
1648
        'highlite' => $synonymUuid,
1649
        // the taxon page is refered from a synonym and the synonym can optionally be named in the page title
1650
        // see theme_taxon_page_title()
1651
        'acceptedFor' => $synonymUuid
1652
      ),
1653
      'fragment' => $synonymUuid
1654
  ));
1655

    
1656
}
1657

    
1658
/**
1659
 * Compses the drupal path to the key identified by the uuid.
1660
 *
1661
 * @param string $keyType
1662
 *    the key typer corresponds to the specific class of the CDM
1663
 *    IdentificationKey. Possible values are
1664
 *      -PolytomousKey
1665
 *      -MultimediaKey
1666
 *      - ...
1667
 * @param UUID $keyUuid
1668
 *   The UUID of the key
1669
 */
1670
function path_to_key($keyType, $keyUuid) {
1671
  if (!$keyUuid || !$keyType) {
1672
    return FALSE;
1673
  }
1674
  $keyType{0} = strtolower($keyType{0});
1675
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1676
}
1677

    
1678
/**
1679
 * @todo Please document this function.
1680
 * @see http://drupal.org/node/1354
1681
 */
1682
function path_to_reference($uuid) {
1683
  if (!$uuid) {
1684
    return FALSE;
1685
  }
1686
  return 'cdm_dataportal/reference/' . $uuid;
1687
}
1688

    
1689
/**
1690
 * @todo Please document this function.
1691
 * @see http://drupal.org/node/1354
1692
 */
1693
function path_to_name($name_uuid) {
1694
  $res = FALSE;
1695
  if ($name_uuid) {
1696
    $res = 'cdm_dataportal/name/' . $name_uuid;
1697
  }
1698
  return $res;
1699
}
1700

    
1701
/**
1702
 * @todo Please document this function.
1703
 * @see http://drupal.org/node/1354
1704
 */
1705
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1706
  if (!$uuid) {
1707
    return FALSE;
1708
  }
1709
  $out = 'cdm_dataportal/media/' . $uuid;
1710
  if ($representaion_uuid) {
1711
    $out .= '/' . $representaion_uuid;
1712
    if ($partId !== FALSE) {
1713
      $out .= '/' . $partId;
1714
    }
1715
  }
1716
  return $out;
1717
}
1718

    
1719
/**
1720
 * Compares thisRank with thatRank.
1721
 *
1722
 * Returns a negative integer, zero, or a positive integer
1723
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1724
 * e.g:
1725
 * <ul>
1726
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1727
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1728
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1729
 * </ul>
1730
 * <p>
1731
 * This compare logic of the underlying webservice is the
1732
 * <b>inverse logic</b> of the the one implemented in
1733
 * java.lang.Comparable#compareTo(java.lang.Object)
1734
 *
1735
 * @param $thisRankUuid
1736
 * @param $thatRankUuid
1737
 *
1738
 * @return int
1739
 *   A negative integer, zero, or a positive integer
1740
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1741
 */
1742
function rank_compare($thisRankUuid, $thatRankUuid) {
1743
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1744
  return $result->Integer;
1745
}
1746

    
1747
/**
1748
 * Composes an HTML element class attribute value composed of
1749
 * the shortname of the cdm class and the uuid of the entity.
1750
 * This class attribute should be used whereever an cdm-entity is rendered.
1751
 *
1752
 * These according class selectors in css must be escaped, eg:
1753
 *    .cdm\:TextData
1754
 *
1755
 * @param $cdmEntity
1756
 */
1757
function html_class_atttibute_ref($cdmEntity) {
1758

    
1759
  if (is_cdm_entity($cdmEntity)) {
1760
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1761
  }
1762
}
1763

    
1764
/**
1765
 * Preprocess the taggedName to normalize newly introduced
1766
 * tagtypes like hybridSign, separator, .. more?
1767
 *
1768
 * @param unknown_type $taggedTextList
1769
 */
1770
function normalize_TaggedName(&$taggedTextList) {
1771

    
1772
  if (is_array($taggedTextList)) {
1773

    
1774
    // First pass: rename.
1775
    for ($i = 0; $i < count($taggedTextList); $i++) {
1776

    
1777
      if ($taggedTextList[$i]->type == "hybridSign") {
1778
        $taggedTextList[$i]->type = "name";
1779
      }
1780
    }
1781

    
1782
    // Second pass: resolve separators.
1783
    $taggedNameListNew = array();
1784
    for ($i = 0; $i < count($taggedTextList); $i++) {
1785

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

    
1788
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1789
          $taggedName = $taggedTextList[$i];
1790
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1791
          $taggedNameListNew[] = $taggedName;
1792
          ++$i;
1793
          ++$i;
1794
        }
1795
      }
1796
      else {
1797
        $taggedNameListNew[] = $taggedTextList[$i];
1798
      }
1799
    }
1800
    $taggedTextList = $taggedNameListNew;
1801
  }
1802
}
1803

    
1804
/**
1805
 * Creates a short taxonname.
1806
 *
1807
 * The short name is created by using the taggename field of
1808
 * NameSTO or NameTO instances.
1809
 * If the taggename if empty the fullname will be returned.
1810
 *
1811
 * @param unknown_type $name
1812
 *   Name or TreeNode.
1813
 *
1814
 * @return string
1815
 */
1816
function cdm_dataportal_shortname_of($name) {
1817
  $nameStr = '';
1818

    
1819
  normalize_TaggedName($name->taggedTitle);
1820

    
1821
  // Get all tagged text tokens of the scientific name.
1822
  foreach ($name->taggedTitle as $tagtxt) {
1823
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1824
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1825
    }
1826
  }
1827
  $nameStr = trim($nameStr);
1828

    
1829
  if ($nameStr) {
1830

    
1831
    // Do not return short names for these.
1832
    if ($name->unplaced || $name->excluded) {
1833
      return $nameStr;
1834
    }
1835

    
1836
    /*
1837
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1838
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1839
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1840
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1841
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1842
    */
1843
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1844
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1845
      return $matches[1][0] . "." . $matches[3][0];
1846
    }
1847
    else {
1848
      return $nameStr;
1849
    }
1850
  }
1851
  else {
1852
    return $name->titleCache;
1853
  }
1854
}
1855

    
1856
/**
1857
 * Check if a taxon is accepted by the current taxonomic tree.
1858
 *
1859
 * @param mixed $taxon
1860
 *   The Taxon obkect to check.
1861
 *
1862
 * @return bool
1863
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1864
 */
1865
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1866

    
1867
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1868

    
1869
  if (isset($taxon->taxonNodes)) {
1870
    $taxonNodes = $taxon->taxonNodes;
1871
  }
1872
  else {
1873
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1874
  }
1875

    
1876
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1877
    foreach ($taxonNodes as $node) {
1878
      if (is_object($node->classification)) {
1879
        if ($node->classification->uuid == $defaultTreeUuid) {
1880
          return TRUE;
1881
        }
1882
      }
1883
      else {
1884
        if ($node->classification == $defaultTreeUuid) {
1885
          return TRUE;
1886
        }
1887
      }
1888
    }
1889
  }
1890

    
1891
  return FALSE;
1892
}
1893

    
1894
/**
1895
 * Workaround for missing original source type.
1896
 *
1897
 * idNamespace is always set in these cases.
1898
 * @todo improve documentation of this function.
1899
 *
1900
 * @param unknown_type $source
1901
 *
1902
 * @return unknown_type
1903
 */
1904
function _is_original_source_type($source) {
1905
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1906
}
1907

    
1908
/**
1909
 * @todo Please document this function.
1910
 * @see http://drupal.org/node/1354
1911
 */
1912
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1913
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1914
}
1915

    
1916
/**
1917
 * Gets the metadata info such as title or artist of a media file.
1918
 *
1919
 * The function tries at first to get all the info from the file metadata
1920
 * and if it is not avaible look at the media file info stored at the database.
1921
 *
1922
 * @param mixed $media
1923
 *   The media file object for which to get the metadata.
1924
 *
1925
 * @return array
1926
 *   The array with the available specified metadata info.
1927
 * TODO rename to read_media_metadata() and move to *.module.
1928
 */
1929
function cdm_read_media_metadata($media) {
1930

    
1931
  $metadata_caption = array(
1932
    'title' => '',// Media_metadata and media.
1933
    'artist' => '',// Media_metadata and media.
1934
    'rights',// Media_metadata and media.
1935
    'location',// Media_metadata.
1936
    'filename' => '',// Media.
1937
    'mediacreated' => '',// Media.
1938
    'description' => '',
1939
  );// Media.
1940

    
1941
  // Getting the media metadata.
1942
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1943
  $media_metadata_aux = (array) $media_metadata;
1944

    
1945
  // Filename.
1946
  if (!empty($media->representations[0]->parts[0]->uri)) {
1947
    $fileUri = $media->representations[0]->parts[0]->uri;
1948
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1949
    $metadata_caption['filename'] = $filename;
1950
  }
1951
  else {
1952
    $metadata_caption['filename'] = '';
1953
  }
1954

    
1955
  // Title.
1956
  if (!empty($media_metadata->ObjectName)) {
1957
    $metadata_caption['title'] = $media_metadata->ObjectName;
1958
  }
1959
  elseif (!empty($media_metadata_aux['Object Name'])) {
1960
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1961
  }
1962
  elseif (!empty($media->title_L10n)) {
1963
    $metadata_caption['title'] = $media->title_L10n;
1964
  }
1965
  elseif (!empty($media->titleCache)) {
1966
    $metadata_caption['title'] = $media->titleCache;
1967
  }
1968

    
1969
  // Append description to title.
1970
  if (!empty($media->description_L10n)) {
1971
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1972
  }
1973

    
1974
  // Artist.
1975
  if (!empty($media_metadata->Artist)) {
1976
    $metadata_caption['artist'] = '' . $media_metadata->Artist;
1977
  }
1978
  elseif (!empty($media->artist->titleCache)) {
1979
    $metadata_caption['artist'] = $media->artist->titleCache;
1980
  }
1981

    
1982
  // Copyright.
1983
  $metadata_caption['rights'] = array(
1984
    'copyright' => array('agentNames' => array()),
1985
    'license' => array(
1986
      'agentNames' => array(),
1987
      'types' => array(),
1988
      'abbreviatedTexts' => array(),
1989
      'uris' => array(),
1990
    ),
1991
  );
1992
  if (!empty($media_metadata->Copyright)) {
1993
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1994
  }
1995
  elseif (isset($media->rights) && is_array($media->rights)) {
1996
    foreach ($media->rights as $right) {
1997
      switch ($right->term->uuid) {
1998
        case UUID_RIGHTS_LICENCE:
1999
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
2000
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
2001
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
2002
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
2003
          break;
2004
        case UUID_RIGHTS_COPYRIGHT:
2005
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
2006
          break;
2007
      }
2008
    }
2009
  }
2010
  else {
2011
    $metadata_caption['rights']['agentNames'][] = '';
2012
  }
2013

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

    
2017
  // Location.
2018
  $metadata_caption['location'] = array();
2019
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
2020
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
2021
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
2022
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
2023

    
2024
  /*
2025
   // Creation date.
2026
   if($media_metadata["Modify Date"])
2027
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
2028
   else
2029
   $metadata_caption['mediacreated'] = $media->created;
2030
   */
2031

    
2032
  // Returned value.
2033
  return $metadata_caption;
2034
}
2035

    
2036
/**
2037
 * Collects all the media from a list of description elements.
2038
 *
2039
 * @param array $descriptionElements
2040
 *   The description elements from which to collect the media.
2041
 *
2042
 * @return array
2043
 *   The output with all the collected media.
2044
 */
2045
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2046

    
2047
  $outArrayOfMedia = array();
2048

    
2049
  // Avoiding a warning box in Drupal for Flora Malesiana.
2050
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2051
    foreach ($descriptionElements as $descriptionElement) {
2052
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2053
        foreach ($descriptionElement->media as $media) {
2054
          if (is_object($media)) {
2055
            $outArrayOfMedia[] = $media;
2056
          }
2057
        }
2058
      }
2059
    }
2060
  }
2061
  return $outArrayOfMedia;
2062
}
2063

    
2064
/**
2065
 * @todo Please document this function.
2066
 * @see http://drupal.org/node/1354
2067
 *
2068
 * @param array $cdmBase_list
2069
 *   An array of CdmBase instances or a single instance.
2070
 * @param string $footnote_list_key
2071
 *
2072
 * @return unknown
2073
 */
2074
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
2075

    
2076
   static $annotations_types_filter = null;
2077
   if(!$annotations_types_filter) {
2078
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2079
   }
2080

    
2081
  $footNoteKeys = array();
2082

    
2083
  // Is argument cdmBase an array?
2084
  if (!is_array($cdmBase_list)) {
2085
    $cdmBase_array = array();
2086
    $cdmBase_array[] = $cdmBase_list;
2087
  }
2088
  else {
2089
    $cdmBase_array = $cdmBase_list;
2090
  }
2091

    
2092
  // Getting the key for the footnotemanager.
2093
  if (isset($footnote_list_key)) {
2094
    $footnoteListKey = $footnote_list_key;
2095
  }
2096
  else {
2097
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2098
  }
2099

    
2100
  // Adding the footnotes keys.
2101
  foreach ($cdmBase_array as $cdmBase_element) {
2102
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2103
    if (is_array($annotations)) {
2104
      foreach ($annotations as $annotation) {
2105
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2106
      }
2107
    }
2108
  }
2109

    
2110
  return $footNoteKeys;
2111
}
2112

    
2113
// @WA Comment: should this not be a theme function?
2114
/**
2115
 *  Creates a CDM Dynabox.
2116
 * @param string $dynabox_id
2117
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
2118
 * @param string $label
2119
 *   The clickable text to show.
2120
 * @param string $content_url
2121
 *   The cdm REST service request url wich will deliver the content to be shown
2122
 *   once the dynabox toggles open.
2123
 * @param string $theme
2124
 *   The theme to be used for rendering the cdm REST service reponse with is
2125
 *   returned from the $content_url.
2126
 * @param string $link_alt_text
2127
 *   The value for the alt attribute of the dynabox link.
2128
 * @param array $enclosingtags
2129
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2130
 *   element itself, $enclosingtags[1] is the tag to be used for the
2131
 *   dynabox_content (optional)
2132
 * @param string $open_callback
2133
 *   optional javascript call back function to be triggered after toggeling the box to
2134
 *   the open state.
2135
 * @param string $close_callback
2136
 *   optional javascript call back function to be triggered after toggeling the box to
2137
 *   the closed state.
2138
 *
2139
 * @return string
2140
 *   Returns HTML for a dynabox.
2141
 */
2142
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
2143
  $out = '';
2144

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

    
2148
  _add_js_domEvent(); // requires domEvent.js
2149
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2150
  drupal_add_js("
2151
  jQuery(document).ready(
2152
      function() {
2153
        dynabox('". $dynabox_id ."',
2154
          {
2155
            open_callback: " . $open_callback .",
2156
            close_callback: " . $close_callback ."
2157
          }
2158
        );
2159
      }
2160
   );",
2161
   array(
2162
    'type'=>'inline',
2163
    'scope'=>'footer'
2164
    )
2165
  );
2166

    
2167
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2168
  $out .= '<!-- ' . $content_url . ' -->';
2169
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2170
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '>' . loading_image_html() . '</' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2171
  $out .= '</' . $enclosingtags[0] . '>';
2172
  return $out;
2173
}
2174

    
2175
/**
2176
 * Checks whether a feature has any description elements.
2177
 *
2178
 * @param mixed $featureNode
2179
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2180
 *
2181
 * @see _mergeFeatureTreeDescriptions()
2182
 *
2183
 * @return bool
2184
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2185
 *   contains at least one non empty TextData or at least one DescriptionElement
2186
 *   of an other type. A TextData element holding a multilanguageText or a
2187
 *   source reference is considered to be not empty.
2188
 */
2189
function hasFeatureNodeDescriptionElements($featureNode) {
2190

    
2191
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2192
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2193
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2194
        return TRUE;
2195
      }
2196
    }
2197
  }
2198
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2199
    foreach ($featureNode->children as $child) {
2200
      if (hasFeatureNodeDescriptionElements($child)) {
2201
        return TRUE;
2202
      }
2203
    }
2204
  }
2205
  return FALSE;
2206
}
(6-6/13)