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
      $block['content'] = drupal_render(drupal_get_form('cdm_dataportal_search_taxon_form'));
681

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

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

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

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

    
737
  $out = drupal_render(drupal_get_form('cdm_taxonomictree_selector_form'));
738
  return $out;
739
}
740

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

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

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

    
756
  $destination_array = drupal_get_destination();
757
  $destination = $destination_array['destination'];
758

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

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

    
772
  return $form;
773

    
774
}
775

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1173
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1174

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1300
  return $taxonpage;
1301
}
1302

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

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

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

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

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

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

    
1409
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1410

    
1411
}
1412

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

    
1423
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1424
}
1425

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

    
1431
  $taxonPager = cdm_dataportal_search_execute();
1432

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

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

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

    
1476
  $tab = get_default_taxon_tab();
1477
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1478

    
1479
  if (!$uuid) {
1480
    return FALSE;
1481
  }
1482

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

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

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

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

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

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

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

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

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

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

    
1611
  if (is_array($taggedTextList)) {
1612

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

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

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

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

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

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

    
1658
  normalize_TaggedName($name->taggedTitle);
1659

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

    
1668
  if ($nameStr) {
1669

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

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

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

    
1706
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1707

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

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

    
1730
  return FALSE;
1731
}
1732

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1887
  // Returned value.
1888
  return $metadata_caption;
1889
}
1890

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

    
1902
  $outArrayOfMedia = array();
1903

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

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

    
1939
  $footNoteKeys = array();
1940

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

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

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

    
1969
  return $footNoteKeys;
1970
}
1971

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

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

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

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