Project

General

Profile

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

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

    
25
module_load_include('inc', 'cdm_dataportal', 'includes/pages');
26
module_load_include('inc', 'cdm_dataportal', 'includes/occurrences');
27
module_load_include('inc', 'cdm_dataportal', 'includes/descriptions');
28
module_load_include('inc', 'cdm_dataportal', 'includes/pre-drupal8');
29

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

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

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

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

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

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

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

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

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

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

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

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

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

    
122
  _add_js_openlayers();
123

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

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

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

    
145
  if (isset($baseLayers['gmap']) || isset($baseLayers['gsat']) || isset($baseLayers['ghyb'])) {
146
    drupal_add_html_head('<script src=http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key=' . $gmap_api_key . '" type="text/javascript"></script>', $key = NULL /* TODO Set this variable. */);
147
    drupal_add_js('http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1', array('type' => 'external'));
148
  }
149

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

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

    
177
}
178

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

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

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

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

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

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

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

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

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

    
235
    $map_service_script_name = "rest_gen.php";
236

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

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

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

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

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

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

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

    
286
      $map_service_script_name = "point.php";
287

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

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

    
309
  return $out;
310
}
311

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

    
326
  _add_js_openlayers_map();
327

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
588
  return $items;
589
}
590

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

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

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

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

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

    
630
  return $form;
631
}
632

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

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

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

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

    
685
    return $block;
686
}
687

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

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

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

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

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

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

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

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

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

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

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

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

    
794
  return $form;
795

    
796
}
797

    
798
/* UNREACHABLE since action of form directly links to view.
799
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
800

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

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

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

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

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

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

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

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

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

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

    
923
  static $media = NULL;
924

    
925
  if(!isset($media)) {
926
    $media = array();
927
  }
928
  if (!isset($media[$taxon->uuid])) {
929

    
930
    // --- GET Images --- //
931
    $mediaQueryParameters = array(
932
        "type" => "ImageFile",
933
    );
934

    
935
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
936
    $mediaQueryParameters['relationships'] = implode(',', get_selection($relationship_choice['direct']));
937
    $mediaQueryParameters['relationshipsInvers'] = implode(',', get_selection($relationship_choice['invers']));
938

    
939
    $ws_endpoint = NULL;
940
    if ( variable_get('cdm_images_include_children', 0) == 0) {
941
      $ws_endpoint = CDM_WS_PORTAL_TAXON_MEDIA;
942
    } else {
943
      $ws_endpoint = CDM_WS_PORTAL_TAXON_SUBTREE_MEDIA;
944
    }
945

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

    
954
  return $media[$taxon->uuid];
955
}
956

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

    
967
  static $occurences = NULL;
968

    
969
  if(!isset($occurences)) {
970
    $occurences = array();
971
  }
972

    
973
  if (!isset($occurences[$taxon->uuid])){
974

    
975
    $relationship_choice = variable_get(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS, unserialize(CDM_AGGREGATE_BY_TAXON_RELATIONSHIPS_DEFAULT));
976
    $relationship_choice['direct'] = get_selection($relationship_choice['direct']);
977
    $relationship_choice['invers'] = get_selection($relationship_choice['invers']);
978

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

    
986
    $pager = cdm_ws_get(CDM_WS_OCCURRENCE_BY_ASSOCIATEDTAXON,
987
        null,
988
        $by_associatedtaxon_query . '&taxonUuid=' . $taxon->uuid
989
    );
990

    
991

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

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

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

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

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

    
1073
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1074

    
1075
  if (!$polytomousKeyNode) {
1076
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1077
    return;
1078
  }
1079

    
1080
  // Load children.
1081
  foreach ($polytomousKeyNode->children as &$childNode) {
1082
    _load_polytomousKeySubGraph($childNode);
1083
  }
1084

    
1085
  // Load subkey.
1086
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1087

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

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

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

    
1107
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1108
  if (is_array($annotationPager->records)) {
1109
    $polytomousKey->annotations = $annotationPager->records;
1110
  }
1111

    
1112
  _load_polytomousKeySubGraph($polytomousKey->root);
1113
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1114
}
1115

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

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

    
1171
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1172
    'taxon' => $taxon,
1173
    'uuid' => $uuid,
1174
    'synonym_uuid' => $synonym_uuid,
1175
  ));
1176

    
1177
  // Check if the taxon id contained in the currently selected tree.
1178
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1179

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

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

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

    
1208
  return $taxonpage;
1209
}
1210

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

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

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

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

    
1306
/**
1307
 * @todo Please document this function.
1308
 * @see http://drupal.org/node/1354
1309
 */
1310
function cdm_dataportal_view_search_advanced() {
1311

    
1312
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1313
  $form = array();
1314
  $form_state = array();
1315
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1316

    
1317
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1318

    
1319
}
1320

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

    
1331
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1332
}
1333

    
1334
/**
1335
 * Executes the search and generates the result list of taxa.
1336
 */
1337
function cdm_dataportal_view_search_results_taxon() {
1338

    
1339
  $taxonPager = cdm_dataportal_search_execute();
1340

    
1341
  $showThumbnails = do_showThumbnails();
1342

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

    
1347
  drupal_add_js('jQuery(document).ready(function() {
1348

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

    
1372
  drupal_set_title(t('Search results'), PASS_THROUGH);
1373

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

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

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

    
1401
  return $showThumbnails;
1402
}
1403

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

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

    
1440
  $tab = get_default_taxon_tab();
1441
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1442

    
1443
  if (!$uuid) {
1444
    return FALSE;
1445
  }
1446

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

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

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

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

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

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

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

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

    
1563
  if (is_cdm_entity($cdmEntity)) {
1564
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1565
  }
1566
}
1567

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

    
1576
  if (is_array($taggedTextList)) {
1577

    
1578
    // First pass: rename.
1579
    for ($i = 0; $i < count($taggedTextList); $i++) {
1580

    
1581
      if ($taggedTextList[$i]->type == "hybridSign") {
1582
        $taggedTextList[$i]->type = "name";
1583
      }
1584
    }
1585

    
1586
    // Second pass: resolve separators.
1587
    $taggedNameListNew = array();
1588
    for ($i = 0; $i < count($taggedTextList); $i++) {
1589

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

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

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

    
1623
  normalize_TaggedName($name->taggedTitle);
1624

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

    
1633
  if ($nameStr) {
1634

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

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

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

    
1671
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1672

    
1673
  if (isset($taxon->taxonNodes)) {
1674
    $taxonNodes = $taxon->taxonNodes;
1675
  }
1676
  else {
1677
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1678
  }
1679

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

    
1695
  return FALSE;
1696
}
1697

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

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

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

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

    
1745
  // Getting the media metadata.
1746
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1747
  $media_metadata_aux = (array) $media_metadata;
1748

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

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

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

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

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

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

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

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

    
1836
  // Returned value.
1837
  return $metadata_caption;
1838
}
1839

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

    
1851
  $outArrayOfMedia = array();
1852

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

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

    
1888
  $footNoteKeys = array();
1889

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

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

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

    
1918
  return $footNoteKeys;
1919
}
1920

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

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

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

    
1974
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
1975
  $out .= '<!-- ' . $content_url . ' -->';
1976
  $out .= '<' . $enclosingtags[0] . ' class="dynabox-' . $dynabox_id . '"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
1977
  $out .= '<' . $enclosingtags[1] . ' class="dynabox-' . $dynabox_id . '-content" title="' . $cdm_proxy_url . '"><' . $enclosingtags[0] . '><img class="loading" src="' . drupal_get_path('module', 'cdm_dataportal') . '/images/loading_circle_grey_16.gif" style="display:none;"></' . $enclosingtags[0] . '></' . $enclosingtags[1] . '>';
1978
  $out .= '</' . $enclosingtags[0] . '>';
1979
  return $out;
1980
}
1981

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

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