Project

General

Profile

Download (72.5 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
 * @todo Please document this function.
707
 * @see http://drupal.org/node/1354
708
 */
709
function cdm_dataportal_init() {
710
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
711
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
712
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
713
}
714

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

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

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

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

    
744
  return $form;
745
}
746

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

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

    
782
/**
783
 * Implements hook_block_info().
784
 */
785
function cdm_dataportal_block_info() {
786

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

    
799
    return $block;
800
}
801

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

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

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

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

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

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

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

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

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

    
892
  $destination_array = drupal_get_destination();
893
  $destination = $destination_array['destination'];
894

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

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

    
908
  return $form;
909

    
910
}
911

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

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

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

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

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

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

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

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

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

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

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

    
1037
  static $media = NULL;
1038

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

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

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

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

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

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

    
1073
  return $media[$taxon->uuid];
1074
}
1075

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

    
1086
  static $occurences = NULL;
1087

    
1088
  if(!isset($occurences)) {
1089
    $occurences = array();
1090
  }
1091

    
1092
  if (!isset($occurences[$taxon->uuid])){
1093

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

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

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

    
1110

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

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

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

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

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

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

    
1211
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1212

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1344
  return $taxonpage;
1345
}
1346

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

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

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

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

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

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

    
1471
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1472

    
1473
}
1474

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

    
1485
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1486
}
1487

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

    
1493
  $taxonPager = cdm_dataportal_search_execute();
1494

    
1495
  $showThumbnails = do_showThumbnails();
1496

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

    
1501
  drupal_add_js('jQuery(document).ready(function() {
1502

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

    
1526
  drupal_set_title(t('Search results'), PASS_THROUGH);
1527

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

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

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

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

    
1565
  return $showThumbnails;
1566
}
1567

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

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

    
1604
  $tab = get_default_taxon_tab();
1605
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1606

    
1607
  if (!$uuid) {
1608
    return FALSE;
1609
  }
1610

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

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

    
1654
}
1655

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

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

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

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

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

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

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

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

    
1770
  if (is_array($taggedTextList)) {
1771

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

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

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

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

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

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

    
1817
  normalize_TaggedName($name->taggedTitle);
1818

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

    
1827
  if ($nameStr) {
1828

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

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

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

    
1865
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1866

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

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

    
1889
  return FALSE;
1890
}
1891

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2030
  // Returned value.
2031
  return $metadata_caption;
2032
}
2033

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

    
2045
  $outArrayOfMedia = array();
2046

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

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

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

    
2079
  $footNoteKeys = array();
2080

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

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

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

    
2108
  return $footNoteKeys;
2109
}
2110

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

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

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

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

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

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