Project

General

Profile

Download (65.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
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
  $edit_map_service = get_edit_map_service_settings();
151
  // window.onload - is executed when the document and images etc is fully loaded
152
  // Query(document).ready - is executed much earlier, when the DOM is loaded
153
  drupal_add_js("
154
          jQuery(document).ready(function() {
155

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

    
177
}
178

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

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

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

    
200
  if ($map_caption) {
201
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
202
  }
203

    
204
  if (get_edit_map_service_version_number() >= 1.1) {
205

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

    
215
      $query_string .= "&" . $occurrenceQuery;
216
    }
217
    elseif ($distributionQuery) {
218
      $query_string .= "&" . $distributionQuery;
219
    }
220

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

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

    
235
    $map_service_script_name = "rest_gen.php";
236

    
237
    $bgcolor_areaStyleId = "y";
238
    $baselayer_areaStyleId = "z";
239
    $bgcolor_layer = '';
240
    $additional_area_styles = array();
241

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

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

    
269
    if ($bgcolor_layer) {
270
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
271
    }
272

    
273
    if (variable_get('map_base_layer_style', '')) {
274
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
275
    }
276

    
277
    foreach ($additional_area_styles as $as) {
278
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
279
    }
280

    
281
  }
282
  else {
283
    // Pre 1.1. version of map service.
284
    if ($occurrenceQuery) {
285

    
286
      $map_service_script_name = "point.php";
287

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

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

    
309
  return $out;
310
}
311

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

    
326
  _add_js_openlayers_map();
327

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

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

    
337
  $openlayers_map_query_string = '&img=false&ms=' . $width
338
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
339
    . ($labels_on ? '&label=' . $labels_on : '');
340

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

    
349
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
350
  }
351

    
352
  if ($distributionQuery) {
353
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
354
  }
355

    
356
  if ($legendFormatQuery) {
357
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
358
  }
359

    
360
  $out .= '></div></div>';
361

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

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

    
395
/**
396
 * Implements hook_menu().
397
 */
398
function cdm_dataportal_menu() {
399
  $items = array();
400

    
401
  // @see settings.php.
402
  cdm_dataportal_menu_admin($items);
403
  cdm_dataportal_menu_help($items);
404

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

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

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

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

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

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

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

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

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

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

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

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

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

    
517
  if (variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
518
    $items['cdm_dataportal/taxon/%'] = array(
519
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'General')),
520
      'page callback' => 'cdm_dataportal_taxon_page_view',
521
      'access arguments' => array('access content'),
522
      'type' => MENU_CALLBACK,
523
      'weight' => 1,
524
      'page arguments' => array(2, "description")
525
      , // Expected callback arguments: name_uuid.
526
    );
527

    
528
    $items['cdm_dataportal/taxon/%/all'] = 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' => 2,
534
      'page arguments' => array(2, "all")
535
      , // Expected callback arguments: name_uuid.
536
    );
537

    
538
    $items['cdm_dataportal/taxon/%/description'] = 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_DEFAULT_LOCAL_TASK,
543
      'weight' => 2,
544
      'page arguments' => array(2, "description")
545
      , // Expected callback arguments: name_uuid.
546
    );
547

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

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

    
577
    $items['cdm_dataportal/taxon/%/keys'] = array(
578
      'title' => theme('cdm_taxonpage_tab', array('tabname' => 'Keys')),
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, "keys")
584
      , // Expected callback arguments: name_uuid.
585
    );
586
  }
587

    
588
  return $items;
589
}
590

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

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

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

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

    
625
  $form['submit'] = array(
626
    '#type' => 'submit',
627
    '#value' => t('Submit'),
628
  );
629

    
630
  return $form;
631
}
632

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

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

    
668
/**
669
 * Implements hook_block_info().
670
 */
671
function cdm_dataportal_block_info() {
672

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

    
682
    return $block;
683
}
684

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

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

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

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

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

    
755
  $form = drupal_get_form('cdm_taxonomictree_selector_form');
756
  $out = drupal_render($form);
757
  return $out;
758
}
759

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

    
766
  $url = url('cdm_api/setvalue/session', array('query' => NULL));
767
  $form['#action'] = $url;
768

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

    
775
  $destination_array = drupal_get_destination();
776
  $destination = $destination_array['destination'];
777

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

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

    
791
  return $form;
792

    
793
}
794

    
795
/* UNREACHABLE since action of form directly links to view.
796
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
797

    
798
 $_SESSION['cdm']['search'] = $form_values;
799
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
800
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
801
 //$paramstr = compose_url_prameterstr($form_values);
802
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
803
 }
804
 */
805
/* ====================== menu callback functions ====================== */
806
/**
807
 * @todo Please document this function.
808
 * @see http://drupal.org/node/1354
809
 */
810
/*
811
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
812
  static $comment_node_disabled =  0;
813
  static $comment_node_read_only =  1;
814
  static $comment_node_read_write =  2;
815

    
816
  if ($form_id == 'node_type_form'
817
   && isset($form['identity']['type'])
818
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
819
  ) {
820
    $form['workflow']['comment'] = array(
821
      '#type' => 'radios',
822
      '#title' => t('Default comment setting'),
823
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
824
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
825
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
826
    );
827
  }
828
}
829
*/
830

    
831
/**
832
 * Displays a list of the known taxonomic names.
833
 *
834
 * When the list of taxonomic names is displayed, long lists are split up into
835
 * multiple pages.
836
 *
837
 * TODO: Parameters are still preliminary.
838
 *
839
 * @param string $beginsWith
840
 * @param string $page
841
 *   Page number to diplay defaults to page 1.
842
 * @param bool $onlyAccepted
843
 */
844
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
845

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

    
848
  /*
849
  // FIXME the filter for accepted names will be a form element, thus this
850
  // widget should be generated via form api preferably as block.
851
  $out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
852
  $out .= theme('cdm_dataportal_widget_names_list', $names, $page);
853
  $out .= theme('cdm_listof_taxa', $taxonPager);
854
  return $out;
855
  */
856
}
857

    
858
/**
859
 * @todo Please document this function.
860
 * @see http://drupal.org/node/1354
861
 */
862
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
863
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
864
  return theme('cdm_reference_page', array('reference' => $reference));
865
}
866

    
867
/**
868
 * @todo Please document this function.
869
 * @see http://drupal.org/node/1354
870
 */
871
function cdm_dataportal_view_reference_list($pageNumber) {
872
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
873
  return theme('cdm_reference_pager', array(
874
    'referencePager' => $referencePager,
875
    'path' => 'cdm_dataportal/reference/list/',
876
    ));
877
}
878

    
879
/**
880
 * @todo Please document this function.
881
 * @see http://drupal.org/node/1354
882
 */
883
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
884
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
885
  return theme('cdm_media_page', array(
886
    'media' => $media,
887
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
888
    'partId' => $part,
889
    ));
890
}
891

    
892
/**
893
 * @todo Please document this function.
894
 * @see http://drupal.org/node/1354
895
 */
896
function _load_taxonBase(&$taxonBase) {
897
  if (isset($taxonBase->uuid)) {
898
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
899
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
900
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
901
  }
902
}
903

    
904
/**
905
 * Loads the media associated to the given taxon from the cdm server.
906
 * The aggregation settings regarding taxon relathionships and
907
 * taxonnomic childen are taken into account.
908
 *
909
 * The media lists are cached in a static variable.
910
 *
911
 * @param Taxon $taxon
912
 *   A CDM Taxon entitiy
913
 *
914
 * @return array
915
 *   An array of CDM Media entities
916
 *
917
 */
918
function _load_media_for_taxon($taxon) {
919

    
920
  static $media = NULL;
921

    
922
  if(!isset($media)) {
923
    $media = array();
924
  }
925
  if (!isset($media[$taxon->uuid])) {
926

    
927
    // --- GET Images --- //
928
    $mediaQueryParameters = array(
929
        "type" => "ImageFile",
930
    );
931

    
932
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
933
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
934
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
935

    
936
    $ws_endpoint = NULL;
937
    if ( variable_get('cdm_images_include_children', 0) == 0) {
938
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
939
    } else {
940
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
941
    }
942

    
943
    $media[$taxon->uuid] = cdm_ws_get($ws_endpoint,
944
        array(
945
            $taxon->uuid,
946
        ),
947
        queryString($mediaQueryParameters)
948
       );
949
  }
950

    
951
  return $media[$taxon->uuid];
952
}
953

    
954
/**
955
 *
956
 * @param Taxon $taxon
957
 *   A CDM Taxon entitiy
958
 *
959
 * @return array
960
 *   An array of CDM SpecimenOrObservation entities
961
 *
962
function _load_occurences_for_taxon($taxon){
963

    
964
  static $occurences = NULL;
965

    
966
  if(!isset($occurences)) {
967
    $occurences = array();
968
  }
969

    
970
  if (!isset($occurences[$taxon->uuid])){
971

    
972
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
973
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
974
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
975

    
976
    $by_associatedtaxon_query = http_build_query(array(
977
        'relationshipsInvers' => implode(',', $relationship_choice['invers']),
978
        'relationships' => implode(',', $relationship_choice['direct']),
979
        'pageSize' => null // all hits in one page
980
    )
981
    );
982

    
983
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
984
        null,
985
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
986
    );
987

    
988

    
989
    if(isset($pager->records[0])){
990
      $occurences[$taxon->uuid] =  $pager->records;
991
    }
992
  }
993
  return $occurences[$taxon->uuid];
994
}
995
 */
996

    
997
/**
998
 * Gets a Drupal variable, string or array and returns it.
999
 *
1000
 * Similar to the variable_get() function of Drupal, except that this function
1001
 * is able to handle arrays correctly. This function is especially useful
1002
 * when dealing with collections of setting form elements (#tree = TRUE).
1003
 *
1004
 * @param string $variableKey
1005
 *   The Unique key of the Drupal variable in the Drupal variables table.
1006
 * @param string $defaultValueString
1007
 *   A string as for example derived from a CONSTANT.
1008
 *
1009
 * @return mixed
1010
 *   Returns usally an array, depending on the nature of the variable.
1011
 */
1012
function mixed_variable_get($variableKey, $defaultValueString) {
1013
  $systemDefaults = unserialize($defaultValueString);
1014
  $storedSettings = variable_get($variableKey, array());
1015
  if (is_array($storedSettings)) {
1016
    $settings = array_merge($systemDefaults, $storedSettings);
1017
  }
1018
  else {
1019
    $settings = $systemDefaults;
1020
  }
1021
  return $settings;
1022
}
1023

    
1024
/**
1025
 * Wrapps the given $html string into a reder array suitable for drupal_render()
1026
 *
1027
 * @param string $html
1028
 *   the html string, see
1029
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1030
 * @param number $weight
1031
 *   A positive or negative number (integer or decimal).
1032
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1033
 *
1034
 * @return
1035
 *   A render array
1036
 *
1037
 */
1038
function markup_to_render_array($html, $weight = 0) {
1039
  return array(
1040
          '#markup' => $html,
1041
          '#weight' => $weight,
1042
      );
1043
}
1044

    
1045
/**
1046
 * Loads the subgraph of a given PolytomousKeyNode.
1047
 *
1048
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1049
 * the CDM REST service.
1050
 *
1051
 * @param mixed $polytomousKeyNode
1052
 *   PolytomousKeyNode passed by reference.
1053
 *
1054
 * @return void
1055
 */
1056
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1057

    
1058
  if (!$polytomousKeyNode) {
1059
    return;
1060
  }
1061
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1062
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1063
    return;
1064
  }
1065
  if (!is_uuid($polytomousKeyNode->uuid)) {
1066
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1067
    return;
1068
  }
1069

    
1070
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1071

    
1072
  if (!$polytomousKeyNode) {
1073
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1074
    return;
1075
  }
1076

    
1077
  // Load children.
1078
  foreach ($polytomousKeyNode->children as &$childNode) {
1079
    _load_polytomousKeySubGraph($childNode);
1080
  }
1081

    
1082
  // Load subkey.
1083
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1084

    
1085
  // Load taxon.
1086
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1087
  _load_taxonBase($polytomousKeyNode->taxon);
1088
  return;
1089
}
1090

    
1091
/**
1092
 * @todo Please document this function.
1093
 * @see http://drupal.org/node/1354
1094
 */
1095
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1096
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1097

    
1098
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1099
  if (is_array($sourcePager->records)) {
1100
    $polytomousKey->sources = $sourcePager->records;
1101
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1102
  }
1103

    
1104
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1105
  if (is_array($annotationPager->records)) {
1106
    $polytomousKey->annotations = $annotationPager->records;
1107
  }
1108

    
1109
  _load_polytomousKeySubGraph($polytomousKey->root);
1110
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1111
}
1112

    
1113
/**
1114
 * Creates a taxon page view or a chapter of it.
1115
 *
1116
 * The taxon page gives detailed information on a taxon, it shows:
1117
 *  - Taxon name.
1118
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1119
 *    heterotypic and finally followed by misapplied names.
1120
 *    The list is ordered historically.
1121
 *  - All description associated with the taxon.
1122
 *
1123
 * @param string $uuid
1124
 * @param string $chapter
1125
 *   Name of the part to display, valid values are:
1126
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1127
 *
1128
 * @return unknown_type
1129
 */
1130
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1131
  // Display the page for the taxon defined by $uuid.
1132
  // set_last_taxon_page_tab(arg(3));
1133
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1134
  if (!empty($taxonpage)) {
1135
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1136
  }
1137
  else {
1138
    return '';
1139
  }
1140
}
1141

    
1142
/**
1143
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1144
 * which has two fields, one for the page title and one for the content. Later on in the
1145
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1146
 * function as the function parameters $title and $content.
1147
 *
1148
 * @param string $uuid
1149
 *   the uuid of the taxon to show
1150
 * @param string $chapter
1151
 *   Name of the part to display, valid values are:
1152
 *   'description', 'images', 'synonymy', 'all'.
1153
 *
1154
 * @return taxonpage object with the following fields:
1155
 *   - title : the title of the page
1156
 *   - content: the content of the page
1157
 *
1158
 */
1159
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1160
  // Taxon object.
1161
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1162
  if (empty($taxon)) {
1163
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1164
    return FALSE;
1165
  }
1166
  $taxonpage = new stdClass();
1167

    
1168
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1169
    'taxon' => $taxon,
1170
    'uuid' => $uuid,
1171
    'synonym_uuid' => $synonym_uuid,
1172
  ));
1173

    
1174
  // Check if the taxon id contained in the currently selected tree.
1175
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1176

    
1177
  if (!$taxon_in_current_tree) {
1178
    $classifications = get_classifications_for_taxon($taxon);
1179
    if (count($classifications) == 0) {
1180
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1181
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1182
      ))), 'warning');
1183
    }
1184
    else {
1185
      $trees = '';
1186
      foreach ($classifications as $classification) {
1187
        if (isset($classification->titleCache)) {
1188
          $trees .= ($trees ? ', ' : '') . '<strong>' . $classification->titleCache . '</strong>';
1189
        }
1190
      }
1191

    
1192
      drupal_set_message(format_plural(count($taxon_nodes),
1193
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1194
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1195
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1196
    }
1197
  }
1198

    
1199
  // Render the taxon page.
1200
  $taxonpage->content = theme('cdm_taxon_page', array(
1201
    'taxon' => $taxon,
1202
    'page_part' => $chapter,
1203
  ));
1204

    
1205
  return $taxonpage;
1206
}
1207

    
1208
/**
1209
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1210
 *
1211
 * The node page shows the taxon name title and the list of taxon related
1212
 * with such taxon. Name on the tree already in use.
1213
 *
1214
 * @param string $taxon_name_uuid
1215
 *   A taxon name UUID.
1216
 *
1217
 * @return mixed
1218
 *   The formatted name page as node.
1219
 */
1220
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1221

    
1222
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1223
  if (!empty($taxonname_page)) {
1224
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1225
  }
1226
  else {
1227
    return '';
1228
  }
1229
}
1230

    
1231
/**
1232
 * Generates an object ready to be transformated to a node.
1233
 *
1234
 * This is a preparation in order to show it as a Drupal node.
1235
 *
1236
 * @param string $taxon_name_uuid
1237
 *
1238
 * @return mixed
1239
 *   The object with the page content and title.
1240
 */
1241
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1242
  // Getting the full taxonname object from the server.
1243
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1244
  if (!$taxon_name) {
1245
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1246
    return FALSE;
1247
  }
1248
  // Searching for all the taxa connected with the taxon name on the tree
1249
  // in use.
1250
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1251
  $request_params = array();
1252
  $request_params['query'] = $name_cache;
1253
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1254
  $request_params['doTaxa'] = 1;
1255
  $request_params['doSynonyms'] = 1;
1256
  $request_params['doTaxaByCommonNames'] = 0;
1257
  $request_params['matchMode'] = "EXACT";
1258
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1259

    
1260
  // Removing the name where we come from.
1261
  foreach ($taxon_pager->records as $k => &$taxon) {
1262
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1263
      unset($taxon_pager->records[$k]);
1264
    }
1265
  }
1266
  // Show the taxa list or go to the singular taxon.
1267
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1268
    reset($taxon_pager->records);
1269
    $singleTaxon = $taxon_pager->records[0];
1270
    if ($singleTaxon->class != "Taxon") {
1271
      // It is a Synonym -> look for the accepted.
1272
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1273
      if (!empty($synonym_uuid)) {
1274
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1275
      }
1276
      else {
1277
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1278
      }
1279
    }
1280
    else {
1281
      // It is an accepted taxon.
1282
      if (!empty($synonym_uuid)) {
1283
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1284
      }
1285
      else {
1286
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1287
      }
1288
    }
1289
  }
1290
  else {// More than one taxa case.
1291
    $taxon_name_page = new stdClass();
1292
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1293
    if ($taxon_pager->records) {
1294
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1295
    }
1296
    else {
1297
      $taxon_name_page->content = 'This name has no taxa';
1298
    }
1299
    return $taxon_name_page;
1300
  }
1301
}
1302

    
1303
/**
1304
 * @todo Please document this function.
1305
 * @see http://drupal.org/node/1354
1306
 */
1307
function cdm_dataportal_view_search_advanced() {
1308

    
1309
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1310
  $form = array();
1311
  $form_state = array();
1312
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1313

    
1314
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1315

    
1316
}
1317

    
1318
/**
1319
 * @todo Please document this function.
1320
 * @see http://drupal.org/node/1354
1321
 */
1322
function cdm_dataportal_view_search_taxon_by_description() {
1323
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1324
  // $form_state = false;
1325
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1326
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1327

    
1328
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1329
}
1330

    
1331
/**
1332
 * Executes the search and generates the result list of taxa.
1333
 */
1334
function cdm_dataportal_view_search_results_taxon() {
1335

    
1336
  $taxonPager = cdm_dataportal_search_execute();
1337

    
1338
  $showThumbnails = do_showThumbnails();
1339

    
1340
  $setSessionUri = url('cdm_api/setvalue/session', array(
1341
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1342
  ));
1343

    
1344
  drupal_add_js('jQuery(document).ready(function() {
1345

    
1346
      // init
1347
      if(' . $showThumbnails . ' == 1){
1348
      jQuery(\'.media_gallery\').show(20);
1349
  } else {
1350
      jQuery(\'.media_gallery\').hide(20);
1351
  }
1352
      // add change hander
1353
      jQuery(\'#showThumbnails\').change(
1354
      function(event){
1355
      var state = 0;
1356
      if(jQuery(this).is(\':checked\')){
1357
      jQuery(\'.media_gallery\').show(20);
1358
      state = 1;
1359
  } else {
1360
      jQuery(\'.media_gallery\').hide(20);
1361
  }
1362
      // store state in session variable
1363
      var uri = \'' . $setSessionUri . '\' + state;
1364
      jQuery.get(uri);
1365
  });
1366
  });',
1367
  array('type' => "inline", 'scope' => JS_DEFAULT));
1368

    
1369
  drupal_set_title(t('Search results'), PASS_THROUGH);
1370

    
1371
  return theme('cdm_search_results', array(
1372
    'pager' => $taxonPager,
1373
    'path' => 'cdm_dataportal/search/results/taxon',
1374
    'query_parameters' => $_REQUEST,
1375
    ));
1376
}
1377

    
1378
/**
1379
 * Returns the state of the the showThumbnails flag set in the
1380
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1381
 *
1382
 * @return Ambigous <boolean, number>
1383
 *    returns 1 if the flag is set
1384
 */
1385
function do_showThumbnails() {
1386
  static $showThumbnails = null;
1387

    
1388
  if($showThumbnails == null) {
1389
    $showThumbnails = FALSE;
1390
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1391
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1392
    }
1393
    if (!is_numeric($showThumbnails)) {
1394
      $showThumbnails = 1;
1395
    }
1396
  }
1397

    
1398
  return $showThumbnails;
1399
}
1400

    
1401
/**
1402
 * View which transforms XML output from a given webservice endpoint into JSON.
1403
 */
1404
/*
1405
 function cdm_view_xml2json(){
1406
 $file = arg(2);
1407
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1408
 return  xml2json::transformXmlStringToJson($datastr);
1409
 }
1410
 */
1411

    
1412
/* ====================== other functions ====================== */
1413
/**
1414
 * Creates a URL to the taxon page specified by the $uuid parameter.
1415
 *
1416
 * The URL will be prepended with a path element to a specific taxon page tab.
1417
 *
1418
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1419
 * be set globally in the administrative settings or individually in the user
1420
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1421
 * the last portal will stay on this last tab.
1422
 *
1423
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1424
 * internal mechanism by a specific value.
1425
 *
1426
 * @param string $uuid
1427
 *   The UUID of the taxon.
1428
 * @param string $page_tab
1429
 *   Overwriting the preset mechanism by defining specific value for the
1430
 *   taxon page tab.
1431
 *
1432
 * @return string
1433
 *   The created URL.
1434
 */
1435
function path_to_taxon($uuid, $page_tab = FALSE) {
1436

    
1437
  $tab = get_default_taxon_tab();
1438
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1439

    
1440
  if (!$uuid) {
1441
    return FALSE;
1442
  }
1443

    
1444
  if ($page_tab) {
1445
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1446
  }
1447
  elseif (!$tab || strtolower($tab) == 'general') {
1448
    return 'cdm_dataportal/taxon/' . $uuid;
1449
  }
1450
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1451
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1452
  }
1453
  else {
1454
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1455
  }
1456
}
1457

    
1458
/**
1459
 * @todo Please document this function.
1460
 * @see http://drupal.org/node/1354
1461
 */
1462
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1463
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1464
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1465
}
1466

    
1467
/**
1468
 * @todo Please document this function.
1469
 * @see http://drupal.org/node/1354
1470
 */
1471
function path_to_key($keyType, $keyUuid) {
1472
  if (!$keyUuid || !$keyType) {
1473
    return FALSE;
1474
  }
1475
  $keyType{0} = strtolower($keyType{0});
1476
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1477
}
1478

    
1479
/**
1480
 * @todo Please document this function.
1481
 * @see http://drupal.org/node/1354
1482
 */
1483
function path_to_reference($uuid) {
1484
  if (!$uuid) {
1485
    return FALSE;
1486
  }
1487
  return 'cdm_dataportal/reference/' . $uuid;
1488
}
1489

    
1490
/**
1491
 * @todo Please document this function.
1492
 * @see http://drupal.org/node/1354
1493
 */
1494
function path_to_name($name_uuid) {
1495
  $res = FALSE;
1496
  if ($name_uuid) {
1497
    $res = 'cdm_dataportal/name/' . $name_uuid;
1498
  }
1499
  return $res;
1500
}
1501

    
1502
/**
1503
 * @todo Please document this function.
1504
 * @see http://drupal.org/node/1354
1505
 */
1506
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1507
  if (!$uuid) {
1508
    return FALSE;
1509
  }
1510
  $out = 'cdm_dataportal/media/' . $uuid;
1511
  if ($representaion_uuid) {
1512
    $out .= '/' . $representaion_uuid;
1513
    if ($partId !== FALSE) {
1514
      $out .= '/' . $partId;
1515
    }
1516
  }
1517
  return $out;
1518
}
1519

    
1520
/**
1521
 * Compares thisRank with thatRank.
1522
 *
1523
 * Returns a negative integer, zero, or a positive integer
1524
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1525
 * e.g:
1526
 * <ul>
1527
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1528
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1529
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1530
 * </ul>
1531
 * <p>
1532
 * This compare logic of the underlying webservice is the
1533
 * <b>inverse logic</b> of the the one implemented in
1534
 * java.lang.Comparable#compareTo(java.lang.Object)
1535
 *
1536
 * @param $thisRankUuid
1537
 * @param $thatRankUuid
1538
 *
1539
 * @return int
1540
 *   A negative integer, zero, or a positive integer
1541
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1542
 */
1543
function rank_compare($thisRankUuid, $thatRankUuid) {
1544
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1545
  return $result->Integer;
1546
}
1547

    
1548
/**
1549
 * Composes an HTML element class attribute value composed of
1550
 * the shortname of the cdm class and the uuid of the entity.
1551
 * This class attribute should be used whereever an cdm-entity is rendered.
1552
 *
1553
 * These according class selectors in css must be escaped, eg:
1554
 *    .cdm\:TextData
1555
 *
1556
 * @param $cdmEntity
1557
 */
1558
function html_class_atttibute_ref($cdmEntity) {
1559

    
1560
  if (is_cdm_entity($cdmEntity)) {
1561
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1562
  }
1563
}
1564

    
1565
/**
1566
 * Preprocess the taggedName to normalize newly introduced
1567
 * tagtypes like hybridSign, separator, .. more?
1568
 *
1569
 * @param unknown_type $taggedTextList
1570
 */
1571
function normalize_TaggedName(&$taggedTextList) {
1572

    
1573
  if (is_array($taggedTextList)) {
1574

    
1575
    // First pass: rename.
1576
    for ($i = 0; $i < count($taggedTextList); $i++) {
1577

    
1578
      if ($taggedTextList[$i]->type == "hybridSign") {
1579
        $taggedTextList[$i]->type = "name";
1580
      }
1581
    }
1582

    
1583
    // Second pass: resolve separators.
1584
    $taggedNameListNew = array();
1585
    for ($i = 0; $i < count($taggedTextList); $i++) {
1586

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

    
1589
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1590
          $taggedName = $taggedTextList[$i];
1591
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1592
          $taggedNameListNew[] = $taggedName;
1593
          ++$i;
1594
          ++$i;
1595
        }
1596
      }
1597
      else {
1598
        $taggedNameListNew[] = $taggedTextList[$i];
1599
      }
1600
    }
1601
    $taggedTextList = $taggedNameListNew;
1602
  }
1603
}
1604

    
1605
/**
1606
 * Creates a short taxonname.
1607
 *
1608
 * The short name is created by using the taggename field of
1609
 * NameSTO or NameTO instances.
1610
 * If the taggename if empty the fullname will be returned.
1611
 *
1612
 * @param unknown_type $name
1613
 *   Name or TreeNode.
1614
 *
1615
 * @return string
1616
 */
1617
function cdm_dataportal_shortname_of($name) {
1618
  $nameStr = '';
1619

    
1620
  normalize_TaggedName($name->taggedTitle);
1621

    
1622
  // Get all tagged text tokens of the scientific name.
1623
  foreach ($name->taggedTitle as $tagtxt) {
1624
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1625
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1626
    }
1627
  }
1628
  $nameStr = trim($nameStr);
1629

    
1630
  if ($nameStr) {
1631

    
1632
    // Do not return short names for these.
1633
    if ($name->unplaced || $name->excluded) {
1634
      return $nameStr;
1635
    }
1636

    
1637
    /*
1638
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1639
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1640
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1641
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1642
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1643
    */
1644
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1645
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1646
      return $matches[1][0] . "." . $matches[3][0];
1647
    }
1648
    else {
1649
      return $nameStr;
1650
    }
1651
  }
1652
  else {
1653
    return $name->titleCache;
1654
  }
1655
}
1656

    
1657
/**
1658
 * Check if a taxon is accepted by the current taxonomic tree.
1659
 *
1660
 * @param mixed $taxon
1661
 *   The Taxon obkect to check.
1662
 *
1663
 * @return bool
1664
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1665
 */
1666
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1667

    
1668
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1669

    
1670
  if (isset($taxon->taxonNodes)) {
1671
    $taxonNodes = $taxon->taxonNodes;
1672
  }
1673
  else {
1674
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1675
  }
1676

    
1677
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1678
    foreach ($taxonNodes as $node) {
1679
      if (is_object($node->classification)) {
1680
        if ($node->classification->uuid == $defaultTreeUuid) {
1681
          return TRUE;
1682
        }
1683
      }
1684
      else {
1685
        if ($node->classification == $defaultTreeUuid) {
1686
          return TRUE;
1687
        }
1688
      }
1689
    }
1690
  }
1691

    
1692
  return FALSE;
1693
}
1694

    
1695
/**
1696
 * Workaround for missing original source type.
1697
 *
1698
 * idNamespace is always set in these cases.
1699
 * @todo improve documentation of this function.
1700
 *
1701
 * @param unknown_type $source
1702
 *
1703
 * @return unknown_type
1704
 */
1705
function _is_original_source_type($source) {
1706
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1707
}
1708

    
1709
/**
1710
 * @todo Please document this function.
1711
 * @see http://drupal.org/node/1354
1712
 */
1713
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1714
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1715
}
1716

    
1717
/**
1718
 * Gets the metadata info such as title or artist of a media file.
1719
 *
1720
 * The function tries at first to get all the info from the file metadata
1721
 * and if it is not avaible look at the media file info stored at the database.
1722
 *
1723
 * @param mixed $media
1724
 *   The media file object for which to get the metadata.
1725
 *
1726
 * @return array
1727
 *   The array with the available specified metadata info.
1728
 * TODO rename to read_media_metadata() and move to *.module.
1729
 */
1730
function cdm_read_media_metadata($media) {
1731

    
1732
  $metadata_caption = array(
1733
    'title' => '',// Media_metadata and media.
1734
    'artist' => '',// Media_metadata and media.
1735
    'rights',// Media_metadata and media.
1736
    'location',// Media_metadata.
1737
    'filename' => '',// Media.
1738
    'mediacreated' => '',// Media.
1739
    'description' => '',
1740
  );// Media.
1741

    
1742
  // Getting the media metadata.
1743
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1744
  $media_metadata_aux = (array) $media_metadata;
1745

    
1746
  // Filename.
1747
  if (!empty($media->representations[0]->parts[0]->uri)) {
1748
    $fileUri = $media->representations[0]->parts[0]->uri;
1749
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1750
    $metadata_caption['filename'] = $filename;
1751
  }
1752
  else {
1753
    $metadata_caption['filename'] = '';
1754
  }
1755

    
1756
  // Title.
1757
  if (!empty($media_metadata->ObjectName)) {
1758
    $metadata_caption['title'] = $media_metadata->ObjectName;
1759
  }
1760
  elseif (!empty($media_metadata_aux['Object Name'])) {
1761
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1762
  }
1763
  elseif (!empty($media->title_L10n)) {
1764
    $metadata_caption['title'] = $media->title_L10n;
1765
  }
1766
  elseif (!empty($media->titleCache)) {
1767
    $metadata_caption['title'] = $media->titleCache;
1768
  }
1769

    
1770
  // Append description to title.
1771
  if (!empty($media->description_L10n)) {
1772
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1773
  }
1774

    
1775
  // Artist.
1776
  if ($media_metadata->Artist) {
1777
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1778
  }
1779
  elseif (!empty($media->artist->titleCache)) {
1780
    $metadata_caption['artist'] = $media->artist->titleCache;
1781
  }
1782

    
1783
  // Copyright.
1784
  $metadata_caption['rights'] = array(
1785
    'copyright' => array('agentNames' => array()),
1786
    'license' => array(
1787
      'agentNames' => array(),
1788
      'types' => array(),
1789
      'abbreviatedTexts' => array(),
1790
      'uris' => array(),
1791
    ),
1792
  );
1793
  if (!empty($media_metadata->Copyright)) {
1794
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1795
  }
1796
  elseif (isset($media->rights) && is_array($media->rights)) {
1797
    foreach ($media->rights as $right) {
1798
      switch ($right->term->uuid) {
1799
        case UUID_RIGHTS_LICENCE:
1800
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1801
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1802
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1803
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1804
          break;
1805
        case UUID_RIGHTS_COPYRIGHT:
1806
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1807
          break;
1808
      }
1809
    }
1810
  }
1811
  else {
1812
    $metadata_caption['rights']['agentNames'][] = '';
1813
  }
1814

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

    
1818
  // Location.
1819
  $metadata_caption['location'] = array();
1820
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1821
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1822
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1823
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1824

    
1825
  /*
1826
   // Creation date.
1827
   if($media_metadata["Modify Date"])
1828
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1829
   else
1830
   $metadata_caption['mediacreated'] = $media->created;
1831
   */
1832

    
1833
  // Returned value.
1834
  return $metadata_caption;
1835
}
1836

    
1837
/**
1838
 * Collects all the media from a list of description elements.
1839
 *
1840
 * @param array $descriptionElements
1841
 *   The description elements from which to collect the media.
1842
 *
1843
 * @return array
1844
 *   The output with all the collected media.
1845
 */
1846
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1847

    
1848
  $outArrayOfMedia = array();
1849

    
1850
  // Avoiding a warning box in Drupal for Flora Malesiana.
1851
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1852
    foreach ($descriptionElements as $descriptionElement) {
1853
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1854
        foreach ($descriptionElement->media as $media) {
1855
          if (is_object($media)) {
1856
            $outArrayOfMedia[] = $media;
1857
          }
1858
        }
1859
      }
1860
    }
1861
  }
1862
  return $outArrayOfMedia;
1863
}
1864

    
1865
/**
1866
 * @todo Please document this function.
1867
 * @see http://drupal.org/node/1354
1868
 *
1869
 * @param array $cdmBase_list
1870
 *   An array of CdmBase instances or a single instance.
1871
 * @param string $footnote_list_key
1872
 *
1873
 * @return unknown
1874
 */
1875
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
1876
  // Comment @WA: undefined variable.
1877
  /*
1878
   static $annotations_types_filter;
1879
   if(!$annotations_types_filter) {
1880
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1881
   }
1882
   */
1883
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1884

    
1885
  $footNoteKeys = array();
1886

    
1887
  // Is argument cdmBase an array?
1888
  if (!is_array($cdmBase_list)) {
1889
    $cdmBase_array = array();
1890
    $cdmBase_array[] = $cdmBase_list;
1891
  }
1892
  else {
1893
    $cdmBase_array = $cdmBase_list;
1894
  }
1895

    
1896
  // Getting the key for the footnotemanager.
1897
  if (isset($footnote_list_key)) {
1898
    $footnoteListKey = $footnote_list_key;
1899
  }
1900
  else {
1901
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1902
  }
1903

    
1904
  // Adding the footnotes keys.
1905
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1906
  foreach ($cdmBase_array as $cdmBase_element) {
1907
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1908
    if (is_array($annotations)) {
1909
      foreach ($annotations as $annotation) {
1910
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1911
      }
1912
    }
1913
  }
1914

    
1915
  return $footNoteKeys;
1916
}
1917

    
1918
// @WA Comment: should this not be a theme function?
1919
/**
1920
 *  Creates a CDM Dynabox.
1921
 * @param string $dynabox_id
1922
 *   a uninque name for tha dynabox, using a cdm entity uuid herefore is good pratice
1923
 * @param string $label
1924
 *   The clickable text to show.
1925
 * @param string $content_url
1926
 *   The cdm REST service request url wich will deliver the content to be shown
1927
 *   once the dynabox toggles open.
1928
 * @param string $theme
1929
 *   The theme to be used for rendering the cdm REST service reponse with is
1930
 *   returned from the $content_url.
1931
 * @param string $link_alt_text
1932
 *   The value for the alt attribute of the dynabox link.
1933
 * @param array $enclosingtags
1934
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
1935
 *   element itself, $enclosingtags[1] is the tag to be used for the
1936
 *   dynabox_content (optional)
1937
 * @param string $open_callback
1938
 *   optional javascript call back function to be triggered after toggeling the box to
1939
 *   the open state.
1940
 * @param string $close_callback
1941
 *   optional javascript call back function to be triggered after toggeling the box to
1942
 *   the closed state.
1943
 *
1944
 * @return string
1945
 *   Returns HTML for a dynabox.
1946
 */
1947
function cdm_dynabox($dynabox_id, $label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul'), $open_callback = 'function(){}', $close_callback = 'function(){}') {
1948
  $out = '';
1949

    
1950
  // check for plain class attribute string
1951
  $dynabox_id = preg_replace('/[^a-zA-Z0-9\-]/', '', $dynabox_id);
1952

    
1953
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
1954
  drupal_add_js("
1955
      jQuery(document).ready(
1956
		function() {
1957
			dynabox('". $dynabox_id ."',
1958
			{
1959
              open_callback: " . $open_callback .",
1960
              close_callback: " . $close_callback .",
1961
            }
1962
          );
1963
		}
1964
      );",
1965
      array(
1966
        'type'=>'inline',
1967
        'scope'=>'footer'
1968
      )
1969
    );
1970

    
1971
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
1972
  $out .= '<!-- ' . $content_url . ' -->';
1973
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
1974
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-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] . '>';
1975
  $out .= '</' . $enclosingtags[0] . '>';
1976
  return $out;
1977
}
1978

    
1979
/**
1980
 * Checks whether a feature has any description elements.
1981
 *
1982
 * @param mixed $featureNode
1983
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
1984
 *
1985
 * @see _mergeFeatureTreeDescriptions()
1986
 *
1987
 * @return bool
1988
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
1989
 *   contains at least one non empty TextData or at least one DescriptionElement
1990
 *   of an other type. A TextData element holding a multilanguageText or a
1991
 *   source reference is considered to be not empty.
1992
 */
1993
function hasFeatureNodeDescriptionElements($featureNode) {
1994

    
1995
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
1996
    foreach ($featureNode->descriptionElements as $descriptionElement) {
1997
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0]) || isset($descriptionElement->media[0]) ) {
1998
        return TRUE;
1999
      }
2000
    }
2001
  }
2002
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2003
    foreach ($featureNode->children as $child) {
2004
      if (hasFeatureNodeDescriptionElements($child)) {
2005
        return TRUE;
2006
      }
2007
    }
2008
  }
2009
  return FALSE;
2010
}
(6-6/13)