Project

General

Profile

Download (63.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
// $Id$
3

    
4
/*
5
 * @file
6
 * cdm_dataportal
7
 *
8
 * Copyright (C) 2007 EDIT
9
 * European Distributed Institute of Taxonomy
10
 * http://www.e-taxonomy.eu
11
 *
12
 * The contents of this file are subject to the Mozilla Public License Version 1.1
13
 * See http://www.mozilla.org/MPL/MPL-1.1.html for the full license terms.
14
 */
15

    
16
require_once('node_types.php');
17
require_once('settings.php');
18
require_once('help.php');
19

    
20
require_once('theme/cdm_dataportal.common.theme');
21
require_once('theme/cdm_dataportal.descriptions.theme');
22
require_once('theme/cdm_dataportal.media.theme');
23
require_once('theme/cdm_dataportal.occurrence.theme');
24
require_once('theme/cdm_dataportal.page.theme');
25
require_once('theme/cdm_dataportal.taxon.theme');
26
require_once('theme/cdm_dataportal.name.theme');
27
require_once('theme/cdm_dataportal.references.theme');
28

    
29
require_once('classes/footnotemanager.php');
30
require_once('classes/footnote.php');
31
require_once('classes/footnotekey.php');
32
require_once('classes/renderhints.php');
33

    
34
function _add_js_progressbar(){
35
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/jquery.progressbar/js/jquery.progressbar.js');
36
}
37

    
38
function _add_js_treeselector(){
39
  //drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
40
  drupal_add_js("
41
    if (Drupal.jsEnabled) {
42
      $(document).ready(function() {
43
          $('#cdm-taxonomictree-selector-form #edit-val').change(function () {
44
              $('#cdm-taxonomictree-selector-form').submit();
45
          });
46

    
47
      });
48
    }", 'inline');
49
}
50

    
51
function _add_js_openlayers_map(){
52

    
53
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/OpenLayers/OpenLayers.js', 'core', 'header');
54
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/openlayers_map.js');
55

    
56
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
57

    
58
  $baseLayers = variable_get('baselayers', array());
59
  if(!is_array($baseLayers) || count($baseLayers) == 0){
60
    $baseLayers = array('metacarta_vmap0' => 'Metacarta Vmap0', 'PREFERRED' => 'metacarta_vmap0');
61
  }
62
  $layerNames = '';
63
  foreach($baseLayers as $layerName => $layerLabel){
64
    if($layerName == 'PREFERRED'){
65
      $preferredLayer = $baseLayers['PREFERRED'];
66
    } else {
67
      $layerNames .= ($layerNames ? ', ': '') . "'$layerName'";
68
    }
69
  }
70

    
71
  if( isset($baseLayers['gmap']) || isset($baseLayers['gsat']) || isset($baseLayers['ghyb']) ){
72
    drupal_set_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>');
73
    drupal_set_html_head('<script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script>');
74
  }
75

    
76
  drupal_add_js("
77
        if (Drupal.jsEnabled) {
78
          $(document).ready(function() {
79
              $('#openlayers_map').cdm_openlayers_map('"
80
              .getEDITMapServiceURI()."', {
81
                legendPosition: 3,
82
                displayWidth: '" . variable_get('cdm_dataportal_geoservice_display_width', false) . "',
83
                boundingBox: '" . variable_get('cdm_dataportal_geoservice_bounding_box', false) . "',
84
                distributionOpacity: '" . variable_get('cdm_dataportal_geoservice_distributionOpacity', '0.5') . "',
85
                legendOpacity: '" . variable_get('cdm_dataportal_geoservice_legendOpacity', '0.5') . "',
86
                showLayerSwitcher: " . (variable_get('cdm_dataportal_geoservice_showLayerSwitcher', TRUE) ? 'true':'false') . ",
87
                baseLayerNames: [".$layerNames."],
88
                defaultBaseLayerName: '".$preferredLayer."',
89
            });
90
          });
91
        }", 'inline');
92

    
93
}
94

    
95
/**
96
 *
97
 * Enter description here ...
98
 * @param unknown_type $width
99
 * @param unknown_type $occurrenceQuery
100
 * @param unknown_type $distributionQuery
101
 * @param unknown_type $legendFormatQuery
102
 * @param unknown_type $map_caption
103
 */
104
function get_image_map($width,  $bounding_box=false, $occurrenceQuery = false, $distributionQuery = false, $legendFormatQuery = false, $map_caption = false ){
105

    
106
  $server = getEDITMapServiceURI();
107

    
108
  if(!$server){
109
    //warning message
110
    drupal_set_message('No \'Geoservice Access Point\' has been set so far. '
111
    . 'Please configure the variable \'Geoservice Access Point\' here '
112
    . l('CDM Dataportal Settings', 'admin/settings/cdm_dataportal/geo'), 'warning');
113
    //message to render
114
    return "<p>No geoservice specified</p>";
115
  }
116

    
117
  // additional query parameters as set in the data portal admin section
118
  $labels_on = variable_get('cdm_dataportal_geoservice_labels_on', 0);
119

    
120
  $query_string .= '&image=true&recalculate=false&legend=1&ms=' . $width
121
    . ($bounding_box ? '&bbox=' .  $bounding_box : '')
122
    . ($labels_on ? '&label=' .  $labels_on : '');
123

    
124
  if($map_caption){
125
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
126
  }
127

    
128
  if (getEDITMapServiceVersionNumber() >= 1.1) {
129

    
130
    // either occurrence or distribution - combined maps will be possible in future
131
    if ($occurrenceQuery){
132

    
133
      //fix $occurrenceQuery
134
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
135
      //$occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
136
      $occurrenceQuery .= '&l=tdwg4&as='; // will be replaced below // HACK!!!
137
      $query_string .= "&" .$occurrenceQuery;
138

    
139
    } else if($distributionQuery){
140

    
141
      $query_string .= "&" .$distributionQuery;
142

    
143
    }
144

    
145
    //  apply Plain Image map settings special for version >= 1.1
146
    /*
147
     * example : title=a:Naturalized++non-invasive
148
    * &ad=cyprusdivs:bdcode:a:5&as=a:ff9900,,0.1,&l=tdwg4
149
    * &ms=500&bbox=32,34,35,36&img=true&legend=1&mlp=3
150
    * &mc_s=Georgia,15,blue&mc=&recalculate=false
151
    *
152
    * http://edit.br.fgov.be/edit_wp5/v1/rest_gen.php?
153
    * l=background_gis:b,cyprusdivs&ad=cyprusdivs%3Abdcode%3Aa%3A8%2C4
154
    * &as=a%3A339966%2C%2C0.1%2C|b:0000ff,,
155
    * &bbox=32%2C34%2C35%2C36&img=true&legend=1&mc=&mc_s=Georgia%2C15%2Cblue
156
    * &mlp=3&ms=500&recalculate=false&title=a%3Aindigenous
157
    */
158

    
159
    $map_service_script_name = "rest_gen.php";
160

    
161
    $bgcolor_areaStyleId= "y";
162
    $baselayer_areaStyleId= "z";
163
    $bgcolor_layer='';
164
    $additional_area_styles = array();
165

    
166
    // background color:
167
    if(variable_get('map_bg_color', '')){
168
      $bgcolor_layer = "background_gis:".$bgcolor_areaStyleId;
169
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
170
    }
171

    
172
    //TODO HACK to replace the default base layer which currently is tdwg4 !!! only needed for distribution maps
173
    if(strpos($query_string, "?l=") !== FALSE){
174
      $layer_param_token = "?l=";
175
    } else {
176
      $layer_param_token = "&l=";
177
    }
178
    if(strpos($query_string, "?as=") !== FALSE){
179
      $areystyle_param_token = "?as=";
180
    } else {
181
      $areystyle_param_token = "&as=";
182
    }
183
    if(variable_get('map_base_layer', '')){
184
      $query_string = str_replace($layer_param_token."tdwg4", "$layer_param_token".variable_get('map_base_layer', ''). ":" . $baselayer_areaStyleId, $query_string);
185
    } else {
186
      $query_string = str_replace($layer_param_token."tdwg4", $layer_param_token."tdwg4:".$baselayer_areaStyleId . ",", $query_string);
187
    }
188

    
189
    if($bgcolor_layer){
190
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
191
    }
192

    
193
    if(variable_get('map_base_layer_style', '')){
194
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
195
    }
196

    
197
    foreach ($additional_area_styles as $as) {
198
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
199
    }
200

    
201
  } else {
202
    // pre 1.1. version of map service
203
    if ($occurrenceQuery){
204

    
205
      $map_service_script_name = "point.php";
206

    
207
      //fix $occurrenceQuery
208
      $occurrenceQuery = str_replace("&image=false", "", $occurrenceQuery);
209
      //$occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
210
      $occurrenceQuery .= '&l=v:e_w_0';
211
      $query_string .= "&" .$occurrenceQuery;
212

    
213
    } else if($distributionQuery){
214

    
215
      $query_string .= "&" .$distributionQuery;
216
      $map_service_script_name = "areas.php";
217

    
218
    }
219

    
220
  }
221

    
222
  $mapUri = url("$server/$map_service_script_name?$query_string");
223
  $out = '<img class="distribution_map" src="' . $mapUri . '" alt="Map" />';
224
  // showing map caption
225
  if($map_caption){
226
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />'; //FIXME: replace <br> by according css style
227
    $out .= '</div>';
228
  }
229

    
230
  return $out;
231

    
232

    
233
}
234

    
235
/**
236
 *
237
 * Enter description here ...
238
 * @param unknown_type $width
239
 * @param unknown_type $occurrenceQuery
240
 * @param unknown_type $distributionQuery
241
 * @param unknown_type $legendFormatQuery
242
 * @param unknown_type $map_caption
243
 */
244
function get_openlayers_map($width, $bounding_box=false, $occurrenceQuery = false, $distributionQuery = false, $legendFormatQuery = false, $map_caption = false ){
245

    
246
  _add_js_openlayers_map();
247

    
248
  $out = '<div id="openlayers">';
249
  $out .= '<div id="openlayers_map" class="smallmap"';
250
  $out .= ' style="width: ' . $width . 'px; height:'.( $width / 2).'px"';
251

    
252
  // additional query parameters as set in the data portal admin section
253
  $labels_on = variable_get('cdm_dataportal_geoservice_labels_on', 0);
254

    
255
  $openlayers_map_query_string .= '&img=false&ms=' . $width
256
    . ($bounding_box ? '&bbox=' .  $bounding_box : '')
257
    . ($labels_on ? '&label=' .  $labels_on : '');
258

    
259
  if($occurrenceQuery){
260
    //fix $occurrenceQuery
261
    $occurrenceQuery .= '&bbox=-180,-90,180,90';
262
    $occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
263
    //$occurrenceQuery .= '&l=v:e_w_0';
264
    $occurrenceQuery .= '&legend=0'; //TODO add to cdm service?
265

    
266
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
267
  }
268

    
269
  if($distributionQuery){
270
    $out .= ' distributionQuery="' . $distributionQuery . '&' . $openlayers_map_query_string . '"';
271
  }
272

    
273
  if($legendFormatQuery){
274
    $out .= ' legendFormatQuery="'.$legendFormatQuery.'"';
275
  }
276

    
277
  $out .= '></div></div>';
278

    
279
  // showing map caption
280
  if($map_caption){
281
    $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />'; //FIXME: replace <br> by according css style
282
    $out .= '</div>';
283
  }
284
  return $out;
285
}
286

    
287
/* ====================== hook implementations ====================== */
288

    
289

    
290
/**
291
 * Implementation of hook_perm()
292
 *
293
 * Valid permissions for this module
294
 * @return array An array of valid permissions for the portfolio module
295
 */
296
function cdm_dataportal_perm() {
297
  return array(
298
      'administer cdm_dataportal',
299
      'cdm_dataportal view notes',
300
  //TODO which else permission are required? -> check the WP6 requirements document
301
  );
302
}
303

    
304

    
305
/**
306
 * Implementation of hook_menu()
307
 */
308
function cdm_dataportal_menu($may_cache) {
309
  $items = array();
310

    
311
  cdm_dataportal_menu_admin($may_cache, $items);
312
  cdm_dataportal_menu_help($may_cache, $items);
313

    
314
  if ($may_cache) {
315

    
316
   $items[] = array(
317
      'path' => 'cdm_dataportal/names',
318
      'callback' => 'cdm_dataportal_view_names',
319
      'access' => true,
320
      'type' => MENU_CALLBACK,
321
    );
322
    // optional callback arguments: page
323

    
324
    $items[] = array(
325
      'path' => 'cdm_dataportal/taxon',
326
      'callback' => 'cdm_dataportal_taxon_page_view',
327
      'access' => true,
328
      'type' => MENU_CALLBACK,
329
    // expected callback arguments: uuid
330
    );
331

    
332
    $items[] = array(
333
      'path' => 'cdm_dataportal/name',
334
      'callback' => 'cdm_dataportal_name_page_view',
335
      'access' => true,
336
      'type' => MENU_CALLBACK,
337
    // expected callback arguments: uuid
338
    );
339

    
340
    $items[] = array(
341
      'path' => 'cdm_dataportal/reference',
342
      'callback' => 'cdm_dataportal_view_reference',
343
      'access' => true,
344
      'type' => MENU_CALLBACK,
345
    // expected callback arguments: uuid
346
    );
347

    
348
    $items[] = array(
349
      'path' => 'cdm_dataportal/reference/list',
350
      'callback' => 'cdm_dataportal_view_reference_list',
351
      'access' => true,
352
      'type' => MENU_CALLBACK,
353
    // expected callback arguments: uuid
354
    );
355

    
356
    $items[] = array(
357
      'path' => 'cdm_dataportal/media',
358
      'callback' => 'cdm_dataportal_view_media',
359
      'access' => true,
360
      'type' => MENU_CALLBACK,
361
    // expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
362
    );
363

    
364
    $items[] = array(
365
      'path' => 'cdm_dataportal/polytomousKey',
366
      'callback' => 'cdm_dataportal_view_polytomousKey',
367
      'access' => true,
368
      'type' => MENU_CALLBACK,
369
    // expected callback arguments: polytomousKey->uuid
370
    );
371

    
372
    $items[] = array(
373
      'path' => 'cdm_dataportal/search',
374
      'callback' => 'cdm_dataportal_view_search_advanced',
375
      'access' => true,
376
      'type' => MENU_CALLBACK,
377
    );
378

    
379
    $items[] = array(
380
      'path' => 'cdm_dataportal/search/taxon',
381
      'callback' => 'cdm_dataportal_view_search_taxon',
382
      'access' => true,
383
      'type' => MENU_CALLBACK,
384
    );
385

    
386
    $items[] = array(
387
      'path' => 'cdm/xml2json',
388
      'callback' => 'cdm_view_xml2json',
389
      'access' => true,
390
      'type' => MENU_CALLBACK,
391
    );
392

    
393
  }elseif (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
394
    //user configuration of cdm_dataportal
395
    $items[] = array('path' => 'user/'.$uid.'/cdm_dataportal',
396
        'title' => t('cdm_dataportal'),
397
        'access' => TRUE,
398
        'callback' => 'drupal_get_form',
399
        'callback arguments' => array('cdm_dataportal_user_form'),
400
        'type' => MENU_LOCAL_TASK,
401
        'weight' => 10,
402
      );
403
  } else {
404
    // may not cache
405
    // --- local tasks for Taxon
406
    $items[] = array(
407
      'path' => 'cdm_dataportal/name/'.arg(2),
408
    //'callback' => 'cdm_dataportal_view_name',
409
      'callback' => 'cdm_dataportal_name_page_view',
410
      'callback arguments' => array(arg(2), arg(3), arg(4)),
411
      'access' => true,
412
      'type' => MENU_CALLBACK,
413
    );
414

    
415
    if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
416

    
417
      $items[] = array(
418
      'path' => 'cdm_dataportal/taxon/'.arg(2),
419
      'title' => theme('cdm_taxonpage_tab', 'General'),
420
      'callback' => 'cdm_dataportal_taxon_page_view',
421
      'access' => true,
422
      'type' => MENU_CALLBACK,
423
      'weight' => 1,
424
      'callback arguments' => array(arg(2), "description")
425
      // expected callback arguments: name_uuid
426
      );
427

    
428
      $items[] = array(
429
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/all',
430
      'title' => theme('cdm_taxonpage_tab', 'General'),
431
      'callback' => 'cdm_dataportal_taxon_page_view',
432
      'access' => true,
433
      'type' => MENU_CALLBACK,
434
      'weight' => 2,
435
      'callback arguments' => array(arg(2), "all")
436
      // expected callback arguments: name_uuid
437
      );
438

    
439
      $items[] = array(
440
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/description',
441
      'title' => theme('cdm_taxonpage_tab', 'General'),
442
      'callback' => 'cdm_dataportal_taxon_page_view',
443
      'access' => true,
444
      'type' => MENU_DEFAULT_LOCAL_TASK,
445
      'weight' => 2,
446
      'callback arguments' => array(arg(2), "description")
447
      // expected callback arguments: name_uuid
448
      );
449

    
450
      $items[] = array(
451
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
452
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
453
      'callback' => 'cdm_dataportal_taxon_page_view',
454
      'access' => true,
455
      'type' => MENU_LOCAL_TASK,
456
      'weight' => 4,
457
      'callback arguments' => array(arg(2), "synonymy", arg(4))
458
      // expected callback arguments: name_uuid
459
      );
460
      $items[] = array(
461
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
462
      'title' => theme('cdm_taxonpage_tab', 'Images'),
463
      'callback' => 'cdm_dataportal_taxon_page_view',
464
      'access' => true,
465
      'type' => MENU_LOCAL_TASK,
466
      'weight' => 5,
467
      'callback arguments' => array(arg(2), "images")
468
      // expected callback arguments: name_uuid
469
      );
470

    
471
     $items[] = array(
472
     'path' => 'cdm_dataportal/taxon/'.arg(2).'/specimens',
473
     'title' => theme('cdm_taxonpage_tab', 'Specimens'),
474
     'callback' => 'cdm_dataportal_taxon_page_view',
475
     'access' => true,
476
     'type' => MENU_LOCAL_TASK,
477
     'weight' => 6,
478
     'callback arguments' => array(arg(2), "specimens")
479
     // expected callback arguments: name_uuid
480
     );
481

    
482
     $items[] = array(
483
     'path' => 'cdm_dataportal/taxon/'.arg(2).'/keys',
484
     'title' => theme('cdm_taxonpage_tab', 'Keys'),
485
     'callback' => 'cdm_dataportal_taxon_page_view',
486
     'access' => true,
487
     'type' => MENU_LOCAL_TASK,
488
     'weight' => 6,
489
     'callback arguments' => array(arg(2), "keys")
490
     // expected callback arguments: name_uuid
491
     );
492
    }
493
  }
494

    
495
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
496
  //drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
497
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
498

    
499
  return $items;
500

    
501
}
502
/**
503
 * The function generate form for own user cdm dataportal configurations
504
 */
505
function cdm_dataportal_user_form() {
506

    
507
  global $user;
508
    $checkbox_value = 'cdm_dataportal_' .$user->uid . '_default_tab_active';
509

    
510
  $form['check'] = array
511
    (
512
    '#type'            => 'checkbox',
513
    '#title'         => t('Activate user default configuration'),
514
    '#default_value'   => variable_get($checkbox_value, 0),
515
    '#description' => t('Check this if you want configure your own default tab from the below menu.')
516
    );
517

    
518
  $form['cdm_dataportal_user_form'] =  array(
519
      '#type'          => 'select',
520
      '#title'         => t('Default tab to display'),
521
      '#default_value' => get_default_taxon_tab(true),
522
      '#options'       => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
523
      '#description'   => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
524
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
525
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
526
  );
527

    
528
  $form['submit'] = array(
529
    '#type' => 'submit',
530
    '#value' => t('Submit')
531
  );
532

    
533
  return $form;
534
}
535

    
536
/**
537
 * The function submit the user cdm dataportal configurations
538
 * @param unknown_type $form
539
 * @param unknown_type $form_values
540
 */
541
function cdm_dataportal_user_form_submit($form, $form_values) {
542
  global $user;
543
  $msg_type = 'status';
544
  $username = $user->name;
545
  $variable_to_use = 'cdm_dataportal_' .$user->uid . '_default_tab';
546

    
547
  //if is the right user the variables are setted
548
  if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid) && $user->uid==$uid){
549
    $variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
550
    variable_set($variable_to_use . '_active', $form_values['check']);
551
    variable_set($variable_to_use, $form_values['cdm_dataportal_user_form']);
552
    if ($form_values['check']){
553
      drupal_set_message('The user default tab will be used for the next taxon site visit.');
554
      drupal_set_message('The user default tab have been changed to: '
555
            . $variable[variable_get($variable_to_use, 0)]
556
            . ' for the user ' . $username, $msg_type);
557
    }else{
558
      drupal_set_message('The user default tab wont be used for the next taxon site, check the box if you want to use the user default configuration.');
559
    }
560
  //problem with the user id => variables wont be saved
561
  }else{
562
    $msg_type = 'warning';
563
    drupal_set_message('Default tab have not been saved due to user id problems', $msg_type);
564
  }
565
}
566

    
567
/**
568
 * Implementation of hook_block()
569
 *
570
 * Provides the following blocks:
571
 *  0: list of links useful during development
572
 *
573
 * @param String $op
574
 * @param int $delta
575
 */
576
function cdm_dataportal_block($op='list', $delta=0) {
577
  // listing of blocks, such as on the admin/block page
578
  if ($op == "list") {
579
    //$block[0]["info"] = t("CDM DataPortal DevLinks");
580
    //$block[1]["info"] = t("CDM DataPortal Credits");
581
    $block[2]["info"] = t("CDM Search Taxa");
582
    //$block[3]["info"] = t("CDM Filters");
583
    $block[4]["info"] = t("CDM Dataportal Print");
584
    $block["keys"]["info"] = t("CDM identification keys");
585
    $block["fundedByEDIT"]["info"] = t('Funded by EDIT');
586
    return $block;
587
  }
588
  else if ($op == 'view') {
589
    switch($delta){
590
      //			case 1:
591
      //				$block['subject'] = t('Credits');
592
      //				$block['content'] = theme('cdm_credits');
593
      //				return $block;
594
      case 2:
595
        $block['subject'] = t('Search taxa');
596
        $block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
597
        if (variable_get('cdm_dataportal_show_advanced_search', 1)){
598
            $block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
599
        }
600
        return $block;
601
      case 4:
602
        $block['subject'] = t('<none>');
603
        $block['content'] = theme('cdm_print_button');;
604
        return $block;
605
      case "keys":
606
        $block['subject'] = t('Identification Keys');
607
        $block['content'] = theme('cdm_block_IdentificationKeys');
608
        return $block;
609
      case "fundedByEDIT":
610
        $text = '<none>'; //t('Funded by EDIT');
611
        $block['subject'] = $text;
612
        $img_tag = '<img src="' . drupal_get_path('module', 'cdm_dataportal').'/images/funded_by_EDIT.png' . '" alt="'.$text.'"/>';
613
        $block['content'] = l($img_tag, "http://www.e-taxonomy.eu/", array("target"=>"EDIT"), NULL, NULL, TRUE, TRUE);
614
        return $block;
615
    }
616
  }
617
}
618

    
619

    
620

    
621
/*
622
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
623
 $_SESSION['cdm'] = null;
624
 if(is_string($cdm_ws_uri_update)){
625
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
626
 }
627
 }
628

    
629
 function cdm_dataportal_session_validate(){
630

    
631
 if(!isset($_SESSION['cdm']['ws_uri'])){
632
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
633
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
634
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
635
 }
636
 }
637
 */
638

    
639
function cdm_dataportal_search_taxon_form($advancedForm = false){
640
  global $theme_key;
641

    
642
  $tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
643
  $selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
644

    
645
  if(isset($_SESSION['cdm']['search']) && !$preset_UseDefaults) {
646
    $preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
647
  }
648

    
649
  $url = 'cdm_dataportal/search/taxon';
650
  $form['#method'] = 'get';
651
  $form['#process'] = array('cdm_dataportal_search_process' => array());
652
  $form['#action'] = url($url, NULL, NULL, true);
653

    
654
  if(!$advancedForm) {
655
  $form['query'] = array(
656
    '#delta' => 0,
657
    '#type' => 'textfield',
658
    '#size' => 20,
659
    '#attributes' => array('title' => t('Enter the name or part of a name you wish to search for. The asterisk  character * can always be used as wildcard')),
660
    '#value' => $preset_query,
661
  );
662
  }
663
  //AT RBG KEW - 14/11/2011 Added to extend the text box in the Advanced form only
664
  else {
665
       $form['query'] = array(
666
      '#delta' => 0,
667
      '#type' => 'textfield',
668
      '#size' => 68,
669
      '#attributes' => array('title' => t('Enter the name or part of a name you wish to search for. The asterisk  character * can always be used as wildcard')),
670
      '#value' => $preset_query,
671
    );
672
  }
673

    
674
  $form['search'] = array(
675
      '#delta' => 1,
676
      '#tree' => true,
677
  //'#type' => $advancedForm ? 'fieldset': 'hidden',
678
      '#title' => t('Options')
679
  );
680

    
681
  $form['search']['tree'] = array(
682
    '#delta' => -1,
683
    '#type' => 'hidden',
684
    '#value' => get_taxonomictree_uuid_selected()
685
  );
686

    
687

    
688
  // clean URL get forms breaks if we don't give it a 'q'.
689
  if (!(bool)variable_get('clean_url', '0')) {
690
    $form['search']['q'] = array(
691
      '#delta' => -1,
692
      '#type' => 'hidden',
693
      '#value' => $url,
694
      '#name' => 'q',
695
    );
696
  }
697

    
698
  $form['search']['pageSize'] = array(
699
      '#delta' => -1,
700
      '#type' => 'hidden',
701
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
702
  );
703

    
704
  $form['search']['pageNumber'] = array(
705
      '#delta' => -1,
706
      '#type' => 'hidden',
707
      '#value' => 0
708
  );
709

    
710
  if($advancedForm){
711

    
712
    // get presets from settings
713
    $preset_doTaxa = variable_get('cdm_search_doTaxa', 1);
714
    $preset_doSynonyms = variable_get('cdm_search_doSynonyms', 1);
715
    $preset_doTaxaByCommonNames = variable_get('cdm_search_doTaxaByCommonNames', 0);
716
    $preset_doMisappliedNames = variable_get('cdm_search_doMisappliedNames', 1);
717
    $preset_UseDefaults = variable_get('cdm_search_use_default_values', 1);
718

    
719
    // overwrite presets by user choice stored in session
720
    if(isset($_SESSION['cdm']['search']) && !$preset_UseDefaults) {
721
      $preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
722
      $preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
723
      $preset_doMisappliedNames = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
724
      $preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
725
    }
726
    // general search parameters
727

    
728
    $form['search']['doTaxa'] = array(
729
      '#delta' => 2,
730
      '#type' => 'checkbox',
731
      '#title' => t('Search for accepted taxa'),
732
      '#value' => $preset_doTaxa
733
    );
734
    $form['search']['doSynonyms'] = array(
735
      '#delta' => 3,
736
      '#type' => 'checkbox',
737
      '#title' => t('Search for synonyms'),
738
      '#value' => $preset_doSynonyms
739
    );
740
    $form['search']['doMisappliedNames'] = array(
741
          '#delta' => 4,
742
          '#type' => 'checkbox',
743
          '#title' => t('Search for misapplied names'),
744
          '#value' => $preset_doMisappliedNames
745
    );
746
    $form['search']['doTaxaByCommonNames'] = array(
747
      '#delta' => 5,
748
      '#type' => 'checkbox',
749
      '#title' => t('Search for common names'),
750
      '#value' => $preset_doTaxaByCommonNames
751
    );
752

    
753
    // Geographic Range
754
    $form['search']['geographic_range'] = array(
755
      '#type' => 'fieldset',
756
      '#delta' => 5,
757
      '#tree' => true,
758
      '#title' => t('Geographic range'),
759
    );
760

    
761
  $form['search']['geographic_range']['tdwg_level_select'] = array(
762
      '#type' => 'radios',
763
      '#title' => t('Select a TDWG distribution level and code'),
764
       '#default_value' => $tdwg_level_select,
765
      '#options' => array(
766
        t('TDWG level-1, i.e. a continent'),
767
        t('TDWG level-2'),
768
        t('TDWG level-3, i.e. a country'),
769
        t('TDWG level-4')
770
      )
771
    );
772
    $tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
773
    $tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
774
    $tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
775
  $tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
776

    
777
    $tdwg_js = '';
778
    foreach($tdwg as $key=>$tdwg_level){
779
      $tdwgOptions = array();
780
      $tdwgOptionsSelected = array();
781
      foreach($tdwg_level as $area){
782
        $representation = $area->representations[0];
783
        $tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
784
        if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
785
          $tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
786
        }
787
      }
788
      asort($tdwgOptions);
789
      $form['search']['geographic_range']['tdwg_level_'.$key] = array(
790
        '#type' => 'select',
791
        '#title'         => t('TDWG level').' '.$key,
792
        '#default_value' => $tdwgOptionsSelected,
793
        '#multiple' => TRUE,
794
        '#options' => $tdwgOptions
795
      );
796
      $tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
797
    }
798

    
799
    drupal_add_js(
800
    "$(document).ready(function(){
801

    
802
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change(
803
        function(event){
804
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
805
          var i;
806
          for(i = 0; i < 4; i++){
807
            if(selectId == i){
808
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
809
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
810
            } else {
811
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
812
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
813
            }
814
          }
815
        }
816
      );
817

    
818
      $tdwg_js
819
    });",
820
    'inline');
821

    
822
  } else {
823
    $preset_doTaxa = variable_get('cdm_search_doTaxa', 1);
824
    $preset_doSynonyms = variable_get('cdm_search_doSynonyms', 1);
825
    $preset_doTaxaByCommonNames = variable_get('cdm_search_doTaxaByCommonNames', 0);
826
    $preset_doMisappliedNames = variable_get('cdm_search_doMisappliedNames', 1);
827
    $preset_UseDefaults = variable_get('cdm_search_use_default_values', 1);
828

    
829
    // overwrite presets by user choice stored in session
830
    if(isset($_SESSION['cdm']['search']) && !$preset_UseDefaults) {
831
      $preset_doMisappliedNames = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
832
    }
833

    
834
    $form['search']['doTaxa'] = array(
835
        '#delta' => -2,
836
        '#type' => 'hidden',
837
        '#value' => $preset_doTaxa
838
    );
839
    $form['search']['doSynonyms'] = array(
840
        '#delta' => -3,
841
        '#type' => 'hidden',
842
        '#value' => $preset_doSynonyms
843
    );
844
    $form['search']['doMisappliedNames'] = array(
845
        '#delta' => -4,
846
        '#type' => 'checkbox',
847
        '#title' => t('Misapplied names'),
848
        '#value' => $preset_doMisappliedNames
849
    );
850
    $form['search']['doTaxaByCommonNames'] = array(
851
        '#delta' => -5,
852
        '#type' => 'hidden',
853
        '#value' => $preset_doTaxaByCommonNames
854
    );
855
  }
856

    
857
  $form['submit'] = array(
858
    '#delta' => 9,
859
    '#type' => 'submit',
860
    '#name' => '',
861
    '#value' => t('Search')
862
  );
863

    
864
  return $form;
865
}
866

    
867
function cdm_dataportal_search_taxon_form_advanced(){
868
  return cdm_dataportal_search_taxon_form(true);
869
}
870

    
871
function cdm_taxonomictree_selector(){
872
  _add_js_treeselector();
873

    
874
  $out = drupal_get_form('cdm_taxonomictree_selector_form');
875

    
876
  return $out;
877
}
878

    
879

    
880
function cdm_taxonomictree_selector_form(){
881

    
882
  $url = url('cdm_api/setvalue/session', null);
883
  $form['#action'] = $url;
884

    
885
  $form['var'] = array(
886
        '#delta' => -3,
887
        '#type' => 'hidden',
888
        '#value' => '[cdm][taxonomictree_uuid]'
889
        );
890

    
891
        $form['destination'] = array(
892
     '#delta' => -3,
893
     '#type' => 'hidden',
894
     '#value' => substr(drupal_get_destination(), strlen('destination='))
895
        );
896

    
897
        $form['val'] = array(
898
      '#type' => 'select',
899
      '#title'         => t('Available classifications'),
900
      '#default_value' => get_taxonomictree_uuid_selected(),
901
      '#options' => cdm_get_taxontrees_as_options()
902
        );
903

    
904
        return $form;
905

    
906
}
907

    
908
/**
909
 * Implementation #process method call, see form_builder()
910
 * <p>
911
 * Removes Drupal internal form elements from query
912
 * @param $form
913
 * @return unknown_type
914
 */
915
function cdm_dataportal_search_process($form) {
916
  unset($form['form_id']);
917
  unset($form['form_token']);
918
  return $form;
919
}
920

    
921
/**
922
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
923
 * returns the processed request parameters submitted by the search form.
924
 */
925
function cdm_dataportal_search_form_request(){
926

    
927

    
928
  $form_params = array();
929
  array_deep_copy($_REQUEST['search'], $form_params);
930
  $form_params['query'] =  trim($_REQUEST['query']);
931

    
932
  // split of  geographic range
933
  if(isset($_REQUEST['search']['geographic_range'])){
934
    $geographicRange = $_REQUEST['search']['geographic_range'];
935
    // remove
936
    unset($form_params['geographic_range']);
937
  }
938

    
939
  // add geographic range
940
  if($geographicRange){
941
    $form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
942
    for($i = 1; $i < 5; $i++){
943
      if(isset($geographicRange['tdwg_level_'.$i])){
944
        $form_params['area'] = $geographicRange['tdwg_level_'.$i];
945
      }
946
    }
947
  }
948

    
949
  // store in session
950
  $_SESSION['cdm']['search'] = $form_params;
951

    
952
  return $form_params;
953
}
954

    
955

    
956
/* UNREACHABLE since action of form directly links to view
957
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
958

    
959
 $_SESSION['cdm']['search'] = $form_values;
960
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
961
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
962
 //$paramstr = compose_url_prameterstr($form_values);
963
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
964
 }
965
 */
966
/* ====================== menu callback functions ====================== */
967

    
968

    
969

    
970
function cdm_dataportal_form_alter($form_id, &$form) {
971

    
972
  static $comment_node_disabled =  0;
973
  static $comment_node_read_only =  1;
974
  static $comment_node_read_write =  2;
975

    
976

    
977
  if ($form_id == 'node_type_form'
978
  && isset($form['identity']['type'])
979
  && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
980
  ) {
981
    $form['workflow']['comment'] = array(
982
      '#type' => 'radios',
983
      '#title' => t('Default comment setting'),
984
      '#default_value' => variable_get('comment_'. $form['#node_type']->type, $comment_node_disabled),
985
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
986
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
987
    );
988
  }
989
}
990

    
991

    
992

    
993
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed, $form_description = ''){
994
//TODO move into settings.php
995
  $form[$form_name] = array(
996
    '#type' => 'fieldset',
997
    '#title' => t($form_tittle),
998
    '#collapsible' => TRUE,
999
    '#collapsed' => $collapsed,
1000
    '#tree' => true,
1001
  '#description' => t($form_description),
1002
  );
1003

    
1004
  $default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
1005
  $gallery_settings = variable_get($form_name, $default_values);
1006
  //$test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1007

    
1008
  if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
1009
    /* TODO: why cdm_dataportal_search_items_on_page does not save the value on $test???
1010
     $form[$form_name]['cdm_dataportal_search_items_on_page'] = array(
1011
     '#type' => 'textfield',
1012
     '#title' => t('Search Page Size'),
1013
     '#default_value' => $test,
1014
     '#description' => t('Number of Names to display per page in search results.')
1015
     );
1016
     */
1017
    $form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
1018
      '#type' => 'checkbox',
1019
      '#title' => t('Show media thumbnails for accepted taxa'),
1020
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
1021
    );
1022

    
1023
    $form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
1024
      '#type' => 'checkbox',
1025
      '#title' => t('Show media thumbnails for synonyms'),
1026
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
1027
      '#description' => t('')
1028
    );
1029
  }
1030

    
1031
  //$showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
1032
  $form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
1033
    '#type' => 'checkbox',
1034
    '#title' => t('Show captions under thumbnails'),
1035
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
1036
    '#description' => t('')
1037
  );
1038

    
1039
  $form[$form_name]['cdm_dataportal_media_maxextend'] = array(
1040
    '#type' => 'textfield',
1041
    '#title' => t('Thumbnail size'),
1042
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
1043
    '#description' => t('Select the size of each individual thumbnail.')
1044
  );
1045

    
1046
  if($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME){
1047
     $form[$form_name]['cdm_dataportal_media_cols'] = array(
1048
        '#type' => 'textfield',
1049
        '#title' => t('Number of columns'),
1050
        '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
1051
        '#description' => t('Group the thumbnails in columns: select how many columns should the gallery display.')
1052
     );
1053
  }
1054

    
1055
  if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
1056
    $form[$form_name]['cdm_dataportal_media_maxRows'] = array(
1057
      '#type' => 'textfield',
1058
      '#title' => t('Maximum number of rows'),
1059
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
1060
      '#description' => t('You can group the thumbnails in rows, select in how many rows should be the thumbnails grouped.<br>
1061
                           <b>Note:</b> If you want an unlimited number of rows please set to 0')
1062
    );
1063
  }
1064

    
1065
  return $form;
1066
}
1067

    
1068

    
1069
/**
1070
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
1071
 *
1072
 * TODO: parameters are still preliminar
1073
 * @param String $page page number to diplay defaults to page 1
1074
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
1075
 */
1076
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
1077

    
1078
  $request_params  = array(
1079
    'q' => $beginsWith,
1080
  //'sec' = '',
1081
  //'higherTaxa' => getFiters(),
1082
  // 'matchAnywhere' => false, // default is false
1083
    'page' => $page,
1084
    'onlyAccepted' => $onlyAccepted,
1085
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
1086

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

    
1098
function cdm_dataportal_view_reference($uuid, $arg2 = null){
1099
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1100
  return theme('cdm_reference_page', $reference);
1101
}
1102

    
1103
function cdm_dataportal_view_reference_list($pageNumber){
1104
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1105
  return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
1106
}
1107

    
1108
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
1109
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1110
  return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
1111
}
1112

    
1113
function _load_taxonBase(&$taxonBase){
1114
  if(isset($taxonBase->uuid)){
1115
      $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1116
      $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1117
      $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1118
    }
1119
}
1120

    
1121
/**
1122
 * similar to the variable_get() function of Drupal, except of thst this function
1123
 * is able to handle arrays correctly. This function is especially useful
1124
 * when dealing with collections of setting form elemens (#tree = true)
1125
 *
1126
 * @param String $variableKey
1127
 * @param String $defaultValueString a sting as for example derived from a CONSTANT
1128
 * @return mixed, usually an array
1129
 */
1130
function mixed_variable_get($variableKey, $defaultValueString){
1131
    $systemDefaults = unserialize($defaultValueString);
1132
    $storedSettings = variable_get($variableKey, array());
1133
    if(is_array($storedSettings)){
1134
      $settings =  array_merge($systemDefaults, $storedSettings);
1135
    } else {
1136
      $settings = $systemDefaults;
1137
    }
1138
    return $settings;
1139
}
1140

    
1141
/**
1142
 * Loads the subgraph of the given PolytomousKeyNode recursively from the cdm REST service.
1143
 * @param PolytomousKeyNode $polytomousKeyNode passed by reference
1144
 * @return nothing
1145
 */
1146
function _load_polytomousKeySubGraph(&$polytomousKeyNode){
1147

    
1148
  if(!$polytomousKeyNode){
1149
    return;
1150
  }
1151
  if($polytomousKeyNode->class != "PolytomousKeyNode"){
1152
    drupal_set_message("_load_polytomousKeySubGraph() invalid type given.", "error");
1153
    return;
1154
  }
1155
  if(!is_uuid($polytomousKeyNode->uuid)){
1156
    drupal_set_message("_load_polytomousKeySubGraph() invalid type given.", "error");
1157
    return;
1158
  }
1159

    
1160
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1161

    
1162
  if(!$polytomousKeyNode){
1163
    //drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1164
    return;
1165
  }
1166

    
1167
  // load children
1168
  foreach($polytomousKeyNode->children as &$childNode){
1169
    _load_polytomousKeySubGraph($childNode);
1170
  }
1171

    
1172
  // load subkey
1173
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1174

    
1175
  // load taxon
1176
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1177
  _load_taxonBase($polytomousKeyNode->taxon);
1178
  return;
1179
}
1180

    
1181
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid){
1182
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1183

    
1184
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "sources"));
1185
  if(is_array($sourcePager->records)){
1186
    $polytomousKey->sources =  $sourcePager->records;
1187
    //$polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "sources"));
1188
  }
1189

    
1190
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "annotations"));
1191
  if(is_array($annotationPager->records)){
1192
    $polytomousKey->annotations = $annotationPager->records;
1193
  }
1194

    
1195
  _load_polytomousKeySubGraph($polytomousKey->root);
1196
  return theme('cdm_polytomousKey_page', $polytomousKey);
1197
}
1198

    
1199
/**
1200
 * The taxon page gives detailed information on a taxon, it shows:
1201
 *  - Taxon name
1202
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1203
 *    heterotypic and finally followed by misapplied names.
1204
 *    The list is ordered historically.
1205
 *  - All description associated with the taxon.
1206
 *
1207
 * @param $uuid
1208
 * @param $chapter name of the part to display,
1209
 *         valid values are: 'description', 'images', 'synonymy', 'specimens', 'all'
1210
 * @return unknown_type
1211
 */
1212
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = null){
1213
  // display the page for the taxon defined by $uuid
1214
  set_last_taxon_page_tab(arg(3));
1215
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1216
  return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
1217
}
1218

    
1219
/**
1220
 * @param $uuid
1221
 * @param $chapter name of the part to display,
1222
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1223
 * @return unknown_type
1224
 */
1225
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = null){
1226
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1227
  if(!$taxon){
1228
    drupal_set_title(t('Taxon does not exist'));
1229
    return false;
1230
  }
1231

    
1232
  $taxonpage->title = theme('cdm_taxon_page_title', $taxon, $uuid, $synonym_uuid);
1233

    
1234
  // check if the taxon id contained in the currently selected tree
1235
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1236
  $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1237
  if(!$taxon_in_current_tree){
1238
    if(count($taxon_nodes) == 0){
1239
      drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained any classification.'
1240
      ,'warning');
1241
    } else {
1242
      $trees = '';
1243
      foreach($taxon_nodes as $node){
1244
        $trees .= ($trees?', ':'').'<strong>'.$node->classification->titleCache.'</strong>';
1245

    
1246
      }
1247
      drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained in the currently chosen classification, but in '
1248
      .(count($taxon_nodes) > 1? ' one of these: ' : ' this one: ') . $trees
1249
      , 'warning');
1250
    }
1251
  }
1252

    
1253
  // render the taxon page
1254
  $taxonpage->content = theme('cdm_taxon_page', $taxon, $chapter);
1255

    
1256
  return $taxonpage;
1257
}
1258

    
1259
/**
1260
 * The function returns a name page as a drupal node ready to be renderized by drupal.
1261
 * The node page show the taxon name title and the list of taxon related with such taxon
1262
 * name on the tree already in used.
1263
 * @param $taxon_name_uuid A taxon name uuid
1264
 * @return The formatted name page as node
1265
 */
1266
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1267
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1268
  return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
1269
}
1270

    
1271
/**
1272
 * The function genates a object ready to be transformated to a node
1273
 * in order to show as a drupal node
1274
 * @param $taxon_name_uuid
1275
 * @return the object with the page content and title
1276
 */
1277
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1278
  //getting the full taxonname object from the server
1279
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1280
  if(!$taxon_name){
1281
    drupal_set_title(t('Taxon name does not exist'));
1282
    return false;
1283
  }
1284
  //searching for all the taxa connected with the taxon name on the tree in used
1285
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1286
  $request_params = array();
1287
  $request_params['query'] = $name_cache;
1288
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1289
  $request_params['doTaxa'] = 1;
1290
  $request_params['doSynonyms'] = 1;
1291
  $request_params['doTaxaByCommonNames'] = 0;
1292
  $request_params['matchMode'] = "EXACT";
1293
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1294

    
1295
  //removing the name where we come from and
1296
  foreach($taxon_pager->records as $k=>&$taxon){
1297
    if($taxon->uuid == $taxon_to_hide_uuid){
1298
      unset($taxon_pager->records[$k]);
1299
    }
1300
  }
1301
  //show the taxa list or go to the singular taxon
1302
  if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
1303
    reset($taxon_pager->records);
1304
    $singleTaxon = $taxon_pager->records[0];
1305
    if($singleTaxon->class != "Taxon"){
1306
      // it is a Synonym -> look for the accepted
1307
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1308
      if($synonym_uuid){
1309
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
1310
      }else {
1311
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $singleTaxon->uuid);
1312
      }
1313
    }else{
1314
      // it is an accepted taxon
1315
      if($synonym_uuid){
1316
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
1317
      }else{
1318
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1319
      }
1320
    }
1321
  }else{ //more than one taxa case
1322
    $taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1323
    if($taxon_pager->records){
1324
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1325
    }else{
1326
      $taxon_name_page->content = 'This name has no taxa';
1327
    }
1328
    return $taxon_name_page;
1329
  }
1330
}
1331

    
1332
function cdm_dataportal_view_search_advanced(){
1333

    
1334
  drupal_set_title(t('Advanced search'));
1335

    
1336
  $searchForm = cdm_dataportal_search_taxon_form(true);
1337

    
1338
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1339

    
1340
}
1341

    
1342
/**
1343
 *
1344
 * future extensions to meet palmweb mockup requirements:
1345
 *  - habitat
1346
 *  - uses
1347
 *  - conservation status
1348
 *  - locality / tdwg region
1349
 */
1350
function cdm_dataportal_view_search_taxon(){
1351

    
1352
  $_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1353

    
1354
  $request_params = cdm_dataportal_search_form_request();
1355
  $taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1356

    
1357
  $search_params = $_REQUEST;
1358
  unset($search_params['q']);
1359
  return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1360
}
1361

    
1362

    
1363
function cdm_view_xml2json(){
1364
  $file = arg(2);
1365
  $datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1366
  return  xml2json::transformXmlStringToJson($datastr);
1367
}
1368

    
1369
/* ====================== other functions ====================== */
1370

    
1371

    
1372
/**
1373
 * Creates a URL to the taxon page specified by the $uuid parameter.
1374
 * The URL will be prepended with a path element to a specific taxon page tab.
1375
 *
1376
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1377
 * be set globally in the administrative settings or individually in the user
1378
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1379
 * the last portal will stay on this last tab.
1380
 *
1381
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1382
 * internal mechanism by a specific value.
1383
 *
1384
 * @param String $uuid the UUID of the taxon
1385
 * @param String $page_tab overwriting the preset mechanism by defining specific valuefor the taxon page tab.
1386
 *
1387
 * @return the URL
1388
 */
1389
function path_to_taxon($uuid, $page_tab = false){
1390

    
1391
  $tab = get_default_taxon_tab();
1392
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1393

    
1394
  if(!$uuid) return false;
1395

    
1396
  if($page_tab){
1397
    return 'cdm_dataportal/taxon/'.$uuid . '/' . $page_tab;
1398
  } else if (!$tab){
1399
    return 'cdm_dataportal/taxon/'.$uuid;
1400
  }else if(get_last_taxon_page_tab() &&  $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]){
1401
    return 'cdm_dataportal/taxon/'.$uuid . '/' . get_last_taxon_page_tab();
1402
  } else {
1403
    return 'cdm_dataportal/taxon/'.$uuid . '/' . strtolower($tab);
1404
  }
1405
}
1406

    
1407
function uri_to_synonym($synonymUuid, $acceptedUuid){
1408
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1409
  return url($acceptedPath, 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid, $synonymUuid);
1410
}
1411

    
1412
function path_to_key($keyType, $keyUuid){
1413
  if(!$keyUuid || !$keyType) return false;
1414
  $keyType{0} = strtolower($keyType{0});
1415
  return "cdm_dataportal/".$keyType."/$keyUuid";
1416
}
1417

    
1418
function path_to_reference($uuid){
1419
  if(!$uuid) return false;
1420
  return 'cdm_dataportal/reference/'.$uuid;
1421
}
1422

    
1423
function path_to_name($name_uuid){
1424
  $res = false;
1425
  if($name_uuid){
1426
   $res = 'cdm_dataportal/name/'.$name_uuid;
1427
  }
1428
  return $res;
1429
}
1430

    
1431
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1432
  if(!$uuid) return false;
1433
  $out = 'cdm_dataportal/media/'.$uuid;
1434
  if($representaion_uuid){
1435
    $out .= '/'.$representaion_uuid;
1436
    if($partId !== false){
1437
      $out .= '/'.$partId;
1438
    }
1439
  }
1440
  return $out;
1441
}
1442

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

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

    
1479
  if(is_cdm_entity($cdmEntity)) {
1480
    return "cdm:".$cdmEntity->class." uuid:".$cdmEntity->uuid;
1481
  }
1482
}
1483

    
1484

    
1485
/**
1486
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1487
 *
1488
 * @param unknown_type $taggedTextList
1489
 */
1490
function normalize_TaggedName(&$taggedTextList){
1491

    
1492
    if(is_array($taggedTextList)) {
1493

    
1494
      // first pass: rename
1495
      for($i = 0; $i < count($taggedTextList); $i++){
1496

    
1497
        if($taggedTextList[$i]->type == "hybridSign"){
1498
          $taggedTextList[$i]->type = "name";
1499
        }
1500

    
1501
      }
1502

    
1503
      // second pass: resolve separators
1504
      $taggedNameListNew = array();
1505
      for($i = 0; $i < count($taggedTextList); $i++){
1506

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

    
1509
          if($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type){
1510
            $taggedName = $taggedTextList[$i];
1511
            $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1512
            $taggedNameListNew[] = $taggedName;
1513
            ++$i;
1514
            ++$i;
1515
          }
1516
        } else {
1517
          $taggedNameListNew[] = $taggedTextList[$i];
1518
        }
1519
    }
1520
     $taggedTextList = $taggedNameListNew;
1521
    }
1522
}
1523

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

    
1534
  normalize_TaggedName($name->taggedTitle);
1535

    
1536
  // get all tagged text tokens of the scientific name
1537
  foreach($name->taggedTitle as $tagtxt){
1538
    if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1539
      $nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1540
    }
1541
  }
1542
  $nameStr = trim($nameStr);
1543
  if($nameStr){
1544
    // do not return short names for these
1545
    //if (stristr(strtolower($nameStr), 'incertae sedis') !== FALSE ||
1546
    //	stristr(strtolower($nameStr), 'nomina excludenda') !== FALSE) {
1547
    if ($name->unplaced || $name->excluded){
1548
      return $nameStr;
1549
    }
1550
    if($pos = stripos($nameStr, ' ')){
1551
      return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1552
    } else {
1553
      return $nameStr;
1554
    }
1555
  } else {
1556
    return $name->titleCache;
1557
  }
1558
}
1559

    
1560

    
1561
/**
1562
 * Check if a taxon is accepted by the current taxonomic tree
1563
 *
1564
 * @param Taxon $taxon
1565
 * @return true if $taxon is accepted, false otherwise
1566
 */
1567

    
1568
function _cdm_dataportal_acceptedByCurrentView($taxon){
1569

    
1570
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1571

    
1572
  if(isset($taxon->taxonNodes)) {
1573
    $taxonNodes = $taxon->taxonNodes;
1574
  } else {
1575
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1576
  }
1577

    
1578
  if($taxon->class == "Taxon" && isset($taxonNodes)){
1579
    foreach($taxonNodes as $node){
1580
      if(is_object($node->classification)){
1581
        if($node->classification->uuid == $defaultTreeUuid) {
1582
          return true;
1583
        }
1584
      } else {
1585
        if($node->classification == $defaultTreeUuid) {
1586
          return true;
1587
        }
1588
      }
1589
    }
1590
  }
1591

    
1592
  return false;
1593
}
1594

    
1595
/**@Deprecated
1596
 *
1597
 */
1598
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1599
  $pstr = '';
1600
  foreach($parameters as $key=>$value){
1601
    if(is_array($value)){
1602

    
1603
    } else {
1604
      $pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1605
    }
1606
  }
1607
  return $pstr;
1608
}
1609

    
1610
/**
1611
 * workaround for missing original source type, idNamespace is always set in these cases
1612
 * @param unknown_type $source
1613
 * @return unknown_type
1614
 */
1615
function _is_original_source_type($source){
1616
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1617
}
1618

    
1619
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon){
1620
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1621
}
1622

    
1623

    
1624

    
1625
/**
1626
 * The function read the metadata info such title or artist of a media file. The
1627
 * function tries at first to get all the info from the file metadata and if it is
1628
 * not avaible look at the media file info stored at the database.
1629
 * @param $media The media file
1630
 * @return array The array with the avilable specified metadata info.
1631
 * TODO rename to read_media_metadata() and move to *.module
1632
 */
1633
function cdm_read_media_metadata($media){
1634

    
1635
  $metadata_caption = array('title' => '',           //media_metadata and media
1636
                              'artist' => '',          //media_metadata and media
1637
                              'rights',                //media_metadata and media
1638
                              'location',              //media_metadata
1639
                              'filename' => '',        //media
1640
                              'mediacreated' => '',    //media
1641
                              'description' => '');    //media
1642

    
1643
  //getting the media metadata
1644
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1645
  $media_metadata_aux = (array) $media_metadata;
1646

    
1647
  //filename
1648
  if(isset($media->representations[0]->parts[0]->uri)){
1649
    $fileUri = $media->representations[0]->parts[0]->uri;
1650
    $filename = substr($fileUri, strrpos($fileUri, "/")+1);
1651
    $metadata_caption['filename'] = $filename;
1652
  }
1653
  else{
1654
      $metadata_caption['filename'] = '';
1655
  }
1656

    
1657
  //title
1658
  if ($media_metadata->ObjectName) {
1659
    $metadata_caption['title'] = $media_metadata->ObjectName;
1660
  } else if ($media_metadata_aux['Object Name']){
1661
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1662
  } else if ($media->title_L10n){
1663
    $metadata_caption['title'] = $media->title_L10n;
1664
  } else if ($media->titleCache){
1665
    $metadata_caption['title'] = $media->titleCache;
1666
  }
1667

    
1668
  // append description to title
1669
  if ($media->description_L10n) {
1670
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1671
  }
1672

    
1673
  //artist
1674
  if ($media_metadata->Artist){
1675
   $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1676
  }
1677
  elseif ($media->artist->titleCache){
1678
   $metadata_caption['artist'] = $media->artist->titleCache;
1679
  }
1680

    
1681
  //copyright
1682
  $metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1683
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1684
  if ($media_metadata->Copyright)
1685
  $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1686
  elseif ($media->rights){
1687
    foreach($media->rights as $right){
1688
      switch($right->term->uuid){
1689
        case UUID_RIGHTS_LICENCE:
1690
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1691
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1692
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1693
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1694
          break;
1695
        case UUID_RIGHTS_COPYRIGHT:
1696
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1697
          break;
1698
      }
1699
    }
1700
  } else {
1701
    $metadata_caption['rights']['agentNames'][] = '';
1702
  }
1703

    
1704
  //filling the description (though there is no description in the db???)
1705
  //$metadata_caption['description'] = $media->description_L10n;
1706

    
1707
  //location
1708
  $metadata_caption['location'] = array();
1709
  $metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1710
  $metadata_caption['location']['city'] = $media_metadata->City;
1711
  $metadata_caption['location']['province'] = $media_metadata->Province;
1712
  $metadata_caption['location']['country'] = $media_metadata->Country;
1713

    
1714
  /*
1715
   //creation date
1716
   if($media_metadata["Modify Date"])
1717
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1718
   else
1719
   $metadata_caption['mediacreated'] = $media->created;
1720
   */
1721
  //returned value
1722
  return $metadata_caption;
1723
}
1724

    
1725
/**
1726
 * This function collects all the media from a list of description elements
1727
 * and return them as an Array.
1728
 *
1729
 * @param $descriptionElementes The description elements
1730
 * @return Array The output with all the media
1731
 */
1732
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1733
  //variables
1734
  $outArrayOfMedia = array(); //return value
1735
  //implementation
1736
  if(is_array($descriptionElements)){//avoiding warning box in drupal for flora malesiana
1737
    foreach($descriptionElements as $descriptionElement){
1738
      if(is_array($descriptionElement->media)){
1739
        foreach($descriptionElement->media as $media){
1740
          if(is_object($media)){
1741
            $outArrayOfMedia[] = $media;
1742
          }
1743
        }
1744
      }
1745
    }
1746
  }
1747
  return $outArrayOfMedia;
1748
}
1749

    
1750
/**
1751
 *
1752
 * @param - $cdmBase_list @param $cdmBase_list an array of CdmBase instances or a single instance
1753
 * @param - $footnote_list_key
1754
 */
1755
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = null){
1756
  static $annotations_types_filter;
1757

    
1758
  if(!$annotations_types_filter) {
1759
    unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1760
  }
1761

    
1762
  $footNoteKeys = array();
1763

    
1764
  //is argument cdmBase an array?
1765
  if (!is_array($cdmBase_list)){
1766
    $cdmBase_array = array();
1767
    $cdmBase_array[] = $cdmBase_list;
1768
  }else{
1769
    $cdmBase_array = $cdmBase_list;
1770
  }
1771

    
1772
  //getting the key for the footnotemanager
1773
  if( $footnote_list_key ){
1774
    $footnoteListKey = $footnote_list_key;
1775
  }else{
1776
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1777
  }
1778

    
1779
  //adding the footnotes keys
1780
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1781
  foreach($cdmBase_array as $cdmBase_element){
1782
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1783
    if(is_array($annotations)){
1784
      foreach($annotations as $annotation){
1785
          $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1786
      }
1787
    }
1788
  }
1789

    
1790
  return $footNoteKeys;
1791
}
1792

    
1793
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')){
1794

    
1795
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cdm_dynabox.js');
1796

    
1797
  $cdm_proxy_url = url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
1798
  $out .= '<'. $enclosingtags[0]. ' class="dynabox"><a href="'.$content_url.'" class="label" alt="'.t($link_alt_text).'">'.$label.'</a>';
1799
  $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]. '>';
1800
  $out .= '</'. $enclosingtags[0]. '>';
1801
  return $out;
1802
}
1803

    
1804
/**
1805
 * returns true if the given $featureNode or any of its subordinate nodes contains
1806
 * at least one non empty TextData or at least one DescriptionElement of an other type.
1807
 * A TextData element holding a multilanguageText or a source reference is considered to be not empty.
1808
 *
1809
 * @param unknown_type $featureNode A heature node as produced by the function _mergeFeatureTreeDescriptions()
1810
 */
1811
function hasFeatureNodeDescriptionElements($featureNode) {
1812

    
1813
  if(is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
1814
    foreach ($featureNode->descriptionElements as $descriptionElement) {
1815
      if($descriptionElement->class != "TextData" || $descriptionElement->multilanguageText_L10n->text || isset($descriptionElement->sources[0]) ){
1816
        return true;
1817
      }
1818
    }
1819
  } else if(is_array($featureNode->children)) {
1820
    foreach ($featureNode->children as $child) {
1821
      if(hasFeatureNodeDescriptionElements($child)){
1822
        return true;
1823
      }
1824
    }
1825
  }
1826
  return false;
1827
}
1828

    
(6-6/12)