Project

General

Profile

Download (71.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
 * @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', $synonym_uuid = NULL) {
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
    'uuid' => $uuid,
1312
    'synonym_uuid' => $synonym_uuid,
1313
  ));
1314

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

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

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

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

    
1346
  return $taxonpage;
1347
}
1348

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

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

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

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

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

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

    
1473
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1474

    
1475
}
1476

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

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

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

    
1495
  $taxonPager = cdm_dataportal_search_execute();
1496

    
1497
  $showThumbnails = do_showThumbnails();
1498

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

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

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

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

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

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

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

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

    
1567
  return $showThumbnails;
1568
}
1569

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

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

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

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

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

    
1627
/**
1628
 * @todo Please document this function.
1629
 * @see http://drupal.org/node/1354
1630
 */
1631
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1632
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1633
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1634
}
1635

    
1636
/**
1637
 * Compses the drupal path to the key identified by the uuid.
1638
 *
1639
 * @param string $keyType
1640
 *    the key typer corresponds to the specific class of the CDM
1641
 *    IdentificationKey. Possible values are
1642
 *      -PolytomousKey
1643
 *      -MultimediaKey
1644
 *      - ...
1645
 * @param UUID $keyUuid
1646
 *   The UUID of the key
1647
 */
1648
function path_to_key($keyType, $keyUuid) {
1649
  if (!$keyUuid || !$keyType) {
1650
    return FALSE;
1651
  }
1652
  $keyType{0} = strtolower($keyType{0});
1653
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1654
}
1655

    
1656
/**
1657
 * @todo Please document this function.
1658
 * @see http://drupal.org/node/1354
1659
 */
1660
function path_to_reference($uuid) {
1661
  if (!$uuid) {
1662
    return FALSE;
1663
  }
1664
  return 'cdm_dataportal/reference/' . $uuid;
1665
}
1666

    
1667
/**
1668
 * @todo Please document this function.
1669
 * @see http://drupal.org/node/1354
1670
 */
1671
function path_to_name($name_uuid) {
1672
  $res = FALSE;
1673
  if ($name_uuid) {
1674
    $res = 'cdm_dataportal/name/' . $name_uuid;
1675
  }
1676
  return $res;
1677
}
1678

    
1679
/**
1680
 * @todo Please document this function.
1681
 * @see http://drupal.org/node/1354
1682
 */
1683
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1684
  if (!$uuid) {
1685
    return FALSE;
1686
  }
1687
  $out = 'cdm_dataportal/media/' . $uuid;
1688
  if ($representaion_uuid) {
1689
    $out .= '/' . $representaion_uuid;
1690
    if ($partId !== FALSE) {
1691
      $out .= '/' . $partId;
1692
    }
1693
  }
1694
  return $out;
1695
}
1696

    
1697
/**
1698
 * Compares thisRank with thatRank.
1699
 *
1700
 * Returns a negative integer, zero, or a positive integer
1701
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1702
 * e.g:
1703
 * <ul>
1704
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1705
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1706
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1707
 * </ul>
1708
 * <p>
1709
 * This compare logic of the underlying webservice is the
1710
 * <b>inverse logic</b> of the the one implemented in
1711
 * java.lang.Comparable#compareTo(java.lang.Object)
1712
 *
1713
 * @param $thisRankUuid
1714
 * @param $thatRankUuid
1715
 *
1716
 * @return int
1717
 *   A negative integer, zero, or a positive integer
1718
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1719
 */
1720
function rank_compare($thisRankUuid, $thatRankUuid) {
1721
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1722
  return $result->Integer;
1723
}
1724

    
1725
/**
1726
 * Composes an HTML element class attribute value composed of
1727
 * the shortname of the cdm class and the uuid of the entity.
1728
 * This class attribute should be used whereever an cdm-entity is rendered.
1729
 *
1730
 * These according class selectors in css must be escaped, eg:
1731
 *    .cdm\:TextData
1732
 *
1733
 * @param $cdmEntity
1734
 */
1735
function html_class_atttibute_ref($cdmEntity) {
1736

    
1737
  if (is_cdm_entity($cdmEntity)) {
1738
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1739
  }
1740
}
1741

    
1742
/**
1743
 * Preprocess the taggedName to normalize newly introduced
1744
 * tagtypes like hybridSign, separator, .. more?
1745
 *
1746
 * @param unknown_type $taggedTextList
1747
 */
1748
function normalize_TaggedName(&$taggedTextList) {
1749

    
1750
  if (is_array($taggedTextList)) {
1751

    
1752
    // First pass: rename.
1753
    for ($i = 0; $i < count($taggedTextList); $i++) {
1754

    
1755
      if ($taggedTextList[$i]->type == "hybridSign") {
1756
        $taggedTextList[$i]->type = "name";
1757
      }
1758
    }
1759

    
1760
    // Second pass: resolve separators.
1761
    $taggedNameListNew = array();
1762
    for ($i = 0; $i < count($taggedTextList); $i++) {
1763

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

    
1766
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1767
          $taggedName = $taggedTextList[$i];
1768
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1769
          $taggedNameListNew[] = $taggedName;
1770
          ++$i;
1771
          ++$i;
1772
        }
1773
      }
1774
      else {
1775
        $taggedNameListNew[] = $taggedTextList[$i];
1776
      }
1777
    }
1778
    $taggedTextList = $taggedNameListNew;
1779
  }
1780
}
1781

    
1782
/**
1783
 * Creates a short taxonname.
1784
 *
1785
 * The short name is created by using the taggename field of
1786
 * NameSTO or NameTO instances.
1787
 * If the taggename if empty the fullname will be returned.
1788
 *
1789
 * @param unknown_type $name
1790
 *   Name or TreeNode.
1791
 *
1792
 * @return string
1793
 */
1794
function cdm_dataportal_shortname_of($name) {
1795
  $nameStr = '';
1796

    
1797
  normalize_TaggedName($name->taggedTitle);
1798

    
1799
  // Get all tagged text tokens of the scientific name.
1800
  foreach ($name->taggedTitle as $tagtxt) {
1801
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1802
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1803
    }
1804
  }
1805
  $nameStr = trim($nameStr);
1806

    
1807
  if ($nameStr) {
1808

    
1809
    // Do not return short names for these.
1810
    if ($name->unplaced || $name->excluded) {
1811
      return $nameStr;
1812
    }
1813

    
1814
    /*
1815
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1816
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1817
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1818
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1819
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1820
    */
1821
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1822
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1823
      return $matches[1][0] . "." . $matches[3][0];
1824
    }
1825
    else {
1826
      return $nameStr;
1827
    }
1828
  }
1829
  else {
1830
    return $name->titleCache;
1831
  }
1832
}
1833

    
1834
/**
1835
 * Check if a taxon is accepted by the current taxonomic tree.
1836
 *
1837
 * @param mixed $taxon
1838
 *   The Taxon obkect to check.
1839
 *
1840
 * @return bool
1841
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1842
 */
1843
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1844

    
1845
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1846

    
1847
  if (isset($taxon->taxonNodes)) {
1848
    $taxonNodes = $taxon->taxonNodes;
1849
  }
1850
  else {
1851
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1852
  }
1853

    
1854
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1855
    foreach ($taxonNodes as $node) {
1856
      if (is_object($node->classification)) {
1857
        if ($node->classification->uuid == $defaultTreeUuid) {
1858
          return TRUE;
1859
        }
1860
      }
1861
      else {
1862
        if ($node->classification == $defaultTreeUuid) {
1863
          return TRUE;
1864
        }
1865
      }
1866
    }
1867
  }
1868

    
1869
  return FALSE;
1870
}
1871

    
1872
/**
1873
 * Workaround for missing original source type.
1874
 *
1875
 * idNamespace is always set in these cases.
1876
 * @todo improve documentation of this function.
1877
 *
1878
 * @param unknown_type $source
1879
 *
1880
 * @return unknown_type
1881
 */
1882
function _is_original_source_type($source) {
1883
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1884
}
1885

    
1886
/**
1887
 * @todo Please document this function.
1888
 * @see http://drupal.org/node/1354
1889
 */
1890
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1891
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1892
}
1893

    
1894
/**
1895
 * Gets the metadata info such as title or artist of a media file.
1896
 *
1897
 * The function tries at first to get all the info from the file metadata
1898
 * and if it is not avaible look at the media file info stored at the database.
1899
 *
1900
 * @param mixed $media
1901
 *   The media file object for which to get the metadata.
1902
 *
1903
 * @return array
1904
 *   The array with the available specified metadata info.
1905
 * TODO rename to read_media_metadata() and move to *.module.
1906
 */
1907
function cdm_read_media_metadata($media) {
1908

    
1909
  $metadata_caption = array(
1910
    'title' => '',// Media_metadata and media.
1911
    'artist' => '',// Media_metadata and media.
1912
    'rights',// Media_metadata and media.
1913
    'location',// Media_metadata.
1914
    'filename' => '',// Media.
1915
    'mediacreated' => '',// Media.
1916
    'description' => '',
1917
  );// Media.
1918

    
1919
  // Getting the media metadata.
1920
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1921
  $media_metadata_aux = (array) $media_metadata;
1922

    
1923
  // Filename.
1924
  if (!empty($media->representations[0]->parts[0]->uri)) {
1925
    $fileUri = $media->representations[0]->parts[0]->uri;
1926
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1927
    $metadata_caption['filename'] = $filename;
1928
  }
1929
  else {
1930
    $metadata_caption['filename'] = '';
1931
  }
1932

    
1933
  // Title.
1934
  if (!empty($media_metadata->ObjectName)) {
1935
    $metadata_caption['title'] = $media_metadata->ObjectName;
1936
  }
1937
  elseif (!empty($media_metadata_aux['Object Name'])) {
1938
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1939
  }
1940
  elseif (!empty($media->title_L10n)) {
1941
    $metadata_caption['title'] = $media->title_L10n;
1942
  }
1943
  elseif (!empty($media->titleCache)) {
1944
    $metadata_caption['title'] = $media->titleCache;
1945
  }
1946

    
1947
  // Append description to title.
1948
  if (!empty($media->description_L10n)) {
1949
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1950
  }
1951

    
1952
  // Artist.
1953
  if ($media_metadata->Artist) {
1954
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1955
  }
1956
  elseif (!empty($media->artist->titleCache)) {
1957
    $metadata_caption['artist'] = $media->artist->titleCache;
1958
  }
1959

    
1960
  // Copyright.
1961
  $metadata_caption['rights'] = array(
1962
    'copyright' => array('agentNames' => array()),
1963
    'license' => array(
1964
      'agentNames' => array(),
1965
      'types' => array(),
1966
      'abbreviatedTexts' => array(),
1967
      'uris' => array(),
1968
    ),
1969
  );
1970
  if (!empty($media_metadata->Copyright)) {
1971
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1972
  }
1973
  elseif (isset($media->rights) && is_array($media->rights)) {
1974
    foreach ($media->rights as $right) {
1975
      switch ($right->term->uuid) {
1976
        case UUID_RIGHTS_LICENCE:
1977
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1978
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1979
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1980
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1981
          break;
1982
        case UUID_RIGHTS_COPYRIGHT:
1983
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1984
          break;
1985
      }
1986
    }
1987
  }
1988
  else {
1989
    $metadata_caption['rights']['agentNames'][] = '';
1990
  }
1991

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

    
1995
  // Location.
1996
  $metadata_caption['location'] = array();
1997
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1998
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1999
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
2000
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
2001

    
2002
  /*
2003
   // Creation date.
2004
   if($media_metadata["Modify Date"])
2005
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
2006
   else
2007
   $metadata_caption['mediacreated'] = $media->created;
2008
   */
2009

    
2010
  // Returned value.
2011
  return $metadata_caption;
2012
}
2013

    
2014
/**
2015
 * Collects all the media from a list of description elements.
2016
 *
2017
 * @param array $descriptionElements
2018
 *   The description elements from which to collect the media.
2019
 *
2020
 * @return array
2021
 *   The output with all the collected media.
2022
 */
2023
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
2024

    
2025
  $outArrayOfMedia = array();
2026

    
2027
  // Avoiding a warning box in Drupal for Flora Malesiana.
2028
  if (isset($descriptionElements) && is_array($descriptionElements)) {
2029
    foreach ($descriptionElements as $descriptionElement) {
2030
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
2031
        foreach ($descriptionElement->media as $media) {
2032
          if (is_object($media)) {
2033
            $outArrayOfMedia[] = $media;
2034
          }
2035
        }
2036
      }
2037
    }
2038
  }
2039
  return $outArrayOfMedia;
2040
}
2041

    
2042
/**
2043
 * @todo Please document this function.
2044
 * @see http://drupal.org/node/1354
2045
 *
2046
 * @param array $cdmBase_list
2047
 *   An array of CdmBase instances or a single instance.
2048
 * @param string $footnote_list_key
2049
 *
2050
 * @return unknown
2051
 */
2052
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
2053

    
2054
   static $annotations_types_filter = null;
2055
   if(!$annotations_types_filter) {
2056
     $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2057
   }
2058

    
2059
  $footNoteKeys = array();
2060

    
2061
  // Is argument cdmBase an array?
2062
  if (!is_array($cdmBase_list)) {
2063
    $cdmBase_array = array();
2064
    $cdmBase_array[] = $cdmBase_list;
2065
  }
2066
  else {
2067
    $cdmBase_array = $cdmBase_list;
2068
  }
2069

    
2070
  // Getting the key for the footnotemanager.
2071
  if (isset($footnote_list_key)) {
2072
    $footnoteListKey = $footnote_list_key;
2073
  }
2074
  else {
2075
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2076
  }
2077

    
2078
  // Adding the footnotes keys.
2079
  foreach ($cdmBase_array as $cdmBase_element) {
2080
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2081
    if (is_array($annotations)) {
2082
      foreach ($annotations as $annotation) {
2083
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2084
      }
2085
    }
2086
  }
2087

    
2088
  return $footNoteKeys;
2089
}
2090

    
2091
// @WA Comment: should this not be a theme function?
2092
/**
2093
 *  Creates a CDM Dynabox.
2094
 * @param string $dynabox_id
2095
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
2096
 * @param string $label
2097
 *   The clickable text to show.
2098
 * @param string $content_url
2099
 *   The cdm REST service request url wich will deliver the content to be shown
2100
 *   once the dynabox toggles open.
2101
 * @param string $theme
2102
 *   The theme to be used for rendering the cdm REST service reponse with is
2103
 *   returned from the $content_url.
2104
 * @param string $link_alt_text
2105
 *   The value for the alt attribute of the dynabox link.
2106
 * @param array $enclosingtags
2107
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2108
 *   element itself, $enclosingtags[1] is the tag to be used for the
2109
 *   dynabox_content (optional)
2110
 * @param string $open_callback
2111
 *   optional javascript call back function to be triggered after toggeling the box to
2112
 *   the open state.
2113
 * @param string $close_callback
2114
 *   optional javascript call back function to be triggered after toggeling the box to
2115
 *   the closed state.
2116
 *
2117
 * @return string
2118
 *   Returns HTML for a dynabox.
2119
 */
2120
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
2121
  $out = '';
2122

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

    
2126
  _add_js_domEvent(); // requires domEvent.js
2127
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2128
  drupal_add_js("
2129
  jQuery(document).ready(
2130
      function() {
2131
        dynabox('". $dynabox_id ."',
2132
          {
2133
            open_callback: " . $open_callback .",
2134
            close_callback: " . $close_callback ."
2135
          }
2136
        );
2137
      }
2138
   );",
2139
   array(
2140
    'type'=>'inline',
2141
    'scope'=>'footer'
2142
    )
2143
  );
2144

    
2145
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2146
  $out .= '<!-- ' . $content_url . ' -->';
2147
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2148
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '>' . loading_image_html() . '</' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2149
  $out .= '</' . $enclosingtags[0] . '>';
2150
  return $out;
2151
}
2152

    
2153
/**
2154
 * Checks whether a feature has any description elements.
2155
 *
2156
 * @param mixed $featureNode
2157
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2158
 *
2159
 * @see _mergeFeatureTreeDescriptions()
2160
 *
2161
 * @return bool
2162
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2163
 *   contains at least one non empty TextData or at least one DescriptionElement
2164
 *   of an other type. A TextData element holding a multilanguageText or a
2165
 *   source reference is considered to be not empty.
2166
 */
2167
function hasFeatureNodeDescriptionElements($featureNode) {
2168

    
2169
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2170
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2171
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
2172
        return TRUE;
2173
      }
2174
    }
2175
  }
2176
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2177
    foreach ($featureNode->children as $child) {
2178
      if (hasFeatureNodeDescriptionElements($child)) {
2179
        return TRUE;
2180
      }
2181
    }
2182
  }
2183
  return FALSE;
2184
}
(6-6/13)