Project

General

Profile

Download (63.2 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["uses"]["info"] = t("CDM Uses");
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
      //Creating a block specific for the Use Interface.
610
      case "uses":
611
      	$block['subject'] = t('Uses');
612
        $block['content'] = theme('cdm_block_uses');
613
        return $block;
614
    }
615
  }
616
}
617

    
618

    
619

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

    
628
 function cdm_dataportal_session_validate(){
629

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

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

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

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

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

    
653
  if(!$advancedForm) {
654
  $form['query'] = array(
655
    '#delta' => 0,
656
    '#type' => 'textfield',
657
    '#size' => 20,
658
    '#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')),
659
    '#value' => $preset_query,
660
  );
661
  }
662
  //AT RBG KEW - 14/11/2011 Added to extend the text box in the Advanced form only
663
  else {
664
       $form['query'] = array(
665
      '#delta' => 0,
666
      '#type' => 'textfield',
667
      '#size' => 68,
668
      '#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')),
669
      '#value' => $preset_query,
670
    );
671
  }
672

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

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

    
686

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

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

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

    
709
  if($advancedForm){
710

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

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

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

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

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

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

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

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

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

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

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

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

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

    
863
  return $form;
864
}
865

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

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

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

    
875
  return $out;
876
}
877

    
878

    
879
function cdm_taxonomictree_selector_form(){
880

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

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

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

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

    
903
        return $form;
904

    
905
}
906

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

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

    
926

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

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

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

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

    
951
  return $form_params;
952
}
953

    
954

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

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

    
967

    
968

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

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

    
975

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

    
990

    
991

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

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

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

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

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

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

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

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

    
1064
  return $form;
1065
}
1066

    
1067

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1255
  return $taxonpage;
1256
}
1257

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

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

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

    
1331
function cdm_dataportal_view_search_advanced(){
1332

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

    
1335
  $searchForm = cdm_dataportal_search_taxon_form(true);
1336

    
1337
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1338

    
1339
}
1340

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

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

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

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

    
1361

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

    
1368
/* ====================== other functions ====================== */
1369

    
1370

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

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

    
1393
  if(!$uuid) return false;
1394

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

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

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

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

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

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

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

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

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

    
1483

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

    
1491
    if(is_array($taggedTextList)) {
1492

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

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

    
1500
      }
1501

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

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

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

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

    
1533
  normalize_TaggedName($name->taggedTitle);
1534

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

    
1559

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

    
1567
function _cdm_dataportal_acceptedByCurrentView($taxon){
1568

    
1569
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1570
  if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1571
    foreach($taxon->taxonNodes as $node){
1572
      if($node->classification == $defaultTreeUuid) {
1573
        return true;
1574
      }
1575
    }
1576
  }
1577
  return false;
1578
}
1579

    
1580
/**@Deprecated
1581
 *
1582
 */
1583
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1584
  $pstr = '';
1585
  foreach($parameters as $key=>$value){
1586
    if(is_array($value)){
1587

    
1588
    } else {
1589
      $pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1590
    }
1591
  }
1592
  return $pstr;
1593
}
1594

    
1595
/**
1596
 * workaround for missing original source type, idNamespace is always set in these cases
1597
 * @param unknown_type $source
1598
 * @return unknown_type
1599
 */
1600
function _is_original_source_type($source){
1601
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1602
}
1603

    
1604
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon){
1605
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1606
}
1607

    
1608

    
1609

    
1610
/**
1611
 * The function read the metadata info such title or artist of a media file. The
1612
 * function tries at first to get all the info from the file metadata and if it is
1613
 * not avaible look at the media file info stored at the database.
1614
 * @param $media The media file
1615
 * @return array The array with the avilable specified metadata info.
1616
 * TODO rename to read_media_metadata() and move to *.module
1617
 */
1618
function cdm_read_media_metadata($media){
1619

    
1620
  $metadata_caption = array('title' => '',           //media_metadata and media
1621
                              'artist' => '',          //media_metadata and media
1622
                              'rights',                //media_metadata and media
1623
                              'location',              //media_metadata
1624
                              'filename' => '',        //media
1625
                              'mediacreated' => '',    //media
1626
                              'description' => '');    //media
1627

    
1628
  //getting the media metadata
1629
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1630
  $media_metadata_aux = (array) $media_metadata;
1631

    
1632
  //filename
1633
  if(isset($media->representations[0]->parts[0]->uri)){
1634
    $fileUri = $media->representations[0]->parts[0]->uri;
1635
    $filename = substr($fileUri, strrpos($fileUri, "/")+1);
1636
    $metadata_caption['filename'] = $filename;
1637
  }
1638
  else{
1639
      $metadata_caption['filename'] = '';
1640
  }
1641

    
1642
  //title
1643
  if ($media_metadata->ObjectName) {
1644
    $metadata_caption['title'] = $media_metadata->ObjectName;
1645
  } else if ($media_metadata_aux['Object Name']){
1646
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1647
  } else if ($media->title_L10n){
1648
    $metadata_caption['title'] = $media->title_L10n;
1649
  } else if ($media->titleCache){
1650
    $metadata_caption['title'] = $media->titleCache;
1651
  }
1652

    
1653
  // append description to title
1654
  if ($media->description_L10n) {
1655
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1656
  }
1657

    
1658
  //artist
1659
  if ($media_metadata->Artist){
1660
   $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1661
  }
1662
  elseif ($media->artist->titleCache){
1663
   $metadata_caption['artist'] = $media->artist->titleCache;
1664
  }
1665

    
1666
  //copyright
1667
  $metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1668
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1669
  if ($media_metadata->Copyright)
1670
  $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1671
  elseif ($media->rights){
1672
    foreach($media->rights as $right){
1673
      switch($right->term->uuid){
1674
        case UUID_RIGHTS_LICENCE:
1675
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1676
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1677
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1678
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1679
          break;
1680
        case UUID_RIGHTS_COPYRIGHT:
1681
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1682
          break;
1683
      }
1684
    }
1685
  } else {
1686
    $metadata_caption['rights']['agentNames'][] = '';
1687
  }
1688

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

    
1692
  //location
1693
  $metadata_caption['location'] = array();
1694
  $metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1695
  $metadata_caption['location']['city'] = $media_metadata->City;
1696
  $metadata_caption['location']['province'] = $media_metadata->Province;
1697
  $metadata_caption['location']['country'] = $media_metadata->Country;
1698

    
1699
  /*
1700
   //creation date
1701
   if($media_metadata["Modify Date"])
1702
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1703
   else
1704
   $metadata_caption['mediacreated'] = $media->created;
1705
   */
1706
  //returned value
1707
  return $metadata_caption;
1708
}
1709

    
1710
/**
1711
 * This function collects all the media from a list of description elements
1712
 * and return them as an Array.
1713
 *
1714
 * @param $descriptionElementes The description elements
1715
 * @return Array The output with all the media
1716
 */
1717
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1718
  //variables
1719
  $outArrayOfMedia = array(); //return value
1720
  //implementation
1721
  if(is_array($descriptionElements)){//avoiding warning box in drupal for flora malesiana
1722
    foreach($descriptionElements as $descriptionElement){
1723
      if(is_array($descriptionElement->media)){
1724
        foreach($descriptionElement->media as $media){
1725
          if(is_object($media)){
1726
            $outArrayOfMedia[] = $media;
1727
          }
1728
        }
1729
      }
1730
    }
1731
  }
1732
  return $outArrayOfMedia;
1733
}
1734

    
1735
/**
1736
 *
1737
 * @param - $cdmBase_list @param $cdmBase_list an array of CdmBase instances or a single instance
1738
 * @param - $footnote_list_key
1739
 */
1740
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = null){
1741
  static $annotations_types_filter;
1742

    
1743
  if(!$annotations_types_filter) {
1744
    unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1745
  }
1746

    
1747
  $footNoteKeys = array();
1748

    
1749
  //is argument cdmBase an array?
1750
  if (!is_array($cdmBase_list)){
1751
    $cdmBase_array = array();
1752
    $cdmBase_array[] = $cdmBase_list;
1753
  }else{
1754
    $cdmBase_array = $cdmBase_list;
1755
  }
1756

    
1757
  //getting the key for the footnotemanager
1758
  if( $footnote_list_key ){
1759
    $footnoteListKey = $footnote_list_key;
1760
  }else{
1761
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1762
  }
1763

    
1764
  //adding the footnotes keys
1765
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1766
  foreach($cdmBase_array as $cdmBase_element){
1767
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
1768
    if(is_array($annotations)){
1769
      foreach($annotations as $annotation){
1770
          $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1771
      }
1772
    }
1773
  }
1774

    
1775
  return $footNoteKeys;
1776
}
1777

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

    
1780
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cdm_dynabox.js');
1781

    
1782
  $cdm_proxy_url = url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
1783
  $out .= '<'. $enclosingtags[0]. ' class="dynabox"><a href="'.$content_url.'" class="label" alt="'.t($link_alt_text).'">'.$label.'</a>';
1784
  $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]. '>';
1785
  $out .= '</'. $enclosingtags[0]. '>';
1786
  return $out;
1787
}
1788

    
1789
/**
1790
 * returns true if the given $featureNode or any of its subordinate nodes contains
1791
 * at least one non empty TextData or at leas one DescriptionElement of an other type.
1792
 *
1793
 * @param unknown_type $featureNode A heature node as produced by the function _mergeFeatureTreeDescriptions()
1794
 */
1795
function hasFeatureNodeDescriptionElements($featureNode) {
1796

    
1797
  if(is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
1798
    foreach ($featureNode->descriptionElements as $descriptionElement) {
1799
      if($descriptionElement->class != "TextData" || $descriptionElement->multilanguageText_L10n->text){
1800
        return true;
1801
      }
1802
    }
1803
  } else if(is_array($featureNode->children)) {
1804
    foreach ($featureNode->children as $child) {
1805
      if(hasFeatureNodeDescriptionElements($child)){
1806
        return true;
1807
      }
1808
    }
1809
  }
1810
  return false;
1811
}
1812

    
(6-6/12)