Project

General

Profile

Download (69.9 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
    ", array('type' => 'inline'));
93
}
94

    
95
/**
96
 * @todo Please document this function.
97
 * @see http://drupal.org/node/1354
98
 */
99
function _add_js_openlayers_map() {
100

    
101
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/OpenLayers/OpenLayers.js', array(
102
    'type' => 'file',
103
    'weight' => JS_LIBRARY,
104
    'cache' => FALSE,
105
  ));
106
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
107

    
108
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
109

    
110
  $baseLayers = variable_get('baselayers', array());
111
  if (!is_array($baseLayers) || count($baseLayers) == 0) {
112
    $baseLayers = array(
113
      'metacarta_vmap0' => 'Metacarta Vmap0',
114
      'PREFERRED' => 'metacarta_vmap0',
115
    );
116
  }
117
  $layerNames = '';
118
  foreach ($baseLayers as $layerName => $layerLabel) {
119
    if ($layerName == 'PREFERRED') {
120
      $preferredLayer = $baseLayers['PREFERRED'];
121
    }
122
    else {
123
      $layerNames .= ($layerNames ? ', ' : '') . "'$layerName'";
124
    }
125
  }
126

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

    
132
  drupal_add_js("
133
          jQuery(document).ready(function() {
134
              jQuery('#openlayers_map').cdm_openlayers_map('"
135
              . getEDITMapServiceURI() . "', {
136
                legendPosition: 3,
137
                displayWidth: '" . variable_get('cdm_dataportal_geoservice_display_width', FALSE) . "',
138
                boundingBox: '" . variable_get('cdm_dataportal_geoservice_bounding_box', FALSE) . "',
139
                distributionOpacity: '" . variable_get('cdm_dataportal_geoservice_distributionOpacity', '0.5') . "',
140
                legendOpacity: '" . variable_get('cdm_dataportal_geoservice_legendOpacity', '0.5') . "',
141
                showLayerSwitcher: " . (variable_get('cdm_dataportal_geoservice_showLayerSwitcher', TRUE) ? 'true' : 'false') . ",
142
                baseLayerNames: [" . $layerNames . "],
143
                defaultBaseLayerName: '" . $preferredLayer . "',
144
            });
145
          });
146
        ", array('type' => 'inline'));
147

    
148
}
149

    
150
/**
151
 * @todo Enter description here ...
152
 *
153
 * @param unknown_type $width
154
 * @param unknown_type $bounding_box
155
 * @param unknown_type $occurrenceQuery
156
 * @param unknown_type $distributionQuery
157
 * @param unknown_type $legendFormatQuery
158
 * @param unknown_type $map_caption
159
 *
160
 * @return unknown
161
 */
162
function get_image_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
163

    
164
  $server = getEDITMapServiceURI();
165

    
166
  if (!$server) {
167
    // Warning message.
168
    drupal_set_message(t(
169
      "No 'Geoservice Access Point' has been set so far.
170
      Please configure the variable 'Geoservice Access Point' here !url", array(
171
        '!url' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/geo'),
172
      )), 'warning');
173

    
174
    // Message to render.
175
    return '<p>' . t('No geoservice specified') . '</p>';
176
  }
177

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

    
181
  $query_string = '&image=true&recalculate=false&legend=1&ms=' . $width
182
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
183
    . ($labels_on ? '&label=' . $labels_on : '');
184

    
185
  if ($map_caption) {
186
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
187
  }
188

    
189
  if (getEDITMapServiceVersionNumber() >= 1.1) {
190

    
191
    // Either occurrence or distribution - combined maps will be possible
192
    // in the future.
193
    if ($occurrenceQuery) {
194
      // @todo Fix $occurrenceQuery.
195
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
196
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
197
      // Will be replaced below.. HACK!!!
198
      $occurrenceQuery .= '&l=tdwg4&as=';
199

    
200
      $query_string .= "&" . $occurrenceQuery;
201
    }
202
    elseif ($distributionQuery) {
203
      $query_string .= "&" . $distributionQuery;
204
    }
205

    
206
    // Apply Plain Image map settings special for version >= 1.1.
207
    /*
208
    example : title=a:Naturalized++non-invasive
209
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
210
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
211
    &mc_s=Georgia,15,blue&mc=&recalculate=false
212

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

    
220
    $map_service_script_name = "rest_gen.php";
221

    
222
    $bgcolor_areaStyleId = "y";
223
    $baselayer_areaStyleId = "z";
224
    $bgcolor_layer = '';
225
    $additional_area_styles = array();
226

    
227
    // Background color:
228
    if (variable_get('map_bg_color', '')) {
229
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
230
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
231
    }
232

    
233
    // TODO HACK to replace the default base layer which currently is tdwg4 !!!
234
    // only needed for distribution maps.
235
    if (strpos($query_string, "?l=") !== FALSE) {
236
      $layer_param_token = "?l=";
237
    }
238
    else {
239
      $layer_param_token = "&l=";
240
    }
241
    if (strpos($query_string, "?as=") !== FALSE) {
242
      $areystyle_param_token = "?as=";
243
    }
244
    else {
245
      $areystyle_param_token = "&as=";
246
    }
247
    if (variable_get('map_base_layer', '')) {
248
      $query_string = str_replace($layer_param_token . "tdwg4", "$layer_param_token" . variable_get('map_base_layer', '') . ":" . $baselayer_areaStyleId, $query_string);
249
    }
250
    else {
251
      $query_string = str_replace($layer_param_token . "tdwg4", $layer_param_token . "tdwg4:" . $baselayer_areaStyleId . ",", $query_string);
252
    }
253

    
254
    if ($bgcolor_layer) {
255
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
256
    }
257

    
258
    if (variable_get('map_base_layer_style', '')) {
259
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
260
    }
261

    
262
    foreach ($additional_area_styles as $as) {
263
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
264
    }
265

    
266
  }
267
  else {
268
    // Pre 1.1. version of map service.
269
    if ($occurrenceQuery) {
270

    
271
      $map_service_script_name = "point.php";
272

    
273
      // Fix $occurrenceQuery.
274
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
275
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
276
      $occurrenceQuery .= '&l=v:e_w_0';
277
      $query_string .= "&" . $occurrenceQuery;
278
    }
279
    elseif ($distributionQuery) {
280
      $query_string .= "&" . $distributionQuery;
281
      $map_service_script_name = "areas.php";
282
    }
283
  }
284

    
285
  $mapUri = url("$server/$map_service_script_name?$query_string");
286
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
287
  // Showing map caption.
288
  if ($map_caption) {
289
    // FIXME: replace <br> by according css style.
290
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
291
    $out .= '</div>';
292
  }
293

    
294
  return $out;
295
}
296

    
297
/**
298
 * @todo Enter description here ...
299
 *
300
 * @param unknown_type $width
301
 * @param unknown_type $bounding_box
302
 * @param unknown_type $occurrenceQuery
303
 * @param unknown_type $distributionQuery
304
 * @param unknown_type $legendFormatQuery
305
 * @param unknown_type $map_caption
306
 *
307
 * @return unknown
308
 */
309
function get_openlayers_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
310

    
311
  _add_js_openlayers_map();
312

    
313
  $out = '<div id="openlayers">';
314
  $out .= '<div id="openlayers_map" class="smallmap"';
315
  $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
316

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

    
320
  $openlayers_map_query_string = '&img=false&ms=' . $width
321
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
322
    . ($labels_on ? '&label=' . $labels_on : '');
323

    
324
  if ($occurrenceQuery) {
325
    // @todo Fix $occurrenceQuery.
326
    $occurrenceQuery .= '&bbox=-180,-90,180,90';
327
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
328
    // $occurrenceQuery .= '&l=v:e_w_0';
329
    // TODO add to cdm service?
330
    $occurrenceQuery .= '&legend=0';
331

    
332
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
333
  }
334

    
335
  if ($distributionQuery) {
336
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
337
  }
338

    
339
  if ($legendFormatQuery) {
340
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
341
  }
342

    
343
  $out .= '></div></div>';
344

    
345
  // Showing map caption.
346
  if ($map_caption) {
347
    // FIXME: replace <br> by according css style.
348
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
349
    $out .= '</div>';
350
  }
351
  return $out;
352
}
353

    
354
/* ====================== hook implementations ====================== */
355
/**
356
 * Implements hook_permission().
357
 *
358
 * Valid permissions for this module.
359
 *
360
 * @return array
361
 *   An array of valid permissions for the portfolio module.
362
 */
363
function cdm_dataportal_permission() {
364
  return array(
365
    'administer cdm_dataportal' => array(
366
      'title' => t('administer cdm_dataportal'),
367
      'description' => t("TODO Add a description for 'administer cdm_dataportal'"),
368
    ),
369
    'cdm_dataportal view notes' => array(
370
      'title' => t('cdm_dataportal view notes'),
371
      'description' => t("TODO Add a description for 'cdm_dataportal view notes'"),
372
    ),
373
    // TODO Which other permissions are required?
374
    // -> check the WP6 requirements document.
375
  );
376
}
377

    
378
/**
379
 * Implements hook_menu().
380
 */
381
function cdm_dataportal_menu() {
382
  $items = array();
383

    
384
  // @see settings.php.
385
  cdm_dataportal_menu_admin($items);
386
  cdm_dataportal_menu_help($items);
387

    
388
  $items['cdm_dataportal/names'] = array(
389
    'page callback' => 'cdm_dataportal_view_names',
390
    'access arguments' => array('access content'),
391
    'type' => MENU_CALLBACK,
392
  );
393

    
394
  // Optional callback arguments: page.
395
  $items['cdm_dataportal/taxon'] = array(
396
    'page callback' => 'cdm_dataportal_taxon_page_view',
397
    'access arguments' => array('access content'),
398
    'type' => MENU_CALLBACK,
399
    // Expected callback arguments: uuid.
400
  );
401

    
402
  $items['cdm_dataportal/name'] = array(
403
    'page callback' => 'cdm_dataportal_name_page_view',
404
      /*
405
    'page arguments' => array(
406
       'taxon_name_uuid',
407
       'taxon_to_hide_uuid',
408
       'synonym_uuid' => NULL
409
      ),
410
      */
411
    'access arguments' => array('access content'),
412
    'type' => MENU_CALLBACK,
413
    // Expected callback arguments: uuid.
414
  );
415

    
416
  $items['cdm_dataportal/reference'] = array(
417
    'page callback' => 'cdm_dataportal_view_reference',
418
    'access arguments' => array('access content'),
419
    'type' => MENU_CALLBACK,
420
    // Expected callback arguments: uuid.
421
  );
422

    
423
  $items['cdm_dataportal/reference/list'] = array(
424
    'page callback' => 'cdm_dataportal_view_reference_list',
425
    'access arguments' => array('access content'),
426
    'type' => MENU_CALLBACK,
427
    // Expected callback arguments: uuid.
428
  );
429

    
430
  $items['cdm_dataportal/media'] = array(
431
    'page callback' => 'cdm_dataportal_view_media',
432
    'access arguments' => array('access content'),
433
    'type' => MENU_CALLBACK,
434
    // Expected callback arguments:
435
    // uuid, mediarepresentation_uuid, part_uuid or part#.
436
  );
437

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

    
445
  $items['cdm_dataportal/search'] = array(
446
    'page callback' => 'cdm_dataportal_view_search_advanced',
447
    'access arguments' => array('access content'),
448
    'type' => MENU_CALLBACK,
449
  );
450

    
451
  $items['cdm_dataportal/search/advanced'] = array(
452
    'title' => 'Advanced',
453
    'page callback' => 'cdm_dataportal_view_search_advanced',
454
    'access arguments' => array('access content'),
455
    'type' => MENU_DEFAULT_LOCAL_TASK,
456
  );
457

    
458
  $items['cdm_dataportal/search/taxon_by_description'] = array(
459
    'title' => 'By description full text',
460
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
461
    'access arguments' => array('access content'),
462
    'type' => MENU_LOCAL_TASK,
463
  );
464

    
465
  $items['cdm_dataportal/search/results/taxon'] = array(
466
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
467
    'access arguments' => array('access content'),
468
    'type' => MENU_CALLBACK,
469
  );
470
  /*
471
   $items['cdm/xml2json'] = array(
472
   'page callback' => 'cdm_view_xml2json',
473
   'access arguments' => array('access content'),
474
   'type' => MENU_CALLBACK,
475
   );
476
   */
477

    
478
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
479
  // User configuration of cdm_dataportal.
480
  $items['user/%/cdm_dataportal'] = array(
481
    'title' => 'cdm_dataportal',
482
    'access arguments' => array('access content'),
483
    'page callback' => 'drupal_get_form',
484
    'page arguments' => array('cdm_dataportal_user_form'),
485
    'type' => MENU_LOCAL_TASK,
486
    'weight' => 10,
487
  );
488
  // }
489

    
490
  // 'May not cache' in D5.
491
  // --- Local tasks for Taxon.
492
  $items['cdm_dataportal/name/%'] = array(
493
    // 'page callback' => 'cdm_dataportal_view_name',
494
    'page callback' => 'cdm_dataportal_name_page_view',
495
    'page arguments' => array(2, 3, 4),
496
    'access arguments' => array('access content'),
497
    'type' => MENU_CALLBACK,
498
  );
499

    
500
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
501
    $items['cdm_dataportal/taxon/%'] = array(
502
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
503
      'page callback' => 'cdm_dataportal_taxon_page_view',
504
      'access arguments' => array('access content'),
505
      'type' => MENU_CALLBACK,
506
      'weight' => 1,
507
      'page arguments' => array(2, "description")
508
      , // Expected callback arguments: name_uuid.
509
    );
510

    
511
    $items['cdm_dataportal/taxon/%/all'] = array(
512
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
513
      'page callback' => 'cdm_dataportal_taxon_page_view',
514
      'access arguments' => array('access content'),
515
      'type' => MENU_CALLBACK,
516
      'weight' => 2,
517
      'page arguments' => array(2, "all")
518
      , // Expected callback arguments: name_uuid.
519
    );
520

    
521
    $items['cdm_dataportal/taxon/%/description'] = array(
522
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
523
      'page callback' => 'cdm_dataportal_taxon_page_view',
524
      'access arguments' => array('access content'),
525
      'type' => MENU_DEFAULT_LOCAL_TASK,
526
      'weight' => 2,
527
      'page arguments' => array(2, "description")
528
      , // Expected callback arguments: name_uuid.
529
    );
530

    
531
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
532
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
533
      'page callback' => 'cdm_dataportal_taxon_page_view',
534
      'access arguments' => array('access content'),
535
      'type' => MENU_LOCAL_TASK,
536
      'weight' => 4,
537
      'page arguments' => array(2, "synonymy", 4)
538
      , // Expected callback arguments: name_uuid.
539
    );
540
    $items['cdm_dataportal/taxon/%/images'] = array(
541
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
542
      'page callback' => 'cdm_dataportal_taxon_page_view',
543
      'access arguments' => array('access content'),
544
      'type' => MENU_LOCAL_TASK,
545
      'weight' => 5,
546
      'page arguments' => array(2, "images")
547
      , // Expected callback arguments: name_uuid.
548
    );
549

    
550
    $items['cdm_dataportal/taxon/%/specimens'] = array(
551
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Specimens')),
552
      'page callback' => 'cdm_dataportal_taxon_page_view',
553
      'access arguments' => array('access content'),
554
      'type' => MENU_LOCAL_TASK,
555
      'weight' => 6,
556
      'page arguments' => array(2, "specimens")
557
      , // Expected callback arguments: name_uuid.
558
    );
559

    
560
    $items['cdm_dataportal/taxon/%/keys'] = array(
561
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
562
      'page callback' => 'cdm_dataportal_taxon_page_view',
563
      'access arguments' => array('access content'),
564
      'type' => MENU_LOCAL_TASK,
565
      'weight' => 6,
566
      'page arguments' => array(2, "keys")
567
      , // Expected callback arguments: name_uuid.
568
    );
569
  }
570

    
571
  return $items;
572
}
573

    
574
/**
575
 * @todo Please document this function.
576
 * @see http://drupal.org/node/1354
577
 */
578
function cdm_dataportal_init() {
579
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
580
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
581
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
582
}
583

    
584
/**
585
 * The function generate form for own user cdm dataportal configurations.
586
 */
587
function cdm_dataportal_user_form($form, &$form_state) {
588
  global $user;
589
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
590

    
591
  $form['check'] = array(
592
    '#type' => 'checkbox',
593
    '#title' => t('Activate user default configuration'),
594
    '#default_value' => variable_get($checkbox_value, 0),
595
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
596
  );
597

    
598
  $form['cdm_dataportal_user_form'] = array(
599
    '#type' => 'select',
600
    '#title' => t('Default tab to display'),
601
    '#default_value' => get_default_taxon_tab(TRUE),
602
    '#options' => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
603
    '#description' => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
604
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
605
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
606
  );
607

    
608
  $form['submit'] = array(
609
    '#type' => 'submit',
610
    '#value' => t('Submit'),
611
  );
612

    
613
  return $form;
614
}
615

    
616
/**
617
 * Form submission handler for user_form().
618
 *
619
 * Submits the user cdm dataportal configurations.
620
 */
621
function cdm_dataportal_user_form_submit($form, &$form_state) {
622
  global $user;
623
  $msg_type = 'status';
624
  $username = $user->name;
625
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
626

    
627
  // If is the right user the variables are setted.
628
  if (arg(0) == 'user' && ($uid = arg(1)) && is_numeric($uid) && $user->uid == $uid) {
629
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
630
    variable_set($variable_to_use . '_active', $form_state['values']['check']);
631
    variable_set($variable_to_use, $form_state['values']['cdm_dataportal_user_form']);
632
    if ($form_state['values']['check']) {
633
      drupal_set_message(check_plain(t('The user default tab will be used for the next taxon site visit.')));
634
      drupal_set_message(check_plain(t('The user default tab has been changed to: !tab for the user !user', array(
635
        '!tab' => $variable[variable_get($variable_to_use, 0)],
636
        '!user' => $username,
637
      ))), $msg_type);
638
    }
639
    else {
640
      drupal_set_message(check_plain(t('The user default tab wont be used for
641
        the next taxon site, check the box if you want to use the user default configuration.')));
642
    }
643
    // Problem with the user id => variables wont be saved.
644
  }
645
  else {
646
    $msg_type = 'warning';
647
    drupal_set_message(check_plain(t('Default tab has not been saved due to user id problems')), $msg_type);
648
  }
649
}
650

    
651
/**
652
 * Implements hook_block_info().
653
 */
654
function cdm_dataportal_block_info() {
655

    
656
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
657
    // $block[1]["info"] = t("CDM DataPortal Credits");
658
    $block["2"]["info"] = t("CDM Search Taxa");
659
    // $block[3]["info"] = t("CDM Filters");
660
    $block["4"]["info"] = t("CDM Dataportal Print");
661
    $block["keys"]["info"] = t("CDM identification keys");
662
    $block["uses"]["info"] = t("CDM Uses");
663
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
664

    
665
    return $block;
666
}
667

    
668
/**
669
 * Implements hook_block_view().
670
 */
671
function cdm_dataportal_block_view($delta) {
672
  // TODO Rename block deltas (e.g. '2') to readable strings.
673
  switch ($delta) {
674
    // case 'delta-1':
675
    // $block['subject'] = t('Credits');
676
    // $block['content'] = theme('cdm_credits');
677
    // return $block;
678
    case '2':
679
      $block['subject'] = t('Search taxa');
680
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
681
      $block['content'] = drupal_render($form);
682

    
683
      if (variable_get('cdm_dataportal_show_advanced_search', 1)) {
684
        $block['content'] .= '<div>' . l(t('Advanced Search'), 'cdm_dataportal/search') . '</div>';
685
      }
686
      return $block;
687
    case '4':
688
      $block['subject'] = t('<none>');
689
      $block['content'] = theme('cdm_print_button');
690
      return $block;
691
    case "keys":
692
      $block['subject'] = t('Identification Keys');
693
      $block['content'] = theme('cdm_block_IdentificationKeys', array('taxonUuid' => NULL));
694
      return $block;
695
      // Creating a block specific for the Use Interface.
696
    case "uses":
697
      $block['subject'] = t('Uses');
698
      $block['content'] = theme('cdm_block_uses', array('taxonUuid' => NULL));
699
      return $block;
700
    case "fundedByEDIT":
701
      // t('Funded by EDIT');
702
      $text = '<none>';
703
      $block['subject'] = $text;
704
      $img_tag = '<img src="' . drupal_get_path('module', 'cdm_dataportal') . '/images/funded_by_EDIT.png' . '" alt="' . $text . '"/>';
705
      $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array(
706
        'attributes' => array("target" => "EDIT"),
707
        'absolute' => TRUE,
708
        'html' => TRUE,
709
      ));
710
      return $block;
711
  }
712
}
713

    
714
/*
715
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
716
 $_SESSION['cdm'] = NULL;
717
 if(is_string($cdm_ws_uri_update)){
718
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
719
 }
720
 }
721

    
722
 function cdm_dataportal_session_validate(){
723
 if(!isset($_SESSION['cdm']['ws_uri'])){
724
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
725
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
726
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
727
 }
728
 }
729
 */
730

    
731
/**
732
 * @todo Please document this function.
733
 * @see http://drupal.org/node/1354
734
 */
735
function cdm_taxonomictree_selector() {
736
  _add_js_treeselector();
737

    
738
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
739
  $out = drupal_render($form);
740
  return $out;
741
}
742

    
743
/**
744
 * @todo Please document this function.
745
 * @see http://drupal.org/node/1354
746
 */
747
function cdm_taxonomictree_selector_form($form, &$form_state) {
748

    
749
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
750
  $form['#action'] = $url;
751

    
752
  $form['var'] = array(
753
    '#weight' => -3,
754
    '#type' => 'hidden',
755
    '#value' => '[cdm][taxonomictree_uuid]',
756
  );
757

    
758
  $destination_array = drupal_get_destination();
759
  $destination = $destination_array['destination'];
760

    
761
  $form['destination'] = array(
762
    '#weight' => -3,
763
    '#type' => 'hidden',
764
    '#value' =>  $destination,
765
  );
766

    
767
  $form['val'] = array(
768
    '#type' => 'select',
769
    '#title' => t('Available classifications'),
770
    '#default_value' => get_taxonomictree_uuid_selected(),
771
    '#options' => cdm_get_taxontrees_as_options(),
772
  );
773

    
774
  return $form;
775

    
776
}
777

    
778
/**
779
 * Implements hook_theme().
780
 *
781
 * Registering themes with a theme hook is needed since Drupal 6.
782
 *
783
 * @author W. Addink <w.addink@eti.uva.nl>
784
 */
785
function cdm_dataportal_theme() {
786
  return array(
787
    // Themes in help.php.
788
    'cdm_dataportal_admin_config_cdm_dataportal_general' => array('variables' => array()),
789
    'cdm_dataportal_admin_config_cdm_dataportal_geo' => array('variables' => array()),
790
    'cdm_dataportal_admin_config_cdm_dataportal_layout' => array('variables' => array()),
791
    'cdm_dataportal_admin_config_cdm_dataportal_cachesite' => array('variables' => array()),
792
    'cdm_dataportal_admin_config_more_help_link' => array('variables' => array()),
793

    
794
    // Themes in settings.php.
795
    'checkboxes_preferred' => array('render element' => 'element'),
796

    
797
    // Themes in cdm_dataportal.common.theme.
798
    'cdm_taggedtext2html' => array('variables' => array(
799
      'taggedtxt' => array(),
800
      'tag' => 'span',
801
      'glue' => ' ',
802
      'skiptags' => array(),
803
      )),
804
    'cdm_annotations_as_footnotekeys' => array('variables' => array('cdmBase_list' => NULL, 'footnote_list_key' => NULL)),
805
    'cdm_annotation_footnotes' => array('variables' => array('footnoteListKey' => NULL, 'enclosingTag' => 'span')),
806
    'cdm_annotation_content' => array('variables' => array('AnnotationTO' => NULL)),
807
    'cdm_list_of_annotations' => array('variables' => array('annotationElements' => NULL)),
808
    'cdm_footnote_key' => array('variables' => array(
809
      'footnoteKey' => NULL,
810
      'separator' => '',
811
      'highlightable' => TRUE,
812
      'separator_off' => FALSE,
813
      )),
814
    'cdm_footnote' => array('variables' => array('footnoteKey' => NULL, 'footnoteText' => NULL)),
815
    'cdm_footnotes' => array('variables' => array(
816
      'footnoteListKey' => NULL,
817
      'enclosingTag' => 'span',
818
      )),
819
    'cdm_annotations' => array('variables' => array('annotations' => NULL, 'enclosingTag' => 'span')),
820
    'cdm_pager' => array('variables' => array('pager' => NULL, 'path' => NULL, 'parameters' => NULL)),
821
    'cdm_pager_link' => array('variables' => array(
822
      'text' => NULL,
823
      'linkIndex' => NULL,
824
      'pager' => NULL,
825
      'path' => NULL,
826
      'parameters' => array(),
827
      'attributes' => NULL,
828
      )),
829
    'cdm_back_to_search_result_button' => array('variables' => array()),
830
    'cdm_back_to_image_gallery_button' => array('variables' => array()),
831
    'cdm_print_button' => array('variables' => array()),
832

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

    
889
    // Themes in cdm_dataportal.media.theme.
890
    'cdm_media' => array('variables' => array('descriptionElement' => NULL, 'mimeTypePreference' => NULL)),
891
    'cdm_mediaTypeTerm' => array('variables' => array('feature' => NULL, 'mediaUrl' => FALSE)),
892
    'cdm_media_mime_application' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
893
    'cdm_media_mime_image' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
894
    'cdm_media_mime_text' => array('variables' => array('representation' => NULL, 'feature' => NULL)),
895
    'cdm_media_caption' => array('variables' => array(
896
      'media' => NULL,
897
      'elements' => array('title', 'description', 'artist', 'location', 'rights'),
898
      'fileUri' => NULL,
899
      )),
900
    'cdm_media_gallerie' => array('variables' => array(
901
      'mediaList' => NULL,
902
      'galleryName' => NULL,
903
      'maxExtend' => 150,
904
      'cols' => 4,
905
      'maxRows' => FALSE,
906
      'captionElements' => array('title'),
907
      'mediaLinkType' => 'LIGHTBOX',
908
      'alternativeMediaUri' => NULL,
909
      'galleryLinkUri' => NULL,
910
      'showCaption' => TRUE,
911
      )),
912
    'cdm_media_gallerie_image' => array('variables' => array(
913
      'mediaRepresentationPart' => NULL,
914
      'maxExtend' => NULL,
915
      'addPassePartout' => FALSE,
916
      'attributes' => NULL,
917
      )),
918
    'cdm_media_gallerie_application' => array('variables' => array(
919
      'mediaRepresentationPart' => NULL,
920
      'maxExtend' => NULL,
921
      'addPassePartout' => FALSE,
922
      'attributes' => NULL,
923
      )),
924
    'cdm_media_gallerie_text' => array('variables' => array(
925
      'mediaRepresentationPart' => NULL,
926
      'maxExtend' => NULL,
927
      'addPassePartout' => FALSE,
928
      'attributes' => NULL,
929
      )),
930
    'cdm_openlayers_image' => array('variables' => array('mediaRepresentationPart' => NULL, 'maxExtend' => NULL)),
931
    'cdm_preferredImage' => array('variables' => array(
932
      'media' => NULL,
933
      'defaultRepresentationPart' => NULL,
934
      'imageMaxExtend' => NULL,
935
      'parameters' => '',
936
      )),
937

    
938
    // Themes in cdm_dataportal.name.theme.
939
    'cdm_taxonName' => array('variables' => array(
940
      'taxonName' => NULL,
941
      'nameLink' => NULL,
942
      'refenceLink' => NULL,
943
      'show_annotations' => TRUE,
944
      'is_type_designation' => FALSE,
945
      'skiptags' => array(),
946
      )),
947
    'cdm_typedesignations' => array('variables' => array('typeDesignations' => array())),
948
    'cdm_nameRelationships' => array('variables' => array('nameRelationships' => NULL, 'skipTypes' => FALSE)),
949
    'cdm_homotypicSynonymLine' => array('variables' => array('taxon' => NULL)),
950
    'cdm_heterotypicSynonymyGroup' => array('variables' => array('homotypicalGroup' => NULL)),
951
    'cdm_homotypicSynonymyGroup' => array('variables' => array(
952
      'synonymList' => NULL,
953
      'accepted_taxon_uuid' => NULL,
954
      'prependedSynonyms' => array(),
955
      )),
956
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
957
    'get_partDefinition' => array('variables' => array('nameType' => NULL)),
958
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
959

    
960
    // Themes in cdm_dataportal.occurrence.theme.
961
    'cdm_specimen' => array('variables' => array('specimenTypeDesignation' => NULL)),
962
    'cdm_derivedUnitFacade' => array('variables' => array('derivedUnitFacade' => NULL)),
963

    
964
    // Themes in cdm_dataportal.page.theme.
965
    'cdm_taxon_page_title' => array('variables' => array('taxon' => NULL, 'uuid' => NULL)),
966
    'cdm_name_page_title' => array('variables' => array('taxon_name' => NULL)),
967
    'cdm_taxon_page' => array('variables' => array('taxon' => NULL, 'page_part' => 'description')),
968
    'cdm_taxon_page_profile' => array('variables' => array(
969
      'taxon' => NULL,
970
      'mergedTrees' => NULL,
971
      'media' => NULL,
972
      'hideImages' => FALSE,
973
      )),
974
    'cdm_taxon_page_specimens' => array('variables' => array('taxon' => NULL)),
975
    'cdm_taxon_page_synonymy' => array('variables' => array('taxon' => NULL, 'addAcceptedTaxon' => NULL)),
976
    'cdm_reference_page' => array('variables' => array('reference' => NULL)),
977
    'cdm_media_page' => array('variables' => array(
978
      'media' => NULL,
979
      'mediarepresentation_uuid' => FALSE,
980
      'partId' => FALSE,
981
      )),
982
    'cdm_polytomousKey_page' => array('variables' => array('polytomousKey' => NULL)),
983
    'cdm_taxonpage_tab' => array('variables' => array('tabname' => NULL)),
984

    
985
    // Themes in cdm_dataportal.references.theme.
986
    'cdm_reference_pager' => array('variables' => array(
987
      'referencePager' => NULL,
988
      'path' => NULL,
989
      'parameters' => array(),
990
      )),
991
    'cdm_reference' => array('variables' => array(
992
      'reference' => NULL,
993
      'microReference' => NULL,
994
      'doLink' => FALSE,
995
      'referenceStyle' => NULL,
996
      )),
997

    
998
    // Themes in cdm_dataportal.taxon.theme.
999
    'cdm_search_results' => array('variables' => array(
1000
      'pager' => NULL,
1001
      'path' => NULL,
1002
      'query_parameters' => NULL,
1003
      )),
1004
    'cdm_taxonRelationships' => array('variables' => array('taxonRelationships' => NULL, 'focusedTaxon' => NULL)),
1005
    'cdm_acceptedFor' => array('variables' => array()),
1006
    'cdm_list_of_taxa' => array('variables' => array('records' => NULL, 'freetextSearchResults' => array())),
1007
    'cdm_taxon_list_thumbnails' => array('variables' => array('taxon' => NULL)),
1008

    
1009
    // Themes in cdm_dataportal.bibliography.theme.
1010
    'cdm_descriptionElementBibliography' => array('variables' => array('descriptionElementsBibliography' => array())),
1011
  );
1012
}
1013

    
1014
/* UNREACHABLE since action of form directly links to view.
1015
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1016

    
1017
 $_SESSION['cdm']['search'] = $form_values;
1018
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1019
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1020
 //$paramstr = compose_url_prameterstr($form_values);
1021
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1022
 }
1023
 */
1024
/* ====================== menu callback functions ====================== */
1025
/**
1026
 * @todo Please document this function.
1027
 * @see http://drupal.org/node/1354
1028
 */
1029
/*
1030
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1031
  static $comment_node_disabled =  0;
1032
  static $comment_node_read_only =  1;
1033
  static $comment_node_read_write =  2;
1034

    
1035
  if ($form_id == 'node_type_form'
1036
   && isset($form['identity']['type'])
1037
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1038
  ) {
1039
    $form['workflow']['comment'] = array(
1040
      '#type' => 'radios',
1041
      '#title' => t('Default comment setting'),
1042
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1043
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1044
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1045
    );
1046
  }
1047
}
1048
*/
1049

    
1050
/**
1051
 * Displays a list of the known taxonomic names.
1052
 *
1053
 * When the list of taxonomic names is displayed, long lists are split up into
1054
 * multiple pages.
1055
 *
1056
 * TODO: Parameters are still preliminary.
1057
 *
1058
 * @param string $beginsWith
1059
 * @param string $page
1060
 *   Page number to diplay defaults to page 1.
1061
 * @param bool $onlyAccepted
1062
 */
1063
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1064

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

    
1067
  /*
1068
  // FIXME the filter for accepted names will be a form element, thus this
1069
  // widget should be generated via form api preferably as block.
1070
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1071
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1072
  $out .= theme('cdm_listof_taxa', $taxonPager);
1073
  return $out;
1074
  */
1075
}
1076

    
1077
/**
1078
 * @todo Please document this function.
1079
 * @see http://drupal.org/node/1354
1080
 */
1081
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1082
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1083
  return theme('cdm_reference_page', array('reference' => $reference));
1084
}
1085

    
1086
/**
1087
 * @todo Please document this function.
1088
 * @see http://drupal.org/node/1354
1089
 */
1090
function cdm_dataportal_view_reference_list($pageNumber) {
1091
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1092
  return theme('cdm_reference_pager', array(
1093
    'referencePager' => $referencePager,
1094
    'path' => 'cdm_dataportal/reference/list/',
1095
    ));
1096
}
1097

    
1098
/**
1099
 * @todo Please document this function.
1100
 * @see http://drupal.org/node/1354
1101
 */
1102
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1103
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1104
  return theme('cdm_media_page', array(
1105
    'media' => $media,
1106
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1107
    'partId' => $part,
1108
    ));
1109
}
1110

    
1111
/**
1112
 * @todo Please document this function.
1113
 * @see http://drupal.org/node/1354
1114
 */
1115
function _load_taxonBase(&$taxonBase) {
1116
  if (isset($taxonBase->uuid)) {
1117
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1118
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1119
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1120
  }
1121
}
1122

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

    
1150
/**
1151
 * Loads the subgraph of a given PolytomousKeyNode.
1152
 *
1153
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1154
 * the CDM REST service.
1155
 *
1156
 * @param mixed $polytomousKeyNode
1157
 *   PolytomousKeyNode passed by reference.
1158
 *
1159
 * @return void
1160
 */
1161
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1162

    
1163
  if (!$polytomousKeyNode) {
1164
    return;
1165
  }
1166
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1167
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1168
    return;
1169
  }
1170
  if (!is_uuid($polytomousKeyNode->uuid)) {
1171
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1172
    return;
1173
  }
1174

    
1175
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1176

    
1177
  if (!$polytomousKeyNode) {
1178
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1179
    return;
1180
  }
1181

    
1182
  // Load children.
1183
  foreach ($polytomousKeyNode->children as &$childNode) {
1184
    _load_polytomousKeySubGraph($childNode);
1185
  }
1186

    
1187
  // Load subkey.
1188
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1189

    
1190
  // Load taxon.
1191
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1192
  _load_taxonBase($polytomousKeyNode->taxon);
1193
  return;
1194
}
1195

    
1196
/**
1197
 * @todo Please document this function.
1198
 * @see http://drupal.org/node/1354
1199
 */
1200
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1201
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1202

    
1203
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1204
  if (is_array($sourcePager->records)) {
1205
    $polytomousKey->sources = $sourcePager->records;
1206
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1207
  }
1208

    
1209
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1210
  if (is_array($annotationPager->records)) {
1211
    $polytomousKey->annotations = $annotationPager->records;
1212
  }
1213

    
1214
  _load_polytomousKeySubGraph($polytomousKey->root);
1215
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1216
}
1217

    
1218
/**
1219
 * Creates a taxon page view or a chapter of it.
1220
 *
1221
 * The taxon page gives detailed information on a taxon, it shows:
1222
 *  - Taxon name.
1223
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1224
 *    heterotypic and finally followed by misapplied names.
1225
 *    The list is ordered historically.
1226
 *  - All description associated with the taxon.
1227
 *
1228
 * @param string $uuid
1229
 * @param string $chapter
1230
 *   Name of the part to display, valid values are:
1231
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1232
 *
1233
 * @return unknown_type
1234
 */
1235
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1236
  // Display the page for the taxon defined by $uuid.
1237
  // set_last_taxon_page_tab(arg(3));
1238
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1239
  if (!empty($taxonpage)) {
1240
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1241
  }
1242
  else {
1243
    return '';
1244
  }
1245
}
1246

    
1247
/**
1248
 * @todo improve documentation for this function.
1249
 *
1250
 * @param string $uuid
1251
 * @param string $chapter
1252
 *   Name of the part to display, valid values are:
1253
 *   'description', 'images', 'synonymy', 'all'.
1254
 *
1255
 * @return unknown_type
1256
 */
1257
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1258
  // Taxon object.
1259
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1260
  if (empty($taxon)) {
1261
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1262
    return FALSE;
1263
  }
1264
  $taxonpage = new stdClass();
1265

    
1266
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1267
    'taxon' => $taxon,
1268
    'uuid' => $uuid,
1269
    'synonym_uuid' => $synonym_uuid,
1270
  ));
1271

    
1272
  // Check if the taxon id contained in the currently selected tree.
1273
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1274
  $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1275
  if (!$taxon_in_current_tree) {
1276
    if (count($taxon_nodes) == 0) {
1277
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained any classification.', array(
1278
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1279
      ))), 'warning');
1280
    }
1281
    else {
1282
      $trees = '';
1283
      foreach ($taxon_nodes as $node) {
1284
        if (isset($node->classification->titleCache)) {
1285
          $trees .= ($trees ? ', ' : '') . '<strong>' . $node->classification->titleCache . '</strong>';
1286
        }
1287
      }
1288

    
1289
      drupal_set_message(format_plural(count($taxon_nodes),
1290
          'This concept of the taxon !taxonname is not contained in the currently chosen classification, but in this one: !trees',
1291
          'This concept of the taxon !taxonname is not contained in the currently chosen classification, but in one of these: !trees',
1292
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1293
    }
1294
  }
1295

    
1296
  // Render the taxon page.
1297
  $taxonpage->content = theme('cdm_taxon_page', array(
1298
    'taxon' => $taxon,
1299
    'page_part' => $chapter,
1300
  ));
1301

    
1302
  return $taxonpage;
1303
}
1304

    
1305
/**
1306
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1307
 *
1308
 * The node page shows the taxon name title and the list of taxon related
1309
 * with such taxon. Name on the tree already in use.
1310
 *
1311
 * @param string $taxon_name_uuid
1312
 *   A taxon name UUID.
1313
 *
1314
 * @return mixed
1315
 *   The formatted name page as node.
1316
 */
1317
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1318

    
1319
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1320
  if (!empty($taxonname_page)) {
1321
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1322
  }
1323
  else {
1324
    return '';
1325
  }
1326
}
1327

    
1328
/**
1329
 * Generates an object ready to be transformated to a node.
1330
 *
1331
 * This is a preparation in order to show it as a Drupal node.
1332
 *
1333
 * @param string $taxon_name_uuid
1334
 *
1335
 * @return mixed
1336
 *   The object with the page content and title.
1337
 */
1338
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1339
  // Getting the full taxonname object from the server.
1340
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1341
  if (!$taxon_name) {
1342
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1343
    return FALSE;
1344
  }
1345
  // Searching for all the taxa connected with the taxon name on the tree
1346
  // in use.
1347
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1348
  $request_params = array();
1349
  $request_params['query'] = $name_cache;
1350
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1351
  $request_params['doTaxa'] = 1;
1352
  $request_params['doSynonyms'] = 1;
1353
  $request_params['doTaxaByCommonNames'] = 0;
1354
  $request_params['matchMode'] = "EXACT";
1355
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1356

    
1357
  // Removing the name where we come from.
1358
  foreach ($taxon_pager->records as $k => &$taxon) {
1359
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1360
      unset($taxon_pager->records[$k]);
1361
    }
1362
  }
1363
  // Show the taxa list or go to the singular taxon.
1364
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1365
    reset($taxon_pager->records);
1366
    $singleTaxon = $taxon_pager->records[0];
1367
    if ($singleTaxon->class != "Taxon") {
1368
      // It is a Synonym -> look for the accepted.
1369
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1370
      if (!empty($synonym_uuid)) {
1371
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1372
      }
1373
      else {
1374
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1375
      }
1376
    }
1377
    else {
1378
      // It is an accepted taxon.
1379
      if (!empty($synonym_uuid)) {
1380
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1381
      }
1382
      else {
1383
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1384
      }
1385
    }
1386
  }
1387
  else {// More than one taxa case.
1388
    $taxon_name_page = new stdClass();
1389
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name . ''));
1390
    if ($taxon_pager->records) {
1391
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1392
    }
1393
    else {
1394
      $taxon_name_page->content = 'This name has no taxa';
1395
    }
1396
    return $taxon_name_page;
1397
  }
1398
}
1399

    
1400
/**
1401
 * @todo Please document this function.
1402
 * @see http://drupal.org/node/1354
1403
 */
1404
function cdm_dataportal_view_search_advanced() {
1405

    
1406
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1407
  $form = array();
1408
  $form_state = array();
1409
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1410

    
1411
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1412

    
1413
}
1414

    
1415
/**
1416
 * @todo Please document this function.
1417
 * @see http://drupal.org/node/1354
1418
 */
1419
function cdm_dataportal_view_search_taxon_by_description() {
1420
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1421
  // $form_state = false;
1422
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1423
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1424

    
1425
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1426
}
1427

    
1428
/**
1429
 * Executes the search and generates the result list of taxa.
1430
 */
1431
function cdm_dataportal_view_search_results_taxon() {
1432

    
1433
  $taxonPager = cdm_dataportal_search_execute();
1434

    
1435
  return theme('cdm_search_results', array(
1436
    'pager' => $taxonPager,
1437
    'path' => 'cdm_dataportal/search/results/taxon',
1438
    'query_parameters' => $_REQUEST,
1439
    ));
1440
}
1441

    
1442
/**
1443
 * View which transforms XML output from a given webservice endpoint into JSON.
1444
 */
1445
/*
1446
 function cdm_view_xml2json(){
1447
 $file = arg(2);
1448
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1449
 return  xml2json::transformXmlStringToJson($datastr);
1450
 }
1451
 */
1452

    
1453
/* ====================== other functions ====================== */
1454
/**
1455
 * Creates a URL to the taxon page specified by the $uuid parameter.
1456
 *
1457
 * The URL will be prepended with a path element to a specific taxon page tab.
1458
 *
1459
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1460
 * be set globally in the administrative settings or individually in the user
1461
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1462
 * the last portal will stay on this last tab.
1463
 *
1464
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1465
 * internal mechanism by a specific value.
1466
 *
1467
 * @param string $uuid
1468
 *   The UUID of the taxon.
1469
 * @param string $page_tab
1470
 *   Overwriting the preset mechanism by defining specific value for the
1471
 *   taxon page tab.
1472
 *
1473
 * @return string
1474
 *   The created URL.
1475
 */
1476
function path_to_taxon($uuid, $page_tab = FALSE) {
1477

    
1478
  $tab = get_default_taxon_tab();
1479
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1480

    
1481
  if (!$uuid) {
1482
    return FALSE;
1483
  }
1484

    
1485
  if ($page_tab) {
1486
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1487
  }
1488
  elseif (!$tab || strtolower($tab) == 'general') {
1489
    return 'cdm_dataportal/taxon/' . $uuid;
1490
  }
1491
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1492
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1493
  }
1494
  else {
1495
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1496
  }
1497
}
1498

    
1499
/**
1500
 * @todo Please document this function.
1501
 * @see http://drupal.org/node/1354
1502
 */
1503
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1504
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1505
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1506
}
1507

    
1508
/**
1509
 * @todo Please document this function.
1510
 * @see http://drupal.org/node/1354
1511
 */
1512
function path_to_key($keyType, $keyUuid) {
1513
  if (!$keyUuid || !$keyType) {
1514
    return FALSE;
1515
  }
1516
  $keyType{0} = strtolower($keyType{0});
1517
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1518
}
1519

    
1520
/**
1521
 * @todo Please document this function.
1522
 * @see http://drupal.org/node/1354
1523
 */
1524
function path_to_reference($uuid) {
1525
  if (!$uuid) {
1526
    return FALSE;
1527
  }
1528
  return 'cdm_dataportal/reference/' . $uuid;
1529
}
1530

    
1531
/**
1532
 * @todo Please document this function.
1533
 * @see http://drupal.org/node/1354
1534
 */
1535
function path_to_name($name_uuid) {
1536
  $res = FALSE;
1537
  if ($name_uuid) {
1538
    $res = 'cdm_dataportal/name/' . $name_uuid;
1539
  }
1540
  return $res;
1541
}
1542

    
1543
/**
1544
 * @todo Please document this function.
1545
 * @see http://drupal.org/node/1354
1546
 */
1547
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1548
  if (!$uuid) {
1549
    return FALSE;
1550
  }
1551
  $out = 'cdm_dataportal/media/' . $uuid;
1552
  if ($representaion_uuid) {
1553
    $out .= '/' . $representaion_uuid;
1554
    if ($partId !== FALSE) {
1555
      $out .= '/' . $partId;
1556
    }
1557
  }
1558
  return $out;
1559
}
1560

    
1561
/**
1562
 * Compares thisRank with thatRank.
1563
 *
1564
 * Returns a negative integer, zero, or a positive integer
1565
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1566
 * e.g:
1567
 * <ul>
1568
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1569
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1570
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1571
 * </ul>
1572
 * <p>
1573
 * This compare logic of the underlying webservice is the
1574
 * <b>inverse logic</b> of the the one implemented in
1575
 * java.lang.Comparable#compareTo(java.lang.Object)
1576
 *
1577
 * @param $thisRankUuid
1578
 * @param $thatRankUuid
1579
 *
1580
 * @return int
1581
 *   A negative integer, zero, or a positive integer
1582
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1583
 */
1584
function rank_compare($thisRankUuid, $thatRankUuid) {
1585
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1586
  return $result->Integer;
1587
}
1588

    
1589
/**
1590
 * Composes an HTML element class attribute value composed of
1591
 * the shortname of the cdm class and the uuid of the entity.
1592
 * This class attribute should be used whereever an cdm-entity is rendered.
1593
 *
1594
 * These according class selectors in css must be escaped, eg:
1595
 *    .cdm\:TextData
1596
 *
1597
 * @param $cdmEntity
1598
 */
1599
function html_class_atttibute_ref($cdmEntity) {
1600

    
1601
  if (is_cdm_entity($cdmEntity)) {
1602
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1603
  }
1604
}
1605

    
1606
/**
1607
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1608
 *
1609
 * @param unknown_type $taggedTextList
1610
 */
1611
function normalize_TaggedName(&$taggedTextList) {
1612

    
1613
  if (is_array($taggedTextList)) {
1614

    
1615
    // First pass: rename.
1616
    for ($i = 0; $i < count($taggedTextList); $i++) {
1617

    
1618
      if ($taggedTextList[$i]->type == "hybridSign") {
1619
        $taggedTextList[$i]->type = "name";
1620
      }
1621
    }
1622

    
1623
    // Second pass: resolve separators.
1624
    $taggedNameListNew = array();
1625
    for ($i = 0; $i < count($taggedTextList); $i++) {
1626

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

    
1629
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1630
          $taggedName = $taggedTextList[$i];
1631
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1632
          $taggedNameListNew[] = $taggedName;
1633
          ++$i;
1634
          ++$i;
1635
        }
1636
      }
1637
      else {
1638
        $taggedNameListNew[] = $taggedTextList[$i];
1639
      }
1640
    }
1641
    $taggedTextList = $taggedNameListNew;
1642
  }
1643
}
1644

    
1645
/**
1646
 * Creates a short taxonname.
1647
 *
1648
 * The short name is created by using the taggename field of
1649
 * NameSTO or NameTO instances.
1650
 * If the taggename if empty the fullname will be returned.
1651
 *
1652
 * @param unknown_type $name
1653
 *   Name or TreeNode.
1654
 *
1655
 * @return string
1656
 */
1657
function cdm_dataportal_shortname_of($name) {
1658
  $nameStr = '';
1659

    
1660
  normalize_TaggedName($name->taggedTitle);
1661

    
1662
  // Get all tagged text tokens of the scientific name.
1663
  foreach ($name->taggedTitle as $tagtxt) {
1664
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1665
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1666
    }
1667
  }
1668
  $nameStr = trim($nameStr);
1669

    
1670
  if ($nameStr) {
1671

    
1672
    // Do not return short names for these.
1673
    if ($name->unplaced || $name->excluded) {
1674
      return $nameStr;
1675
    }
1676

    
1677
    /*
1678
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1679
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1680
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1681
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1682
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1683
    */
1684
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1685
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1686
      return $matches[1][0] . "." . $matches[3][0];
1687
    }
1688
    else {
1689
      return $nameStr;
1690
    }
1691
  }
1692
  else {
1693
    return $name->titleCache;
1694
  }
1695
}
1696

    
1697
/**
1698
 * Check if a taxon is accepted by the current taxonomic tree.
1699
 *
1700
 * @param mixed $taxon
1701
 *   The Taxon obkect to check.
1702
 *
1703
 * @return bool
1704
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1705
 */
1706
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1707

    
1708
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1709

    
1710
  if (isset($taxon->taxonNodes)) {
1711
    $taxonNodes = $taxon->taxonNodes;
1712
  }
1713
  else {
1714
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1715
  }
1716

    
1717
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1718
    foreach ($taxonNodes as $node) {
1719
      if (is_object($node->classification)) {
1720
        if ($node->classification->uuid == $defaultTreeUuid) {
1721
          return TRUE;
1722
        }
1723
      }
1724
      else {
1725
        if ($node->classification == $defaultTreeUuid) {
1726
          return TRUE;
1727
        }
1728
      }
1729
    }
1730
  }
1731

    
1732
  return FALSE;
1733
}
1734

    
1735
/**
1736
 * @deprecated
1737
 */
1738
function compose_url_prameterstr($parameters = array(), $parentPropertyName = FALSE) {
1739
  $pstr = '';
1740
  foreach ($parameters as $key => $value) {
1741
    if (is_array($value)) {
1742

    
1743
    }
1744
    else {
1745
      $pstr .= ($pstr ? '&' : '') . $key . '=' . urlencode($value);
1746
    }
1747
  }
1748
  return $pstr;
1749
}
1750

    
1751
/**
1752
 * Workaround for missing original source type.
1753
 *
1754
 * idNamespace is always set in these cases.
1755
 * @todo improve documentation of this function.
1756
 *
1757
 * @param unknown_type $source
1758
 *
1759
 * @return unknown_type
1760
 */
1761
function _is_original_source_type($source) {
1762
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1763
}
1764

    
1765
/**
1766
 * @todo Please document this function.
1767
 * @see http://drupal.org/node/1354
1768
 */
1769
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1770
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1771
}
1772

    
1773
/**
1774
 * Gets the metadata info such as title or artist of a media file.
1775
 *
1776
 * The function tries at first to get all the info from the file metadata
1777
 * and if it is not avaible look at the media file info stored at the database.
1778
 *
1779
 * @param mixed $media
1780
 *   The media file object for which to get the metadata.
1781
 *
1782
 * @return array
1783
 *   The array with the available specified metadata info.
1784
 * TODO rename to read_media_metadata() and move to *.module.
1785
 */
1786
function cdm_read_media_metadata($media) {
1787

    
1788
  $metadata_caption = array(
1789
    'title' => '',// Media_metadata and media.
1790
    'artist' => '',// Media_metadata and media.
1791
    'rights',// Media_metadata and media.
1792
    'location',// Media_metadata.
1793
    'filename' => '',// Media.
1794
    'mediacreated' => '',// Media.
1795
    'description' => '',
1796
  );// Media.
1797

    
1798
  // Getting the media metadata.
1799
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1800
  $media_metadata_aux = (array) $media_metadata;
1801

    
1802
  // Filename.
1803
  if (isset($media->representations[0]->parts[0]->uri)) {
1804
    $fileUri = $media->representations[0]->parts[0]->uri;
1805
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1806
    $metadata_caption['filename'] = $filename;
1807
  }
1808
  else {
1809
    $metadata_caption['filename'] = '';
1810
  }
1811

    
1812
  // Title.
1813
  if (!empty($media_metadata->ObjectName)) {
1814
    $metadata_caption['title'] = $media_metadata->ObjectName;
1815
  }
1816
  elseif ($media_metadata_aux['Object Name']) {
1817
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1818
  }
1819
  elseif ($media->title_L10n) {
1820
    $metadata_caption['title'] = $media->title_L10n;
1821
  }
1822
  elseif ($media->titleCache) {
1823
    $metadata_caption['title'] = $media->titleCache;
1824
  }
1825

    
1826
  // Append description to title.
1827
  if (!empty($media->description_L10n)) {
1828
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1829
  }
1830

    
1831
  // Artist.
1832
  if ($media_metadata->Artist) {
1833
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1834
  }
1835
  elseif ($media->artist->titleCache) {
1836
    $metadata_caption['artist'] = $media->artist->titleCache;
1837
  }
1838

    
1839
  // Copyright.
1840
  $metadata_caption['rights'] = array(
1841
    'copyright' => array('agentNames' => array()),
1842
    'license' => array(
1843
      'agentNames' => array(),
1844
      'types' => array(),
1845
      'abbreviatedTexts' => array(),
1846
      'uris' => array(),
1847
    ),
1848
  );
1849
  if ($media_metadata->Copyright) {
1850
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1851
  }
1852
  elseif (isset($media->rights) && is_array($media->rights)) {
1853
    foreach ($media->rights as $right) {
1854
      switch ($right->term->uuid) {
1855
        case UUID_RIGHTS_LICENCE:
1856
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1857
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1858
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1859
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1860
          break;
1861
        case UUID_RIGHTS_COPYRIGHT:
1862
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1863
          break;
1864
      }
1865
    }
1866
  }
1867
  else {
1868
    $metadata_caption['rights']['agentNames'][] = '';
1869
  }
1870

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

    
1874
  // Location.
1875
  $metadata_caption['location'] = array();
1876
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1877
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1878
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1879
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1880

    
1881
  /*
1882
   // Creation date.
1883
   if($media_metadata["Modify Date"])
1884
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1885
   else
1886
   $metadata_caption['mediacreated'] = $media->created;
1887
   */
1888

    
1889
  // Returned value.
1890
  return $metadata_caption;
1891
}
1892

    
1893
/**
1894
 * Collects all the media from a list of description elements.
1895
 *
1896
 * @param array $descriptionElements
1897
 *   The description elements from which to collect the media.
1898
 *
1899
 * @return array
1900
 *   The output with all the collected media.
1901
 */
1902
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1903

    
1904
  $outArrayOfMedia = array();
1905

    
1906
  // Avoiding a warning box in Drupal for Flora Malesiana.
1907
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1908
    foreach ($descriptionElements as $descriptionElement) {
1909
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1910
        foreach ($descriptionElement->media as $media) {
1911
          if (is_object($media)) {
1912
            $outArrayOfMedia[] = $media;
1913
          }
1914
        }
1915
      }
1916
    }
1917
  }
1918
  return $outArrayOfMedia;
1919
}
1920

    
1921
/**
1922
 * @todo Please document this function.
1923
 * @see http://drupal.org/node/1354
1924
 *
1925
 * @param array $cdmBase_list
1926
 *   An array of CdmBase instances or a single instance.
1927
 * @param string $footnote_list_key
1928
 *
1929
 * @return unknown
1930
 */
1931
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1932
  // Comment @WA: undefined variable.
1933
  /*
1934
   static $annotations_types_filter;
1935
   if(!$annotations_types_filter) {
1936
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1937
   }
1938
   */
1939
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1940

    
1941
  $footNoteKeys = array();
1942

    
1943
  // Is argument cdmBase an array?
1944
  if (!is_array($cdmBase_list)) {
1945
    $cdmBase_array = array();
1946
    $cdmBase_array[] = $cdmBase_list;
1947
  }
1948
  else {
1949
    $cdmBase_array = $cdmBase_list;
1950
  }
1951

    
1952
  // Getting the key for the footnotemanager.
1953
  if (isset($footnote_list_key)) {
1954
    $footnoteListKey = $footnote_list_key;
1955
  }
1956
  else {
1957
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1958
  }
1959

    
1960
  // Adding the footnotes keys.
1961
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1962
  foreach ($cdmBase_array as $cdmBase_element) {
1963
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1964
    if (is_array($annotations)) {
1965
      foreach ($annotations as $annotation) {
1966
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1967
      }
1968
    }
1969
  }
1970

    
1971
  return $footNoteKeys;
1972
}
1973

    
1974
// @WA Comment: should this not be a theme function?
1975
/**
1976
 *  Creates a CDM Dynabox.
1977
 *
1978
 * @param string $label
1979
 *   The clickable text to show.
1980
 * @param string $content_url
1981
 *   The cdm REST service request url wich will deliver the content to be shown
1982
 *   once the dynabox toggles open.
1983
 * @param string $theme
1984
 *   The theme to be used for rendering the cdm REST service reponse with is
1985
 *   returned from the $content_url.
1986
 * @param string $link_alt_text
1987
 *   The value for the alt attribute of the dynabox link.
1988
 * @param array $enclosingtags
1989
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
1990
 *   element itself, $enclosingtags[1] is the tag to be used for the
1991
 *   dynabox_content.
1992
 *
1993
 * @return string
1994
 *   Returns HTML for a dynabox.
1995
 */
1996
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')) {
1997
  $out = '';
1998
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
1999

    
2000
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2001
  $out .= '<!-- ' . $content_url . ' -->';
2002
  $out .= '<' . $enclosingtags[0] . ' class="dynabox"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2003
  $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] . '>';
2004
  $out .= '</' . $enclosingtags[0] . '>';
2005
  return $out;
2006
}
2007

    
2008
/**
2009
 * Checks whether a feature has any description elements.
2010
 *
2011
 * @param mixed $featureNode
2012
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2013
 *
2014
 * @see _mergeFeatureTreeDescriptions()
2015
 *
2016
 * @return bool
2017
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2018
 *   contains at least one non empty TextData or at least one DescriptionElement
2019
 *   of an other type. A TextData element holding a multilanguageText or a
2020
 *   source reference is considered to be not empty.
2021
 */
2022
function hasFeatureNodeDescriptionElements($featureNode) {
2023

    
2024
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2025
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2026
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0])) {
2027
        return TRUE;
2028
      }
2029
    }
2030
  }
2031
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2032
    foreach ($featureNode->children as $child) {
2033
      if (hasFeatureNodeDescriptionElements($child)) {
2034
        return TRUE;
2035
      }
2036
    }
2037
  }
2038
  return FALSE;
2039
}
(6-6/13)