Project

General

Profile

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

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

    
25
module_load_include('inc', 'cdm_dataportal', 'includes/pages');
26
module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
27

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

    
38
module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
39
module_load_include('php', 'cdm_dataportal', 'classes/footnote');
40
module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
41
module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
42

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

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

    
64
/**
65
 * @param unknown_type $link_element_selector
66
 * @param unknown_type $progress_element_selector
67
 */
68
function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
69

    
70
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
71

    
72
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
73

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

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

    
94
      });
95
    ",
96
    array(
97
      'type' => 'inline',
98
      'scope' => 'footer'
99
    )
100
  );
101
}
102

    
103
/**
104
 * @todo Please document this function.
105
 * @see http://drupal.org/node/1354
106
 */
107
function _add_js_openlayers_map() {
108

    
109
  $openlayers = '/js/OpenLayers-2.11/OpenLayers.js';
110

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

    
117
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
118

    
119
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
120

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

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

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

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

    
166
}
167

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

    
182
  $server = getEDITMapServiceURI();
183

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

    
192
    // Message to render.
193
    return '<p>' . t('No geoservice specified') . '</p>';
194
  }
195

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

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

    
203
  if ($map_caption) {
204
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
205
  }
206

    
207
  if (getEDITMapServiceVersionNumber() >= 1.1) {
208

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

    
218
      $query_string .= "&" . $occurrenceQuery;
219
    }
220
    elseif ($distributionQuery) {
221
      $query_string .= "&" . $distributionQuery;
222
    }
223

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

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

    
238
    $map_service_script_name = "rest_gen.php";
239

    
240
    $bgcolor_areaStyleId = "y";
241
    $baselayer_areaStyleId = "z";
242
    $bgcolor_layer = '';
243
    $additional_area_styles = array();
244

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

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

    
272
    if ($bgcolor_layer) {
273
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
274
    }
275

    
276
    if (variable_get('map_base_layer_style', '')) {
277
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
278
    }
279

    
280
    foreach ($additional_area_styles as $as) {
281
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
282
    }
283

    
284
  }
285
  else {
286
    // Pre 1.1. version of map service.
287
    if ($occurrenceQuery) {
288

    
289
      $map_service_script_name = "point.php";
290

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

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

    
312
  return $out;
313
}
314

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

    
329
  _add_js_openlayers_map();
330

    
331
  $out = '<div id="openlayers">';
332
  $out .= '<div id="openlayers_map" class="smallmap"';
333
  if($width) {
334
    $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
335
  }
336

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

    
340
  $openlayers_map_query_string = '&img=false&ms=' . $width
341
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
342
    . ($labels_on ? '&label=' . $labels_on : '');
343

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

    
352
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
353
  }
354

    
355
  if ($distributionQuery) {
356
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
357
  }
358

    
359
  if ($legendFormatQuery) {
360
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
361
  }
362

    
363
  $out .= '></div></div>';
364

    
365
  // Showing map caption.
366
  if ($map_caption) {
367
    // FIXME: replace <br> by according css style.
368
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
369
    $out .= '</div>';
370
  }
371
  return $out;
372
}
373

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

    
398
/**
399
 * Implements hook_menu().
400
 */
401
function cdm_dataportal_menu() {
402
  $items = array();
403

    
404
  // @see settings.php.
405
  cdm_dataportal_menu_admin($items);
406
  cdm_dataportal_menu_help($items);
407

    
408
  $items['cdm_dataportal/names'] = array(
409
    'page callback' => 'cdm_dataportal_view_names',
410
    'access arguments' => array('access content'),
411
    'type' => MENU_CALLBACK,
412
  );
413

    
414
  // Optional callback arguments: page.
415
  $items['cdm_dataportal/taxon'] = array(
416
    'page callback' => 'cdm_dataportal_taxon_page_view',
417
    'access arguments' => array('access content'),
418
    'type' => MENU_CALLBACK,
419
    // Expected callback arguments: uuid.
420
  );
421

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

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

    
443
  $items['cdm_dataportal/reference/list'] = array(
444
    'page callback' => 'cdm_dataportal_view_reference_list',
445
    'access arguments' => array('access content'),
446
    'type' => MENU_CALLBACK,
447
    // Expected callback arguments: uuid.
448
  );
449

    
450
  $items['cdm_dataportal/media'] = array(
451
    'page callback' => 'cdm_dataportal_view_media',
452
    'access arguments' => array('access content'),
453
    'type' => MENU_CALLBACK,
454
    // Expected callback arguments:
455
    // uuid, mediarepresentation_uuid, part_uuid or part#.
456
  );
457

    
458
  $items['cdm_dataportal/polytomousKey'] = array(
459
    'page callback' => 'cdm_dataportal_view_polytomousKey',
460
    'access arguments' => array('access content'),
461
    'type' => MENU_CALLBACK,
462
    // Expected callback arguments: polytomousKey->uuid.
463
  );
464

    
465
  $items['cdm_dataportal/search'] = array(
466
    'page callback' => 'cdm_dataportal_view_search_advanced',
467
    'access arguments' => array('access content'),
468
    'type' => MENU_CALLBACK,
469
  );
470

    
471
  $items['cdm_dataportal/search/advanced'] = array(
472
    'title' => 'Advanced',
473
    'page callback' => 'cdm_dataportal_view_search_advanced',
474
    'access arguments' => array('access content'),
475
    'type' => MENU_DEFAULT_LOCAL_TASK,
476
  );
477

    
478
  $items['cdm_dataportal/search/taxon_by_description'] = array(
479
    'title' => 'By description full text',
480
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
481
    'access arguments' => array('access content'),
482
    'type' => MENU_LOCAL_TASK,
483
  );
484

    
485
  $items['cdm_dataportal/search/results/taxon'] = array(
486
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
487
    'access arguments' => array('access content'),
488
    'type' => MENU_CALLBACK,
489
  );
490
  /*
491
   $items['cdm/xml2json'] = array(
492
   'page callback' => 'cdm_view_xml2json',
493
   'access arguments' => array('access content'),
494
   'type' => MENU_CALLBACK,
495
   );
496
   */
497

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

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

    
520
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
521
    $items['cdm_dataportal/taxon/%'] = 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_CALLBACK,
526
      'weight' => 1,
527
      'page arguments' => array(2, "description")
528
      , // Expected callback arguments: name_uuid.
529
    );
530

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

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

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

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

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

    
591
  return $items;
592
}
593

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

    
604
/**
605
 * The function generate form for own user cdm dataportal configurations.
606
 */
607
function cdm_dataportal_user_form($form, &$form_state) {
608
  global $user;
609
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
610

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

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

    
628
  $form['submit'] = array(
629
    '#type' => 'submit',
630
    '#value' => t('Submit'),
631
  );
632

    
633
  return $form;
634
}
635

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

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

    
671
/**
672
 * Implements hook_block_info().
673
 */
674
function cdm_dataportal_block_info() {
675

    
676
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
677
    // $block[1]["info"] = t("CDM DataPortal Credits");
678
    $block["2"]["info"] = t("CDM Search Taxa");
679
    // $block[3]["info"] = t("CDM Filters");
680
    $block["4"]["info"] = t("CDM Dataportal Print");
681
    $block["keys"]["info"] = t("CDM identification keys");
682
    $block["uses"]["info"] = t("CDM Uses");
683
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
684

    
685
    return $block;
686
}
687

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

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

    
734
/*
735
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
736
 $_SESSION['cdm'] = NULL;
737
 if(is_string($cdm_ws_uri_update)){
738
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
739
 }
740
 }
741

    
742
 function cdm_dataportal_session_validate(){
743
 if(!isset($_SESSION['cdm']['ws_uri'])){
744
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
745
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
746
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
747
 }
748
 }
749
 */
750

    
751
/**
752
 * @todo Please document this function.
753
 * @see http://drupal.org/node/1354
754
 */
755
function cdm_taxonomictree_selector() {
756
  _add_js_treeselector();
757

    
758
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
759
  $out = drupal_render($form);
760
  return $out;
761
}
762

    
763
/**
764
 * @todo Please document this function.
765
 * @see http://drupal.org/node/1354
766
 */
767
function cdm_taxonomictree_selector_form($form, &$form_state) {
768

    
769
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
770
  $form['#action'] = $url;
771

    
772
  $form['var'] = array(
773
    '#weight' => -3,
774
    '#type' => 'hidden',
775
    '#value' => '[cdm][taxonomictree_uuid]',
776
  );
777

    
778
  $destination_array = drupal_get_destination();
779
  $destination = $destination_array['destination'];
780

    
781
  $form['destination'] = array(
782
    '#weight' => -3,
783
    '#type' => 'hidden',
784
    '#value' =>  $destination,
785
  );
786

    
787
  $form['val'] = array(
788
    '#type' => 'select',
789
    '#title' => t('Available classifications'),
790
    '#default_value' => get_taxonomictree_uuid_selected(),
791
    '#options' => cdm_get_taxontrees_as_options(),
792
  );
793

    
794
  return $form;
795

    
796
}
797

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

    
814
    // Themes in settings.php.
815
    'checkboxes_preferred' => array('render element' => 'element'),
816

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

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

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

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

    
979
    // Themes in cdm_dataportal.occurrence.theme.
980
    'cdm_specimen' => array('variables' => array('specimenTypeDesignation' => NULL)),
981
    'cdm_derivedUnitFacade' => array('variables' => array('derivedUnitFacade' => NULL)),
982

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

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

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

    
1027
    // Themes in cdm_dataportal.bibliography.theme.
1028
    'cdm_descriptionElementBibliography' => array('variables' => array('descriptionElementsBibliography' => array())),
1029
  );
1030
}
1031

    
1032
/* UNREACHABLE since action of form directly links to view.
1033
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1034

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

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

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

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

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

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

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

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

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

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

    
1168
/**
1169
 * Wrapps the given $html string into a reder array suitable for drupal_render()
1170
 *
1171
 * @param string $html
1172
 *   the html string, see
1173
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1174
 * @param number $weight
1175
 *   A positive or negative number (integer or decimal).
1176
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1177
 *
1178
 * @return
1179
 *   A render array
1180
 *
1181
 */
1182
function markup_to_render_array($html, $weight = 0) {
1183
  return array(
1184
          '#markup' => $html,
1185
          '#weight' => $weight,
1186
      );
1187
}
1188

    
1189
/**
1190
 * Loads the subgraph of a given PolytomousKeyNode.
1191
 *
1192
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1193
 * the CDM REST service.
1194
 *
1195
 * @param mixed $polytomousKeyNode
1196
 *   PolytomousKeyNode passed by reference.
1197
 *
1198
 * @return void
1199
 */
1200
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1201

    
1202
  if (!$polytomousKeyNode) {
1203
    return;
1204
  }
1205
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1206
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1207
    return;
1208
  }
1209
  if (!is_uuid($polytomousKeyNode->uuid)) {
1210
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1211
    return;
1212
  }
1213

    
1214
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1215

    
1216
  if (!$polytomousKeyNode) {
1217
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1218
    return;
1219
  }
1220

    
1221
  // Load children.
1222
  foreach ($polytomousKeyNode->children as &$childNode) {
1223
    _load_polytomousKeySubGraph($childNode);
1224
  }
1225

    
1226
  // Load subkey.
1227
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1228

    
1229
  // Load taxon.
1230
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1231
  _load_taxonBase($polytomousKeyNode->taxon);
1232
  return;
1233
}
1234

    
1235
/**
1236
 * @todo Please document this function.
1237
 * @see http://drupal.org/node/1354
1238
 */
1239
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1240
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1241

    
1242
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1243
  if (is_array($sourcePager->records)) {
1244
    $polytomousKey->sources = $sourcePager->records;
1245
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1246
  }
1247

    
1248
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1249
  if (is_array($annotationPager->records)) {
1250
    $polytomousKey->annotations = $annotationPager->records;
1251
  }
1252

    
1253
  _load_polytomousKeySubGraph($polytomousKey->root);
1254
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1255
}
1256

    
1257
/**
1258
 * Creates a taxon page view or a chapter of it.
1259
 *
1260
 * The taxon page gives detailed information on a taxon, it shows:
1261
 *  - Taxon name.
1262
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1263
 *    heterotypic and finally followed by misapplied names.
1264
 *    The list is ordered historically.
1265
 *  - All description associated with the taxon.
1266
 *
1267
 * @param string $uuid
1268
 * @param string $chapter
1269
 *   Name of the part to display, valid values are:
1270
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1271
 *
1272
 * @return unknown_type
1273
 */
1274
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1275
  // Display the page for the taxon defined by $uuid.
1276
  // set_last_taxon_page_tab(arg(3));
1277
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1278
  if (!empty($taxonpage)) {
1279
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1280
  }
1281
  else {
1282
    return '';
1283
  }
1284
}
1285

    
1286
/**
1287
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1288
 * which has two fields, one for the page title and one for the content. Later on in the
1289
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1290
 * function as the function parameters $title and $content.
1291
 *
1292
 * @param string $uuid
1293
 *   the uuid of the taxon to show
1294
 * @param string $chapter
1295
 *   Name of the part to display, valid values are:
1296
 *   'description', 'images', 'synonymy', 'all'.
1297
 *
1298
 * @return taxonpage object with the following fields:
1299
 *   - title : the title of the page
1300
 *   - content: the content of the page
1301
 *
1302
 */
1303
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1304
  // Taxon object.
1305
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1306
  if (empty($taxon)) {
1307
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1308
    return FALSE;
1309
  }
1310
  $taxonpage = new stdClass();
1311

    
1312
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1313
    'taxon' => $taxon,
1314
    'uuid' => $uuid,
1315
    'synonym_uuid' => $synonym_uuid,
1316
  ));
1317

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

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

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

    
1348
  return $taxonpage;
1349
}
1350

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

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

    
1374
/**
1375
 * Generates an object ready to be transformated to a node.
1376
 *
1377
 * This is a preparation in order to show it as a Drupal node.
1378
 *
1379
 * @param string $taxon_name_uuid
1380
 *
1381
 * @return mixed
1382
 *   The object with the page content and title.
1383
 */
1384
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1385
  // Getting the full taxonname object from the server.
1386
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1387
  if (!$taxon_name) {
1388
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1389
    return FALSE;
1390
  }
1391
  // Searching for all the taxa connected with the taxon name on the tree
1392
  // in use.
1393
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1394
  $request_params = array();
1395
  $request_params['query'] = $name_cache;
1396
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1397
  $request_params['doTaxa'] = 1;
1398
  $request_params['doSynonyms'] = 1;
1399
  $request_params['doTaxaByCommonNames'] = 0;
1400
  $request_params['matchMode'] = "EXACT";
1401
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1402

    
1403
  // Removing the name where we come from.
1404
  foreach ($taxon_pager->records as $k => &$taxon) {
1405
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1406
      unset($taxon_pager->records[$k]);
1407
    }
1408
  }
1409
  // Show the taxa list or go to the singular taxon.
1410
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1411
    reset($taxon_pager->records);
1412
    $singleTaxon = $taxon_pager->records[0];
1413
    if ($singleTaxon->class != "Taxon") {
1414
      // It is a Synonym -> look for the accepted.
1415
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1416
      if (!empty($synonym_uuid)) {
1417
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1418
      }
1419
      else {
1420
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1421
      }
1422
    }
1423
    else {
1424
      // It is an accepted taxon.
1425
      if (!empty($synonym_uuid)) {
1426
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1427
      }
1428
      else {
1429
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1430
      }
1431
    }
1432
  }
1433
  else {// More than one taxa case.
1434
    $taxon_name_page = new stdClass();
1435
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1436
    if ($taxon_pager->records) {
1437
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1438
    }
1439
    else {
1440
      $taxon_name_page->content = 'This name has no taxa';
1441
    }
1442
    return $taxon_name_page;
1443
  }
1444
}
1445

    
1446
/**
1447
 * @todo Please document this function.
1448
 * @see http://drupal.org/node/1354
1449
 */
1450
function cdm_dataportal_view_search_advanced() {
1451

    
1452
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1453
  $form = array();
1454
  $form_state = array();
1455
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1456

    
1457
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1458

    
1459
}
1460

    
1461
/**
1462
 * @todo Please document this function.
1463
 * @see http://drupal.org/node/1354
1464
 */
1465
function cdm_dataportal_view_search_taxon_by_description() {
1466
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1467
  // $form_state = false;
1468
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1469
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1470

    
1471
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1472
}
1473

    
1474
/**
1475
 * Executes the search and generates the result list of taxa.
1476
 */
1477
function cdm_dataportal_view_search_results_taxon() {
1478

    
1479
  $taxonPager = cdm_dataportal_search_execute();
1480

    
1481
  $showThumbnails = do_showThumbnails();
1482

    
1483
  $setSessionUri = url('cdm_api/setvalue/session', array(
1484
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1485
  ));
1486

    
1487
  drupal_add_js('jQuery(document).ready(function() {
1488

    
1489
      // init
1490
      if(' . $showThumbnails . ' == 1){
1491
      jQuery(\'.media_gallery\').show(20);
1492
  } else {
1493
      jQuery(\'.media_gallery\').hide(20);
1494
  }
1495
      // add change hander
1496
      jQuery(\'#showThumbnails\').change(
1497
      function(event){
1498
      var state = 0;
1499
      if(jQuery(this).is(\':checked\')){
1500
      jQuery(\'.media_gallery\').show(20);
1501
      state = 1;
1502
  } else {
1503
      jQuery(\'.media_gallery\').hide(20);
1504
  }
1505
      // store state in session variable
1506
      var uri = \'' . $setSessionUri . '\' + state;
1507
      jQuery.get(uri);
1508
  });
1509
  });',
1510
  array('type' => "inline", 'scope' => JS_DEFAULT));
1511

    
1512
  drupal_set_title(t('Search results'), PASS_THROUGH);
1513

    
1514
  return theme('cdm_search_results', array(
1515
    'pager' => $taxonPager,
1516
    'path' => 'cdm_dataportal/search/results/taxon',
1517
    'query_parameters' => $_REQUEST,
1518
    ));
1519
}
1520

    
1521
/**
1522
 * Returns the state of the the showThumbnails flag set in the
1523
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1524
 *
1525
 * @return Ambigous <boolean, number>
1526
 *    returns 1 if the flag is set
1527
 */
1528
function do_showThumbnails() {
1529
  static $showThumbnails = null;
1530

    
1531
  if($showThumbnails == null) {
1532
    $showThumbnails = FALSE;
1533
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1534
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1535
    }
1536
    if (!is_numeric($showThumbnails)) {
1537
      $showThumbnails = 1;
1538
    }
1539
  }
1540

    
1541
  return $showThumbnails;
1542
}
1543

    
1544
/**
1545
 * View which transforms XML output from a given webservice endpoint into JSON.
1546
 */
1547
/*
1548
 function cdm_view_xml2json(){
1549
 $file = arg(2);
1550
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1551
 return  xml2json::transformXmlStringToJson($datastr);
1552
 }
1553
 */
1554

    
1555
/* ====================== other functions ====================== */
1556
/**
1557
 * Creates a URL to the taxon page specified by the $uuid parameter.
1558
 *
1559
 * The URL will be prepended with a path element to a specific taxon page tab.
1560
 *
1561
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1562
 * be set globally in the administrative settings or individually in the user
1563
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1564
 * the last portal will stay on this last tab.
1565
 *
1566
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1567
 * internal mechanism by a specific value.
1568
 *
1569
 * @param string $uuid
1570
 *   The UUID of the taxon.
1571
 * @param string $page_tab
1572
 *   Overwriting the preset mechanism by defining specific value for the
1573
 *   taxon page tab.
1574
 *
1575
 * @return string
1576
 *   The created URL.
1577
 */
1578
function path_to_taxon($uuid, $page_tab = FALSE) {
1579

    
1580
  $tab = get_default_taxon_tab();
1581
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1582

    
1583
  if (!$uuid) {
1584
    return FALSE;
1585
  }
1586

    
1587
  if ($page_tab) {
1588
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1589
  }
1590
  elseif (!$tab || strtolower($tab) == 'general') {
1591
    return 'cdm_dataportal/taxon/' . $uuid;
1592
  }
1593
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1594
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1595
  }
1596
  else {
1597
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1598
  }
1599
}
1600

    
1601
/**
1602
 * @todo Please document this function.
1603
 * @see http://drupal.org/node/1354
1604
 */
1605
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1606
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1607
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1608
}
1609

    
1610
/**
1611
 * @todo Please document this function.
1612
 * @see http://drupal.org/node/1354
1613
 */
1614
function path_to_key($keyType, $keyUuid) {
1615
  if (!$keyUuid || !$keyType) {
1616
    return FALSE;
1617
  }
1618
  $keyType{0} = strtolower($keyType{0});
1619
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1620
}
1621

    
1622
/**
1623
 * @todo Please document this function.
1624
 * @see http://drupal.org/node/1354
1625
 */
1626
function path_to_reference($uuid) {
1627
  if (!$uuid) {
1628
    return FALSE;
1629
  }
1630
  return 'cdm_dataportal/reference/' . $uuid;
1631
}
1632

    
1633
/**
1634
 * @todo Please document this function.
1635
 * @see http://drupal.org/node/1354
1636
 */
1637
function path_to_name($name_uuid) {
1638
  $res = FALSE;
1639
  if ($name_uuid) {
1640
    $res = 'cdm_dataportal/name/' . $name_uuid;
1641
  }
1642
  return $res;
1643
}
1644

    
1645
/**
1646
 * @todo Please document this function.
1647
 * @see http://drupal.org/node/1354
1648
 */
1649
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1650
  if (!$uuid) {
1651
    return FALSE;
1652
  }
1653
  $out = 'cdm_dataportal/media/' . $uuid;
1654
  if ($representaion_uuid) {
1655
    $out .= '/' . $representaion_uuid;
1656
    if ($partId !== FALSE) {
1657
      $out .= '/' . $partId;
1658
    }
1659
  }
1660
  return $out;
1661
}
1662

    
1663
/**
1664
 * Compares thisRank with thatRank.
1665
 *
1666
 * Returns a negative integer, zero, or a positive integer
1667
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1668
 * e.g:
1669
 * <ul>
1670
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1671
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1672
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1673
 * </ul>
1674
 * <p>
1675
 * This compare logic of the underlying webservice is the
1676
 * <b>inverse logic</b> of the the one implemented in
1677
 * java.lang.Comparable#compareTo(java.lang.Object)
1678
 *
1679
 * @param $thisRankUuid
1680
 * @param $thatRankUuid
1681
 *
1682
 * @return int
1683
 *   A negative integer, zero, or a positive integer
1684
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1685
 */
1686
function rank_compare($thisRankUuid, $thatRankUuid) {
1687
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1688
  return $result->Integer;
1689
}
1690

    
1691
/**
1692
 * Composes an HTML element class attribute value composed of
1693
 * the shortname of the cdm class and the uuid of the entity.
1694
 * This class attribute should be used whereever an cdm-entity is rendered.
1695
 *
1696
 * These according class selectors in css must be escaped, eg:
1697
 *    .cdm\:TextData
1698
 *
1699
 * @param $cdmEntity
1700
 */
1701
function html_class_atttibute_ref($cdmEntity) {
1702

    
1703
  if (is_cdm_entity($cdmEntity)) {
1704
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1705
  }
1706
}
1707

    
1708
/**
1709
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1710
 *
1711
 * @param unknown_type $taggedTextList
1712
 */
1713
function normalize_TaggedName(&$taggedTextList) {
1714

    
1715
  if (is_array($taggedTextList)) {
1716

    
1717
    // First pass: rename.
1718
    for ($i = 0; $i < count($taggedTextList); $i++) {
1719

    
1720
      if ($taggedTextList[$i]->type == "hybridSign") {
1721
        $taggedTextList[$i]->type = "name";
1722
      }
1723
    }
1724

    
1725
    // Second pass: resolve separators.
1726
    $taggedNameListNew = array();
1727
    for ($i = 0; $i < count($taggedTextList); $i++) {
1728

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

    
1731
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1732
          $taggedName = $taggedTextList[$i];
1733
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1734
          $taggedNameListNew[] = $taggedName;
1735
          ++$i;
1736
          ++$i;
1737
        }
1738
      }
1739
      else {
1740
        $taggedNameListNew[] = $taggedTextList[$i];
1741
      }
1742
    }
1743
    $taggedTextList = $taggedNameListNew;
1744
  }
1745
}
1746

    
1747
/**
1748
 * Creates a short taxonname.
1749
 *
1750
 * The short name is created by using the taggename field of
1751
 * NameSTO or NameTO instances.
1752
 * If the taggename if empty the fullname will be returned.
1753
 *
1754
 * @param unknown_type $name
1755
 *   Name or TreeNode.
1756
 *
1757
 * @return string
1758
 */
1759
function cdm_dataportal_shortname_of($name) {
1760
  $nameStr = '';
1761

    
1762
  normalize_TaggedName($name->taggedTitle);
1763

    
1764
  // Get all tagged text tokens of the scientific name.
1765
  foreach ($name->taggedTitle as $tagtxt) {
1766
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1767
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1768
    }
1769
  }
1770
  $nameStr = trim($nameStr);
1771

    
1772
  if ($nameStr) {
1773

    
1774
    // Do not return short names for these.
1775
    if ($name->unplaced || $name->excluded) {
1776
      return $nameStr;
1777
    }
1778

    
1779
    /*
1780
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1781
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1782
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1783
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1784
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1785
    */
1786
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1787
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1788
      return $matches[1][0] . "." . $matches[3][0];
1789
    }
1790
    else {
1791
      return $nameStr;
1792
    }
1793
  }
1794
  else {
1795
    return $name->titleCache;
1796
  }
1797
}
1798

    
1799
/**
1800
 * Check if a taxon is accepted by the current taxonomic tree.
1801
 *
1802
 * @param mixed $taxon
1803
 *   The Taxon obkect to check.
1804
 *
1805
 * @return bool
1806
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1807
 */
1808
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1809

    
1810
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1811

    
1812
  if (isset($taxon->taxonNodes)) {
1813
    $taxonNodes = $taxon->taxonNodes;
1814
  }
1815
  else {
1816
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1817
  }
1818

    
1819
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1820
    foreach ($taxonNodes as $node) {
1821
      if (is_object($node->classification)) {
1822
        if ($node->classification->uuid == $defaultTreeUuid) {
1823
          return TRUE;
1824
        }
1825
      }
1826
      else {
1827
        if ($node->classification == $defaultTreeUuid) {
1828
          return TRUE;
1829
        }
1830
      }
1831
    }
1832
  }
1833

    
1834
  return FALSE;
1835
}
1836

    
1837
/**
1838
 * Workaround for missing original source type.
1839
 *
1840
 * idNamespace is always set in these cases.
1841
 * @todo improve documentation of this function.
1842
 *
1843
 * @param unknown_type $source
1844
 *
1845
 * @return unknown_type
1846
 */
1847
function _is_original_source_type($source) {
1848
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1849
}
1850

    
1851
/**
1852
 * @todo Please document this function.
1853
 * @see http://drupal.org/node/1354
1854
 */
1855
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1856
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1857
}
1858

    
1859
/**
1860
 * Gets the metadata info such as title or artist of a media file.
1861
 *
1862
 * The function tries at first to get all the info from the file metadata
1863
 * and if it is not avaible look at the media file info stored at the database.
1864
 *
1865
 * @param mixed $media
1866
 *   The media file object for which to get the metadata.
1867
 *
1868
 * @return array
1869
 *   The array with the available specified metadata info.
1870
 * TODO rename to read_media_metadata() and move to *.module.
1871
 */
1872
function cdm_read_media_metadata($media) {
1873

    
1874
  $metadata_caption = array(
1875
    'title' => '',// Media_metadata and media.
1876
    'artist' => '',// Media_metadata and media.
1877
    'rights',// Media_metadata and media.
1878
    'location',// Media_metadata.
1879
    'filename' => '',// Media.
1880
    'mediacreated' => '',// Media.
1881
    'description' => '',
1882
  );// Media.
1883

    
1884
  // Getting the media metadata.
1885
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1886
  $media_metadata_aux = (array) $media_metadata;
1887

    
1888
  // Filename.
1889
  if (isset($media->representations[0]->parts[0]->uri)) {
1890
    $fileUri = $media->representations[0]->parts[0]->uri;
1891
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1892
    $metadata_caption['filename'] = $filename;
1893
  }
1894
  else {
1895
    $metadata_caption['filename'] = '';
1896
  }
1897

    
1898
  // Title.
1899
  if (!empty($media_metadata->ObjectName)) {
1900
    $metadata_caption['title'] = $media_metadata->ObjectName;
1901
  }
1902
  elseif ($media_metadata_aux['Object Name']) {
1903
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1904
  }
1905
  elseif ($media->title_L10n) {
1906
    $metadata_caption['title'] = $media->title_L10n;
1907
  }
1908
  elseif ($media->titleCache) {
1909
    $metadata_caption['title'] = $media->titleCache;
1910
  }
1911

    
1912
  // Append description to title.
1913
  if (!empty($media->description_L10n)) {
1914
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1915
  }
1916

    
1917
  // Artist.
1918
  if ($media_metadata->Artist) {
1919
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1920
  }
1921
  elseif ($media->artist->titleCache) {
1922
    $metadata_caption['artist'] = $media->artist->titleCache;
1923
  }
1924

    
1925
  // Copyright.
1926
  $metadata_caption['rights'] = array(
1927
    'copyright' => array('agentNames' => array()),
1928
    'license' => array(
1929
      'agentNames' => array(),
1930
      'types' => array(),
1931
      'abbreviatedTexts' => array(),
1932
      'uris' => array(),
1933
    ),
1934
  );
1935
  if ($media_metadata->Copyright) {
1936
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1937
  }
1938
  elseif (isset($media->rights) && is_array($media->rights)) {
1939
    foreach ($media->rights as $right) {
1940
      switch ($right->term->uuid) {
1941
        case UUID_RIGHTS_LICENCE:
1942
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1943
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1944
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1945
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1946
          break;
1947
        case UUID_RIGHTS_COPYRIGHT:
1948
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1949
          break;
1950
      }
1951
    }
1952
  }
1953
  else {
1954
    $metadata_caption['rights']['agentNames'][] = '';
1955
  }
1956

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

    
1960
  // Location.
1961
  $metadata_caption['location'] = array();
1962
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1963
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1964
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1965
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1966

    
1967
  /*
1968
   // Creation date.
1969
   if($media_metadata["Modify Date"])
1970
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1971
   else
1972
   $metadata_caption['mediacreated'] = $media->created;
1973
   */
1974

    
1975
  // Returned value.
1976
  return $metadata_caption;
1977
}
1978

    
1979
/**
1980
 * Collects all the media from a list of description elements.
1981
 *
1982
 * @param array $descriptionElements
1983
 *   The description elements from which to collect the media.
1984
 *
1985
 * @return array
1986
 *   The output with all the collected media.
1987
 */
1988
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1989

    
1990
  $outArrayOfMedia = array();
1991

    
1992
  // Avoiding a warning box in Drupal for Flora Malesiana.
1993
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1994
    foreach ($descriptionElements as $descriptionElement) {
1995
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1996
        foreach ($descriptionElement->media as $media) {
1997
          if (is_object($media)) {
1998
            $outArrayOfMedia[] = $media;
1999
          }
2000
        }
2001
      }
2002
    }
2003
  }
2004
  return $outArrayOfMedia;
2005
}
2006

    
2007
/**
2008
 * @todo Please document this function.
2009
 * @see http://drupal.org/node/1354
2010
 *
2011
 * @param array $cdmBase_list
2012
 *   An array of CdmBase instances or a single instance.
2013
 * @param string $footnote_list_key
2014
 *
2015
 * @return unknown
2016
 */
2017
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
2018
  // Comment @WA: undefined variable.
2019
  /*
2020
   static $annotations_types_filter;
2021
   if(!$annotations_types_filter) {
2022
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2023
   }
2024
   */
2025
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2026

    
2027
  $footNoteKeys = array();
2028

    
2029
  // Is argument cdmBase an array?
2030
  if (!is_array($cdmBase_list)) {
2031
    $cdmBase_array = array();
2032
    $cdmBase_array[] = $cdmBase_list;
2033
  }
2034
  else {
2035
    $cdmBase_array = $cdmBase_list;
2036
  }
2037

    
2038
  // Getting the key for the footnotemanager.
2039
  if (isset($footnote_list_key)) {
2040
    $footnoteListKey = $footnote_list_key;
2041
  }
2042
  else {
2043
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2044
  }
2045

    
2046
  // Adding the footnotes keys.
2047
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2048
  foreach ($cdmBase_array as $cdmBase_element) {
2049
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2050
    if (is_array($annotations)) {
2051
      foreach ($annotations as $annotation) {
2052
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2053
      }
2054
    }
2055
  }
2056

    
2057
  return $footNoteKeys;
2058
}
2059

    
2060
// @WA Comment: should this not be a theme function?
2061
/**
2062
 *  Creates a CDM Dynabox.
2063
 *
2064
 * @param string $label
2065
 *   The clickable text to show.
2066
 * @param string $content_url
2067
 *   The cdm REST service request url wich will deliver the content to be shown
2068
 *   once the dynabox toggles open.
2069
 * @param string $theme
2070
 *   The theme to be used for rendering the cdm REST service reponse with is
2071
 *   returned from the $content_url.
2072
 * @param string $link_alt_text
2073
 *   The value for the alt attribute of the dynabox link.
2074
 * @param array $enclosingtags
2075
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2076
 *   element itself, $enclosingtags[1] is the tag to be used for the
2077
 *   dynabox_content.
2078
 *
2079
 * @return string
2080
 *   Returns HTML for a dynabox.
2081
 */
2082
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')) {
2083
  $out = '';
2084
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2085

    
2086
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2087
  $out .= '<!-- ' . $content_url . ' -->';
2088
  $out .= '<' . $enclosingtags[0] . ' class="dynabox"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2089
  $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] . '>';
2090
  $out .= '</' . $enclosingtags[0] . '>';
2091
  return $out;
2092
}
2093

    
2094
/**
2095
 * Checks whether a feature has any description elements.
2096
 *
2097
 * @param mixed $featureNode
2098
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2099
 *
2100
 * @see _mergeFeatureTreeDescriptions()
2101
 *
2102
 * @return bool
2103
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2104
 *   contains at least one non empty TextData or at least one DescriptionElement
2105
 *   of an other type. A TextData element holding a multilanguageText or a
2106
 *   source reference is considered to be not empty.
2107
 */
2108
function hasFeatureNodeDescriptionElements($featureNode) {
2109

    
2110
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2111
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2112
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0])) {
2113
        return TRUE;
2114
      }
2115
    }
2116
  }
2117
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2118
    foreach ($featureNode->children as $child) {
2119
      if (hasFeatureNodeDescriptionElements($child)) {
2120
        return TRUE;
2121
      }
2122
    }
2123
  }
2124
  return FALSE;
2125
}
(6-6/14)