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
 * Created a view on a all references contained in the portal.
988
 *
989
 * This function is used at the path cdm_dataportal/reference/list
990
 */
991
function cdm_dataportal_view_reference_list($pageNumber) {
992
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
993
  return theme('cdm_reference_pager', array(
994
    'referencePager' => $referencePager,
995
    'path' => 'cdm_dataportal/reference/list/',
996
    ));
997
}
998

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

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

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

    
1040
  static $media = NULL;
1041

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

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

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

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

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

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

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

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

    
1089
  static $occurences = NULL;
1090

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

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

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

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

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

    
1113

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1347
  return $taxonpage;
1348
}
1349

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

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

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

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

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

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

    
1474
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1475

    
1476
}
1477

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

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

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

    
1496
  $taxonPager = cdm_dataportal_search_execute();
1497

    
1498
  $showThumbnails = do_showThumbnails();
1499

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

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

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

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

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

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

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

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

    
1568
  return $showThumbnails;
1569
}
1570

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

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

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

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

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

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

    
1657
}
1658

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

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

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

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

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

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

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

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

    
1773
  if (is_array($taggedTextList)) {
1774

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

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

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

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

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

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

    
1820
  normalize_TaggedName($name->taggedTitle);
1821

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

    
1830
  if ($nameStr) {
1831

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

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

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

    
1868
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1869

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

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

    
1892
  return FALSE;
1893
}
1894

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2048
  $outArrayOfMedia = array();
2049

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

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

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

    
2082
  $footNoteKeys = array();
2083

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

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

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

    
2111
  return $footNoteKeys;
2112
}
2113

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

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

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

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

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

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