Project

General

Profile

Download (71.8 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Module to provide a CDM Dataportal.
5
 *
6
 * @copyright
7
 *   (C) 2007-2012 EDIT
8
 *   European Distributed Institute of Taxonomy
9
 *   http://www.e-taxonomy.eu
10
 *
11
 *   The contents of this module are subject to the Mozilla
12
 *   Public License Version 1.1.
13
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
14
 *
15
 * @author
16
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
17
 *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
18
 */
19

    
20
module_load_include('php', 'cdm_dataportal', 'node_types');
21
module_load_include('php', 'cdm_dataportal', 'settings');
22
module_load_include('php', 'cdm_dataportal', 'help');
23
module_load_include('php', 'cdm_dataportal', 'cdm_dataportal.search');
24

    
25
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
26
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
27
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
28
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
29
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
30
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
31
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
32
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
33
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.bibliography');
34

    
35
module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
36
module_load_include('php', 'cdm_dataportal', 'classes/footnote');
37
module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
38
module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
39

    
40
/**
41
* loads external java script files asynchronously.
42
*
43
* @param unknown_type $script_url
44
*/
45
function drupal_add_js_async($script_url, $callback){
46

    
47
  drupal_add_js("
48
        jQuery(document).ready(function() {
49
          jQuery.ajax({
50
            url: '" . $script_url . "',
51
            dataType: 'script',
52
            cache: true, // otherwise will get fresh copy every page load
53
            success: function() {
54
                  " . $callback . "
55
            }
56
          });
57
        });"
58
  , 'inline');
59
}
60

    
61
/**
62
 * @param unknown_type $link_element_selector
63
 * @param unknown_type $progress_element_selector
64
 */
65
function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
66

    
67
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
68

    
69
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
70

    
71
  //   drupal_add_js("
72
  //   	  if (Drupal.jsEnabled) {
73
  //         $(document).ready(function() {
74
  //       		$('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');
75
  //         });
76
  //       }", 'inline');
77
  }
78

    
79
/**
80
 * @todo Please document this function.
81
 * @see http://drupal.org/node/1354
82
 */
83
function _add_js_treeselector() {
84
  // drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
85
  drupal_add_js("
86
      jQuery(document).ready(function() {
87
         jQuery('#cdm-taxonomictree-selector-form #edit-val').change(function () {
88
              jQuery('#cdm-taxonomictree-selector-form').submit();
89
          });
90

    
91
      });
92
    ",
93
    array(
94
      'type' => 'inline',
95
      'scope' => 'footer'
96
    )
97
  );
98
}
99

    
100
/**
101
 * @todo Please document this function.
102
 * @see http://drupal.org/node/1354
103
 */
104
function _add_js_openlayers_map() {
105

    
106
  $openlayers = '/js/OpenLayers-2.11/OpenLayers.js';
107

    
108
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $openlayers, array(
109
      'type' => 'file',
110
      'weight' => JS_LIBRARY,
111
      'cache' => FALSE,
112
  ));
113

    
114
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
115

    
116
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
117

    
118
  $baseLayers = variable_get('baselayers', array());
119
  if (!is_array($baseLayers) || count($baseLayers) == 0) {
120
    $baseLayers = array(
121
      'metacarta_vmap0' => 'Metacarta Vmap0',
122
      'PREFERRED' => 'metacarta_vmap0',
123
    );
124
  }
125
  $layerNames = '';
126
  foreach ($baseLayers as $layerName => $layerLabel) {
127
    if ($layerName == 'PREFERRED') {
128
      $preferredLayer = $baseLayers['PREFERRED'];
129
    }
130
    else {
131
      $layerNames .= ($layerNames ? ', ' : '') . "'$layerName'";
132
    }
133
  }
134

    
135
  if (isset($baseLayers['gmap']) || isset($baseLayers['gsat']) || isset($baseLayers['ghyb'])) {
136
    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. */);
137
    drupal_add_js('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1', array('type' => 'external'));
138
  }
139

    
140
  // window.onload - is executed when the document and images etc is fully loaded
141
  // Query(document).ready - is executed much earlier, when the DOM is loaded
142
  drupal_add_js("
143
          jQuery(document).ready(function() {
144

    
145
                window.onload = function () {
146
    			  // ---
147
                  jQuery('#openlayers_map').cdm_openlayers_map('"
148
                  . getEDITMapServiceURI() . "', {
149
                    legendPosition: 3,
150
                    displayWidth: '" . variable_get('cdm_dataportal_geoservice_display_width', FALSE) . "',
151
                    boundingBox: '" . variable_get('cdm_dataportal_geoservice_bounding_box', FALSE) . "',
152
                    distributionOpacity: '" . variable_get('cdm_dataportal_geoservice_distributionOpacity', '0.5') . "',
153
                    legendOpacity: '" . variable_get('cdm_dataportal_geoservice_legendOpacity', '0.5') . "',
154
                    showLayerSwitcher: " . (variable_get('cdm_dataportal_geoservice_showLayerSwitcher', TRUE) ? 'true' : 'false') . ",
155
                    baseLayerNames: [" . $layerNames . "],
156
                    defaultBaseLayerName: '" . $preferredLayer . "',
157
               	  });
158
               	  // ---
159
				};
160
          });
161
        ", array('type' => 'inline'));
162

    
163
}
164

    
165
/**
166
 * @todo Enter description here ...
167
 *
168
 * @param unknown_type $width
169
 * @param unknown_type $bounding_box
170
 * @param unknown_type $occurrenceQuery
171
 * @param unknown_type $distributionQuery
172
 * @param unknown_type $legendFormatQuery
173
 * @param unknown_type $map_caption
174
 *
175
 * @return unknown
176
 */
177
function get_image_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
178

    
179
  $server = getEDITMapServiceURI();
180

    
181
  if (!$server) {
182
    // Warning message.
183
    drupal_set_message(t(
184
      "No 'Geoservice Access Point' has been set so far.
185
      Please configure the variable 'Geoservice Access Point' here !url", array(
186
        '!url' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/geo'),
187
      )), 'warning');
188

    
189
    // Message to render.
190
    return '<p>' . t('No geoservice specified') . '</p>';
191
  }
192

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

    
196
  $query_string = '&image=true&recalculate=false&legend=1&ms=' . $width
197
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
198
    . ($labels_on ? '&label=' . $labels_on : '');
199

    
200
  if ($map_caption) {
201
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
202
  }
203

    
204
  if (getEDITMapServiceVersionNumber() >= 1.1) {
205

    
206
    // Either occurrence or distribution - combined maps will be possible
207
    // in the future.
208
    if ($occurrenceQuery) {
209
      // @todo Fix $occurrenceQuery.
210
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
211
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
212
      // Will be replaced below.. HACK!!!
213
      $occurrenceQuery .= '&l=tdwg4&as=';
214

    
215
      $query_string .= "&" . $occurrenceQuery;
216
    }
217
    elseif ($distributionQuery) {
218
      $query_string .= "&" . $distributionQuery;
219
    }
220

    
221
    // Apply Plain Image map settings special for version >= 1.1.
222
    /*
223
    example : title=a:Naturalized++non-invasive
224
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
225
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
226
    &mc_s=Georgia,15,blue&mc=&recalculate=false
227

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

    
235
    $map_service_script_name = "rest_gen.php";
236

    
237
    $bgcolor_areaStyleId = "y";
238
    $baselayer_areaStyleId = "z";
239
    $bgcolor_layer = '';
240
    $additional_area_styles = array();
241

    
242
    // Background color:
243
    if (variable_get('map_bg_color', '')) {
244
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
245
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
246
    }
247

    
248
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
249
    // only needed for distribution maps.
250
    if (strpos($query_string, "?l=") !== FALSE) {
251
      $layer_param_token = "?l=";
252
    }
253
    else {
254
      $layer_param_token = "&l=";
255
    }
256
    if (strpos($query_string, "?as=") !== FALSE) {
257
      $areystyle_param_token = "?as=";
258
    }
259
    else {
260
      $areystyle_param_token = "&as=";
261
    }
262
    if (variable_get('map_base_layer', '')) {
263
      $query_string = str_replace($layer_param_token . "tdwg4", "$layer_param_token" . variable_get('map_base_layer', '') . ":" . $baselayer_areaStyleId, $query_string);
264
    }
265
    else {
266
      $query_string = str_replace($layer_param_token . "tdwg4", $layer_param_token . "tdwg4:" . $baselayer_areaStyleId . ",", $query_string);
267
    }
268

    
269
    if ($bgcolor_layer) {
270
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
271
    }
272

    
273
    if (variable_get('map_base_layer_style', '')) {
274
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
275
    }
276

    
277
    foreach ($additional_area_styles as $as) {
278
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
279
    }
280

    
281
  }
282
  else {
283
    // Pre 1.1. version of map service.
284
    if ($occurrenceQuery) {
285

    
286
      $map_service_script_name = "point.php";
287

    
288
      // Fix $occurrenceQuery.
289
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
290
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
291
      $occurrenceQuery .= '&l=v:e_w_0';
292
      $query_string .= "&" . $occurrenceQuery;
293
    }
294
    elseif ($distributionQuery) {
295
      $query_string .= "&" . $distributionQuery;
296
      $map_service_script_name = "areas.php";
297
    }
298
  }
299

    
300
  $mapUri = url("$server/$map_service_script_name?$query_string");
301
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
302
  // Showing map caption.
303
  if ($map_caption) {
304
    // FIXME: replace <br> by according css style.
305
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
306
    $out .= '</div>';
307
  }
308

    
309
  return $out;
310
}
311

    
312
/**
313
 * @todo Enter description here ...
314
 *
315
 * @param unknown_type $width
316
 * @param unknown_type $bounding_box
317
 * @param unknown_type $occurrenceQuery
318
 * @param unknown_type $distributionQuery
319
 * @param unknown_type $legendFormatQuery
320
 * @param unknown_type $map_caption
321
 *
322
 * @return unknown
323
 */
324
function get_openlayers_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
325

    
326
  _add_js_openlayers_map();
327

    
328
  $out = '<div id="openlayers">';
329
  $out .= '<div id="openlayers_map" class="smallmap"';
330
  $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
331

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

    
335
  $openlayers_map_query_string = '&img=false&ms=' . $width
336
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
337
    . ($labels_on ? '&label=' . $labels_on : '');
338

    
339
  if ($occurrenceQuery) {
340
    // @todo Fix $occurrenceQuery.
341
    $occurrenceQuery .= '&bbox=-180,-90,180,90';
342
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
343
    // $occurrenceQuery .= '&l=v:e_w_0';
344
    // TODO add to cdm service?
345
    $occurrenceQuery .= '&legend=0';
346

    
347
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
348
  }
349

    
350
  if ($distributionQuery) {
351
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
352
  }
353

    
354
  if ($legendFormatQuery) {
355
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
356
  }
357

    
358
  $out .= '></div></div>';
359

    
360
  // Showing map caption.
361
  if ($map_caption) {
362
    // FIXME: replace <br> by according css style.
363
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
364
    $out .= '</div>';
365
  }
366
  return $out;
367
}
368

    
369
/* ====================== hook implementations ====================== */
370
/**
371
 * Implements hook_permission().
372
 *
373
 * Valid permissions for this module.
374
 *
375
 * @return array
376
 *   An array of valid permissions for the portfolio module.
377
 */
378
function cdm_dataportal_permission() {
379
  return array(
380
    'administer cdm_dataportal' => array(
381
      'title' => t('administer cdm_dataportal'),
382
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
383
    ),
384
    'cdm_dataportal view notes' => array(
385
      'title' => t('cdm_dataportal view notes'),
386
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
387
    ),
388
    // TODO Which other permissions are required?
389
    // -> check the WP6 requirements document.
390
  );
391
}
392

    
393
/**
394
 * Implements hook_menu().
395
 */
396
function cdm_dataportal_menu() {
397
  $items = array();
398

    
399
  // @see settings.php.
400
  cdm_dataportal_menu_admin($items);
401
  cdm_dataportal_menu_help($items);
402

    
403
  $items['cdm_dataportal/names'] = array(
404
    'page callback' => 'cdm_dataportal_view_names',
405
    'access arguments' => array('access content'),
406
    'type' => MENU_CALLBACK,
407
  );
408

    
409
  // Optional callback arguments: page.
410
  $items['cdm_dataportal/taxon'] = array(
411
    'page callback' => 'cdm_dataportal_taxon_page_view',
412
    'access arguments' => array('access content'),
413
    'type' => MENU_CALLBACK,
414
    // Expected callback arguments: uuid.
415
  );
416

    
417
  $items['cdm_dataportal/name'] = array(
418
    'page callback' => 'cdm_dataportal_name_page_view',
419
      /*
420
    'page arguments' => array(
421
       'taxon_name_uuid',
422
       'taxon_to_hide_uuid',
423
       'synonym_uuid' => NULL
424
      ),
425
      */
426
    'access arguments' => array('access content'),
427
    'type' => MENU_CALLBACK,
428
    // Expected callback arguments: uuid.
429
  );
430

    
431
  $items['cdm_dataportal/reference'] = array(
432
    'page callback' => 'cdm_dataportal_view_reference',
433
    'access arguments' => array('access content'),
434
    'type' => MENU_CALLBACK,
435
    // Expected callback arguments: uuid.
436
  );
437

    
438
  $items['cdm_dataportal/reference/list'] = array(
439
    'page callback' => 'cdm_dataportal_view_reference_list',
440
    'access arguments' => array('access content'),
441
    'type' => MENU_CALLBACK,
442
    // Expected callback arguments: uuid.
443
  );
444

    
445
  $items['cdm_dataportal/media'] = array(
446
    'page callback' => 'cdm_dataportal_view_media',
447
    'access arguments' => array('access content'),
448
    'type' => MENU_CALLBACK,
449
    // Expected callback arguments:
450
    // uuid, mediarepresentation_uuid, part_uuid or part#.
451
  );
452

    
453
  $items['cdm_dataportal/polytomousKey'] = array(
454
    'page callback' => 'cdm_dataportal_view_polytomousKey',
455
    'access arguments' => array('access content'),
456
    'type' => MENU_CALLBACK,
457
    // Expected callback arguments: polytomousKey->uuid.
458
  );
459

    
460
  $items['cdm_dataportal/search'] = array(
461
    'page callback' => 'cdm_dataportal_view_search_advanced',
462
    'access arguments' => array('access content'),
463
    'type' => MENU_CALLBACK,
464
  );
465

    
466
  $items['cdm_dataportal/search/advanced'] = array(
467
    'title' => 'Advanced',
468
    'page callback' => 'cdm_dataportal_view_search_advanced',
469
    'access arguments' => array('access content'),
470
    'type' => MENU_DEFAULT_LOCAL_TASK,
471
  );
472

    
473
  $items['cdm_dataportal/search/taxon_by_description'] = array(
474
    'title' => 'By description full text',
475
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
476
    'access arguments' => array('access content'),
477
    'type' => MENU_LOCAL_TASK,
478
  );
479

    
480
  $items['cdm_dataportal/search/results/taxon'] = array(
481
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
482
    'access arguments' => array('access content'),
483
    'type' => MENU_CALLBACK,
484
  );
485
  /*
486
   $items['cdm/xml2json'] = array(
487
   'page callback' => 'cdm_view_xml2json',
488
   'access arguments' => array('access content'),
489
   'type' => MENU_CALLBACK,
490
   );
491
   */
492

    
493
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
494
  // User configuration of cdm_dataportal.
495
  $items['user/%/cdm_dataportal'] = array(
496
    'title' => 'cdm_dataportal',
497
    'access arguments' => array('access content'),
498
    'page callback' => 'drupal_get_form',
499
    'page arguments' => array('cdm_dataportal_user_form'),
500
    'type' => MENU_LOCAL_TASK,
501
    'weight' => 10,
502
  );
503
  // }
504

    
505
  // 'May not cache' in D5.
506
  // --- Local tasks for Taxon.
507
  $items['cdm_dataportal/name/%'] = array(
508
    // 'page callback' => 'cdm_dataportal_view_name',
509
    'page callback' => 'cdm_dataportal_name_page_view',
510
    'page arguments' => array(2, 3, 4),
511
    'access arguments' => array('access content'),
512
    'type' => MENU_CALLBACK,
513
  );
514

    
515
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
516
    $items['cdm_dataportal/taxon/%'] = array(
517
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
518
      'page callback' => 'cdm_dataportal_taxon_page_view',
519
      'access arguments' => array('access content'),
520
      'type' => MENU_CALLBACK,
521
      'weight' => 1,
522
      'page arguments' => array(2, "description")
523
      , // Expected callback arguments: name_uuid.
524
    );
525

    
526
    $items['cdm_dataportal/taxon/%/all'] = array(
527
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
528
      'page callback' => 'cdm_dataportal_taxon_page_view',
529
      'access arguments' => array('access content'),
530
      'type' => MENU_CALLBACK,
531
      'weight' => 2,
532
      'page arguments' => array(2, "all")
533
      , // Expected callback arguments: name_uuid.
534
    );
535

    
536
    $items['cdm_dataportal/taxon/%/description'] = array(
537
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
538
      'page callback' => 'cdm_dataportal_taxon_page_view',
539
      'access arguments' => array('access content'),
540
      'type' => MENU_DEFAULT_LOCAL_TASK,
541
      'weight' => 2,
542
      'page arguments' => array(2, "description")
543
      , // Expected callback arguments: name_uuid.
544
    );
545

    
546
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
547
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
548
      'page callback' => 'cdm_dataportal_taxon_page_view',
549
      'access arguments' => array('access content'),
550
      'type' => MENU_LOCAL_TASK,
551
      'weight' => 4,
552
      'page arguments' => array(2, "synonymy", 4)
553
      , // Expected callback arguments: name_uuid.
554
    );
555
    $items['cdm_dataportal/taxon/%/images'] = array(
556
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
557
      'page callback' => 'cdm_dataportal_taxon_page_view',
558
      'access arguments' => array('access content'),
559
      'type' => MENU_LOCAL_TASK,
560
      'weight' => 5,
561
      'page arguments' => array(2, "images")
562
      , // Expected callback arguments: name_uuid.
563
    );
564

    
565
    $items['cdm_dataportal/taxon/%/specimens'] = array(
566
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
567
      'page callback' => 'cdm_dataportal_taxon_page_view',
568
      'access arguments' => array('access content'),
569
      'type' => MENU_LOCAL_TASK,
570
      'weight' => 6,
571
      'page arguments' => array(2, "specimens")
572
      , // Expected callback arguments: name_uuid.
573
    );
574

    
575
    $items['cdm_dataportal/taxon/%/keys'] = array(
576
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
577
      'page callback' => 'cdm_dataportal_taxon_page_view',
578
      'access arguments' => array('access content'),
579
      'type' => MENU_LOCAL_TASK,
580
      'weight' => 6,
581
      'page arguments' => array(2, "keys")
582
      , // Expected callback arguments: name_uuid.
583
    );
584
  }
585

    
586
  return $items;
587
}
588

    
589
/**
590
 * @todo Please document this function.
591
 * @see http://drupal.org/node/1354
592
 */
593
function cdm_dataportal_init() {
594
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
595
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
596
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
597
}
598

    
599
/**
600
 * The function generate form for own user cdm dataportal configurations.
601
 */
602
function cdm_dataportal_user_form($form, &$form_state) {
603
  global $user;
604
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
605

    
606
  $form['check'] = array(
607
    '#type' => 'checkbox',
608
    '#title' => t('Activate user default configuration'),
609
    '#default_value' => variable_get($checkbox_value, 0),
610
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
611
  );
612

    
613
  $form['cdm_dataportal_user_form'] = array(
614
    '#type' => 'select',
615
    '#title' => t('Default tab to display'),
616
    '#default_value' => get_default_taxon_tab(TRUE),
617
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
618
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
619
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
620
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
621
  );
622

    
623
  $form['submit'] = array(
624
    '#type' => 'submit',
625
    '#value' => t('Submit'),
626
  );
627

    
628
  return $form;
629
}
630

    
631
/**
632
 * Form submission handler for user_form().
633
 *
634
 * Submits the user cdm dataportal configurations.
635
 */
636
function cdm_dataportal_user_form_submit($form, &$form_state) {
637
  global $user;
638
  $msg_type = 'status';
639
  $username = $user->name;
640
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
641

    
642
  // If is the right user the variables are setted.
643
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
644
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
645
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
646
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
647
    if ($form_state['values']['check']) {
648
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
649
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
650
        '!tab' => $variable[variable_get($variable_to_use, 0)],
651
        '!user' => $username,
652
      ))), $msg_type);
653
    }
654
    else {
655
      drupal_set_message(check_plain(t('The user default tab wont be used for
656
        the next taxon site, check the box if you want to use the user default configuration.')));
657
    }
658
    // Problem with the user id => variables wont be saved.
659
  }
660
  else {
661
    $msg_type = 'warning';
662
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
663
  }
664
}
665

    
666
/**
667
 * Implements hook_block_info().
668
 */
669
function cdm_dataportal_block_info() {
670

    
671
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
672
    // $block[1]["info"] = t("CDM DataPortal Credits");
673
    $block["2"]["info"] = t("CDM Search Taxa");
674
    // $block[3]["info"] = t("CDM Filters");
675
    $block["4"]["info"] = t("CDM Dataportal Print");
676
    $block["keys"]["info"] = t("CDM identification keys");
677
    $block["uses"]["info"] = t("CDM Uses");
678
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
679

    
680
    return $block;
681
}
682

    
683
/**
684
 * Implements hook_block_view().
685
 */
686
function cdm_dataportal_block_view($delta) {
687
  // TODO Rename block deltas (e.g. '2') to readable strings.
688
  switch ($delta) {
689
    // case 'delta-1':
690
    // $block['subject'] = t('Credits');
691
    // $block['content'] = theme('cdm_credits');
692
    // return $block;
693
    case '2':
694
      $block['subject'] = t('Search taxa');
695
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
696
      $block['content'] = drupal_render($form);
697

    
698
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
699
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
700
      }
701
      return $block;
702
    case '4':
703
      $block['subject'] = t('<none>');
704
      $block['content'] = theme('cdm_print_button');
705
      return $block;
706
    case "keys":
707
      $block['subject'] = t('Identification Keys');
708
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
709
      return $block;
710
      // Creating a block specific for the Use Interface.
711
    case "uses":
712
      $block['subject'] = t('Uses');
713
      $block['content'] = theme('cdm_block_uses', array('taxonUuid' => NULL));
714
      return $block;
715
    case "fundedByEDIT":
716
      // t('Funded by EDIT');
717
      $text = '<none>';
718
      $block['subject'] = $text;
719
      $img_tag = '<img src="' . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
720
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
721
        'attributes' => array("target" => "EDIT"),
722
        'absolute' => TRUE,
723
        'html' => TRUE,
724
      ));
725
      return $block;
726
  }
727
}
728

    
729
/*
730
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
731
 $_SESSION['cdm'] = NULL;
732
 if(is_string($cdm_ws_uri_update)){
733
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
734
 }
735
 }
736

    
737
 function cdm_dataportal_session_validate(){
738
 if(!isset($_SESSION['cdm']['ws_uri'])){
739
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
740
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
741
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
742
 }
743
 }
744
 */
745

    
746
/**
747
 * @todo Please document this function.
748
 * @see http://drupal.org/node/1354
749
 */
750
function cdm_taxonomictree_selector() {
751
  _add_js_treeselector();
752

    
753
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
754
  $out = drupal_render($form);
755
  return $out;
756
}
757

    
758
/**
759
 * @todo Please document this function.
760
 * @see http://drupal.org/node/1354
761
 */
762
function cdm_taxonomictree_selector_form($form, &$form_state) {
763

    
764
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
765
  $form['#action'] = $url;
766

    
767
  $form['var'] = array(
768
    '#weight' => -3,
769
    '#type' => 'hidden',
770
    '#value' => '[cdm][taxonomictree_uuid]',
771
  );
772

    
773
  $destination_array = drupal_get_destination();
774
  $destination = $destination_array['destination'];
775

    
776
  $form['destination'] = array(
777
    '#weight' => -3,
778
    '#type' => 'hidden',
779
    '#value' =>  $destination,
780
  );
781

    
782
  $form['val'] = array(
783
    '#type' => 'select',
784
    '#title' => t('Available classifications'),
785
    '#default_value' => get_taxonomictree_uuid_selected(),
786
    '#options' => cdm_get_taxontrees_as_options(),
787
  );
788

    
789
  return $form;
790

    
791
}
792

    
793
/**
794
 * Implements hook_theme().
795
 *
796
 * Registering themes with a theme hook is needed since Drupal 6.
797
 *
798
 * @author W. Addink <w.addink@eti.uva.nl>
799
 */
800
function cdm_dataportal_theme() {
801
  return array(
802
    // Themes in help.php.
803
    'cdm_dataportal_admin_config_cdm_dataportal_general' => array('variables' => array()),
804
    'cdm_dataportal_admin_config_cdm_dataportal_geo' => array('variables' => array()),
805
    'cdm_dataportal_admin_config_cdm_dataportal_layout' => array('variables' => array()),
806
    'cdm_dataportal_admin_config_cdm_dataportal_cachesite' => array('variables' => array()),
807
    'cdm_dataportal_admin_config_more_help_link' => array('variables' => array()),
808

    
809
    // Themes in settings.php.
810
    'checkboxes_preferred' => array('render element' => 'element'),
811

    
812
    // Themes in cdm_dataportal.common.theme.
813
    'cdm_taggedtext2html' => array('variables' => array(
814
      'taggedtxt' => array(),
815
      'tag' => 'span',
816
      'glue' => ' ',
817
      'skiptags' => array(),
818
      )),
819
    'cdm_annotations_as_footnotekeys' => array('variables' => array('cdmBase_list' => NULL, 'footnote_list_key' => NULL)),
820
    'cdm_annotation_footnotes' => array('variables' => array('footnoteListKey' => NULL, 'enclosingTag' => 'span')),
821
    'cdm_annotation_content' => array('variables' => array('AnnotationTO' => NULL)),
822
    'cdm_list_of_annotations' => array('variables' => array('annotationElements' => NULL)),
823
    'cdm_footnote_key' => array('variables' => array(
824
      'footnoteKey' => NULL,
825
      'separator' => '',
826
      'highlightable' => TRUE,
827
      'separator_off' => FALSE,
828
      )),
829
    'cdm_footnote' => array('variables' => array('footnoteKey' => NULL, 'footnoteText' => NULL)),
830
    'cdm_footnotes' => array('variables' => array(
831
      'footnoteListKey' => NULL,
832
      'enclosingTag' => 'span',
833
      )),
834
    'cdm_annotations' => array('variables' => array('annotations' => NULL, 'enclosingTag' => 'span')),
835
    'cdm_pager' => array('variables' => array('pager' => NULL, 'path' => NULL, 'parameters' => NULL)),
836
    'cdm_pager_link' => array('variables' => array(
837
      'text' => NULL,
838
      'linkIndex' => NULL,
839
      'pager' => NULL,
840
      'path' => NULL,
841
      'parameters' => array(),
842
      'attributes' => NULL,
843
      )),
844
    'cdm_back_to_search_result_button' => array('variables' => array()),
845
    'cdm_back_to_image_gallery_button' => array('variables' => array()),
846
    'cdm_print_button' => array('variables' => array()),
847

    
848
    // Themes in cdm_dataportal.descriptions.theme.
849
    'cdm_feature_nodesTOC' => array('variables' => array('featureNodes' => NULL)),
850
    'cdm_feature_name' => array('variables' => array('feature_name' => NULL)),
851
    'cdm_featureTrees' => array('variables' => array('mergedTrees' => NULL, 'taxon' => NULL)),
852
    'cdm_featureTreeTOCs' => array('variables' => array('mergedTrees' => NULL)),
853
    'cdm_feature_nodes' => array('variables' => array('mergedFeatureNodes' => NULL, 'taxon' => NULL)),
854
    'FeatureTree_hierarchy' => array('variables' => array('FeatureTreeUuid' => NULL)),
855
    'FeatureTree_hierarchy_children' => array('variables' => array('node' => NULL)),
856
    'cdm_descriptionElementArray' => array('variables' => array(
857
      'elementArray' => array(),
858
      'feature' => NULL,
859
      'glue' => '',
860
      'sortArray' => FALSE,
861
      'enclosingHtml' => 'ul',
862
      )),
863
    'cdm_descriptionElement_CommonTaxonName' => array('render element' => 'element'),
864
    'cdm_descriptionElement_CategoricalData' => array('render element' => 'element'),
865
    'cdm_descriptionElementTextData' => array('variables' => array(
866
      'element' => NULL,
867
      'asListElement' => NULL,
868
      'feature_uuid' => NULL,
869
      )),
870
    'cdm_common_names' => array('render element' => 'elements'),
871
    'cdm_descriptionElements' => array('variables' => array(
872
      'descriptionElements' => NULL,
873
      'featureUuid' => NULL,
874
      'taxon_uuid' => NULL,
875
      )),
876
    'cdm_description_element_image_source' => array('variables' => array(
877
      'image_sources' => NULL,
878
      'asListElement' => NULL,
879
      )),
880
    'cdm_descriptionElementDistribution' => array('variables' => array(
881
      'descriptionElements' => NULL,
882
      'enclosingTag' => 'span',
883
      )),
884
    'cdm_description_ordered_distributions' => array('variables' => array(
885
      'taxon_uuid' => NULL,
886
      'descriptionElements' => NULL,
887
      )),
888
    'cdm_DescriptionElementSource' => array('variables' => array('descriptionElementSource' => NULL, 'doLink' => TRUE)),
889
    'cdm_IdentifieableSource' => array('variables' => array('source' => NULL, 'doLink' => TRUE)),
890
    'cdm_distribution_map' => array('variables' => array('taxon' => NULL)),
891
    'cdm_IdentificationKey' => array('variables' => array(
892
      'identificationKey' => NULL,
893
      'doLinkToKeyPage' => TRUE,
894
      'showIdentificationKeyTitle' => TRUE,
895
      )),
896
    'cdm_polytomousKey' => array('variables' => array('polytomousKey' => NULL)),
897
    'cdm_polytomousKey_linkedStyle_subgraph' => array('variables' => array('polytomousKeyNode' => NULL)),
898
    'cdm_poytomousKeyNode_modifyingText' => array('variables' => array('modifyingText' => NULL)),
899
    'cdm_list_IdentificationKeys' => array('variables' => array('type' => NULL, 'taxonUuid' => NULL)),
900
    'cdm_block_IdentificationKeys' => array('variables' => array('taxonUuid' => NULL)),
901
    'cdm_UseDescription' => array('variables' => array('description' => NULL, 'taxonUuid' => NULL)),
902
    'cdm_block_Uses' => array('variables' => array('taxonUuid' => NULL)),
903

    
904
    // Themes in cdm_dataportal.media.theme.
905
    'cdm_media' => array('variables' => array('descriptionElement' => NULL, 'mimeTypePreference' => NULL)),
906
    'cdm_mediaTypeTerm' => array('variables' => array('feature' => NULL, 'mediaUrl' => FALSE)),
907
    'cdm_media_mime_application' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
908
    'cdm_media_mime_image' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
909
    'cdm_media_mime_text' => array('variables' => array('representation' => NULL, 'feature' => NULL)),
910
    'cdm_media_caption' => array('variables' => array(
911
      'media' => NULL,
912
      'elements' => array('title', 'description', 'artist', 'location', 'rights'),
913
      'fileUri' => NULL,
914
      )),
915
    'cdm_media_gallerie' => array('variables' => array(
916
      'mediaList' => NULL,
917
      'galleryName' => NULL,
918
      'maxExtend' => 150,
919
      'cols' => 4,
920
      'maxRows' => FALSE,
921
      'captionElements' => array('title'),
922
      'mediaLinkType' => 'LIGHTBOX',
923
      'alternativeMediaUri' => NULL,
924
      'galleryLinkUri' => NULL,
925
      'showCaption' => TRUE,
926
      )),
927
    'cdm_media_gallerie_image' => array('variables' => array(
928
      'mediaRepresentationPart' => NULL,
929
      'maxExtend' => NULL,
930
      'addPassePartout' => FALSE,
931
      'attributes' => NULL,
932
      )),
933
    'cdm_media_gallerie_application' => array('variables' => array(
934
      'mediaRepresentationPart' => NULL,
935
      'maxExtend' => NULL,
936
      'addPassePartout' => FALSE,
937
      'attributes' => NULL,
938
      )),
939
    'cdm_media_gallerie_text' => array('variables' => array(
940
      'mediaRepresentationPart' => NULL,
941
      'maxExtend' => NULL,
942
      'addPassePartout' => FALSE,
943
      'attributes' => NULL,
944
      )),
945
    'cdm_openlayers_image' => array('variables' => array('mediaRepresentationPart' => NULL, 'maxExtend' => NULL)),
946
    'cdm_preferredImage' => array('variables' => array(
947
      'media' => NULL,
948
      'defaultRepresentationPart' => NULL,
949
      'imageMaxExtend' => NULL,
950
      'parameters' => '',
951
      )),
952

    
953
    // Themes in cdm_dataportal.name.theme.
954
    'cdm_taxonName' => array('variables' => array(
955
      'taxonName' => NULL,
956
      'nameLink' => NULL,
957
      'refenceLink' => NULL,
958
      'show_annotations' => TRUE,
959
      'is_type_designation' => FALSE,
960
      'skiptags' => array(),
961
      )),
962
    'cdm_typedesignations' => array('variables' => array('typeDesignations' => array())),
963
    'cdm_nameRelationships' => array('variables' => array('nameRelationships' => NULL, 'skipTypes' => FALSE)),
964
    'cdm_homotypicSynonymLine' => array('variables' => array('taxon' => NULL)),
965
    'cdm_heterotypicSynonymyGroup' => array('variables' => array('homotypicalGroup' => NULL)),
966
    'cdm_homotypicSynonymyGroup' => array('variables' => array(
967
      'synonymList' => NULL,
968
      'accepted_taxon_uuid' => NULL,
969
      'prependedSynonyms' => array(),
970
      )),
971
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
972
    'get_partDefinition' => array('variables' => array('nameType' => NULL)),
973
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
974

    
975
    // Themes in cdm_dataportal.occurrence.theme.
976
    'cdm_specimen' => array('variables' => array('specimenTypeDesignation' => NULL)),
977
    'cdm_derivedUnitFacade' => array('variables' => array('derivedUnitFacade' => NULL)),
978

    
979
    // Themes in cdm_dataportal.page.theme.
980
    'cdm_taxon_page_title' => array('variables' => array('taxon' => NULL, 'uuid' => NULL)),
981
    'cdm_name_page_title' => array('variables' => array('taxon_name' => NULL)),
982
    'cdm_taxon_page' => array('variables' => array('taxon' => NULL, 'page_part' => 'description')),
983
    'cdm_taxon_page_profile' => array('variables' => array(
984
      'taxon' => NULL,
985
      'mergedTrees' => NULL,
986
      'media' => NULL,
987
      'hideImages' => FALSE,
988
      )),
989
    'cdm_taxon_page_specimens' => array('variables' => array('taxon' => NULL)),
990
    'cdm_taxon_page_synonymy' => array('variables' => array('taxon' => NULL, 'addAcceptedTaxon' => NULL)),
991
    'cdm_reference_page' => array('variables' => array('reference' => NULL)),
992
    'cdm_media_page' => array('variables' => array(
993
      'media' => NULL,
994
      'mediarepresentation_uuid' => FALSE,
995
      'partId' => FALSE,
996
      )),
997
    'cdm_polytomousKey_page' => array('variables' => array('polytomousKey' => NULL)),
998
    'cdm_taxonpage_tab' => array('variables' => array('tabname' => NULL)),
999

    
1000
    // Themes in cdm_dataportal.references.theme.
1001
    'cdm_reference_pager' => array('variables' => array(
1002
      'referencePager' => NULL,
1003
      'path' => NULL,
1004
      'parameters' => array(),
1005
      )),
1006
    'cdm_reference' => array('variables' => array(
1007
      'reference' => NULL,
1008
      'microReference' => NULL,
1009
      'doLink' => FALSE,
1010
      'referenceStyle' => NULL,
1011
      )),
1012

    
1013
    // Themes in cdm_dataportal.taxon.theme.
1014
    'cdm_search_results' => array('variables' => array(
1015
      'pager' => NULL,
1016
      'path' => NULL,
1017
      'query_parameters' => NULL,
1018
      )),
1019
    'cdm_taxonRelationships' => array('variables' => array('taxonRelationships' => NULL, 'focusedTaxon' => NULL)),
1020
    'cdm_acceptedFor' => array('variables' => array()),
1021
    'cdm_list_of_taxa' => array('variables' => array('records' => NULL, 'freetextSearchResults' => array())),
1022
    'cdm_taxon_list_thumbnails' => array('variables' => array('taxon' => NULL)),
1023

    
1024
    // Themes in cdm_dataportal.bibliography.theme.
1025
    'cdm_descriptionElementBibliography' => array('variables' => array('descriptionElementsBibliography' => array())),
1026
  );
1027
}
1028

    
1029
/* UNREACHABLE since action of form directly links to view.
1030
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1031

    
1032
 $_SESSION['cdm']['search'] = $form_values;
1033
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1034
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1035
 //$paramstr = compose_url_prameterstr($form_values);
1036
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1037
 }
1038
 */
1039
/* ====================== menu callback functions ====================== */
1040
/**
1041
 * @todo Please document this function.
1042
 * @see http://drupal.org/node/1354
1043
 */
1044
/*
1045
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1046
  static $comment_node_disabled =  0;
1047
  static $comment_node_read_only =  1;
1048
  static $comment_node_read_write =  2;
1049

    
1050
  if ($form_id == 'node_type_form'
1051
   && isset($form['identity']['type'])
1052
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1053
  ) {
1054
    $form['workflow']['comment'] = array(
1055
      '#type' => 'radios',
1056
      '#title' => t('Default comment setting'),
1057
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1058
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1059
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1060
    );
1061
  }
1062
}
1063
*/
1064

    
1065
/**
1066
 * Displays a list of the known taxonomic names.
1067
 *
1068
 * When the list of taxonomic names is displayed, long lists are split up into
1069
 * multiple pages.
1070
 *
1071
 * TODO: Parameters are still preliminary.
1072
 *
1073
 * @param string $beginsWith
1074
 * @param string $page
1075
 *   Page number to diplay defaults to page 1.
1076
 * @param bool $onlyAccepted
1077
 */
1078
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1079

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

    
1082
  /*
1083
  // FIXME the filter for accepted names will be a form element, thus this
1084
  // widget should be generated via form api preferably as block.
1085
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1086
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1087
  $out .= theme('cdm_listof_taxa', $taxonPager);
1088
  return $out;
1089
  */
1090
}
1091

    
1092
/**
1093
 * @todo Please document this function.
1094
 * @see http://drupal.org/node/1354
1095
 */
1096
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1097
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1098
  return theme('cdm_reference_page', array('reference' => $reference));
1099
}
1100

    
1101
/**
1102
 * @todo Please document this function.
1103
 * @see http://drupal.org/node/1354
1104
 */
1105
function cdm_dataportal_view_reference_list($pageNumber) {
1106
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1107
  return theme('cdm_reference_pager', array(
1108
    'referencePager' => $referencePager,
1109
    'path' => 'cdm_dataportal/reference/list/',
1110
    ));
1111
}
1112

    
1113
/**
1114
 * @todo Please document this function.
1115
 * @see http://drupal.org/node/1354
1116
 */
1117
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1118
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1119
  return theme('cdm_media_page', array(
1120
    'media' => $media,
1121
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1122
    'partId' => $part,
1123
    ));
1124
}
1125

    
1126
/**
1127
 * @todo Please document this function.
1128
 * @see http://drupal.org/node/1354
1129
 */
1130
function _load_taxonBase(&$taxonBase) {
1131
  if (isset($taxonBase->uuid)) {
1132
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1133
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1134
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1135
  }
1136
}
1137

    
1138
/**
1139
 * Gets a Drupal variable, string or array and returns it.
1140
 *
1141
 * Similar to the variable_get() function of Drupal, except that this function
1142
 * is able to handle arrays correctly. This function is especially useful
1143
 * when dealing with collections of setting form elements (#tree = TRUE).
1144
 *
1145
 * @param string $variableKey
1146
 *   The Unique key of the Drupal variable in the Drupal variables table.
1147
 * @param string $defaultValueString
1148
 *   A string as for example derived from a CONSTANT.
1149
 *
1150
 * @return mixed
1151
 *   Returns usally an array, depending on the nature of the variable.
1152
 */
1153
function mixed_variable_get($variableKey, $defaultValueString) {
1154
  $systemDefaults = unserialize($defaultValueString);
1155
  $storedSettings = variable_get($variableKey, array());
1156
  if (is_array($storedSettings)) {
1157
    $settings = array_merge($systemDefaults, $storedSettings);
1158
  }
1159
  else {
1160
    $settings = $systemDefaults;
1161
  }
1162
  return $settings;
1163
}
1164

    
1165
/**
1166
 * Loads the subgraph of a given PolytomousKeyNode.
1167
 *
1168
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1169
 * the CDM REST service.
1170
 *
1171
 * @param mixed $polytomousKeyNode
1172
 *   PolytomousKeyNode passed by reference.
1173
 *
1174
 * @return void
1175
 */
1176
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1177

    
1178
  if (!$polytomousKeyNode) {
1179
    return;
1180
  }
1181
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1182
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1183
    return;
1184
  }
1185
  if (!is_uuid($polytomousKeyNode->uuid)) {
1186
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1187
    return;
1188
  }
1189

    
1190
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1191

    
1192
  if (!$polytomousKeyNode) {
1193
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1194
    return;
1195
  }
1196

    
1197
  // Load children.
1198
  foreach ($polytomousKeyNode->children as &$childNode) {
1199
    _load_polytomousKeySubGraph($childNode);
1200
  }
1201

    
1202
  // Load subkey.
1203
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1204

    
1205
  // Load taxon.
1206
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1207
  _load_taxonBase($polytomousKeyNode->taxon);
1208
  return;
1209
}
1210

    
1211
/**
1212
 * @todo Please document this function.
1213
 * @see http://drupal.org/node/1354
1214
 */
1215
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1216
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1217

    
1218
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1219
  if (is_array($sourcePager->records)) {
1220
    $polytomousKey->sources = $sourcePager->records;
1221
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1222
  }
1223

    
1224
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1225
  if (is_array($annotationPager->records)) {
1226
    $polytomousKey->annotations = $annotationPager->records;
1227
  }
1228

    
1229
  _load_polytomousKeySubGraph($polytomousKey->root);
1230
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1231
}
1232

    
1233
/**
1234
 * Creates a taxon page view or a chapter of it.
1235
 *
1236
 * The taxon page gives detailed information on a taxon, it shows:
1237
 *  - Taxon name.
1238
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1239
 *    heterotypic and finally followed by misapplied names.
1240
 *    The list is ordered historically.
1241
 *  - All description associated with the taxon.
1242
 *
1243
 * @param string $uuid
1244
 * @param string $chapter
1245
 *   Name of the part to display, valid values are:
1246
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1247
 *
1248
 * @return unknown_type
1249
 */
1250
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1251
  // Display the page for the taxon defined by $uuid.
1252
  // set_last_taxon_page_tab(arg(3));
1253
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1254
  if (!empty($taxonpage)) {
1255
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1256
  }
1257
  else {
1258
    return '';
1259
  }
1260
}
1261

    
1262
/**
1263
 * @todo improve documentation for this function.
1264
 *
1265
 * @param string $uuid
1266
 * @param string $chapter
1267
 *   Name of the part to display, valid values are:
1268
 *   'description', 'images', 'synonymy', 'all'.
1269
 *
1270
 * @return unknown_type
1271
 */
1272
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1273
  // Taxon object.
1274
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1275
  if (empty($taxon)) {
1276
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1277
    return FALSE;
1278
  }
1279
  $taxonpage = new stdClass();
1280

    
1281
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1282
    'taxon' => $taxon,
1283
    'uuid' => $uuid,
1284
    'synonym_uuid' => $synonym_uuid,
1285
  ));
1286

    
1287
  // Check if the taxon id contained in the currently selected tree.
1288
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1289
  $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1290
  if (!$taxon_in_current_tree) {
1291
    if (count($taxon_nodes) == 0) {
1292
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained any classification.', array(
1293
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1294
      ))), 'warning');
1295
    }
1296
    else {
1297
      $trees = '';
1298
      foreach ($taxon_nodes as $node) {
1299
        if (isset($node->classification->titleCache)) {
1300
          $trees .= ($trees ? ', ' : '') . '<strong>' . $node->classification->titleCache . '</strong>';
1301
        }
1302
      }
1303

    
1304
      drupal_set_message(format_plural(count($taxon_nodes),
1305
          'This concept of the taxon !taxonname is not contained in the currently chosen classification, but in this one: !trees',
1306
          'This concept of the taxon !taxonname is not contained in the currently chosen classification, but in one of these: !trees',
1307
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1308
    }
1309
  }
1310

    
1311
  // Render the taxon page.
1312
  $taxonpage->content = theme('cdm_taxon_page', array(
1313
    'taxon' => $taxon,
1314
    'page_part' => $chapter,
1315
  ));
1316

    
1317
  return $taxonpage;
1318
}
1319

    
1320
/**
1321
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1322
 *
1323
 * The node page shows the taxon name title and the list of taxon related
1324
 * with such taxon. Name on the tree already in use.
1325
 *
1326
 * @param string $taxon_name_uuid
1327
 *   A taxon name UUID.
1328
 *
1329
 * @return mixed
1330
 *   The formatted name page as node.
1331
 */
1332
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1333

    
1334
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1335
  if (!empty($taxonname_page)) {
1336
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1337
  }
1338
  else {
1339
    return '';
1340
  }
1341
}
1342

    
1343
/**
1344
 * Generates an object ready to be transformated to a node.
1345
 *
1346
 * This is a preparation in order to show it as a Drupal node.
1347
 *
1348
 * @param string $taxon_name_uuid
1349
 *
1350
 * @return mixed
1351
 *   The object with the page content and title.
1352
 */
1353
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1354
  // Getting the full taxonname object from the server.
1355
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1356
  if (!$taxon_name) {
1357
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1358
    return FALSE;
1359
  }
1360
  // Searching for all the taxa connected with the taxon name on the tree
1361
  // in use.
1362
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1363
  $request_params = array();
1364
  $request_params['query'] = $name_cache;
1365
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1366
  $request_params['doTaxa'] = 1;
1367
  $request_params['doSynonyms'] = 1;
1368
  $request_params['doTaxaByCommonNames'] = 0;
1369
  $request_params['matchMode'] = "EXACT";
1370
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1371

    
1372
  // Removing the name where we come from.
1373
  foreach ($taxon_pager->records as $k => &$taxon) {
1374
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1375
      unset($taxon_pager->records[$k]);
1376
    }
1377
  }
1378
  // Show the taxa list or go to the singular taxon.
1379
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1380
    reset($taxon_pager->records);
1381
    $singleTaxon = $taxon_pager->records[0];
1382
    if ($singleTaxon->class != "Taxon") {
1383
      // It is a Synonym -> look for the accepted.
1384
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1385
      if (!empty($synonym_uuid)) {
1386
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1387
      }
1388
      else {
1389
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1390
      }
1391
    }
1392
    else {
1393
      // It is an accepted taxon.
1394
      if (!empty($synonym_uuid)) {
1395
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1396
      }
1397
      else {
1398
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1399
      }
1400
    }
1401
  }
1402
  else {// More than one taxa case.
1403
    $taxon_name_page = new stdClass();
1404
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name . ''));
1405
    if ($taxon_pager->records) {
1406
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1407
    }
1408
    else {
1409
      $taxon_name_page->content = 'This name has no taxa';
1410
    }
1411
    return $taxon_name_page;
1412
  }
1413
}
1414

    
1415
/**
1416
 * @todo Please document this function.
1417
 * @see http://drupal.org/node/1354
1418
 */
1419
function cdm_dataportal_view_search_advanced() {
1420

    
1421
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1422
  $form = array();
1423
  $form_state = array();
1424
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1425

    
1426
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1427

    
1428
}
1429

    
1430
/**
1431
 * @todo Please document this function.
1432
 * @see http://drupal.org/node/1354
1433
 */
1434
function cdm_dataportal_view_search_taxon_by_description() {
1435
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1436
  // $form_state = false;
1437
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1438
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1439

    
1440
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1441
}
1442

    
1443
/**
1444
 * Executes the search and generates the result list of taxa.
1445
 */
1446
function cdm_dataportal_view_search_results_taxon() {
1447

    
1448
  $taxonPager = cdm_dataportal_search_execute();
1449

    
1450
  $showThumbnails = do_showThumbnails();
1451

    
1452
  $setSessionUri = url('cdm_api/setvalue/session', array(
1453
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1454
  ));
1455

    
1456
  drupal_add_js('jQuery(document).ready(function() {
1457

    
1458
      // init
1459
      if(' . $showThumbnails . ' == 1){
1460
      jQuery(\'.media_gallery\').show(20);
1461
  } else {
1462
      jQuery(\'.media_gallery\').hide(20);
1463
  }
1464
      // add change hander
1465
      jQuery(\'#showThumbnails\').change(
1466
      function(event){
1467
      var state = 0;
1468
      if(jQuery(this).is(\':checked\')){
1469
      jQuery(\'.media_gallery\').show(20);
1470
      state = 1;
1471
  } else {
1472
      jQuery(\'.media_gallery\').hide(20);
1473
  }
1474
      // store state in session variable
1475
      var uri = \'' . $setSessionUri . '\' + state;
1476
      jQuery.get(uri);
1477
  });
1478
  });',
1479
  array('type' => "inline", 'scope' => JS_DEFAULT));
1480

    
1481
  drupal_set_title(t('Search results'), PASS_THROUGH);
1482

    
1483
  return theme('cdm_search_results', array(
1484
    'pager' => $taxonPager,
1485
    'path' => 'cdm_dataportal/search/results/taxon',
1486
    'query_parameters' => $_REQUEST,
1487
    ));
1488
}
1489

    
1490
/**
1491
 * Returns the state of the the showThumbnails flag set in the
1492
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1493
 *
1494
 * @return Ambigous <boolean, number>
1495
 *    returns 1 if the flag is set
1496
 */
1497
function do_showThumbnails() {
1498
  static $showThumbnails = null;
1499

    
1500
  if($showThumbnails == null) {
1501
    $showThumbnails = FALSE;
1502
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1503
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1504
    }
1505
    if (!is_numeric($showThumbnails)) {
1506
      $showThumbnails = 1;
1507
    }
1508
  }
1509

    
1510
  return $showThumbnails;
1511
}
1512

    
1513
/**
1514
 * View which transforms XML output from a given webservice endpoint into JSON.
1515
 */
1516
/*
1517
 function cdm_view_xml2json(){
1518
 $file = arg(2);
1519
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1520
 return  xml2json::transformXmlStringToJson($datastr);
1521
 }
1522
 */
1523

    
1524
/* ====================== other functions ====================== */
1525
/**
1526
 * Creates a URL to the taxon page specified by the $uuid parameter.
1527
 *
1528
 * The URL will be prepended with a path element to a specific taxon page tab.
1529
 *
1530
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1531
 * be set globally in the administrative settings or individually in the user
1532
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1533
 * the last portal will stay on this last tab.
1534
 *
1535
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1536
 * internal mechanism by a specific value.
1537
 *
1538
 * @param string $uuid
1539
 *   The UUID of the taxon.
1540
 * @param string $page_tab
1541
 *   Overwriting the preset mechanism by defining specific value for the
1542
 *   taxon page tab.
1543
 *
1544
 * @return string
1545
 *   The created URL.
1546
 */
1547
function path_to_taxon($uuid, $page_tab = FALSE) {
1548

    
1549
  $tab = get_default_taxon_tab();
1550
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1551

    
1552
  if (!$uuid) {
1553
    return FALSE;
1554
  }
1555

    
1556
  if ($page_tab) {
1557
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1558
  }
1559
  elseif (!$tab || strtolower($tab) == 'general') {
1560
    return 'cdm_dataportal/taxon/' . $uuid;
1561
  }
1562
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1563
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1564
  }
1565
  else {
1566
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1567
  }
1568
}
1569

    
1570
/**
1571
 * @todo Please document this function.
1572
 * @see http://drupal.org/node/1354
1573
 */
1574
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1575
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1576
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1577
}
1578

    
1579
/**
1580
 * @todo Please document this function.
1581
 * @see http://drupal.org/node/1354
1582
 */
1583
function path_to_key($keyType, $keyUuid) {
1584
  if (!$keyUuid || !$keyType) {
1585
    return FALSE;
1586
  }
1587
  $keyType{0} = strtolower($keyType{0});
1588
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1589
}
1590

    
1591
/**
1592
 * @todo Please document this function.
1593
 * @see http://drupal.org/node/1354
1594
 */
1595
function path_to_reference($uuid) {
1596
  if (!$uuid) {
1597
    return FALSE;
1598
  }
1599
  return 'cdm_dataportal/reference/' . $uuid;
1600
}
1601

    
1602
/**
1603
 * @todo Please document this function.
1604
 * @see http://drupal.org/node/1354
1605
 */
1606
function path_to_name($name_uuid) {
1607
  $res = FALSE;
1608
  if ($name_uuid) {
1609
    $res = 'cdm_dataportal/name/' . $name_uuid;
1610
  }
1611
  return $res;
1612
}
1613

    
1614
/**
1615
 * @todo Please document this function.
1616
 * @see http://drupal.org/node/1354
1617
 */
1618
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1619
  if (!$uuid) {
1620
    return FALSE;
1621
  }
1622
  $out = 'cdm_dataportal/media/' . $uuid;
1623
  if ($representaion_uuid) {
1624
    $out .= '/' . $representaion_uuid;
1625
    if ($partId !== FALSE) {
1626
      $out .= '/' . $partId;
1627
    }
1628
  }
1629
  return $out;
1630
}
1631

    
1632
/**
1633
 * Compares thisRank with thatRank.
1634
 *
1635
 * Returns a negative integer, zero, or a positive integer
1636
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1637
 * e.g:
1638
 * <ul>
1639
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1640
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1641
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1642
 * </ul>
1643
 * <p>
1644
 * This compare logic of the underlying webservice is the
1645
 * <b>inverse logic</b> of the the one implemented in
1646
 * java.lang.Comparable#compareTo(java.lang.Object)
1647
 *
1648
 * @param $thisRankUuid
1649
 * @param $thatRankUuid
1650
 *
1651
 * @return int
1652
 *   A negative integer, zero, or a positive integer
1653
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1654
 */
1655
function rank_compare($thisRankUuid, $thatRankUuid) {
1656
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1657
  return $result->Integer;
1658
}
1659

    
1660
/**
1661
 * Composes an HTML element class attribute value composed of
1662
 * the shortname of the cdm class and the uuid of the entity.
1663
 * This class attribute should be used whereever an cdm-entity is rendered.
1664
 *
1665
 * These according class selectors in css must be escaped, eg:
1666
 *    .cdm\:TextData
1667
 *
1668
 * @param $cdmEntity
1669
 */
1670
function html_class_atttibute_ref($cdmEntity) {
1671

    
1672
  if (is_cdm_entity($cdmEntity)) {
1673
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1674
  }
1675
}
1676

    
1677
/**
1678
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1679
 *
1680
 * @param unknown_type $taggedTextList
1681
 */
1682
function normalize_TaggedName(&$taggedTextList) {
1683

    
1684
  if (is_array($taggedTextList)) {
1685

    
1686
    // First pass: rename.
1687
    for ($i = 0; $i < count($taggedTextList); $i++) {
1688

    
1689
      if ($taggedTextList[$i]->type == "hybridSign") {
1690
        $taggedTextList[$i]->type = "name";
1691
      }
1692
    }
1693

    
1694
    // Second pass: resolve separators.
1695
    $taggedNameListNew = array();
1696
    for ($i = 0; $i < count($taggedTextList); $i++) {
1697

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

    
1700
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1701
          $taggedName = $taggedTextList[$i];
1702
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1703
          $taggedNameListNew[] = $taggedName;
1704
          ++$i;
1705
          ++$i;
1706
        }
1707
      }
1708
      else {
1709
        $taggedNameListNew[] = $taggedTextList[$i];
1710
      }
1711
    }
1712
    $taggedTextList = $taggedNameListNew;
1713
  }
1714
}
1715

    
1716
/**
1717
 * Creates a short taxonname.
1718
 *
1719
 * The short name is created by using the taggename field of
1720
 * NameSTO or NameTO instances.
1721
 * If the taggename if empty the fullname will be returned.
1722
 *
1723
 * @param unknown_type $name
1724
 *   Name or TreeNode.
1725
 *
1726
 * @return string
1727
 */
1728
function cdm_dataportal_shortname_of($name) {
1729
  $nameStr = '';
1730

    
1731
  normalize_TaggedName($name->taggedTitle);
1732

    
1733
  // Get all tagged text tokens of the scientific name.
1734
  foreach ($name->taggedTitle as $tagtxt) {
1735
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1736
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1737
    }
1738
  }
1739
  $nameStr = trim($nameStr);
1740

    
1741
  if ($nameStr) {
1742

    
1743
    // Do not return short names for these.
1744
    if ($name->unplaced || $name->excluded) {
1745
      return $nameStr;
1746
    }
1747

    
1748
    /*
1749
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1750
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1751
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1752
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1753
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1754
    */
1755
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1756
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1757
      return $matches[1][0] . "." . $matches[3][0];
1758
    }
1759
    else {
1760
      return $nameStr;
1761
    }
1762
  }
1763
  else {
1764
    return $name->titleCache;
1765
  }
1766
}
1767

    
1768
/**
1769
 * Check if a taxon is accepted by the current taxonomic tree.
1770
 *
1771
 * @param mixed $taxon
1772
 *   The Taxon obkect to check.
1773
 *
1774
 * @return bool
1775
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1776
 */
1777
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1778

    
1779
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1780

    
1781
  if (isset($taxon->taxonNodes)) {
1782
    $taxonNodes = $taxon->taxonNodes;
1783
  }
1784
  else {
1785
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1786
  }
1787

    
1788
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1789
    foreach ($taxonNodes as $node) {
1790
      if (is_object($node->classification)) {
1791
        if ($node->classification->uuid == $defaultTreeUuid) {
1792
          return TRUE;
1793
        }
1794
      }
1795
      else {
1796
        if ($node->classification == $defaultTreeUuid) {
1797
          return TRUE;
1798
        }
1799
      }
1800
    }
1801
  }
1802

    
1803
  return FALSE;
1804
}
1805

    
1806
/**
1807
 * @deprecated
1808
 */
1809
function compose_url_prameterstr($parameters = array(), $parentPropertyName = FALSE) {
1810
  $pstr = '';
1811
  foreach ($parameters as $key => $value) {
1812
    if (is_array($value)) {
1813

    
1814
    }
1815
    else {
1816
      $pstr .= ($pstr ? '&' : '') . $key . '=' . urlencode($value);
1817
    }
1818
  }
1819
  return $pstr;
1820
}
1821

    
1822
/**
1823
 * Workaround for missing original source type.
1824
 *
1825
 * idNamespace is always set in these cases.
1826
 * @todo improve documentation of this function.
1827
 *
1828
 * @param unknown_type $source
1829
 *
1830
 * @return unknown_type
1831
 */
1832
function _is_original_source_type($source) {
1833
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1834
}
1835

    
1836
/**
1837
 * @todo Please document this function.
1838
 * @see http://drupal.org/node/1354
1839
 */
1840
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1841
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1842
}
1843

    
1844
/**
1845
 * Gets the metadata info such as title or artist of a media file.
1846
 *
1847
 * The function tries at first to get all the info from the file metadata
1848
 * and if it is not avaible look at the media file info stored at the database.
1849
 *
1850
 * @param mixed $media
1851
 *   The media file object for which to get the metadata.
1852
 *
1853
 * @return array
1854
 *   The array with the available specified metadata info.
1855
 * TODO rename to read_media_metadata() and move to *.module.
1856
 */
1857
function cdm_read_media_metadata($media) {
1858

    
1859
  $metadata_caption = array(
1860
    'title' => '',// Media_metadata and media.
1861
    'artist' => '',// Media_metadata and media.
1862
    'rights',// Media_metadata and media.
1863
    'location',// Media_metadata.
1864
    'filename' => '',// Media.
1865
    'mediacreated' => '',// Media.
1866
    'description' => '',
1867
  );// Media.
1868

    
1869
  // Getting the media metadata.
1870
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1871
  $media_metadata_aux = (array) $media_metadata;
1872

    
1873
  // Filename.
1874
  if (isset($media->representations[0]->parts[0]->uri)) {
1875
    $fileUri = $media->representations[0]->parts[0]->uri;
1876
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1877
    $metadata_caption['filename'] = $filename;
1878
  }
1879
  else {
1880
    $metadata_caption['filename'] = '';
1881
  }
1882

    
1883
  // Title.
1884
  if (!empty($media_metadata->ObjectName)) {
1885
    $metadata_caption['title'] = $media_metadata->ObjectName;
1886
  }
1887
  elseif ($media_metadata_aux['Object Name']) {
1888
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1889
  }
1890
  elseif ($media->title_L10n) {
1891
    $metadata_caption['title'] = $media->title_L10n;
1892
  }
1893
  elseif ($media->titleCache) {
1894
    $metadata_caption['title'] = $media->titleCache;
1895
  }
1896

    
1897
  // Append description to title.
1898
  if (!empty($media->description_L10n)) {
1899
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1900
  }
1901

    
1902
  // Artist.
1903
  if ($media_metadata->Artist) {
1904
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1905
  }
1906
  elseif ($media->artist->titleCache) {
1907
    $metadata_caption['artist'] = $media->artist->titleCache;
1908
  }
1909

    
1910
  // Copyright.
1911
  $metadata_caption['rights'] = array(
1912
    'copyright' => array('agentNames' => array()),
1913
    'license' => array(
1914
      'agentNames' => array(),
1915
      'types' => array(),
1916
      'abbreviatedTexts' => array(),
1917
      'uris' => array(),
1918
    ),
1919
  );
1920
  if ($media_metadata->Copyright) {
1921
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1922
  }
1923
  elseif (isset($media->rights) && is_array($media->rights)) {
1924
    foreach ($media->rights as $right) {
1925
      switch ($right->term->uuid) {
1926
        case UUID_RIGHTS_LICENCE:
1927
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1928
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1929
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1930
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1931
          break;
1932
        case UUID_RIGHTS_COPYRIGHT:
1933
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1934
          break;
1935
      }
1936
    }
1937
  }
1938
  else {
1939
    $metadata_caption['rights']['agentNames'][] = '';
1940
  }
1941

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

    
1945
  // Location.
1946
  $metadata_caption['location'] = array();
1947
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1948
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1949
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1950
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1951

    
1952
  /*
1953
   // Creation date.
1954
   if($media_metadata["Modify Date"])
1955
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1956
   else
1957
   $metadata_caption['mediacreated'] = $media->created;
1958
   */
1959

    
1960
  // Returned value.
1961
  return $metadata_caption;
1962
}
1963

    
1964
/**
1965
 * Collects all the media from a list of description elements.
1966
 *
1967
 * @param array $descriptionElements
1968
 *   The description elements from which to collect the media.
1969
 *
1970
 * @return array
1971
 *   The output with all the collected media.
1972
 */
1973
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1974

    
1975
  $outArrayOfMedia = array();
1976

    
1977
  // Avoiding a warning box in Drupal for Flora Malesiana.
1978
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1979
    foreach ($descriptionElements as $descriptionElement) {
1980
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1981
        foreach ($descriptionElement->media as $media) {
1982
          if (is_object($media)) {
1983
            $outArrayOfMedia[] = $media;
1984
          }
1985
        }
1986
      }
1987
    }
1988
  }
1989
  return $outArrayOfMedia;
1990
}
1991

    
1992
/**
1993
 * @todo Please document this function.
1994
 * @see http://drupal.org/node/1354
1995
 *
1996
 * @param array $cdmBase_list
1997
 *   An array of CdmBase instances or a single instance.
1998
 * @param string $footnote_list_key
1999
 *
2000
 * @return unknown
2001
 */
2002
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
2003
  // Comment @WA: undefined variable.
2004
  /*
2005
   static $annotations_types_filter;
2006
   if(!$annotations_types_filter) {
2007
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2008
   }
2009
   */
2010
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2011

    
2012
  $footNoteKeys = array();
2013

    
2014
  // Is argument cdmBase an array?
2015
  if (!is_array($cdmBase_list)) {
2016
    $cdmBase_array = array();
2017
    $cdmBase_array[] = $cdmBase_list;
2018
  }
2019
  else {
2020
    $cdmBase_array = $cdmBase_list;
2021
  }
2022

    
2023
  // Getting the key for the footnotemanager.
2024
  if (isset($footnote_list_key)) {
2025
    $footnoteListKey = $footnote_list_key;
2026
  }
2027
  else {
2028
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2029
  }
2030

    
2031
  // Adding the footnotes keys.
2032
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2033
  foreach ($cdmBase_array as $cdmBase_element) {
2034
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2035
    if (is_array($annotations)) {
2036
      foreach ($annotations as $annotation) {
2037
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2038
      }
2039
    }
2040
  }
2041

    
2042
  return $footNoteKeys;
2043
}
2044

    
2045
// @WA Comment: should this not be a theme function?
2046
/**
2047
 *  Creates a CDM Dynabox.
2048
 *
2049
 * @param string $label
2050
 *   The clickable text to show.
2051
 * @param string $content_url
2052
 *   The cdm REST service request url wich will deliver the content to be shown
2053
 *   once the dynabox toggles open.
2054
 * @param string $theme
2055
 *   The theme to be used for rendering the cdm REST service reponse with is
2056
 *   returned from the $content_url.
2057
 * @param string $link_alt_text
2058
 *   The value for the alt attribute of the dynabox link.
2059
 * @param array $enclosingtags
2060
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2061
 *   element itself, $enclosingtags[1] is the tag to be used for the
2062
 *   dynabox_content.
2063
 *
2064
 * @return string
2065
 *   Returns HTML for a dynabox.
2066
 */
2067
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')) {
2068
  $out = '';
2069
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2070

    
2071
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2072
  $out .= '<!-- ' . $content_url . ' -->';
2073
  $out .= '<' . $enclosingtags[0] . ' class="dynabox"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2074
  $out .= '<' . $enclosingtags[1] . ' class="dynabox_content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '><img class="loading" src="' . drupal_get_path('module', 'cdm_dataportal') . '/images/loading_circle_grey_16.gif" style="display:none;"></' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
2075
  $out .= '</' . $enclosingtags[0] . '>';
2076
  return $out;
2077
}
2078

    
2079
/**
2080
 * Checks whether a feature has any description elements.
2081
 *
2082
 * @param mixed $featureNode
2083
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2084
 *
2085
 * @see _mergeFeatureTreeDescriptions()
2086
 *
2087
 * @return bool
2088
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2089
 *   contains at least one non empty TextData or at least one DescriptionElement
2090
 *   of an other type. A TextData element holding a multilanguageText or a
2091
 *   source reference is considered to be not empty.
2092
 */
2093
function hasFeatureNodeDescriptionElements($featureNode) {
2094

    
2095
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2096
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2097
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0])) {
2098
        return TRUE;
2099
      }
2100
    }
2101
  }
2102
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2103
    foreach ($featureNode->children as $child) {
2104
      if (hasFeatureNodeDescriptionElements($child)) {
2105
        return TRUE;
2106
      }
2107
    }
2108
  }
2109
  return FALSE;
2110
}
(6-6/13)