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
  $out = drupal_render(drupal_get_form('cdm_taxonomictree_selector_form'));
739
  return $out;
740
}
741

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

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

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

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

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

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

    
773
  return $form;
774

    
775
}
776

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1301
  return $taxonpage;
1302
}
1303

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

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

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

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

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

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

    
1410
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1411

    
1412
}
1413

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

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

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

    
1432
  $taxonPager = cdm_dataportal_search_execute();
1433

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1612
  if (is_array($taggedTextList)) {
1613

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

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

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

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

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

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

    
1659
  normalize_TaggedName($name->taggedTitle);
1660

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

    
1669
  if ($nameStr) {
1670

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

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

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

    
1707
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1708

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

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

    
1731
  return FALSE;
1732
}
1733

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1903
  $outArrayOfMedia = array();
1904

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

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

    
1940
  $footNoteKeys = array();
1941

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

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

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

    
1970
  return $footNoteKeys;
1971
}
1972

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

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

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

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