Project

General

Profile

Download (62.4 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
module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
28
module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
29

    
30
module_load_include('inc', 'cdm_dataportal', 'theme/theme_registry');
31
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.common');
32
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.descriptions');
33
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.media');
34
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.occurrence');
35
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.page');
36
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.taxon');
37
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.name');
38
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.references');
39
module_load_include('theme', 'cdm_dataportal', 'theme/cdm_dataportal.bibliography');
40

    
41
module_load_include('php', 'cdm_dataportal', 'classes/footnotemanager');
42
module_load_include('php', 'cdm_dataportal', 'classes/footnote');
43
module_load_include('php', 'cdm_dataportal', 'classes/footnotekey');
44
module_load_include('php', 'cdm_dataportal', 'classes/renderhints');
45

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

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

    
67
/**
68
 * @param unknown_type $link_element_selector
69
 * @param unknown_type $progress_element_selector
70
 */
71
function _add_js_cdm_ws_progressbar($link_element_selector, $progress_element_selector){
72

    
73
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
74

    
75
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
76

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

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

    
97
      });
98
    ",
99
    array(
100
      'type' => 'inline',
101
      'scope' => 'footer'
102
    )
103
  );
104
}
105

    
106
function _add_js_openlayers() {
107
  $openlayers = '/js/OpenLayers-2.11/OpenLayers.js';
108

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

    
116
/**
117
 * @todo Please document this function.
118
 * @see http://drupal.org/node/1354
119
 */
120
function _add_js_openlayers_map() {
121

    
122
  _add_js_openlayers();
123

    
124
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
125

    
126
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
127

    
128
  $baseLayers = variable_get('baselayers', array());
129
  if (!is_array($baseLayers) || count($baseLayers) == 0) {
130
    $baseLayers = array(
131
      'metacarta_vmap0' => 'Metacarta Vmap0',
132
      'PREFERRED' => 'metacarta_vmap0',
133
    );
134
  }
135
  $layerNames = '';
136
  foreach ($baseLayers as $layerName => $layerLabel) {
137
    if ($layerName == 'PREFERRED') {
138
      $preferredLayer = $baseLayers['PREFERRED'];
139
    }
140
    else {
141
      $layerNames .= ($layerNames ? ', ' : '') . "'$layerName'";
142
    }
143
  }
144

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

    
150
  // window.onload - is executed when the document and images etc is fully loaded
151
  // Query(document).ready - is executed much earlier, when the DOM is loaded
152
  drupal_add_js("
153
          jQuery(document).ready(function() {
154

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

    
173
}
174

    
175
/**
176
 * @todo Enter description here ...
177
 *
178
 * @param unknown_type $width
179
 * @param unknown_type $bounding_box
180
 * @param unknown_type $occurrenceQuery
181
 * @param unknown_type $distributionQuery
182
 * @param unknown_type $legendFormatQuery
183
 * @param unknown_type $map_caption
184
 *
185
 * @return unknown
186
 */
187
function get_image_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
188

    
189
  $server = getEDITMapServiceURI();
190

    
191
  if (!$server) {
192
    // Warning message.
193
    drupal_set_message(t(
194
      "No 'Geoservice Access Point' has been set so far.
195
      Please configure the variable 'Geoservice Access Point' here !url", array(
196
        '!url' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/geo'),
197
      )), 'warning');
198

    
199
    // Message to render.
200
    return '<p>' . t('No geoservice specified') . '</p>';
201
  }
202

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

    
206
  $query_string = '&image=true&recalculate=false&legend=1&ms=' . $width
207
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
208
    . ($labels_on ? '&label=' . $labels_on : '');
209

    
210
  if ($map_caption) {
211
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
212
  }
213

    
214
  if (getEDITMapServiceVersionNumber() >= 1.1) {
215

    
216
    // Either occurrence or distribution - combined maps will be possible
217
    // in the future.
218
    if ($occurrenceQuery) {
219
      // @todo Fix $occurrenceQuery.
220
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
221
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
222
      // Will be replaced below.. HACK!!!
223
      $occurrenceQuery .= '&l=tdwg4&as=';
224

    
225
      $query_string .= "&" . $occurrenceQuery;
226
    }
227
    elseif ($distributionQuery) {
228
      $query_string .= "&" . $distributionQuery;
229
    }
230

    
231
    // Apply Plain Image map settings special for version >= 1.1.
232
    /*
233
    example : title=a:Naturalized++non-invasive
234
    &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
235
    &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
236
    &mc_s=Georgia,15,blue&mc=&recalculate=false
237

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

    
245
    $map_service_script_name = "rest_gen.php";
246

    
247
    $bgcolor_areaStyleId = "y";
248
    $baselayer_areaStyleId = "z";
249
    $bgcolor_layer = '';
250
    $additional_area_styles = array();
251

    
252
    // Background color:
253
    if (variable_get('map_bg_color', '')) {
254
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
255
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
256
    }
257

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

    
279
    if ($bgcolor_layer) {
280
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
281
    }
282

    
283
    if (variable_get('map_base_layer_style', '')) {
284
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
285
    }
286

    
287
    foreach ($additional_area_styles as $as) {
288
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
289
    }
290

    
291
  }
292
  else {
293
    // Pre 1.1. version of map service.
294
    if ($occurrenceQuery) {
295

    
296
      $map_service_script_name = "point.php";
297

    
298
      // Fix $occurrenceQuery.
299
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
300
      // $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
301
      $occurrenceQuery .= '&l=v:e_w_0';
302
      $query_string .= "&" . $occurrenceQuery;
303
    }
304
    elseif ($distributionQuery) {
305
      $query_string .= "&" . $distributionQuery;
306
      $map_service_script_name = "areas.php";
307
    }
308
  }
309

    
310
  $mapUri = url("$server/$map_service_script_name?$query_string");
311
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
312
  // Showing map caption.
313
  if ($map_caption) {
314
    // FIXME: replace <br> by according css style.
315
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
316
    $out .= '</div>';
317
  }
318

    
319
  return $out;
320
}
321

    
322
/**
323
 * @todo Enter description here ...
324
 *
325
 * @param unknown_type $width
326
 * @param unknown_type $bounding_box
327
 * @param unknown_type $occurrenceQuery
328
 * @param unknown_type $distributionQuery
329
 * @param unknown_type $legendFormatQuery
330
 * @param unknown_type $map_caption
331
 *
332
 * @return unknown
333
 */
334
function get_openlayers_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
335

    
336
  _add_js_openlayers_map();
337

    
338
  $out = '<div id="openlayers">';
339
  $out .= '<div id="openlayers_map" class="smallmap"';
340
  if($width) {
341
    $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
342
  }
343

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

    
347
  $openlayers_map_query_string = '&img=false&ms=' . $width
348
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
349
    . ($labels_on ? '&label=' . $labels_on : '');
350

    
351
  if ($occurrenceQuery) {
352
    // @todo Fix $occurrenceQuery.
353
//     $occurrenceQuery .= '&bbox=-180,-90,180,90';
354
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
355
    // $occurrenceQuery .= '&l=v:e_w_0';
356
    // TODO add to cdm service?
357
    $occurrenceQuery .= '&legend=0';
358

    
359
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
360
  }
361

    
362
  if ($distributionQuery) {
363
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
364
  }
365

    
366
  if ($legendFormatQuery) {
367
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
368
  }
369

    
370
  $out .= '></div></div>';
371

    
372
  // Showing map caption.
373
  if ($map_caption) {
374
    // FIXME: replace <br> by according css style.
375
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />';
376
    $out .= '</div>';
377
  }
378
  return $out;
379
}
380

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

    
405
/**
406
 * Implements hook_menu().
407
 */
408
function cdm_dataportal_menu() {
409
  $items = array();
410

    
411
  // @see settings.php.
412
  cdm_dataportal_menu_admin($items);
413
  cdm_dataportal_menu_help($items);
414

    
415
  $items['cdm_dataportal/names'] = array(
416
    'page callback' => 'cdm_dataportal_view_names',
417
    'access arguments' => array('access content'),
418
    'type' => MENU_CALLBACK,
419
  );
420

    
421
  // Optional callback arguments: page.
422
  $items['cdm_dataportal/taxon'] = array(
423
    'page callback' => 'cdm_dataportal_taxon_page_view',
424
    'access arguments' => array('access content'),
425
    'type' => MENU_CALLBACK,
426
    // Expected callback arguments: uuid.
427
  );
428

    
429
  $items['cdm_dataportal/name'] = array(
430
    'page callback' => 'cdm_dataportal_name_page_view',
431
      /*
432
    'page arguments' => array(
433
       'taxon_name_uuid',
434
       'taxon_to_hide_uuid',
435
       'synonym_uuid' => NULL
436
      ),
437
      */
438
    'access arguments' => array('access content'),
439
    'type' => MENU_CALLBACK,
440
    // Expected callback arguments: uuid.
441
  );
442

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

    
450
  $items['cdm_dataportal/reference/list'] = array(
451
    'page callback' => 'cdm_dataportal_view_reference_list',
452
    'access arguments' => array('access content'),
453
    'type' => MENU_CALLBACK,
454
    // Expected callback arguments: uuid.
455
  );
456

    
457
  $items['cdm_dataportal/media'] = array(
458
    'page callback' => 'cdm_dataportal_view_media',
459
    'access arguments' => array('access content'),
460
    'type' => MENU_CALLBACK,
461
    // Expected callback arguments:
462
    // uuid, mediarepresentation_uuid, part_uuid or part#.
463
  );
464

    
465
  $items['cdm_dataportal/polytomousKey'] = array(
466
    'page callback' => 'cdm_dataportal_view_polytomousKey',
467
    'access arguments' => array('access content'),
468
    'type' => MENU_CALLBACK,
469
    // Expected callback arguments: polytomousKey->uuid.
470
  );
471

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

    
478
  $items['cdm_dataportal/search/advanced'] = array(
479
    'title' => 'Advanced',
480
    'page callback' => 'cdm_dataportal_view_search_advanced',
481
    'access arguments' => array('access content'),
482
    'type' => MENU_DEFAULT_LOCAL_TASK,
483
  );
484

    
485
  $items['cdm_dataportal/search/taxon_by_description'] = array(
486
    'title' => 'By description full text',
487
    'page callback' => 'cdm_dataportal_view_search_taxon_by_description',
488
    'access arguments' => array('access content'),
489
    'type' => MENU_LOCAL_TASK,
490
  );
491

    
492
  $items['cdm_dataportal/search/results/taxon'] = array(
493
    'page callback' => 'cdm_dataportal_view_search_results_taxon',
494
    'access arguments' => array('access content'),
495
    'type' => MENU_CALLBACK,
496
  );
497
  /*
498
   $items['cdm/xml2json'] = array(
499
   'page callback' => 'cdm_view_xml2json',
500
   'access arguments' => array('access content'),
501
   'type' => MENU_CALLBACK,
502
   );
503
   */
504

    
505
  // if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
506
  // User configuration of cdm_dataportal.
507
  $items['user/%/cdm_dataportal'] = array(
508
    'title' => 'cdm_dataportal',
509
    'access arguments' => array('access content'),
510
    'page callback' => 'drupal_get_form',
511
    'page arguments' => array('cdm_dataportal_user_form'),
512
    'type' => MENU_LOCAL_TASK,
513
    'weight' => 10,
514
  );
515
  // }
516

    
517
  // 'May not cache' in D5.
518
  // --- Local tasks for Taxon.
519
  $items['cdm_dataportal/name/%'] = array(
520
    // 'page callback' => 'cdm_dataportal_view_name',
521
    'page callback' => 'cdm_dataportal_name_page_view',
522
    'page arguments' => array(2, 3, 4),
523
    'access arguments' => array('access content'),
524
    'type' => MENU_CALLBACK,
525
  );
526

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

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

    
548
    $items['cdm_dataportal/taxon/%/description'] = array(
549
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
550
      'page callback' => 'cdm_dataportal_taxon_page_view',
551
      'access arguments' => array('access content'),
552
      'type' => MENU_DEFAULT_LOCAL_TASK,
553
      'weight' => 2,
554
      'page arguments' => array(2, "description")
555
      , // Expected callback arguments: name_uuid.
556
    );
557

    
558
    $items['cdm_dataportal/taxon/%/synonymy'] = array(
559
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Synonymy')),
560
      'page callback' => 'cdm_dataportal_taxon_page_view',
561
      'access arguments' => array('access content'),
562
      'type' => MENU_LOCAL_TASK,
563
      'weight' => 4,
564
      'page arguments' => array(2, "synonymy", 4)
565
      , // Expected callback arguments: name_uuid.
566
    );
567
    $items['cdm_dataportal/taxon/%/images'] = array(
568
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Images')),
569
      'page callback' => 'cdm_dataportal_taxon_page_view',
570
      'access arguments' => array('access content'),
571
      'type' => MENU_LOCAL_TASK,
572
      'weight' => 5,
573
      'page arguments' => array(2, "images")
574
      , // Expected callback arguments: name_uuid.
575
    );
576

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

    
587
    $items['cdm_dataportal/taxon/%/keys'] = array(
588
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
589
      'page callback' => 'cdm_dataportal_taxon_page_view',
590
      'access arguments' => array('access content'),
591
      'type' => MENU_LOCAL_TASK,
592
      'weight' => 6,
593
      'page arguments' => array(2, "keys")
594
      , // Expected callback arguments: name_uuid.
595
    );
596
  }
597

    
598
  return $items;
599
}
600

    
601
/**
602
 * @todo Please document this function.
603
 * @see http://drupal.org/node/1354
604
 */
605
function cdm_dataportal_init() {
606
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal.css');
607
  // drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
608
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_screen.css', array('type' => 'screen'));
609
}
610

    
611
/**
612
 * The function generate form for own user cdm dataportal configurations.
613
 */
614
function cdm_dataportal_user_form($form, &$form_state) {
615
  global $user;
616
  $checkbox_value = 'cdm_dataportal_' . $user->uid . '_default_tab_active';
617

    
618
  $form['check'] = array(
619
    '#type' => 'checkbox',
620
    '#title' => t('Activate user default configuration'),
621
    '#default_value' => variable_get($checkbox_value, 0),
622
    '#description' => t('Check this if you want configure your own default tab from the below menu.'),
623
  );
624

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

    
635
  $form['submit'] = array(
636
    '#type' => 'submit',
637
    '#value' => t('Submit'),
638
  );
639

    
640
  return $form;
641
}
642

    
643
/**
644
 * Form submission handler for user_form().
645
 *
646
 * Submits the user cdm dataportal configurations.
647
 */
648
function cdm_dataportal_user_form_submit($form, &$form_state) {
649
  global $user;
650
  $msg_type = 'status';
651
  $username = $user->name;
652
  $variable_to_use = 'cdm_dataportal_' . $user->uid . '_default_tab';
653

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

    
678
/**
679
 * Implements hook_block_info().
680
 */
681
function cdm_dataportal_block_info() {
682

    
683
    // $block[0]["info"] = t("CDM DataPortal DevLinks");
684
    // $block[1]["info"] = t("CDM DataPortal Credits");
685
    $block["2"]["info"] = t("CDM Search Taxa");
686
    // $block[3]["info"] = t("CDM Filters");
687
    $block["4"]["info"] = t("CDM Dataportal Print");
688
    $block["keys"]["info"] = t("CDM identification keys");
689
    $block["uses"]["info"] = t("CDM Uses");
690
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
691

    
692
    return $block;
693
}
694

    
695
/**
696
 * Implements hook_block_view().
697
 */
698
function cdm_dataportal_block_view($delta) {
699
  // TODO Rename block deltas (e.g. '2') to readable strings.
700
  switch ($delta) {
701
    // case 'delta-1':
702
    // $block['subject'] = t('Credits');
703
    // $block['content'] = theme('cdm_credits');
704
    // return $block;
705
    case '2':
706
      $block['subject'] = t('Search taxa');
707
      $form = drupal_get_form('cdm_dataportal_search_taxon_form');
708
      $block['content'] = drupal_render($form);
709

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

    
741
/*
742
 function cdm_dataportal_session_clear($cdm_ws_uri_update = FALSE){
743
 $_SESSION['cdm'] = NULL;
744
 if(is_string($cdm_ws_uri_update)){
745
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
746
 }
747
 }
748

    
749
 function cdm_dataportal_session_validate(){
750
 if(!isset($_SESSION['cdm']['ws_uri'])){
751
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', FALSE));
752
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', FALSE)){
753
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', FALSE));
754
 }
755
 }
756
 */
757

    
758
/**
759
 * @todo Please document this function.
760
 * @see http://drupal.org/node/1354
761
 */
762
function cdm_taxonomictree_selector() {
763
  _add_js_treeselector();
764

    
765
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
766
  $out = drupal_render($form);
767
  return $out;
768
}
769

    
770
/**
771
 * @todo Please document this function.
772
 * @see http://drupal.org/node/1354
773
 */
774
function cdm_taxonomictree_selector_form($form, &$form_state) {
775

    
776
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
777
  $form['#action'] = $url;
778

    
779
  $form['var'] = array(
780
    '#weight' => -3,
781
    '#type' => 'hidden',
782
    '#value' => '[cdm][taxonomictree_uuid]',
783
  );
784

    
785
  $destination_array = drupal_get_destination();
786
  $destination = $destination_array['destination'];
787

    
788
  $form['destination'] = array(
789
    '#weight' => -3,
790
    '#type' => 'hidden',
791
    '#value' =>  $destination,
792
  );
793

    
794
  $form['val'] = array(
795
    '#type' => 'select',
796
    '#title' => t('Available classifications'),
797
    '#default_value' => get_taxonomictree_uuid_selected(),
798
    '#options' => cdm_get_taxontrees_as_options(),
799
  );
800

    
801
  return $form;
802

    
803
}
804

    
805
/* UNREACHABLE since action of form directly links to view.
806
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
807

    
808
 $_SESSION['cdm']['search'] = $form_values;
809
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
810
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
811
 //$paramstr = compose_url_prameterstr($form_values);
812
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
813
 }
814
 */
815
/* ====================== menu callback functions ====================== */
816
/**
817
 * @todo Please document this function.
818
 * @see http://drupal.org/node/1354
819
 */
820
/*
821
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
822
  static $comment_node_disabled =  0;
823
  static $comment_node_read_only =  1;
824
  static $comment_node_read_write =  2;
825

    
826
  if ($form_id == 'node_type_form'
827
   && isset($form['identity']['type'])
828
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
829
  ) {
830
    $form['workflow']['comment'] = array(
831
      '#type' => 'radios',
832
      '#title' => t('Default comment setting'),
833
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
834
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
835
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
836
    );
837
  }
838
}
839
*/
840

    
841
/**
842
 * Displays a list of the known taxonomic names.
843
 *
844
 * When the list of taxonomic names is displayed, long lists are split up into
845
 * multiple pages.
846
 *
847
 * TODO: Parameters are still preliminary.
848
 *
849
 * @param string $beginsWith
850
 * @param string $page
851
 *   Page number to diplay defaults to page 1.
852
 * @param bool $onlyAccepted
853
 */
854
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
855

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

    
858
  /*
859
  // FIXME the filter for accepted names will be a form element, thus this
860
  // widget should be generated via form api preferably as block.
861
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
862
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
863
  $out .= theme('cdm_listof_taxa', $taxonPager);
864
  return $out;
865
  */
866
}
867

    
868
/**
869
 * @todo Please document this function.
870
 * @see http://drupal.org/node/1354
871
 */
872
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
873
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
874
  return theme('cdm_reference_page', array('reference' => $reference));
875
}
876

    
877
/**
878
 * @todo Please document this function.
879
 * @see http://drupal.org/node/1354
880
 */
881
function cdm_dataportal_view_reference_list($pageNumber) {
882
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
883
  return theme('cdm_reference_pager', array(
884
    'referencePager' => $referencePager,
885
    'path' => 'cdm_dataportal/reference/list/',
886
    ));
887
}
888

    
889
/**
890
 * @todo Please document this function.
891
 * @see http://drupal.org/node/1354
892
 */
893
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
894
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
895
  return theme('cdm_media_page', array(
896
    'media' => $media,
897
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
898
    'partId' => $part,
899
    ));
900
}
901

    
902
/**
903
 * @todo Please document this function.
904
 * @see http://drupal.org/node/1354
905
 */
906
function _load_taxonBase(&$taxonBase) {
907
  if (isset($taxonBase->uuid)) {
908
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
909
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
910
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
911
  }
912
}
913

    
914
/**
915
 * Gets a Drupal variable, string or array and returns it.
916
 *
917
 * Similar to the variable_get() function of Drupal, except that this function
918
 * is able to handle arrays correctly. This function is especially useful
919
 * when dealing with collections of setting form elements (#tree = TRUE).
920
 *
921
 * @param string $variableKey
922
 *   The Unique key of the Drupal variable in the Drupal variables table.
923
 * @param string $defaultValueString
924
 *   A string as for example derived from a CONSTANT.
925
 *
926
 * @return mixed
927
 *   Returns usally an array, depending on the nature of the variable.
928
 */
929
function mixed_variable_get($variableKey, $defaultValueString) {
930
  $systemDefaults = unserialize($defaultValueString);
931
  $storedSettings = variable_get($variableKey, array());
932
  if (is_array($storedSettings)) {
933
    $settings = array_merge($systemDefaults, $storedSettings);
934
  }
935
  else {
936
    $settings = $systemDefaults;
937
  }
938
  return $settings;
939
}
940

    
941
/**
942
 * Wrapps the given $html string into a reder array suitable for drupal_render()
943
 *
944
 * @param string $html
945
 *   the html string, see
946
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
947
 * @param number $weight
948
 *   A positive or negative number (integer or decimal).
949
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
950
 *
951
 * @return
952
 *   A render array
953
 *
954
 */
955
function markup_to_render_array($html, $weight = 0) {
956
  return array(
957
          '#markup' => $html,
958
          '#weight' => $weight,
959
      );
960
}
961

    
962
/**
963
 * Loads the subgraph of a given PolytomousKeyNode.
964
 *
965
 * Loads the subgraph of the given PolytomousKeyNode recursively from
966
 * the CDM REST service.
967
 *
968
 * @param mixed $polytomousKeyNode
969
 *   PolytomousKeyNode passed by reference.
970
 *
971
 * @return void
972
 */
973
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
974

    
975
  if (!$polytomousKeyNode) {
976
    return;
977
  }
978
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
979
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
980
    return;
981
  }
982
  if (!is_uuid($polytomousKeyNode->uuid)) {
983
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
984
    return;
985
  }
986

    
987
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
988

    
989
  if (!$polytomousKeyNode) {
990
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
991
    return;
992
  }
993

    
994
  // Load children.
995
  foreach ($polytomousKeyNode->children as &$childNode) {
996
    _load_polytomousKeySubGraph($childNode);
997
  }
998

    
999
  // Load subkey.
1000
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1001

    
1002
  // Load taxon.
1003
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1004
  _load_taxonBase($polytomousKeyNode->taxon);
1005
  return;
1006
}
1007

    
1008
/**
1009
 * @todo Please document this function.
1010
 * @see http://drupal.org/node/1354
1011
 */
1012
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1013
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1014

    
1015
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1016
  if (is_array($sourcePager->records)) {
1017
    $polytomousKey->sources = $sourcePager->records;
1018
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1019
  }
1020

    
1021
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1022
  if (is_array($annotationPager->records)) {
1023
    $polytomousKey->annotations = $annotationPager->records;
1024
  }
1025

    
1026
  _load_polytomousKeySubGraph($polytomousKey->root);
1027
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1028
}
1029

    
1030
/**
1031
 * Creates a taxon page view or a chapter of it.
1032
 *
1033
 * The taxon page gives detailed information on a taxon, it shows:
1034
 *  - Taxon name.
1035
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1036
 *    heterotypic and finally followed by misapplied names.
1037
 *    The list is ordered historically.
1038
 *  - All description associated with the taxon.
1039
 *
1040
 * @param string $uuid
1041
 * @param string $chapter
1042
 *   Name of the part to display, valid values are:
1043
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1044
 *
1045
 * @return unknown_type
1046
 */
1047
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1048
  // Display the page for the taxon defined by $uuid.
1049
  // set_last_taxon_page_tab(arg(3));
1050
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1051
  if (!empty($taxonpage)) {
1052
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1053
  }
1054
  else {
1055
    return '';
1056
  }
1057
}
1058

    
1059
/**
1060
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1061
 * which has two fields, one for the page title and one for the content. Later on in the
1062
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1063
 * function as the function parameters $title and $content.
1064
 *
1065
 * @param string $uuid
1066
 *   the uuid of the taxon to show
1067
 * @param string $chapter
1068
 *   Name of the part to display, valid values are:
1069
 *   'description', 'images', 'synonymy', 'all'.
1070
 *
1071
 * @return taxonpage object with the following fields:
1072
 *   - title : the title of the page
1073
 *   - content: the content of the page
1074
 *
1075
 */
1076
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1077
  // Taxon object.
1078
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1079
  if (empty($taxon)) {
1080
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1081
    return FALSE;
1082
  }
1083
  $taxonpage = new stdClass();
1084

    
1085
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1086
    'taxon' => $taxon,
1087
    'uuid' => $uuid,
1088
    'synonym_uuid' => $synonym_uuid,
1089
  ));
1090

    
1091
  // Check if the taxon id contained in the currently selected tree.
1092
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1093
  $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1094
  if (!$taxon_in_current_tree) {
1095
    if (count($taxon_nodes) == 0) {
1096
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1097
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1098
      ))), 'warning');
1099
    }
1100
    else {
1101
      $trees = '';
1102
      foreach ($taxon_nodes as $node) {
1103
        if (isset($node->classification->titleCache)) {
1104
          $trees .= ($trees ? ', ' : '') . '<strong>' . $node->classification->titleCache . '</strong>';
1105
        }
1106
      }
1107

    
1108
      drupal_set_message(format_plural(count($taxon_nodes),
1109
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1110
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1111
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1112
    }
1113
  }
1114

    
1115
  // Render the taxon page.
1116
  $taxonpage->content = theme('cdm_taxon_page', array(
1117
    'taxon' => $taxon,
1118
    'page_part' => $chapter,
1119
  ));
1120

    
1121
  return $taxonpage;
1122
}
1123

    
1124
/**
1125
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1126
 *
1127
 * The node page shows the taxon name title and the list of taxon related
1128
 * with such taxon. Name on the tree already in use.
1129
 *
1130
 * @param string $taxon_name_uuid
1131
 *   A taxon name UUID.
1132
 *
1133
 * @return mixed
1134
 *   The formatted name page as node.
1135
 */
1136
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1137

    
1138
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1139
  if (!empty($taxonname_page)) {
1140
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1141
  }
1142
  else {
1143
    return '';
1144
  }
1145
}
1146

    
1147
/**
1148
 * Generates an object ready to be transformated to a node.
1149
 *
1150
 * This is a preparation in order to show it as a Drupal node.
1151
 *
1152
 * @param string $taxon_name_uuid
1153
 *
1154
 * @return mixed
1155
 *   The object with the page content and title.
1156
 */
1157
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1158
  // Getting the full taxonname object from the server.
1159
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1160
  if (!$taxon_name) {
1161
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1162
    return FALSE;
1163
  }
1164
  // Searching for all the taxa connected with the taxon name on the tree
1165
  // in use.
1166
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1167
  $request_params = array();
1168
  $request_params['query'] = $name_cache;
1169
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1170
  $request_params['doTaxa'] = 1;
1171
  $request_params['doSynonyms'] = 1;
1172
  $request_params['doTaxaByCommonNames'] = 0;
1173
  $request_params['matchMode'] = "EXACT";
1174
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1175

    
1176
  // Removing the name where we come from.
1177
  foreach ($taxon_pager->records as $k => &$taxon) {
1178
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1179
      unset($taxon_pager->records[$k]);
1180
    }
1181
  }
1182
  // Show the taxa list or go to the singular taxon.
1183
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1184
    reset($taxon_pager->records);
1185
    $singleTaxon = $taxon_pager->records[0];
1186
    if ($singleTaxon->class != "Taxon") {
1187
      // It is a Synonym -> look for the accepted.
1188
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1189
      if (!empty($synonym_uuid)) {
1190
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1191
      }
1192
      else {
1193
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1194
      }
1195
    }
1196
    else {
1197
      // It is an accepted taxon.
1198
      if (!empty($synonym_uuid)) {
1199
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1200
      }
1201
      else {
1202
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1203
      }
1204
    }
1205
  }
1206
  else {// More than one taxa case.
1207
    $taxon_name_page = new stdClass();
1208
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1209
    if ($taxon_pager->records) {
1210
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1211
    }
1212
    else {
1213
      $taxon_name_page->content = 'This name has no taxa';
1214
    }
1215
    return $taxon_name_page;
1216
  }
1217
}
1218

    
1219
/**
1220
 * @todo Please document this function.
1221
 * @see http://drupal.org/node/1354
1222
 */
1223
function cdm_dataportal_view_search_advanced() {
1224

    
1225
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1226
  $form = array();
1227
  $form_state = array();
1228
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1229

    
1230
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1231

    
1232
}
1233

    
1234
/**
1235
 * @todo Please document this function.
1236
 * @see http://drupal.org/node/1354
1237
 */
1238
function cdm_dataportal_view_search_taxon_by_description() {
1239
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1240
  // $form_state = false;
1241
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1242
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1243

    
1244
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1245
}
1246

    
1247
/**
1248
 * Executes the search and generates the result list of taxa.
1249
 */
1250
function cdm_dataportal_view_search_results_taxon() {
1251

    
1252
  $taxonPager = cdm_dataportal_search_execute();
1253

    
1254
  $showThumbnails = do_showThumbnails();
1255

    
1256
  $setSessionUri = url('cdm_api/setvalue/session', array(
1257
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1258
  ));
1259

    
1260
  drupal_add_js('jQuery(document).ready(function() {
1261

    
1262
      // init
1263
      if(' . $showThumbnails . ' == 1){
1264
      jQuery(\'.media_gallery\').show(20);
1265
  } else {
1266
      jQuery(\'.media_gallery\').hide(20);
1267
  }
1268
      // add change hander
1269
      jQuery(\'#showThumbnails\').change(
1270
      function(event){
1271
      var state = 0;
1272
      if(jQuery(this).is(\':checked\')){
1273
      jQuery(\'.media_gallery\').show(20);
1274
      state = 1;
1275
  } else {
1276
      jQuery(\'.media_gallery\').hide(20);
1277
  }
1278
      // store state in session variable
1279
      var uri = \'' . $setSessionUri . '\' + state;
1280
      jQuery.get(uri);
1281
  });
1282
  });',
1283
  array('type' => "inline", 'scope' => JS_DEFAULT));
1284

    
1285
  drupal_set_title(t('Search results'), PASS_THROUGH);
1286

    
1287
  return theme('cdm_search_results', array(
1288
    'pager' => $taxonPager,
1289
    'path' => 'cdm_dataportal/search/results/taxon',
1290
    'query_parameters' => $_REQUEST,
1291
    ));
1292
}
1293

    
1294
/**
1295
 * Returns the state of the the showThumbnails flag set in the
1296
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1297
 *
1298
 * @return Ambigous <boolean, number>
1299
 *    returns 1 if the flag is set
1300
 */
1301
function do_showThumbnails() {
1302
  static $showThumbnails = null;
1303

    
1304
  if($showThumbnails == null) {
1305
    $showThumbnails = FALSE;
1306
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1307
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1308
    }
1309
    if (!is_numeric($showThumbnails)) {
1310
      $showThumbnails = 1;
1311
    }
1312
  }
1313

    
1314
  return $showThumbnails;
1315
}
1316

    
1317
/**
1318
 * View which transforms XML output from a given webservice endpoint into JSON.
1319
 */
1320
/*
1321
 function cdm_view_xml2json(){
1322
 $file = arg(2);
1323
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1324
 return  xml2json::transformXmlStringToJson($datastr);
1325
 }
1326
 */
1327

    
1328
/* ====================== other functions ====================== */
1329
/**
1330
 * Creates a URL to the taxon page specified by the $uuid parameter.
1331
 *
1332
 * The URL will be prepended with a path element to a specific taxon page tab.
1333
 *
1334
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1335
 * be set globally in the administrative settings or individually in the user
1336
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1337
 * the last portal will stay on this last tab.
1338
 *
1339
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1340
 * internal mechanism by a specific value.
1341
 *
1342
 * @param string $uuid
1343
 *   The UUID of the taxon.
1344
 * @param string $page_tab
1345
 *   Overwriting the preset mechanism by defining specific value for the
1346
 *   taxon page tab.
1347
 *
1348
 * @return string
1349
 *   The created URL.
1350
 */
1351
function path_to_taxon($uuid, $page_tab = FALSE) {
1352

    
1353
  $tab = get_default_taxon_tab();
1354
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1355

    
1356
  if (!$uuid) {
1357
    return FALSE;
1358
  }
1359

    
1360
  if ($page_tab) {
1361
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1362
  }
1363
  elseif (!$tab || strtolower($tab) == 'general') {
1364
    return 'cdm_dataportal/taxon/' . $uuid;
1365
  }
1366
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1367
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1368
  }
1369
  else {
1370
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1371
  }
1372
}
1373

    
1374
/**
1375
 * @todo Please document this function.
1376
 * @see http://drupal.org/node/1354
1377
 */
1378
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1379
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1380
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1381
}
1382

    
1383
/**
1384
 * @todo Please document this function.
1385
 * @see http://drupal.org/node/1354
1386
 */
1387
function path_to_key($keyType, $keyUuid) {
1388
  if (!$keyUuid || !$keyType) {
1389
    return FALSE;
1390
  }
1391
  $keyType{0} = strtolower($keyType{0});
1392
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1393
}
1394

    
1395
/**
1396
 * @todo Please document this function.
1397
 * @see http://drupal.org/node/1354
1398
 */
1399
function path_to_reference($uuid) {
1400
  if (!$uuid) {
1401
    return FALSE;
1402
  }
1403
  return 'cdm_dataportal/reference/' . $uuid;
1404
}
1405

    
1406
/**
1407
 * @todo Please document this function.
1408
 * @see http://drupal.org/node/1354
1409
 */
1410
function path_to_name($name_uuid) {
1411
  $res = FALSE;
1412
  if ($name_uuid) {
1413
    $res = 'cdm_dataportal/name/' . $name_uuid;
1414
  }
1415
  return $res;
1416
}
1417

    
1418
/**
1419
 * @todo Please document this function.
1420
 * @see http://drupal.org/node/1354
1421
 */
1422
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1423
  if (!$uuid) {
1424
    return FALSE;
1425
  }
1426
  $out = 'cdm_dataportal/media/' . $uuid;
1427
  if ($representaion_uuid) {
1428
    $out .= '/' . $representaion_uuid;
1429
    if ($partId !== FALSE) {
1430
      $out .= '/' . $partId;
1431
    }
1432
  }
1433
  return $out;
1434
}
1435

    
1436
/**
1437
 * Compares thisRank with thatRank.
1438
 *
1439
 * Returns a negative integer, zero, or a positive integer
1440
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1441
 * e.g:
1442
 * <ul>
1443
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1444
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1445
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1446
 * </ul>
1447
 * <p>
1448
 * This compare logic of the underlying webservice is the
1449
 * <b>inverse logic</b> of the the one implemented in
1450
 * java.lang.Comparable#compareTo(java.lang.Object)
1451
 *
1452
 * @param $thisRankUuid
1453
 * @param $thatRankUuid
1454
 *
1455
 * @return int
1456
 *   A negative integer, zero, or a positive integer
1457
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1458
 */
1459
function rank_compare($thisRankUuid, $thatRankUuid) {
1460
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1461
  return $result->Integer;
1462
}
1463

    
1464
/**
1465
 * Composes an HTML element class attribute value composed of
1466
 * the shortname of the cdm class and the uuid of the entity.
1467
 * This class attribute should be used whereever an cdm-entity is rendered.
1468
 *
1469
 * These according class selectors in css must be escaped, eg:
1470
 *    .cdm\:TextData
1471
 *
1472
 * @param $cdmEntity
1473
 */
1474
function html_class_atttibute_ref($cdmEntity) {
1475

    
1476
  if (is_cdm_entity($cdmEntity)) {
1477
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1478
  }
1479
}
1480

    
1481
/**
1482
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1483
 *
1484
 * @param unknown_type $taggedTextList
1485
 */
1486
function normalize_TaggedName(&$taggedTextList) {
1487

    
1488
  if (is_array($taggedTextList)) {
1489

    
1490
    // First pass: rename.
1491
    for ($i = 0; $i < count($taggedTextList); $i++) {
1492

    
1493
      if ($taggedTextList[$i]->type == "hybridSign") {
1494
        $taggedTextList[$i]->type = "name";
1495
      }
1496
    }
1497

    
1498
    // Second pass: resolve separators.
1499
    $taggedNameListNew = array();
1500
    for ($i = 0; $i < count($taggedTextList); $i++) {
1501

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

    
1504
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1505
          $taggedName = $taggedTextList[$i];
1506
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1507
          $taggedNameListNew[] = $taggedName;
1508
          ++$i;
1509
          ++$i;
1510
        }
1511
      }
1512
      else {
1513
        $taggedNameListNew[] = $taggedTextList[$i];
1514
      }
1515
    }
1516
    $taggedTextList = $taggedNameListNew;
1517
  }
1518
}
1519

    
1520
/**
1521
 * Creates a short taxonname.
1522
 *
1523
 * The short name is created by using the taggename field of
1524
 * NameSTO or NameTO instances.
1525
 * If the taggename if empty the fullname will be returned.
1526
 *
1527
 * @param unknown_type $name
1528
 *   Name or TreeNode.
1529
 *
1530
 * @return string
1531
 */
1532
function cdm_dataportal_shortname_of($name) {
1533
  $nameStr = '';
1534

    
1535
  normalize_TaggedName($name->taggedTitle);
1536

    
1537
  // Get all tagged text tokens of the scientific name.
1538
  foreach ($name->taggedTitle as $tagtxt) {
1539
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1540
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1541
    }
1542
  }
1543
  $nameStr = trim($nameStr);
1544

    
1545
  if ($nameStr) {
1546

    
1547
    // Do not return short names for these.
1548
    if ($name->unplaced || $name->excluded) {
1549
      return $nameStr;
1550
    }
1551

    
1552
    /*
1553
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1554
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1555
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1556
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1557
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1558
    */
1559
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1560
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1561
      return $matches[1][0] . "." . $matches[3][0];
1562
    }
1563
    else {
1564
      return $nameStr;
1565
    }
1566
  }
1567
  else {
1568
    return $name->titleCache;
1569
  }
1570
}
1571

    
1572
/**
1573
 * Check if a taxon is accepted by the current taxonomic tree.
1574
 *
1575
 * @param mixed $taxon
1576
 *   The Taxon obkect to check.
1577
 *
1578
 * @return bool
1579
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1580
 */
1581
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1582

    
1583
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1584

    
1585
  if (isset($taxon->taxonNodes)) {
1586
    $taxonNodes = $taxon->taxonNodes;
1587
  }
1588
  else {
1589
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1590
  }
1591

    
1592
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1593
    foreach ($taxonNodes as $node) {
1594
      if (is_object($node->classification)) {
1595
        if ($node->classification->uuid == $defaultTreeUuid) {
1596
          return TRUE;
1597
        }
1598
      }
1599
      else {
1600
        if ($node->classification == $defaultTreeUuid) {
1601
          return TRUE;
1602
        }
1603
      }
1604
    }
1605
  }
1606

    
1607
  return FALSE;
1608
}
1609

    
1610
/**
1611
 * Workaround for missing original source type.
1612
 *
1613
 * idNamespace is always set in these cases.
1614
 * @todo improve documentation of this function.
1615
 *
1616
 * @param unknown_type $source
1617
 *
1618
 * @return unknown_type
1619
 */
1620
function _is_original_source_type($source) {
1621
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1622
}
1623

    
1624
/**
1625
 * @todo Please document this function.
1626
 * @see http://drupal.org/node/1354
1627
 */
1628
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1629
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1630
}
1631

    
1632
/**
1633
 * Gets the metadata info such as title or artist of a media file.
1634
 *
1635
 * The function tries at first to get all the info from the file metadata
1636
 * and if it is not avaible look at the media file info stored at the database.
1637
 *
1638
 * @param mixed $media
1639
 *   The media file object for which to get the metadata.
1640
 *
1641
 * @return array
1642
 *   The array with the available specified metadata info.
1643
 * TODO rename to read_media_metadata() and move to *.module.
1644
 */
1645
function cdm_read_media_metadata($media) {
1646

    
1647
  $metadata_caption = array(
1648
    'title' => '',// Media_metadata and media.
1649
    'artist' => '',// Media_metadata and media.
1650
    'rights',// Media_metadata and media.
1651
    'location',// Media_metadata.
1652
    'filename' => '',// Media.
1653
    'mediacreated' => '',// Media.
1654
    'description' => '',
1655
  );// Media.
1656

    
1657
  // Getting the media metadata.
1658
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1659
  $media_metadata_aux = (array) $media_metadata;
1660

    
1661
  // Filename.
1662
  if (!empty($media->representations[0]->parts[0]->uri)) {
1663
    $fileUri = $media->representations[0]->parts[0]->uri;
1664
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1665
    $metadata_caption['filename'] = $filename;
1666
  }
1667
  else {
1668
    $metadata_caption['filename'] = '';
1669
  }
1670

    
1671
  // Title.
1672
  if (!empty($media_metadata->ObjectName)) {
1673
    $metadata_caption['title'] = $media_metadata->ObjectName;
1674
  }
1675
  elseif (!empty($media_metadata_aux['Object Name'])) {
1676
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1677
  }
1678
  elseif (!empty($media->title_L10n)) {
1679
    $metadata_caption['title'] = $media->title_L10n;
1680
  }
1681
  elseif (!empty($media->titleCache)) {
1682
    $metadata_caption['title'] = $media->titleCache;
1683
  }
1684

    
1685
  // Append description to title.
1686
  if (!empty($media->description_L10n)) {
1687
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1688
  }
1689

    
1690
  // Artist.
1691
  if ($media_metadata->Artist) {
1692
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1693
  }
1694
  elseif (!empty($media->artist->titleCache)) {
1695
    $metadata_caption['artist'] = $media->artist->titleCache;
1696
  }
1697

    
1698
  // Copyright.
1699
  $metadata_caption['rights'] = array(
1700
    'copyright' => array('agentNames' => array()),
1701
    'license' => array(
1702
      'agentNames' => array(),
1703
      'types' => array(),
1704
      'abbreviatedTexts' => array(),
1705
      'uris' => array(),
1706
    ),
1707
  );
1708
  if (!empty($media_metadata->Copyright)) {
1709
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1710
  }
1711
  elseif (isset($media->rights) && is_array($media->rights)) {
1712
    foreach ($media->rights as $right) {
1713
      switch ($right->term->uuid) {
1714
        case UUID_RIGHTS_LICENCE:
1715
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1716
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1717
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1718
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1719
          break;
1720
        case UUID_RIGHTS_COPYRIGHT:
1721
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1722
          break;
1723
      }
1724
    }
1725
  }
1726
  else {
1727
    $metadata_caption['rights']['agentNames'][] = '';
1728
  }
1729

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

    
1733
  // Location.
1734
  $metadata_caption['location'] = array();
1735
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1736
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1737
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1738
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1739

    
1740
  /*
1741
   // Creation date.
1742
   if($media_metadata["Modify Date"])
1743
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1744
   else
1745
   $metadata_caption['mediacreated'] = $media->created;
1746
   */
1747

    
1748
  // Returned value.
1749
  return $metadata_caption;
1750
}
1751

    
1752
/**
1753
 * Collects all the media from a list of description elements.
1754
 *
1755
 * @param array $descriptionElements
1756
 *   The description elements from which to collect the media.
1757
 *
1758
 * @return array
1759
 *   The output with all the collected media.
1760
 */
1761
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1762

    
1763
  $outArrayOfMedia = array();
1764

    
1765
  // Avoiding a warning box in Drupal for Flora Malesiana.
1766
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1767
    foreach ($descriptionElements as $descriptionElement) {
1768
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1769
        foreach ($descriptionElement->media as $media) {
1770
          if (is_object($media)) {
1771
            $outArrayOfMedia[] = $media;
1772
          }
1773
        }
1774
      }
1775
    }
1776
  }
1777
  return $outArrayOfMedia;
1778
}
1779

    
1780
/**
1781
 * @todo Please document this function.
1782
 * @see http://drupal.org/node/1354
1783
 *
1784
 * @param array $cdmBase_list
1785
 *   An array of CdmBase instances or a single instance.
1786
 * @param string $footnote_list_key
1787
 *
1788
 * @return unknown
1789
 */
1790
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1791
  // Comment @WA: undefined variable.
1792
  /*
1793
   static $annotations_types_filter;
1794
   if(!$annotations_types_filter) {
1795
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1796
   }
1797
   */
1798
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1799

    
1800
  $footNoteKeys = array();
1801

    
1802
  // Is argument cdmBase an array?
1803
  if (!is_array($cdmBase_list)) {
1804
    $cdmBase_array = array();
1805
    $cdmBase_array[] = $cdmBase_list;
1806
  }
1807
  else {
1808
    $cdmBase_array = $cdmBase_list;
1809
  }
1810

    
1811
  // Getting the key for the footnotemanager.
1812
  if (isset($footnote_list_key)) {
1813
    $footnoteListKey = $footnote_list_key;
1814
  }
1815
  else {
1816
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1817
  }
1818

    
1819
  // Adding the footnotes keys.
1820
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1821
  foreach ($cdmBase_array as $cdmBase_element) {
1822
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1823
    if (is_array($annotations)) {
1824
      foreach ($annotations as $annotation) {
1825
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1826
      }
1827
    }
1828
  }
1829

    
1830
  return $footNoteKeys;
1831
}
1832

    
1833
// @WA Comment: should this not be a theme function?
1834
/**
1835
 *  Creates a CDM Dynabox.
1836
 *
1837
 * @param string $label
1838
 *   The clickable text to show.
1839
 * @param string $content_url
1840
 *   The cdm REST service request url wich will deliver the content to be shown
1841
 *   once the dynabox toggles open.
1842
 * @param string $theme
1843
 *   The theme to be used for rendering the cdm REST service reponse with is
1844
 *   returned from the $content_url.
1845
 * @param string $link_alt_text
1846
 *   The value for the alt attribute of the dynabox link.
1847
 * @param array $enclosingtags
1848
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
1849
 *   element itself, $enclosingtags[1] is the tag to be used for the
1850
 *   dynabox_content.
1851
 *
1852
 * @return string
1853
 *   Returns HTML for a dynabox.
1854
 */
1855
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')) {
1856
  $out = '';
1857
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
1858

    
1859
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
1860
  $out .= '<!-- ' . $content_url . ' -->';
1861
  $out .= '<' . $enclosingtags[0] . ' class="dynabox"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
1862
  $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] . '>';
1863
  $out .= '</' . $enclosingtags[0] . '>';
1864
  return $out;
1865
}
1866

    
1867
/**
1868
 * Checks whether a feature has any description elements.
1869
 *
1870
 * @param mixed $featureNode
1871
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
1872
 *
1873
 * @see _mergeFeatureTreeDescriptions()
1874
 *
1875
 * @return bool
1876
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
1877
 *   contains at least one non empty TextData or at least one DescriptionElement
1878
 *   of an other type. A TextData element holding a multilanguageText or a
1879
 *   source reference is considered to be not empty.
1880
 */
1881
function hasFeatureNodeDescriptionElements($featureNode) {
1882

    
1883
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
1884
    foreach ($featureNode->descriptionElements as $descriptionElement) {
1885
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
1886
        return TRUE;
1887
      }
1888
    }
1889
  }
1890
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
1891
    foreach ($featureNode->children as $child) {
1892
      if (hasFeatureNodeDescriptionElements($child)) {
1893
        return TRUE;
1894
      }
1895
    }
1896
  }
1897
  return FALSE;
1898
}
(6-6/13)