Project

General

Profile

Download (72.8 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/pre-drupal8');
28

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

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

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

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

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

    
71
  $callback = "jQuery('" . $link_element_selector . "').cdm_ws_progress('" . $progress_element_selector . "');";
72

    
73
  drupal_add_js_async(variable_get('cdm_webservice_url', '').'js/cdm_ws_progress.js', $callback);
74

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

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

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

    
104
/**
105
 * @todo Please document this function.
106
 * @see http://drupal.org/node/1354
107
 */
108
function _add_js_openlayers_map() {
109

    
110
  $openlayers = '/js/OpenLayers-2.11/OpenLayers.js';
111

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

    
118
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/openlayers_map.js');
119

    
120
  $gmap_api_key = variable_get('gmap_api_key', 'ABQIAAAAFho6eHAcUOTHLmH9IYHAeBRi_j0U6kJrkFvY4-OX2XYmEAa76BTsyMmEq-tn6nFNtD2UdEGvfhvoCQ');
121

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

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

    
144
  // window.onload - is executed when the document and images etc is fully loaded
145
  // Query(document).ready - is executed much earlier, when the DOM is loaded
146
  drupal_add_js("
147
          jQuery(document).ready(function() {
148

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

    
167
}
168

    
169
/**
170
 * @todo Enter description here ...
171
 *
172
 * @param unknown_type $width
173
 * @param unknown_type $bounding_box
174
 * @param unknown_type $occurrenceQuery
175
 * @param unknown_type $distributionQuery
176
 * @param unknown_type $legendFormatQuery
177
 * @param unknown_type $map_caption
178
 *
179
 * @return unknown
180
 */
181
function get_image_map($width, $bounding_box = FALSE, $occurrenceQuery = FALSE, $distributionQuery = FALSE, $legendFormatQuery = FALSE, $map_caption = FALSE) {
182

    
183
  $server = getEDITMapServiceURI();
184

    
185
  if (!$server) {
186
    // Warning message.
187
    drupal_set_message(t(
188
      "No 'Geoservice Access Point' has been set so far.
189
      Please configure the variable 'Geoservice Access Point' here !url", array(
190
        '!url' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/geo'),
191
      )), 'warning');
192

    
193
    // Message to render.
194
    return '<p>' . t('No geoservice specified') . '</p>';
195
  }
196

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

    
200
  $query_string = '&image=true&recalculate=false&legend=1&ms=' . $width
201
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
202
    . ($labels_on ? '&label=' . $labels_on : '');
203

    
204
  if ($map_caption) {
205
    $query_string .= '&mlp=3&mc_s=Georgia,15,blue&mc=' . $map_caption;
206
  }
207

    
208
  if (getEDITMapServiceVersionNumber() >= 1.1) {
209

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

    
219
      $query_string .= "&" . $occurrenceQuery;
220
    }
221
    elseif ($distributionQuery) {
222
      $query_string .= "&" . $distributionQuery;
223
    }
224

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

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

    
239
    $map_service_script_name = "rest_gen.php";
240

    
241
    $bgcolor_areaStyleId = "y";
242
    $baselayer_areaStyleId = "z";
243
    $bgcolor_layer = '';
244
    $additional_area_styles = array();
245

    
246
    // Background color:
247
    if (variable_get('map_bg_color', '')) {
248
      $bgcolor_layer = "background_gis:" . $bgcolor_areaStyleId;
249
      $additional_area_styles[] = $bgcolor_areaStyleId . ":" . variable_get('map_bg_color', '') . ",,";
250
    }
251

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

    
273
    if ($bgcolor_layer) {
274
      $query_string = str_replace($layer_param_token, $layer_param_token . $bgcolor_layer . ",", $query_string);
275
    }
276

    
277
    if (variable_get('map_base_layer_style', '')) {
278
      $additional_area_styles[] = $baselayer_areaStyleId . ":" . variable_get('map_base_layer_style', '');
279
    }
280

    
281
    foreach ($additional_area_styles as $as) {
282
      $query_string = str_replace($areystyle_param_token, $areystyle_param_token . $as . "|", $query_string);
283
    }
284

    
285
  }
286
  else {
287
    // Pre 1.1. version of map service.
288
    if ($occurrenceQuery) {
289

    
290
      $map_service_script_name = "point.php";
291

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

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

    
313
  return $out;
314
}
315

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

    
330
  _add_js_openlayers_map();
331

    
332
  $out = '<div id="openlayers">';
333
  $out .= '<div id="openlayers_map" class="smallmap"';
334
  if($width) {
335
    $out .= ' style="width: ' . $width . 'px; height:' . ($width / 2) . 'px"';
336
  }
337

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

    
341
  $openlayers_map_query_string = '&img=false&ms=' . $width
342
    . ($bounding_box ? '&bbox=' . $bounding_box : '')
343
    . ($labels_on ? '&label=' . $labels_on : '');
344

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

    
353
    $out .= ' occurrenceQuery="' . $occurrenceQuery . '&' . $openlayers_map_query_string . '"';
354
  }
355

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

    
360
  if ($legendFormatQuery) {
361
    $out .= ' legendFormatQuery="' . $legendFormatQuery . '"';
362
  }
363

    
364
  $out .= '></div></div>';
365

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

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

    
399
/**
400
 * Implements hook_menu().
401
 */
402
function cdm_dataportal_menu() {
403
  $items = array();
404

    
405
  // @see settings.php.
406
  cdm_dataportal_menu_admin($items);
407
  cdm_dataportal_menu_help($items);
408

    
409
  $items['cdm_dataportal/names'] = array(
410
    'page callback' => 'cdm_dataportal_view_names',
411
    'access arguments' => array('access content'),
412
    'type' => MENU_CALLBACK,
413
  );
414

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

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

    
437
  $items['cdm_dataportal/reference'] = array(
438
    'page callback' => 'cdm_dataportal_view_reference',
439
    'access arguments' => array('access content'),
440
    'type' => MENU_CALLBACK,
441
    // Expected callback arguments: uuid.
442
  );
443

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

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

    
459
  $items['cdm_dataportal/polytomousKey'] = array(
460
    'page callback' => 'cdm_dataportal_view_polytomousKey',
461
    'access arguments' => array('access content'),
462
    'type' => MENU_CALLBACK,
463
    // Expected callback arguments: polytomousKey->uuid.
464
  );
465

    
466
  $items['cdm_dataportal/search'] = array(
467
    'page callback' => 'cdm_dataportal_view_search_advanced',
468
    'access arguments' => array('access content'),
469
    'type' => MENU_CALLBACK,
470
  );
471

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

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

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

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

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

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

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

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

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

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

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

    
592
  return $items;
593
}
594

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

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

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

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

    
629
  $form['submit'] = array(
630
    '#type' => 'submit',
631
    '#value' => t('Submit'),
632
  );
633

    
634
  return $form;
635
}
636

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

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

    
672
/**
673
 * Implements hook_block_info().
674
 */
675
function cdm_dataportal_block_info() {
676

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

    
686
    return $block;
687
}
688

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

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

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

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

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

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

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

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

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

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

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

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

    
795
  return $form;
796

    
797
}
798

    
799
/**
800
 * Implements hook_theme().
801
 *
802
 * Registering themes with a theme hook is needed since Drupal 6.
803
 *
804
 * @author W. Addink <w.addink@eti.uva.nl>
805
 */
806
function cdm_dataportal_theme() {
807
  return array(
808
    // Themes in help.php.
809
    'cdm_dataportal_admin_config_cdm_dataportal_general' => array('variables' => array()),
810
    'cdm_dataportal_admin_config_cdm_dataportal_geo' => array('variables' => array()),
811
    'cdm_dataportal_admin_config_cdm_dataportal_layout' => array('variables' => array()),
812
    'cdm_dataportal_admin_config_cdm_dataportal_cachesite' => array('variables' => array()),
813
    'cdm_dataportal_admin_config_more_help_link' => array('variables' => array()),
814

    
815
    // Themes in settings.php.
816
    'checkboxes_preferred' => array('render element' => 'element'),
817

    
818
    // Themes in cdm_dataportal.common.theme.
819
    'cdm_taggedtext2html' => array('variables' => array(
820
      'taggedtxt' => array(),
821
      'tag' => 'span',
822
      'glue' => ' ',
823
      'skiptags' => array(),
824
      )),
825
    'cdm_annotations_as_footnotekeys' => array('variables' => array('cdmBase_list' => NULL, 'footnote_list_key' => NULL)),
826
    'cdm_annotation_footnotes' => array('variables' => array('footnoteListKey' => NULL, 'enclosingTag' => 'span')),
827
    'cdm_annotation_content' => array('variables' => array('AnnotationTO' => NULL)),
828
    'cdm_list_of_annotations' => array('variables' => array('annotationElements' => NULL)),
829
    'cdm_footnote_key' => array('variables' => array(
830
      'footnoteKey' => NULL,
831
      'separator' => '',
832
      'highlightable' => TRUE,
833
      'separator_off' => FALSE,
834
      )),
835
    'cdm_footnote' => array('variables' => array('footnoteKey' => NULL, 'footnoteText' => NULL)),
836
    'cdm_footnotes' => array('variables' => array(
837
      'footnoteListKey' => NULL,
838
      'enclosingTag' => 'span',
839
      )),
840
    'cdm_annotations' => array('variables' => array('annotations' => NULL, 'enclosingTag' => 'span')),
841
    'cdm_pager' => array('variables' => array('pager' => NULL, 'path' => NULL, 'parameters' => NULL)),
842
    'cdm_pager_link' => array('variables' => array(
843
      'text' => NULL,
844
      'linkIndex' => NULL,
845
      'pager' => NULL,
846
      'path' => NULL,
847
      'parameters' => array(),
848
      'attributes' => NULL,
849
      )),
850
    'cdm_back_to_search_result_button' => array('variables' => array()),
851
    'cdm_back_to_image_gallery_button' => array('variables' => array()),
852
    'cdm_print_button' => array('variables' => array()),
853

    
854
    // Themes in cdm_dataportal.descriptions.theme.
855
    'cdm_feature_nodesTOC' => array('variables' => array('featureNodes' => NULL)),
856
    'cdm_feature_name' => array('variables' => array('feature_name' => NULL)),
857
    'cdm_featureTrees' => array('variables' => array('mergedTrees' => NULL, 'taxon' => NULL)),
858
    'cdm_featureTreeTOCs' => array('variables' => array('mergedTrees' => NULL)),
859
    'cdm_feature_nodes' => array('variables' => array('mergedFeatureNodes' => NULL, 'taxon' => NULL)),
860
    'FeatureTree_hierarchy' => array('variables' => array('FeatureTreeUuid' => NULL)),
861
    'FeatureTree_hierarchy_children' => array('variables' => array('node' => NULL)),
862
    'cdm_descriptionElementArray' => array('variables' => array(
863
      'elementArray' => array(),
864
      'feature' => NULL,
865
      'glue' => '',
866
      'sortArray' => FALSE,
867
      'enclosingHtml' => 'ul',
868
      )),
869
    'cdm_descriptionElement_CommonTaxonName' => array('render element' => 'element'),
870
    'cdm_descriptionElement_CategoricalData' => array('render element' => 'element'),
871
    'cdm_descriptionElementTextData' => array('variables' => array(
872
      'element' => NULL,
873
      'asListElement' => NULL,
874
      'feature_uuid' => NULL,
875
      )),
876
    'cdm_common_names' => array('render element' => 'elements'),
877
    'cdm_descriptionElements' => array('variables' => array(
878
      'descriptionElements' => NULL,
879
      'featureUuid' => NULL,
880
      'taxon_uuid' => NULL,
881
      )),
882
    'cdm_description_element_image_source' => array('variables' => array(
883
      'image_sources' => NULL,
884
      'asListElement' => NULL,
885
      )),
886
    'cdm_descriptionElementDistribution' => array('variables' => array(
887
      'descriptionElements' => NULL,
888
      'enclosingTag' => 'span',
889
      )),
890
    'cdm_description_ordered_distributions' => array('variables' => array(
891
      'taxon_uuid' => NULL,
892
      'descriptionElements' => NULL,
893
      )),
894
    'cdm_DescriptionElementSource' => array('variables' => array('descriptionElementSource' => NULL, 'doLink' => TRUE)),
895
    'cdm_IdentifieableSource' => array('variables' => array('source' => NULL, 'doLink' => TRUE)),
896
    'cdm_distribution_map' => array('variables' => array('taxon' => NULL)),
897
    'cdm_IdentificationKey' => array('variables' => array(
898
      'identificationKey' => NULL,
899
      'doLinkToKeyPage' => TRUE,
900
      'showIdentificationKeyTitle' => TRUE,
901
      )),
902
    'cdm_polytomousKey' => array('variables' => array('polytomousKey' => NULL)),
903
    'cdm_polytomousKey_linkedStyle_subgraph' => array('variables' => array('polytomousKeyNode' => NULL)),
904
    'cdm_poytomousKeyNode_modifyingText' => array('variables' => array('modifyingText' => NULL)),
905
    'cdm_list_IdentificationKeys' => array('variables' => array('type' => NULL, 'taxonUuid' => NULL)),
906
    'cdm_block_IdentificationKeys' => array('variables' => array('taxonUuid' => NULL)),
907
    'cdm_UseDescription' => array('variables' => array('description' => NULL, 'taxonUuid' => NULL)),
908
    'cdm_block_Uses' => array('variables' => array('taxonUuid' => NULL)),
909

    
910
    // Themes in cdm_dataportal.media.theme.
911
    'cdm_media' => array('variables' => array('descriptionElement' => NULL, 'mimeTypePreference' => NULL)),
912
    'cdm_mediaTypeTerm' => array('variables' => array('feature' => NULL, 'mediaUrl' => FALSE)),
913
    'cdm_media_mime_application' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
914
    'cdm_media_mime_image' => array('variables' => array('mediaRepresentation' => NULL, 'feature' => NULL)),
915
    'cdm_media_mime_text' => array('variables' => array('representation' => NULL, 'feature' => NULL)),
916
    'cdm_media_caption' => array('variables' => array(
917
      'media' => NULL,
918
      'elements' => array('title', 'description', 'artist', 'location', 'rights'),
919
      )),
920
    'cdm_media_gallerie' => array('variables' => array(
921
      'mediaList' => NULL,
922
      'galleryName' => NULL,
923
      'maxExtend' => 150,
924
      'cols' => 4,
925
      'maxRows' => FALSE,
926
      'captionElements' => array('title'),
927
      'mediaLinkType' => 'LIGHTBOX',
928
      'alternativeMediaUri' => NULL,
929
      'galleryLinkUri' => NULL,
930
      'showCaption' => TRUE,
931
      )),
932
    'cdm_media_gallerie_image' => array('variables' => array(
933
      'mediaRepresentationPart' => NULL,
934
      'maxExtend' => NULL,
935
      'addPassePartout' => FALSE,
936
      'attributes' => NULL,
937
      )),
938
    'cdm_media_gallerie_application' => array('variables' => array(
939
      'mediaRepresentationPart' => NULL,
940
      'maxExtend' => NULL,
941
      'addPassePartout' => FALSE,
942
      'attributes' => NULL,
943
      )),
944
    'cdm_media_gallerie_text' => array('variables' => array(
945
      'mediaRepresentationPart' => NULL,
946
      'maxExtend' => NULL,
947
      'addPassePartout' => FALSE,
948
      'attributes' => NULL,
949
      )),
950
    'cdm_openlayers_image' => array('variables' => array('mediaRepresentationPart' => NULL, 'maxExtend' => NULL)),
951
    'cdm_preferredImage' => array('variables' => array(
952
      'media' => NULL,
953
      'defaultRepresentationPart' => NULL,
954
      'imageMaxExtend' => NULL,
955
      'parameters' => '',
956
      )),
957

    
958
    // Themes in cdm_dataportal.name.theme.
959
    'cdm_taxonName' => array('variables' => array(
960
      'taxonName' => NULL,
961
      'nameLink' => NULL,
962
      'refenceLink' => NULL,
963
      'show_annotations' => TRUE,
964
      'is_type_designation' => FALSE,
965
      'skiptags' => array(),
966
      )),
967
    'cdm_typedesignations' => array('variables' => array('typeDesignations' => array())),
968
    'cdm_nameRelationships' => array('variables' => array('nameRelationships' => NULL, 'skipTypes' => FALSE)),
969
    'cdm_homotypicSynonymLine' => array('variables' => array('taxon' => NULL)),
970
    'cdm_heterotypicSynonymyGroup' => array('variables' => array('homotypicalGroup' => NULL)),
971
    'cdm_homotypicSynonymyGroup' => array('variables' => array(
972
      'synonymList' => NULL,
973
      'accepted_taxon_uuid' => NULL,
974
      'prependedSynonyms' => array(),
975
      )),
976
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
977
    'get_partDefinition' => array('variables' => array('nameType' => NULL)),
978
    'get_nameRenderTemplate' => array('variables' => array('renderPath' => NULL)),
979

    
980
    // Themes in cdm_dataportal.occurrence.theme.
981
    'cdm_specimen' => array('variables' => array('specimenTypeDesignation' => NULL)),
982

    
983
    // Themes in cdm_dataportal.page.theme.
984
    'cdm_taxon_page_title' => array('variables' => array('taxon' => NULL, 'uuid' => NULL)),
985
    'cdm_name_page_title' => array('variables' => array('taxon_name' => NULL)),
986
    'cdm_taxon_page' => array('variables' => array('taxon' => NULL, 'page_part' => 'description')),
987
    'cdm_taxon_page_profile' => array('variables' => array(
988
      'taxon' => NULL,
989
      'mergedTrees' => NULL,
990
      'media' => NULL,
991
      'hideImages' => FALSE,
992
      )),
993
    'cdm_taxon_page_synonymy' => array('variables' => array('taxon' => NULL, 'addAcceptedTaxon' => NULL)),
994
    'cdm_reference_page' => array('variables' => array('reference' => NULL)),
995
    'cdm_media_page' => array('variables' => array(
996
      'media' => NULL,
997
      'mediarepresentation_uuid' => FALSE,
998
      'partId' => FALSE,
999
      )),
1000
    'cdm_polytomousKey_page' => array('variables' => array('polytomousKey' => NULL)),
1001
    'cdm_taxonpage_tab' => array('variables' => array('tabname' => NULL)),
1002

    
1003
    // Themes in cdm_dataportal.references.theme.
1004
    'cdm_reference_pager' => array('variables' => array(
1005
      'referencePager' => NULL,
1006
      'path' => NULL,
1007
      'parameters' => array(),
1008
      )),
1009
    'cdm_reference' => array('variables' => array(
1010
      'reference' => NULL,
1011
      'microReference' => NULL,
1012
      'doLink' => FALSE,
1013
      'referenceStyle' => NULL,
1014
      )),
1015

    
1016
    // Themes in cdm_dataportal.taxon.theme.
1017
    'cdm_search_results' => array('variables' => array(
1018
      'pager' => NULL,
1019
      'path' => NULL,
1020
      'query_parameters' => NULL,
1021
      )),
1022
    'cdm_taxonRelationships' => array('variables' => array('taxonRelationships' => NULL, 'focusedTaxon' => NULL)),
1023
    'cdm_acceptedFor' => array('variables' => array()),
1024
    'cdm_list_of_taxa' => array('variables' => array('records' => NULL, 'freetextSearchResults' => array())),
1025
    'cdm_taxon_list_thumbnails' => array('variables' => array('taxon' => NULL)),
1026

    
1027
    // Themes in cdm_dataportal.bibliography.theme.
1028
    'cdm_descriptionElementBibliography' => array('variables' => array('descriptionElementsBibliography' => array())),
1029

    
1030
    // Themes in includes/pre-drupal8.inc
1031
    'description_list' => array('variables' => array('items' => array(), 'groups' => array(), 'title' => NULL, 'attributes' => array())),
1032
  );
1033
}
1034

    
1035
/* UNREACHABLE since action of form directly links to view.
1036
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
1037

    
1038
 $_SESSION['cdm']['search'] = $form_values;
1039
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
1040
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
1041
 //$paramstr = compose_url_prameterstr($form_values);
1042
 //return url('/cdm_dataportal/search/taxon/', array('query' => $paramstr));
1043
 }
1044
 */
1045
/* ====================== menu callback functions ====================== */
1046
/**
1047
 * @todo Please document this function.
1048
 * @see http://drupal.org/node/1354
1049
 */
1050
/*
1051
function cdm_dataportal_form_alter(&$form, &$form_state, $form_id) {
1052
  static $comment_node_disabled =  0;
1053
  static $comment_node_read_only =  1;
1054
  static $comment_node_read_write =  2;
1055

    
1056
  if ($form_id == 'node_type_form'
1057
   && isset($form['identity']['type'])
1058
   && array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
1059
  ) {
1060
    $form['workflow']['comment'] = array(
1061
      '#type' => 'radios',
1062
      '#title' => t('Default comment setting'),
1063
      '#default_value' => variable_get('comment__' . $node->type . $form['#node_type']->type, $comment_node_disabled),
1064
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
1065
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
1066
    );
1067
  }
1068
}
1069
*/
1070

    
1071
/**
1072
 * Displays a list of the known taxonomic names.
1073
 *
1074
 * When the list of taxonomic names is displayed, long lists are split up into
1075
 * multiple pages.
1076
 *
1077
 * TODO: Parameters are still preliminary.
1078
 *
1079
 * @param string $beginsWith
1080
 * @param string $page
1081
 *   Page number to diplay defaults to page 1.
1082
 * @param bool $onlyAccepted
1083
 */
1084
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = FALSE) {
1085

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

    
1088
  /*
1089
  // FIXME the filter for accepted names will be a form element, thus this
1090
  // widget should be generated via form api preferably as block.
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

    
1098
/**
1099
 * @todo Please document this function.
1100
 * @see http://drupal.org/node/1354
1101
 */
1102
function cdm_dataportal_view_reference($uuid, $arg2 = NULL) {
1103
  $reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1104
  return theme('cdm_reference_page', array('reference' => $reference));
1105
}
1106

    
1107
/**
1108
 * @todo Please document this function.
1109
 * @see http://drupal.org/node/1354
1110
 */
1111
function cdm_dataportal_view_reference_list($pageNumber) {
1112
  $referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1113
  return theme('cdm_reference_pager', array(
1114
    'referencePager' => $referencePager,
1115
    'path' => 'cdm_dataportal/reference/list/',
1116
    ));
1117
}
1118

    
1119
/**
1120
 * @todo Please document this function.
1121
 * @see http://drupal.org/node/1354
1122
 */
1123
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = FALSE, $part = 0) {
1124
  $media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1125
  return theme('cdm_media_page', array(
1126
    'media' => $media,
1127
    'mediarepresentation_uuid' => $mediarepresentation_uuid,
1128
    'partId' => $part,
1129
    ));
1130
}
1131

    
1132
/**
1133
 * @todo Please document this function.
1134
 * @see http://drupal.org/node/1354
1135
 */
1136
function _load_taxonBase(&$taxonBase) {
1137
  if (isset($taxonBase->uuid)) {
1138
    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
1139
    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
1140
    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
1141
  }
1142
}
1143

    
1144
/**
1145
 * Gets a Drupal variable, string or array and returns it.
1146
 *
1147
 * Similar to the variable_get() function of Drupal, except that this function
1148
 * is able to handle arrays correctly. This function is especially useful
1149
 * when dealing with collections of setting form elements (#tree = TRUE).
1150
 *
1151
 * @param string $variableKey
1152
 *   The Unique key of the Drupal variable in the Drupal variables table.
1153
 * @param string $defaultValueString
1154
 *   A string as for example derived from a CONSTANT.
1155
 *
1156
 * @return mixed
1157
 *   Returns usally an array, depending on the nature of the variable.
1158
 */
1159
function mixed_variable_get($variableKey, $defaultValueString) {
1160
  $systemDefaults = unserialize($defaultValueString);
1161
  $storedSettings = variable_get($variableKey, array());
1162
  if (is_array($storedSettings)) {
1163
    $settings = array_merge($systemDefaults, $storedSettings);
1164
  }
1165
  else {
1166
    $settings = $systemDefaults;
1167
  }
1168
  return $settings;
1169
}
1170

    
1171
/**
1172
 * Wrapps the given $html string into a reder array suitable for drupal_render()
1173
 *
1174
 * @param string $html
1175
 *   the html string, see
1176
 *   http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#markup
1177
 * @param number $weight
1178
 *   A positive or negative number (integer or decimal).
1179
 *   see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#weightval
1180
 *
1181
 * @return
1182
 *   A render array
1183
 *
1184
 */
1185
function markup_to_render_array($html, $weight = 0) {
1186
  return array(
1187
          '#markup' => $html,
1188
          '#weight' => $weight,
1189
      );
1190
}
1191

    
1192
/**
1193
 * Loads the subgraph of a given PolytomousKeyNode.
1194
 *
1195
 * Loads the subgraph of the given PolytomousKeyNode recursively from
1196
 * the CDM REST service.
1197
 *
1198
 * @param mixed $polytomousKeyNode
1199
 *   PolytomousKeyNode passed by reference.
1200
 *
1201
 * @return void
1202
 */
1203
function _load_polytomousKeySubGraph(&$polytomousKeyNode) {
1204

    
1205
  if (!$polytomousKeyNode) {
1206
    return;
1207
  }
1208
  if ($polytomousKeyNode->class != "PolytomousKeyNode") {
1209
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1210
    return;
1211
  }
1212
  if (!is_uuid($polytomousKeyNode->uuid)) {
1213
    drupal_set_message(_load_polytomousKeySubGraph() . t('invalid type given.'), 'error');
1214
    return;
1215
  }
1216

    
1217
  $polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
1218

    
1219
  if (!$polytomousKeyNode) {
1220
    // drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
1221
    return;
1222
  }
1223

    
1224
  // Load children.
1225
  foreach ($polytomousKeyNode->children as &$childNode) {
1226
    _load_polytomousKeySubGraph($childNode);
1227
  }
1228

    
1229
  // Load subkey.
1230
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
1231

    
1232
  // Load taxon.
1233
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
1234
  _load_taxonBase($polytomousKeyNode->taxon);
1235
  return;
1236
}
1237

    
1238
/**
1239
 * @todo Please document this function.
1240
 * @see http://drupal.org/node/1354
1241
 */
1242
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid) {
1243
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
1244

    
1245
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1246
  if (is_array($sourcePager->records)) {
1247
    $polytomousKey->sources = $sourcePager->records;
1248
    // $polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'sources'));
1249
  }
1250

    
1251
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, 'annotations'));
1252
  if (is_array($annotationPager->records)) {
1253
    $polytomousKey->annotations = $annotationPager->records;
1254
  }
1255

    
1256
  _load_polytomousKeySubGraph($polytomousKey->root);
1257
  return theme('cdm_polytomousKey_page', array('polytomousKey' => $polytomousKey));
1258
}
1259

    
1260
/**
1261
 * Creates a taxon page view or a chapter of it.
1262
 *
1263
 * The taxon page gives detailed information on a taxon, it shows:
1264
 *  - Taxon name.
1265
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1266
 *    heterotypic and finally followed by misapplied names.
1267
 *    The list is ordered historically.
1268
 *  - All description associated with the taxon.
1269
 *
1270
 * @param string $uuid
1271
 * @param string $chapter
1272
 *   Name of the part to display, valid values are:
1273
 *   'description', 'images', 'synonymy', 'specimens', 'all'.
1274
 *
1275
 * @return unknown_type
1276
 */
1277
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1278
  // Display the page for the taxon defined by $uuid.
1279
  // set_last_taxon_page_tab(arg(3));
1280
  $taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
1281
  if (!empty($taxonpage)) {
1282
    return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title, $taxonpage->content);
1283
  }
1284
  else {
1285
    return '';
1286
  }
1287
}
1288

    
1289
/**
1290
 * This function will genreate the taxon page part ($chapter) and returns a taxonpage object
1291
 * which has two fields, one for the page title and one for the content. Later on in the
1292
 * process chain the value contained in these fields will be passed to the cdm_node_show()
1293
 * function as the function parameters $title and $content.
1294
 *
1295
 * @param string $uuid
1296
 *   the uuid of the taxon to show
1297
 * @param string $chapter
1298
 *   Name of the part to display, valid values are:
1299
 *   'description', 'images', 'synonymy', 'all'.
1300
 *
1301
 * @return taxonpage object with the following fields:
1302
 *   - title : the title of the page
1303
 *   - content: the content of the page
1304
 *
1305
 */
1306
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = NULL) {
1307
  // Taxon object.
1308
  $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1309
  if (empty($taxon)) {
1310
    drupal_set_title(t('Taxon does not exist'), PASS_THROUGH);
1311
    return FALSE;
1312
  }
1313
  $taxonpage = new stdClass();
1314

    
1315
  $taxonpage->title = theme('cdm_taxon_page_title', array(
1316
    'taxon' => $taxon,
1317
    'uuid' => $uuid,
1318
    'synonym_uuid' => $synonym_uuid,
1319
  ));
1320

    
1321
  // Check if the taxon id contained in the currently selected tree.
1322
  $taxon_in_current_tree = taxon_in_current_tree($uuid);
1323
  $taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1324
  if (!$taxon_in_current_tree) {
1325
    if (count($taxon_nodes) == 0) {
1326
      drupal_set_message(check_plain(t('This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification.', array(
1327
        '!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)),
1328
      ))), 'warning');
1329
    }
1330
    else {
1331
      $trees = '';
1332
      foreach ($taxon_nodes as $node) {
1333
        if (isset($node->classification->titleCache)) {
1334
          $trees .= ($trees ? ', ' : '') . '<strong>' . $node->classification->titleCache . '</strong>';
1335
        }
1336
      }
1337

    
1338
      drupal_set_message(format_plural(count($taxon_nodes),
1339
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in this one: !trees',
1340
          'This concept of the taxon !taxonname is not contained as an accepted taxon in currently chosen classification, but in one of these: !trees',
1341
          array('!taxonname' => theme('cdm_taxonName', array('taxonName' => $taxon->name)), '!trees' => $trees)) , 'warning');
1342
    }
1343
  }
1344

    
1345
  // Render the taxon page.
1346
  $taxonpage->content = theme('cdm_taxon_page', array(
1347
    'taxon' => $taxon,
1348
    'page_part' => $chapter,
1349
  ));
1350

    
1351
  return $taxonpage;
1352
}
1353

    
1354
/**
1355
 * Returns a name page as a Drupal node ready to be renderized by Drupal.
1356
 *
1357
 * The node page shows the taxon name title and the list of taxon related
1358
 * with such taxon. Name on the tree already in use.
1359
 *
1360
 * @param string $taxon_name_uuid
1361
 *   A taxon name UUID.
1362
 *
1363
 * @return mixed
1364
 *   The formatted name page as node.
1365
 */
1366
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1367

    
1368
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1369
  if (!empty($taxonname_page)) {
1370
    return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title, $taxonname_page->content);
1371
  }
1372
  else {
1373
    return '';
1374
  }
1375
}
1376

    
1377
/**
1378
 * Generates an object ready to be transformated to a node.
1379
 *
1380
 * This is a preparation in order to show it as a Drupal node.
1381
 *
1382
 * @param string $taxon_name_uuid
1383
 *
1384
 * @return mixed
1385
 *   The object with the page content and title.
1386
 */
1387
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = NULL) {
1388
  // Getting the full taxonname object from the server.
1389
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1390
  if (!$taxon_name) {
1391
    drupal_set_title(t('Taxon name does not exist'), PASS_THROUGH);
1392
    return FALSE;
1393
  }
1394
  // Searching for all the taxa connected with the taxon name on the tree
1395
  // in use.
1396
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1397
  $request_params = array();
1398
  $request_params['query'] = $name_cache;
1399
  $request_params['tree'] = get_taxonomictree_uuid_selected();
1400
  $request_params['doTaxa'] = 1;
1401
  $request_params['doSynonyms'] = 1;
1402
  $request_params['doTaxaByCommonNames'] = 0;
1403
  $request_params['matchMode'] = "EXACT";
1404
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, NULL, queryString($request_params));
1405

    
1406
  // Removing the name where we come from.
1407
  foreach ($taxon_pager->records as $k => &$taxon) {
1408
    if ($taxon->uuid == $taxon_to_hide_uuid) {
1409
      unset($taxon_pager->records[$k]);
1410
    }
1411
  }
1412
  // Show the taxa list or go to the singular taxon.
1413
  if (sizeof($taxon_pager->records) == 1) {// Single taxon case.
1414
    reset($taxon_pager->records);
1415
    $singleTaxon = $taxon_pager->records[0];
1416
    if ($singleTaxon->class != "Taxon") {
1417
      // It is a Synonym -> look for the accepted.
1418
      $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($singleTaxon->uuid, get_taxonomictree_uuid_selected()));
1419
      if (!empty($synonym_uuid)) {
1420
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1421
      }
1422
      else {
1423
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', array('query' => array('highlite' => $singleTaxon->uuid)));
1424
      }
1425
    }
1426
    else {
1427
      // It is an accepted taxon.
1428
      if (!empty($synonym_uuid)) {
1429
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid . '/synonymy', array('query' => array('highlite' => $synonym_uuid)));
1430
      }
1431
      else {
1432
        drupal_goto('cdm_dataportal/taxon/' . $singleTaxon->uuid);
1433
      }
1434
    }
1435
  }
1436
  else {// More than one taxa case.
1437
    $taxon_name_page = new stdClass();
1438
    $taxon_name_page->title = theme('cdm_name_page_title', array('taxon_name' => $taxon_name));
1439
    if ($taxon_pager->records) {
1440
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, FALSE);
1441
    }
1442
    else {
1443
      $taxon_name_page->content = 'This name has no taxa';
1444
    }
1445
    return $taxon_name_page;
1446
  }
1447
}
1448

    
1449
/**
1450
 * @todo Please document this function.
1451
 * @see http://drupal.org/node/1354
1452
 */
1453
function cdm_dataportal_view_search_advanced() {
1454

    
1455
  drupal_set_title(t('Advanced search'), PASS_THROUGH);
1456
  $form = array();
1457
  $form_state = array();
1458
  $searchForm = cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
1459

    
1460
  return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1461

    
1462
}
1463

    
1464
/**
1465
 * @todo Please document this function.
1466
 * @see http://drupal.org/node/1354
1467
 */
1468
function cdm_dataportal_view_search_taxon_by_description() {
1469
  drupal_set_title(t('Search by description full text'), PASS_THROUGH);
1470
  // $form_state = false;
1471
  // $searchForm = cdm_dataportal_search_taxon_by_description_form($form_state);
1472
  $searchForm = cdm_dataportal_search_taxon_by_description_form();
1473

    
1474
  return drupal_get_form('cdm_dataportal_search_taxon_by_description_form');
1475
}
1476

    
1477
/**
1478
 * Executes the search and generates the result list of taxa.
1479
 */
1480
function cdm_dataportal_view_search_results_taxon() {
1481

    
1482
  $taxonPager = cdm_dataportal_search_execute();
1483

    
1484
  $showThumbnails = do_showThumbnails();
1485

    
1486
  $setSessionUri = url('cdm_api/setvalue/session', array(
1487
      'query' => array('var' => '[pageoption][searchtaxa][showThumbnails]', 'val' => ''),
1488
  ));
1489

    
1490
  drupal_add_js('jQuery(document).ready(function() {
1491

    
1492
      // init
1493
      if(' . $showThumbnails . ' == 1){
1494
      jQuery(\'.media_gallery\').show(20);
1495
  } else {
1496
      jQuery(\'.media_gallery\').hide(20);
1497
  }
1498
      // add change hander
1499
      jQuery(\'#showThumbnails\').change(
1500
      function(event){
1501
      var state = 0;
1502
      if(jQuery(this).is(\':checked\')){
1503
      jQuery(\'.media_gallery\').show(20);
1504
      state = 1;
1505
  } else {
1506
      jQuery(\'.media_gallery\').hide(20);
1507
  }
1508
      // store state in session variable
1509
      var uri = \'' . $setSessionUri . '\' + state;
1510
      jQuery.get(uri);
1511
  });
1512
  });',
1513
  array('type' => "inline", 'scope' => JS_DEFAULT));
1514

    
1515
  drupal_set_title(t('Search results'), PASS_THROUGH);
1516

    
1517
  return theme('cdm_search_results', array(
1518
    'pager' => $taxonPager,
1519
    'path' => 'cdm_dataportal/search/results/taxon',
1520
    'query_parameters' => $_REQUEST,
1521
    ));
1522
}
1523

    
1524
/**
1525
 * Returns the state of the the showThumbnails flag set in the
1526
 * users session ($_SESSION['pageoption']['searchtaxa']['showThumbnails']).
1527
 *
1528
 * @return Ambigous <boolean, number>
1529
 *    returns 1 if the flag is set
1530
 */
1531
function do_showThumbnails() {
1532
  static $showThumbnails = null;
1533

    
1534
  if($showThumbnails == null) {
1535
    $showThumbnails = FALSE;
1536
    if (isset($_SESSION['pageoption']['searchtaxa']['showThumbnails'])) {
1537
      $showThumbnails = $_SESSION['pageoption']['searchtaxa']['showThumbnails'];
1538
    }
1539
    if (!is_numeric($showThumbnails)) {
1540
      $showThumbnails = 1;
1541
    }
1542
  }
1543

    
1544
  return $showThumbnails;
1545
}
1546

    
1547
/**
1548
 * View which transforms XML output from a given webservice endpoint into JSON.
1549
 */
1550
/*
1551
 function cdm_view_xml2json(){
1552
 $file = arg(2);
1553
 $datastr = file_get_contents(variable_get('cdm_webservice_url', '').$file);
1554
 return  xml2json::transformXmlStringToJson($datastr);
1555
 }
1556
 */
1557

    
1558
/* ====================== other functions ====================== */
1559
/**
1560
 * Creates a URL to the taxon page specified by the $uuid parameter.
1561
 *
1562
 * The URL will be prepended with a path element to a specific taxon page tab.
1563
 *
1564
 * This tab is either taken from the CDM_DATAPORTAL_DEFAULT_TAXON_TAB which can
1565
 * be set globally in the administrative settings or individually in the user
1566
 * profile. If the CDM_DATAPORTAL_DEFAULT_TAXON_TAB value is set to LAST_VISITED_TAB
1567
 * the last portal will stay on this last tab.
1568
 *
1569
 * A third option is offerered by the $page_tab parameter which allows overwriting this
1570
 * internal mechanism by a specific value.
1571
 *
1572
 * @param string $uuid
1573
 *   The UUID of the taxon.
1574
 * @param string $page_tab
1575
 *   Overwriting the preset mechanism by defining specific value for the
1576
 *   taxon page tab.
1577
 *
1578
 * @return string
1579
 *   The created URL.
1580
 */
1581
function path_to_taxon($uuid, $page_tab = FALSE) {
1582

    
1583
  $tab = get_default_taxon_tab();
1584
  $values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1585

    
1586
  if (!$uuid) {
1587
    return FALSE;
1588
  }
1589

    
1590
  if ($page_tab) {
1591
    return 'cdm_dataportal/taxon/' . $uuid . '/' . $page_tab;
1592
  }
1593
  elseif (!$tab || strtolower($tab) == 'general') {
1594
    return 'cdm_dataportal/taxon/' . $uuid;
1595
  }
1596
  elseif (get_last_taxon_page_tab() &&   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]) {
1597
    return 'cdm_dataportal/taxon/' . $uuid . '/' . get_last_taxon_page_tab();
1598
  }
1599
  else {
1600
    return 'cdm_dataportal/taxon/' . $uuid . '/' . strtolower($tab);
1601
  }
1602
}
1603

    
1604
/**
1605
 * @todo Please document this function.
1606
 * @see http://drupal.org/node/1354
1607
 */
1608
function uri_to_synonym($synonymUuid, $acceptedUuid) {
1609
  $acceptedPath = path_to_taxon($acceptedUuid, "synonymy");
1610
  return url($acceptedPath, array('query' => array('highlite' => $synonymUuid)));
1611
}
1612

    
1613
/**
1614
 * @todo Please document this function.
1615
 * @see http://drupal.org/node/1354
1616
 */
1617
function path_to_key($keyType, $keyUuid) {
1618
  if (!$keyUuid || !$keyType) {
1619
    return FALSE;
1620
  }
1621
  $keyType{0} = strtolower($keyType{0});
1622
  return "cdm_dataportal/" . $keyType . "/$keyUuid";
1623
}
1624

    
1625
/**
1626
 * @todo Please document this function.
1627
 * @see http://drupal.org/node/1354
1628
 */
1629
function path_to_reference($uuid) {
1630
  if (!$uuid) {
1631
    return FALSE;
1632
  }
1633
  return 'cdm_dataportal/reference/' . $uuid;
1634
}
1635

    
1636
/**
1637
 * @todo Please document this function.
1638
 * @see http://drupal.org/node/1354
1639
 */
1640
function path_to_name($name_uuid) {
1641
  $res = FALSE;
1642
  if ($name_uuid) {
1643
    $res = 'cdm_dataportal/name/' . $name_uuid;
1644
  }
1645
  return $res;
1646
}
1647

    
1648
/**
1649
 * @todo Please document this function.
1650
 * @see http://drupal.org/node/1354
1651
 */
1652
function path_to_media($uuid, $representaion_uuid = FALSE, $partId = FALSE) {
1653
  if (!$uuid) {
1654
    return FALSE;
1655
  }
1656
  $out = 'cdm_dataportal/media/' . $uuid;
1657
  if ($representaion_uuid) {
1658
    $out .= '/' . $representaion_uuid;
1659
    if ($partId !== FALSE) {
1660
      $out .= '/' . $partId;
1661
    }
1662
  }
1663
  return $out;
1664
}
1665

    
1666
/**
1667
 * Compares thisRank with thatRank.
1668
 *
1669
 * Returns a negative integer, zero, or a positive integer
1670
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1671
 * e.g:
1672
 * <ul>
1673
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1674
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1675
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1676
 * </ul>
1677
 * <p>
1678
 * This compare logic of the underlying webservice is the
1679
 * <b>inverse logic</b> of the the one implemented in
1680
 * java.lang.Comparable#compareTo(java.lang.Object)
1681
 *
1682
 * @param $thisRankUuid
1683
 * @param $thatRankUuid
1684
 *
1685
 * @return int
1686
 *   A negative integer, zero, or a positive integer
1687
 *   as the thisRank is lower than, equal to, or higher than thatRank.
1688
 */
1689
function rank_compare($thisRankUuid, $thatRankUuid) {
1690
  $result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1691
  return $result->Integer;
1692
}
1693

    
1694
/**
1695
 * Composes an HTML element class attribute value composed of
1696
 * the shortname of the cdm class and the uuid of the entity.
1697
 * This class attribute should be used whereever an cdm-entity is rendered.
1698
 *
1699
 * These according class selectors in css must be escaped, eg:
1700
 *    .cdm\:TextData
1701
 *
1702
 * @param $cdmEntity
1703
 */
1704
function html_class_atttibute_ref($cdmEntity) {
1705

    
1706
  if (is_cdm_entity($cdmEntity)) {
1707
    return "cdm:" . $cdmEntity->class . " uuid:" . $cdmEntity->uuid;
1708
  }
1709
}
1710

    
1711
/**
1712
 * Preprocess the taggedName to normalize newly introduced tagtypes like hybridSign, separator, .. more?
1713
 *
1714
 * @param unknown_type $taggedTextList
1715
 */
1716
function normalize_TaggedName(&$taggedTextList) {
1717

    
1718
  if (is_array($taggedTextList)) {
1719

    
1720
    // First pass: rename.
1721
    for ($i = 0; $i < count($taggedTextList); $i++) {
1722

    
1723
      if ($taggedTextList[$i]->type == "hybridSign") {
1724
        $taggedTextList[$i]->type = "name";
1725
      }
1726
    }
1727

    
1728
    // Second pass: resolve separators.
1729
    $taggedNameListNew = array();
1730
    for ($i = 0; $i < count($taggedTextList); $i++) {
1731

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

    
1734
        if ($taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
1735
          $taggedName = $taggedTextList[$i];
1736
          $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
1737
          $taggedNameListNew[] = $taggedName;
1738
          ++$i;
1739
          ++$i;
1740
        }
1741
      }
1742
      else {
1743
        $taggedNameListNew[] = $taggedTextList[$i];
1744
      }
1745
    }
1746
    $taggedTextList = $taggedNameListNew;
1747
  }
1748
}
1749

    
1750
/**
1751
 * Creates a short taxonname.
1752
 *
1753
 * The short name is created by using the taggename field of
1754
 * NameSTO or NameTO instances.
1755
 * If the taggename if empty the fullname will be returned.
1756
 *
1757
 * @param unknown_type $name
1758
 *   Name or TreeNode.
1759
 *
1760
 * @return string
1761
 */
1762
function cdm_dataportal_shortname_of($name) {
1763
  $nameStr = '';
1764

    
1765
  normalize_TaggedName($name->taggedTitle);
1766

    
1767
  // Get all tagged text tokens of the scientific name.
1768
  foreach ($name->taggedTitle as $tagtxt) {
1769
    if ($tagtxt->type == 'name' || $tagtxt->type == 'rank') {
1770
      $nameStr .= ($nameStr ? ' ' : '') . $tagtxt->text;
1771
    }
1772
  }
1773
  $nameStr = trim($nameStr);
1774

    
1775
  if ($nameStr) {
1776

    
1777
    // Do not return short names for these.
1778
    if ($name->unplaced || $name->excluded) {
1779
      return $nameStr;
1780
    }
1781

    
1782
    /*
1783
    1st capture group (^[a-zA-Z]): First letter of uninomial.
1784
    Second capture group ([\p{L}]+): remaining letters of uninomial ([\p{L} = an UTF-8 letter).
1785
    Third capture group (\s+[^(\x2E]+\s+.+$|\s+[a-zA-Z]+$): letters of name,
1786
    but only matching if no '(' or '.' in second word of name,        ( \x2E = '.')
1787
    OR only one specific epithet \s+[\p{L}\x22\x2D\xD7]+$             (\x22= '"', \x2D='-', \xD7='×' )
1788
    */
1789
    $pattern = '/(^[a-zA-Z])([\p{L}]+)(\s+[^(\x2E]+\s+.+$|\s+[\p{L}\x22\x2D\xD7]+$)/u';
1790
    if (preg_match($pattern, $nameStr, $matches, PREG_OFFSET_CAPTURE)) {
1791
      return $matches[1][0] . "." . $matches[3][0];
1792
    }
1793
    else {
1794
      return $nameStr;
1795
    }
1796
  }
1797
  else {
1798
    return $name->titleCache;
1799
  }
1800
}
1801

    
1802
/**
1803
 * Check if a taxon is accepted by the current taxonomic tree.
1804
 *
1805
 * @param mixed $taxon
1806
 *   The Taxon obkect to check.
1807
 *
1808
 * @return bool
1809
 *   Returns TRUE if $taxon is accepted, FALSE otherwise.
1810
 */
1811
function _cdm_dataportal_acceptedByCurrentView($taxon) {
1812

    
1813
  $defaultTreeUuid = get_taxonomictree_uuid_selected();
1814

    
1815
  if (isset($taxon->taxonNodes)) {
1816
    $taxonNodes = $taxon->taxonNodes;
1817
  }
1818
  else {
1819
    $taxonNodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $taxon->uuid);
1820
  }
1821

    
1822
  if ($taxon->class == "Taxon" && isset($taxonNodes)) {
1823
    foreach ($taxonNodes as $node) {
1824
      if (is_object($node->classification)) {
1825
        if ($node->classification->uuid == $defaultTreeUuid) {
1826
          return TRUE;
1827
        }
1828
      }
1829
      else {
1830
        if ($node->classification == $defaultTreeUuid) {
1831
          return TRUE;
1832
        }
1833
      }
1834
    }
1835
  }
1836

    
1837
  return FALSE;
1838
}
1839

    
1840
/**
1841
 * Workaround for missing original source type.
1842
 *
1843
 * idNamespace is always set in these cases.
1844
 * @todo improve documentation of this function.
1845
 *
1846
 * @param unknown_type $source
1847
 *
1848
 * @return unknown_type
1849
 */
1850
function _is_original_source_type($source) {
1851
  return !$source->idNamespace && strlen($source->idNamespace) == 0;
1852
}
1853

    
1854
/**
1855
 * @todo Please document this function.
1856
 * @see http://drupal.org/node/1354
1857
 */
1858
function _is_invers_taxonRelationship($taxonRelationship, $focusedTaxon) {
1859
  return $taxonRelationship->toTaxon->uuid == $focusedTaxon->uuid;
1860
}
1861

    
1862
/**
1863
 * Gets the metadata info such as title or artist of a media file.
1864
 *
1865
 * The function tries at first to get all the info from the file metadata
1866
 * and if it is not avaible look at the media file info stored at the database.
1867
 *
1868
 * @param mixed $media
1869
 *   The media file object for which to get the metadata.
1870
 *
1871
 * @return array
1872
 *   The array with the available specified metadata info.
1873
 * TODO rename to read_media_metadata() and move to *.module.
1874
 */
1875
function cdm_read_media_metadata($media) {
1876

    
1877
  $metadata_caption = array(
1878
    'title' => '',// Media_metadata and media.
1879
    'artist' => '',// Media_metadata and media.
1880
    'rights',// Media_metadata and media.
1881
    'location',// Media_metadata.
1882
    'filename' => '',// Media.
1883
    'mediacreated' => '',// Media.
1884
    'description' => '',
1885
  );// Media.
1886

    
1887
  // Getting the media metadata.
1888
  $media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1889
  $media_metadata_aux = (array) $media_metadata;
1890

    
1891
  // Filename.
1892
  if (isset($media->representations[0]->parts[0]->uri)) {
1893
    $fileUri = $media->representations[0]->parts[0]->uri;
1894
    $filename = substr($fileUri, strrpos($fileUri, "/") + 1);
1895
    $metadata_caption['filename'] = $filename;
1896
  }
1897
  else {
1898
    $metadata_caption['filename'] = '';
1899
  }
1900

    
1901
  // Title.
1902
  if (!empty($media_metadata->ObjectName)) {
1903
    $metadata_caption['title'] = $media_metadata->ObjectName;
1904
  }
1905
  elseif ($media_metadata_aux['Object Name']) {
1906
    $metadata_caption['title'] = $media_metadata_aux['Object Name'];
1907
  }
1908
  elseif ($media->title_L10n) {
1909
    $metadata_caption['title'] = $media->title_L10n;
1910
  }
1911
  elseif ($media->titleCache) {
1912
    $metadata_caption['title'] = $media->titleCache;
1913
  }
1914

    
1915
  // Append description to title.
1916
  if (!empty($media->description_L10n)) {
1917
    $metadata_caption['title'] .= '<span class="media-description">' . $media->description_L10n . '<span>';
1918
  }
1919

    
1920
  // Artist.
1921
  if ($media_metadata->Artist) {
1922
    $metadata_caption['artist'] = ($media_metadata->Artist ? '' . $media_metadata->Artist : '');
1923
  }
1924
  elseif ($media->artist->titleCache) {
1925
    $metadata_caption['artist'] = $media->artist->titleCache;
1926
  }
1927

    
1928
  // Copyright.
1929
  $metadata_caption['rights'] = array(
1930
    'copyright' => array('agentNames' => array()),
1931
    'license' => array(
1932
      'agentNames' => array(),
1933
      'types' => array(),
1934
      'abbreviatedTexts' => array(),
1935
      'uris' => array(),
1936
    ),
1937
  );
1938
  if ($media_metadata->Copyright) {
1939
    $metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1940
  }
1941
  elseif (isset($media->rights) && is_array($media->rights)) {
1942
    foreach ($media->rights as $right) {
1943
      switch ($right->term->uuid) {
1944
        case UUID_RIGHTS_LICENCE:
1945
          $metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? '' . $right->agent->firstname . ' ' . $right->agent->lastname : '');
1946
          $metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? '' . $right->representation_L10n : '');
1947
          $metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? '' . $right->abbreviatedText : '');
1948
          $metadata_caption['rights']['license']['uris'][] = ($right->uri ? '' . $right->uri : '');
1949
          break;
1950
        case UUID_RIGHTS_COPYRIGHT:
1951
          $metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1952
          break;
1953
      }
1954
    }
1955
  }
1956
  else {
1957
    $metadata_caption['rights']['agentNames'][] = '';
1958
  }
1959

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

    
1963
  // Location.
1964
  $metadata_caption['location'] = array();
1965
  $metadata_caption['location']['sublocation'] = !empty($media_metadata->Sublocation) ? $media_metadata->Sublocation : FALSE;
1966
  $metadata_caption['location']['city'] = !empty($media_metadata->City) ? $media_metadata->City : FALSE;
1967
  $metadata_caption['location']['province'] = !empty($media_metadata->Province) ? $media_metadata->Province : FALSE;
1968
  $metadata_caption['location']['country'] = !empty($media_metadata->Country)? $media_metadata->Country : FALSE;
1969

    
1970
  /*
1971
   // Creation date.
1972
   if($media_metadata["Modify Date"])
1973
   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1974
   else
1975
   $metadata_caption['mediacreated'] = $media->created;
1976
   */
1977

    
1978
  // Returned value.
1979
  return $metadata_caption;
1980
}
1981

    
1982
/**
1983
 * Collects all the media from a list of description elements.
1984
 *
1985
 * @param array $descriptionElements
1986
 *   The description elements from which to collect the media.
1987
 *
1988
 * @return array
1989
 *   The output with all the collected media.
1990
 */
1991
function cdm_dataportal_media_from_descriptionElements($descriptionElements) {
1992

    
1993
  $outArrayOfMedia = array();
1994

    
1995
  // Avoiding a warning box in Drupal for Flora Malesiana.
1996
  if (isset($descriptionElements) && is_array($descriptionElements)) {
1997
    foreach ($descriptionElements as $descriptionElement) {
1998
      if (isset($descriptionElement->media) && is_array($descriptionElement->media)) {
1999
        foreach ($descriptionElement->media as $media) {
2000
          if (is_object($media)) {
2001
            $outArrayOfMedia[] = $media;
2002
          }
2003
        }
2004
      }
2005
    }
2006
  }
2007
  return $outArrayOfMedia;
2008
}
2009

    
2010
/**
2011
 * @todo Please document this function.
2012
 * @see http://drupal.org/node/1354
2013
 *
2014
 * @param array $cdmBase_list
2015
 *   An array of CdmBase instances or a single instance.
2016
 * @param string $footnote_list_key
2017
 *
2018
 * @return unknown
2019
 */
2020
function cdm_annotations_as_footnotekeys($cdmBase_list, $footnote_list_key = NULL) {
2021
  // Comment @WA: undefined variable.
2022
  /*
2023
   static $annotations_types_filter;
2024
   if(!$annotations_types_filter) {
2025
   unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2026
   }
2027
   */
2028
  unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2029

    
2030
  $footNoteKeys = array();
2031

    
2032
  // Is argument cdmBase an array?
2033
  if (!is_array($cdmBase_list)) {
2034
    $cdmBase_array = array();
2035
    $cdmBase_array[] = $cdmBase_list;
2036
  }
2037
  else {
2038
    $cdmBase_array = $cdmBase_list;
2039
  }
2040

    
2041
  // Getting the key for the footnotemanager.
2042
  if (isset($footnote_list_key)) {
2043
    $footnoteListKey = $footnote_list_key;
2044
  }
2045
  else {
2046
    $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
2047
  }
2048

    
2049
  // Adding the footnotes keys.
2050
  $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
2051
  foreach ($cdmBase_array as $cdmBase_element) {
2052
    $annotations = cdm_ws_getAnnotationsFor($cdmBase_element, variable_get('annotations_types_as_footnotes', $annotations_types_filter));
2053
    if (is_array($annotations)) {
2054
      foreach ($annotations as $annotation) {
2055
        $footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
2056
      }
2057
    }
2058
  }
2059

    
2060
  return $footNoteKeys;
2061
}
2062

    
2063
// @WA Comment: should this not be a theme function?
2064
/**
2065
 *  Creates a CDM Dynabox.
2066
 *
2067
 * @param string $label
2068
 *   The clickable text to show.
2069
 * @param string $content_url
2070
 *   The cdm REST service request url wich will deliver the content to be shown
2071
 *   once the dynabox toggles open.
2072
 * @param string $theme
2073
 *   The theme to be used for rendering the cdm REST service reponse with is
2074
 *   returned from the $content_url.
2075
 * @param string $link_alt_text
2076
 *   The value for the alt attribute of the dynabox link.
2077
 * @param array $enclosingtags
2078
 *   An array with two elements: $enclosingtags[0] will be used for the dynabox
2079
 *   element itself, $enclosingtags[1] is the tag to be used for the
2080
 *   dynabox_content.
2081
 *
2082
 * @return string
2083
 *   Returns HTML for a dynabox.
2084
 */
2085
function cdm_dynabox($label, $content_url, $theme, $link_alt_text, $enclosingtags = array('li', 'ul')) {
2086
  $out = '';
2087
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/cdm_dynabox.js');
2088

    
2089
  $cdm_proxy_url = url('cdm_api/proxy/' . urlencode($content_url) . "/$theme");
2090
  $out .= '<!-- ' . $content_url . ' -->';
2091
  $out .= '<' . $enclosingtags[0] . ' class="dynabox"><a href="#" class="label" alt="' . t($link_alt_text) . '">' . $label . '</a>';
2092
  $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] . '>';
2093
  $out .= '</' . $enclosingtags[0] . '>';
2094
  return $out;
2095
}
2096

    
2097
/**
2098
 * Checks whether a feature has any description elements.
2099
 *
2100
 * @param mixed $featureNode
2101
 *   A feature node as produced by the function _mergeFeatureTreeDescriptions().
2102
 *
2103
 * @see _mergeFeatureTreeDescriptions()
2104
 *
2105
 * @return bool
2106
 *   Returns TRUE if the given $featureNode or any of its subordinate nodes
2107
 *   contains at least one non empty TextData or at least one DescriptionElement
2108
 *   of an other type. A TextData element holding a multilanguageText or a
2109
 *   source reference is considered to be not empty.
2110
 */
2111
function hasFeatureNodeDescriptionElements($featureNode) {
2112

    
2113
  if (isset($featureNode->descriptionElements) && is_array($featureNode->descriptionElements) && count($featureNode->descriptionElements) > 0) {
2114
    foreach ($featureNode->descriptionElements as $descriptionElement) {
2115
      if ($descriptionElement->class != "TextData" || isset($descriptionElement->multilanguageText_L10n->text) && $descriptionElement->multilanguageText_L10n->text != '' || isset($descriptionElement->sources[0])) {
2116
        return TRUE;
2117
      }
2118
    }
2119
  }
2120
  elseif (isset($featureNode->children) && is_array($featureNode->children)) {
2121
    foreach ($featureNode->children as $child) {
2122
      if (hasFeatureNodeDescriptionElements($child)) {
2123
        return TRUE;
2124
      }
2125
    }
2126
  }
2127
  return FALSE;
2128
}
(6-6/13)