Project

General

Profile

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

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

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

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

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

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

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

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

    
51
function _add_js_openlayers_map(){
52

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

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

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

    
71
	if( isset($baseLayers['gmap']) || isset($baseLayers['gsat']) || isset($baseLayers['ghyb']) ){
72
	  drupal_set_html_head('<script src=http://maps.google.com/maps?file=api&amp;v=2&amp;sensor=false&amp;key='.$gmap_api_key.'" type="text/javascript"></script>');
73
	  drupal_set_html_head('<script src="http://dev.virtualearth.net/mapcontrol/mapcontrol.ashx?v=6.1" type="text/javascript"></script>');
74
	}
75

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

    
93
}
94

    
95

    
96
function get_openlayers_map($width, $occurrenceQuery = false, $distributionQuery = false, $legendFormatQuery = false, $map_caption = false ){
97

    
98
	_add_js_openlayers_map();
99

    
100
	$out = '<div id="openlayers">';
101
	$out .= '<div id="openlayers_map" class="smallmap"';
102
	$out .= ' style="width: ' . $width . 'px; height:'.( $width / 2).'px"';
103
	if($occurrenceQuery){
104

    
105
		//fix $occurrenceQuery
106
		$occurrenceQuery .= '&ms=400,350';
107
		$occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
108
		$occurrenceQuery .= '&legend=0'; //TODO add to cdm service?
109

    
110
		$out .= ' occurrenceQuery="'.$occurrenceQuery.'"';
111
	}
112
	if($distributionQuery){
113
		$out .= ' distributionQuery="'.$distributionQuery.'"';
114
	}
115
	if($legendFormatQuery){
116
		$out .= ' legendFormatQuery="'.$legendFormatQuery.'"';
117
	}
118
	$out .= '></div></div>';
119

    
120
	// showing map caption
121
	if($map_caption){
122
		$out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />'; //FIXME: replace <br> by according css style
123
		$out .= '</div>';
124
	}
125
	return $out;
126
}
127

    
128
/* ====================== hook implementations ====================== */
129

    
130

    
131
/**
132
 * Implementation of hook_perm()
133
 *
134
 * Valid permissions for this module
135
 * @return array An array of valid permissions for the portfolio module
136
 */
137
function cdm_dataportal_perm() {
138
	return array(
139
    	'administer cdm_dataportal',
140
      'cdm_dataportal view notes',
141
	//TODO which else permission are required? -> check the WP6 requirements document
142
	);
143
}
144

    
145

    
146
/**
147
 * Implementation of hook_menu()
148
 */
149
function cdm_dataportal_menu($may_cache) {
150
	$items = array();
151

    
152
	cdm_dataportal_menu_admin($may_cache, $items);
153
	cdm_dataportal_menu_help($may_cache, $items);
154

    
155
	if ($may_cache) {
156

    
157
	 $items[] = array(
158
	    'path' => 'cdm_dataportal/names',
159
	    'callback' => 'cdm_dataportal_view_names',
160
	    'access' => true,
161
	    'type' => MENU_CALLBACK,
162
		);
163
		// optional callback arguments: page
164

    
165
		$items[] = array(
166
      'path' => 'cdm_dataportal/taxon',
167
      'callback' => 'cdm_dataportal_taxon_page_view',
168
      'access' => true,
169
      'type' => MENU_CALLBACK,
170
		// expected callback arguments: uuid
171
		);
172

    
173
		$items[] = array(
174
      'path' => 'cdm_dataportal/name',
175
      'callback' => 'cdm_dataportal_name_page_view',
176
      'access' => true,
177
      'type' => MENU_CALLBACK,
178
		// expected callback arguments: uuid
179
		);
180

    
181
		$items[] = array(
182
      'path' => 'cdm_dataportal/reference',
183
      'callback' => 'cdm_dataportal_view_reference',
184
      'access' => true,
185
      'type' => MENU_CALLBACK,
186
		// expected callback arguments: uuid
187
		);
188

    
189
		$items[] = array(
190
      'path' => 'cdm_dataportal/reference/list',
191
      'callback' => 'cdm_dataportal_view_reference_list',
192
      'access' => true,
193
      'type' => MENU_CALLBACK,
194
		// expected callback arguments: uuid
195
		);
196

    
197
		$items[] = array(
198
      'path' => 'cdm_dataportal/media',
199
      'callback' => 'cdm_dataportal_view_media',
200
      'access' => true,
201
      'type' => MENU_CALLBACK,
202
		// expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
203
		);
204

    
205
		$items[] = array(
206
      'path' => 'cdm_dataportal/polytomousKey',
207
      'callback' => 'cdm_dataportal_view_polytomousKey',
208
      'access' => true,
209
      'type' => MENU_CALLBACK,
210
    // expected callback arguments: polytomousKey->uuid
211
    );
212

    
213
		$items[] = array(
214
      'path' => 'cdm_dataportal/search',
215
      'callback' => 'cdm_dataportal_view_search_advanced',
216
      'access' => true,
217
      'type' => MENU_CALLBACK,
218
		);
219

    
220
		$items[] = array(
221
      'path' => 'cdm_dataportal/search/taxon',
222
      'callback' => 'cdm_dataportal_view_search_taxon',
223
      'access' => true,
224
      'type' => MENU_CALLBACK,
225
		);
226

    
227
		$items[] = array(
228
      'path' => 'cdm/xml2json',
229
      'callback' => 'cdm_view_xml2json',
230
      'access' => true,
231
      'type' => MENU_CALLBACK,
232
		);
233

    
234
	}elseif (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid)) {
235
		//user configuration of cdm_dataportal
236
		$items[] = array('path' => 'user/'.$uid.'/cdm_dataportal',
237
        'title' => t('cdm_dataportal'),
238
        'access' => TRUE,
239
        'callback' => 'drupal_get_form',
240
        'callback arguments' => array('cdm_dataportal_user_form'),
241
        'type' => MENU_LOCAL_TASK,
242
        'weight' => 10,
243
      );
244
	} else {
245
		// may not cache
246
		// --- local tasks for Taxon
247
		$items[] = array(
248
      'path' => 'cdm_dataportal/name/'.arg(2),
249
		//'callback' => 'cdm_dataportal_view_name',
250
		  'callback' => 'cdm_dataportal_name_page_view',
251
      'callback arguments' => array(arg(2), arg(3), arg(4)),
252
      'access' => true,
253
      'type' => MENU_CALLBACK,
254
		);
255

    
256
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
257

    
258
			$items[] = array(
259
      'path' => 'cdm_dataportal/taxon/'.arg(2),
260
      'title' => theme('cdm_taxonpage_tab', 'General'),
261
      'callback' => 'cdm_dataportal_taxon_page_view',
262
      'access' => true,
263
      'type' => MENU_CALLBACK,
264
      'weight' => 1,
265
      'callback arguments' => array(arg(2), "description")
266
			// expected callback arguments: name_uuid
267
			);
268

    
269
			$items[] = array(
270
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/all',
271
      'title' => theme('cdm_taxonpage_tab', 'General'),
272
      'callback' => 'cdm_dataportal_taxon_page_view',
273
      'access' => true,
274
      'type' => MENU_CALLBACK,
275
      'weight' => 2,
276
      'callback arguments' => array(arg(2), "all")
277
			// expected callback arguments: name_uuid
278
			);
279

    
280
			$items[] = array(
281
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/description',
282
      'title' => theme('cdm_taxonpage_tab', 'General'),
283
      'callback' => 'cdm_dataportal_taxon_page_view',
284
      'access' => true,
285
      'type' => MENU_DEFAULT_LOCAL_TASK,
286
      'weight' => 2,
287
      'callback arguments' => array(arg(2), "description")
288
			// expected callback arguments: name_uuid
289
			);
290

    
291
			$items[] = array(
292
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
293
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
294
      'callback' => 'cdm_dataportal_taxon_page_view',
295
      'access' => true,
296
      'type' => MENU_LOCAL_TASK,
297
      'weight' => 4,
298
      'callback arguments' => array(arg(2), "synonymy", arg(4))
299
			// expected callback arguments: name_uuid
300
			);
301
			$items[] = array(
302
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
303
      'title' => theme('cdm_taxonpage_tab', 'Images'),
304
      'callback' => 'cdm_dataportal_taxon_page_view',
305
      'access' => true,
306
      'type' => MENU_LOCAL_TASK,
307
      'weight' => 5,
308
      'callback arguments' => array(arg(2), "images")
309
			// expected callback arguments: name_uuid
310
			);
311

    
312
		 $items[] = array(
313
		 'path' => 'cdm_dataportal/taxon/'.arg(2).'/specimens',
314
		 'title' => theme('cdm_taxonpage_tab', 'Specimens'),
315
		 'callback' => 'cdm_dataportal_taxon_page_view',
316
		 'access' => true,
317
		 'type' => MENU_LOCAL_TASK,
318
		 'weight' => 6,
319
		 'callback arguments' => array(arg(2), "specimens")
320
		 // expected callback arguments: name_uuid
321
		 );
322

    
323
		 $items[] = array(
324
     'path' => 'cdm_dataportal/taxon/'.arg(2).'/keys',
325
     'title' => theme('cdm_taxonpage_tab', 'Keys'),
326
     'callback' => 'cdm_dataportal_taxon_page_view',
327
     'access' => true,
328
     'type' => MENU_LOCAL_TASK,
329
     'weight' => 6,
330
     'callback arguments' => array(arg(2), "keys")
331
     // expected callback arguments: name_uuid
332
     );
333
		}
334
	}
335

    
336
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
337
	//drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
338
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
339

    
340
	return $items;
341

    
342
}
343
/**
344
 * The function generate form for own user cdm dataportal configurations
345
 */
346
function cdm_dataportal_user_form() {
347

    
348
	global $user;
349
    $checkbox_value = 'cdm_dataportal_' .$user->uid . '_default_tab_active';
350

    
351
	$form['check'] = array
352
    (
353
    '#type'            => 'checkbox',
354
    '#title'         => t('Activate user default configuration'),
355
    '#default_value'   => variable_get($checkbox_value, 0),
356
    '#description' => t('Check this if you want configure your own default tab from the below menu.')
357
    );
358

    
359
	$form['cdm_dataportal_user_form'] =  array(
360
      '#type'          => 'select',
361
      '#title'         => t('Default tab to display'),
362
	    '#default_value' => get_default_taxon_tab(true),
363
      '#options'       => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
364
      '#description'   => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
365
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
366
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
367
	);
368

    
369
	$form['submit'] = array(
370
	  '#type' => 'submit',
371
	  '#value' => t('Submit')
372
	);
373

    
374
	return $form;
375
}
376

    
377
/**
378
 * The function submit the user cdm dataportal configurations
379
 * @param unknown_type $form
380
 * @param unknown_type $form_values
381
 */
382
function cdm_dataportal_user_form_submit($form, $form_values) {
383
	global $user;
384
	$msg_type = 'status';
385
	$username = $user->name;
386
	$variable_to_use = 'cdm_dataportal_' .$user->uid . '_default_tab';
387

    
388
	//if is the right user the variables are setted
389
	if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid) && $user->uid==$uid){
390
		$variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
391
		variable_set($variable_to_use . '_active', $form_values['check']);
392
		variable_set($variable_to_use, $form_values['cdm_dataportal_user_form']);
393
		if ($form_values['check']){
394
			drupal_set_message('The user default tab will be used for the next taxon site visit.');
395
			drupal_set_message('The user default tab have been changed to: '
396
            . $variable[variable_get($variable_to_use, 0)]
397
            . ' for the user ' . $username, $msg_type);
398
		}else{
399
			drupal_set_message('The user default tab wont be used for the next taxon site, check the box if you want to use the user default configuration.');
400
		}
401
	//problem with the user id => variables wont be saved
402
	}else{
403
		$msg_type = 'warning';
404
		drupal_set_message('Default tab have not been saved due to user id problems', $msg_type);
405
	}
406
}
407

    
408
/**
409
 * Implementation of hook_block()
410
 *
411
 * Provides the following blocks:
412
 *  0: list of links useful during development
413
 *
414
 * @param String $op
415
 * @param int $delta
416
 */
417
function cdm_dataportal_block($op='list', $delta=0) {
418
	// listing of blocks, such as on the admin/block page
419
	if ($op == "list") {
420
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
421
		//		$block[1]["info"] = t("CDM DataPortal Credits");
422
		$block[2]["info"] = t("CDM Search Taxa");
423
		//$block[3]["info"] = t("CDM Filters");
424
		$block[4]["info"] = t("CDM Dataportal Print");
425
		$block["keys"]["info"] = t("CDM identification keys");
426
		return $block;
427
	}
428
	else if ($op == 'view') {
429
		switch($delta){
430
			//			case 1:
431
			//				$block['subject'] = t('Credits');
432
			//				$block['content'] = theme('cdm_credits');
433
			//				return $block;
434
			case 2:
435
				$block['subject'] = t('Search taxa');
436
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
437
				if (variable_get('cdm_dataportal_show_advanced_search', 1)){
438
				    $block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
439
				}
440
				return $block;
441
			case 4:
442
				$block['subject'] = t('<none>');
443
				$block['content'] = theme('cdm_print_button');;
444
				return $block;
445
			case "keys":
446
				$block['subject'] = t('Identification Keys');
447
        $block['content'] = theme('cdm_block_IdentificationKeys');
448
        return $block;
449
		}
450
	}
451
}
452

    
453

    
454

    
455
/*
456
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
457
 $_SESSION['cdm'] = null;
458
 if(is_string($cdm_ws_uri_update)){
459
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
460
 }
461
 }
462

    
463
 function cdm_dataportal_session_validate(){
464

    
465
 if(!isset($_SESSION['cdm']['ws_uri'])){
466
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
467
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
468
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
469
 }
470
 }
471
 */
472

    
473
function cdm_dataportal_search_taxon_form($advancedForm = false){
474

    
475
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
476
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
477
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
478
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
479
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
480
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
481

    
482
	$url = 'cdm_dataportal/search/taxon';
483
	$form['#method'] = 'get';
484
	$form['#process'] = array('cdm_dataportal_search_process' => array());
485
	$form['#action'] = url($url, NULL, NULL, true);
486

    
487
	$form['query'] = array(
488
    '#delta' => 0,
489
    '#type' => 'textfield',
490
    '#size' => 20,
491
    '#attributes' => array('title' => t('Enter the name or part of a name you wish to search for. The asterisk  character * can always be used as wildcard')),
492
    '#value' => $preset_query,
493
	);
494

    
495
	$form['search'] = array(
496
      '#delta' => 1,
497
      '#tree' => true,
498
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
499
      '#title' => t('Options')
500
	);
501

    
502
	$form['search']['tree'] = array(
503
    '#delta' => -1,
504
    '#type' => 'hidden',
505
    '#value' => get_taxonomictree_uuid_selected()
506
	);
507

    
508

    
509
	// clean URL get forms breaks if we don't give it a 'q'.
510
	if (!(bool)variable_get('clean_url', '0')) {
511
		$form['search']['q'] = array(
512
      '#delta' => -1,
513
      '#type' => 'hidden',
514
      '#value' => $url,
515
      '#name' => 'q',
516
		);
517
	}
518

    
519
	$form['search']['pageSize'] = array(
520
      '#delta' => -1,
521
      '#type' => 'hidden',
522
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
523
	);
524

    
525
	$form['search']['pageNumber'] = array(
526
      '#delta' => -1,
527
      '#type' => 'hidden',
528
      '#value' => 0
529
  );
530

    
531
	if($advancedForm){
532
		// general search parameters
533
		$form['search']['doTaxa'] = array(
534
      '#delta' => 2,
535
      '#type' => 'checkbox',
536
      '#title' => t('Search for accepted taxa'),
537
      '#value' => $preset_doTaxa
538
		);
539
		$form['search']['doSynonyms'] = array(
540
      '#delta' => 3,
541
      '#type' => 'checkbox',
542
      '#title' => t('Search for synonyms'),
543
      '#value' => $preset_doSynonyms
544
		);
545
		$form['search']['doTaxaByCommonNames'] = array(
546
      '#delta' => 4,
547
      '#type' => 'checkbox',
548
      '#title' => t('Search for common names'),
549
      '#value' => $preset_doTaxaByCommonNames
550
		);
551

    
552
		// Geographic Range
553
		$form['search']['geographic_range'] = array(
554
      '#type' => 'fieldset',
555
      '#delta' => 5,
556
      '#tree' => true,
557
      '#title' => t('Geographic range'),
558
		);
559

    
560
		$form['search']['geographic_range']['tdwg_level_select'] = array(
561
    '#type' => 'radios',
562
    '#title' => t('Select a TDWG distribution level and code'),
563
    '#default_value' => $tdwg_level_select,
564
    '#options' => array(
565
		t('TDWG level-1, i.e. a continent'),
566
		t('TDWG level-2'),
567
		t('TDWG level-3, i.e. a country'),
568
		t('TDWG level-4')
569
		)
570
		);
571
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
572
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
573
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
574
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
575

    
576
		$tdwg_js = '';
577
		foreach($tdwg as $key=>$tdwg_level){
578
			$tdwgOptions = array();
579
			$tdwgOptionsSelected = array();
580
			foreach($tdwg_level as $area){
581
				$representation = $area->representations[0];
582
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
583
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
584
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
585
				}
586
			}
587
			asort($tdwgOptions);
588
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
589
        '#type' => 'select',
590
        '#title'         => t('TDWG level').' '.$key,
591
        '#default_value' => $tdwgOptionsSelected,
592
        '#multiple' => TRUE,
593
        '#options' => $tdwgOptions
594
			);
595
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
596
		}
597

    
598
		drupal_add_js(
599
    "$(document).ready(function(){
600

    
601
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change(
602
        function(event){
603
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
604
          var i;
605
          for(i = 0; i < 4; i++){
606
            if(selectId == i){
607
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
608
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
609
            } else {
610
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
611
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
612
            }
613
          }
614
        }
615
      );
616

    
617
      $tdwg_js
618
    });",
619
    'inline');
620

    
621
	} else {
622
		$form['search']['doTaxa'] = array(
623
	      '#delta' => -2,
624
	      '#type' => 'hidden',
625
	      '#value' => 1
626
		);
627
		$form['search']['doSynonyms'] = array(
628
	      '#delta' => -3,
629
	      '#type' => 'hidden',
630
	      '#value' => 1
631
		);
632
		$form['search']['doTaxaByCommonNames'] = array(
633
	      '#delta' => -4,
634
	      '#type' => 'hidden',
635
	      '#value' => 0
636
		);
637
	}
638

    
639
	$form['submit'] = array(
640
	  '#delta' => 9,
641
	  '#type' => 'submit',
642
	  '#name' => '',
643
	  '#value' => t('Search')
644
	);
645

    
646
	return $form;
647
}
648

    
649
function cdm_dataportal_search_taxon_form_advanced(){
650
	return cdm_dataportal_search_taxon_form(true);
651
}
652

    
653
function cdm_taxonomictree_selector(){
654
	_add_js_treeselector();
655

    
656
	$out = drupal_get_form('cdm_taxonomictree_selector_form');
657

    
658
	return $out;
659
}
660

    
661

    
662
function cdm_taxonomictree_selector_form(){
663

    
664
	$url = url('cdm_api/setvalue/session', null);
665
	$form['#action'] = $url;
666

    
667
	$form['var'] = array(
668
        '#delta' => -3,
669
        '#type' => 'hidden',
670
        '#value' => '[cdm][taxonomictree_uuid]'
671
        );
672

    
673
        $form['destination'] = array(
674
	   '#delta' => -3,
675
	   '#type' => 'hidden',
676
	   '#value' => substr(drupal_get_destination(), strlen('destination='))
677
        );
678

    
679
        $form['val'] = array(
680
      '#type' => 'select',
681
      '#title'         => t('Available classifications'),
682
      '#default_value' => get_taxonomictree_uuid_selected(),
683
      '#options' => cdm_get_taxontrees_as_options()
684
        );
685

    
686
        return $form;
687

    
688
}
689

    
690
/**
691
 * Implementation #process method call, see form_builder()
692
 * <p>
693
 * Removes Drupal internal form elements from query
694
 * @param $form
695
 * @return unknown_type
696
 */
697
function cdm_dataportal_search_process($form) {
698
	unset($form['form_id']);
699
	unset($form['form_token']);
700
	return $form;
701
}
702

    
703
/**
704
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
705
 * returns the processed request parameters submitted by the search form.
706
 */
707
function cdm_dataportal_search_form_request(){
708

    
709

    
710
	$form_params = array();
711
	array_deep_copy($_REQUEST['search'], $form_params);
712
	$form_params['query'] =  trim($_REQUEST['query']);
713

    
714
	// split of  geographic range
715
	if(isset($_REQUEST['search']['geographic_range'])){
716
		$geographicRange = $_REQUEST['search']['geographic_range'];
717
		// remove
718
		unset($form_params['geographic_range']);
719
	}
720

    
721
	// add geographic range
722
	if($geographicRange){
723
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
724
		for($i = 1; $i < 5; $i++){
725
			if(isset($geographicRange['tdwg_level_'.$i])){
726
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
727
			}
728
		}
729
	}
730

    
731
	// store in session
732
	$_SESSION['cdm']['search'] = $form_params;
733

    
734
	return $form_params;
735
}
736

    
737

    
738
/* UNREACHABLE since action of form directly links to view
739
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
740

    
741
 $_SESSION['cdm']['search'] = $form_values;
742
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
743
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
744
 //$paramstr = compose_url_prameterstr($form_values);
745
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
746
 }
747
 */
748
/* ====================== menu callback functions ====================== */
749

    
750

    
751

    
752
function cdm_dataportal_form_alter($form_id, &$form) {
753

    
754
	static $comment_node_disabled =  0;
755
	static $comment_node_read_only =  1;
756
	static $comment_node_read_write =  2;
757

    
758

    
759
	if ($form_id == 'node_type_form'
760
	&& isset($form['identity']['type'])
761
	&& array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
762
	) {
763
		$form['workflow']['comment'] = array(
764
      '#type' => 'radios',
765
      '#title' => t('Default comment setting'),
766
      '#default_value' => variable_get('comment_'. $form['#node_type']->type, $comment_node_disabled),
767
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
768
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
769
		);
770
	}
771
}
772

    
773

    
774

    
775
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed, $form_description = ''){
776
//TODO move into settings.php
777
	$form[$form_name] = array(
778
    '#type' => 'fieldset',
779
    '#title' => t($form_tittle),
780
    '#collapsible' => TRUE,
781
    '#collapsed' => $collapsed,
782
    '#tree' => true,
783
	'#description' => t($form_description),
784
	);
785

    
786
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
787
	$gallery_settings = variable_get($form_name, $default_values);
788
	//$test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
789

    
790
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
791
		/* TODO: why cdm_dataportal_search_items_on_page does not save the value on $test???
792
		 $form[$form_name]['cdm_dataportal_search_items_on_page'] = array(
793
		 '#type' => 'textfield',
794
		 '#title' => t('Search Page Size'),
795
		 '#default_value' => $test,
796
		 '#description' => t('Number of Names to display per page in search results.')
797
		 );
798
		 */
799
		$form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
800
      '#type' => 'checkbox',
801
      '#title' => t('Show media thumbnails for accepted taxa'),
802
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
803
		);
804

    
805
		$form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
806
      '#type' => 'checkbox',
807
      '#title' => t('Show media thumbnails for synonyms'),
808
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
809
      '#description' => t('')
810
		);
811
	}
812

    
813
	//$showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
814
	$form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
815
    '#type' => 'checkbox',
816
    '#title' => t('Show captions under thumbnails'),
817
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
818
    '#description' => t('')
819
	);
820

    
821
	$form[$form_name]['cdm_dataportal_media_maxextend'] = array(
822
    '#type' => 'textfield',
823
    '#title' => t('Thumbnail size'),
824
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
825
    '#description' => t('Select the size of each individual thumbnail.')
826
	);
827

    
828
	if($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME){
829
	   $form[$form_name]['cdm_dataportal_media_cols'] = array(
830
        '#type' => 'textfield',
831
        '#title' => t('Number of columns'),
832
        '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
833
        '#description' => t('Group the thumbnails in columns: select how many columns should the gallery display.')
834
	   );
835
	}
836

    
837
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
838
		$form[$form_name]['cdm_dataportal_media_maxRows'] = array(
839
      '#type' => 'textfield',
840
      '#title' => t('Maximum number of rows'),
841
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
842
      '#description' => t('You can group the thumbnails in rows, select in how many rows should be the thumbnails grouped.<br>
843
                           <b>Note:</b> If you want an unlimited number of rows please set to 0')
844
		);
845
	}
846

    
847
	return $form;
848
}
849

    
850

    
851
/**
852
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
853
 *
854
 * TODO: parameters are still preliminar
855
 * @param String $page page number to diplay defaults to page 1
856
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
857
 */
858
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
859

    
860
	$request_params  = array(
861
    'q' => $beginsWith,
862
	//'sec' = '',
863
	//'higherTaxa' => getFiters(),
864
	// 'matchAnywhere' => false, // default is false
865
    'page' => $page,
866
    'onlyAccepted' => $onlyAccepted,
867
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
868

    
869
	$taxonPager = cdm_ws_find(CDM_WS_PORTAL_TAXON_FIND, $request_params);
870
	/*
871
	 * FIXME the filter for accepted names will be a form element, thus this widget
872
	 * should be generated via form api preferably as block
873
	 */
874
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
875
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
876
	$out .= theme('cdm_listof_taxa', $taxonPager);
877
	return $out;
878
}
879

    
880
function cdm_dataportal_view_reference($uuid, $arg2 = null){
881
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
882
	return theme('cdm_reference_page', $reference);
883
}
884

    
885
function cdm_dataportal_view_reference_list($pageNumber){
886
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
887
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
888
}
889

    
890
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
891
	$media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
892
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
893
}
894

    
895
function _load_taxonBase(&$taxonBase){
896
	if(isset($taxonBase->uuid)){
897
	    $taxonBase->name = cdm_ws_get(CDM_WS_TAXON, array($taxonBase->uuid, "name"));
898
	    $taxonBase->name->taggedName = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "taggedName"));
899
	    $taxonBase->name->nomenclaturalReference = cdm_ws_get(CDM_WS_NAME, array($taxonBase->name->uuid, "nomenclaturalReference"));
900
	  }
901
}
902

    
903
/**
904
 * similar to the variable_get() function of Drupal, except of thst this function
905
 * is able to handle arrays correctly. This function is especially useful
906
 * when dealing with collections of setting form elemens (#tree = true)
907
 *
908
 * @param String $variableKey
909
 * @param String $defaultValueString a sting as for example derived from a CONSTANT
910
 * @return mixed, usually an array
911
 */
912
function mixed_variable_get($variableKey, $defaultValueString){
913
    $systemDefaults = unserialize($defaultValueString);
914
    $storedSettings = variable_get($variableKey, array());
915
    if(is_array($storedSettings)){
916
      $settings =  array_merge($systemDefaults, $storedSettings);
917
    } else {
918
      $settings = $systemDefaults;
919
    }
920
    return $settings;
921
}
922

    
923
/**
924
 * Loads the subgraph of the given PolytomousKeyNode recursively from the cdm REST service.
925
 * @param PolytomousKeyNode $polytomousKeyNode passed by reference
926
 * @return nothing
927
 */
928
function _load_polytomousKeySubGraph(&$polytomousKeyNode){
929

    
930
	if(!$polytomousKeyNode){
931
		return;
932
	}
933
	if($polytomousKeyNode->class != "PolytomousKeyNode"){
934
		drupal_set_message("_load_polytomousKeySubGraph() invalid type given.", "error");
935
		return;
936
	}
937
  if(!is_uuid($polytomousKeyNode->uuid)){
938
    drupal_set_message("_load_polytomousKeySubGraph() invalid type given.", "error");
939
    return;
940
  }
941

    
942
	$polytomousKeyNode = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, $polytomousKeyNode->uuid);
943

    
944
  if(!$polytomousKeyNode){
945
  	//drupal_set_message("_load_polytomousKeyChildNodes() : could not load polytomousKeyNode", "error");
946
  	return;
947
  }
948

    
949
  // load children
950
  foreach($polytomousKeyNode->children as &$childNode){
951
    _load_polytomousKeySubGraph($childNode);
952
  }
953

    
954
  // load subkey
955
  $polytomousKeyNode->subkey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "subkey"));
956

    
957
  // load taxon
958
  $polytomousKeyNode->taxon = cdm_ws_get(CDM_WS_POLYTOMOUSKEY_NODE, array($polytomousKeyNode->uuid, "taxon"));
959
  _load_taxonBase($polytomousKeyNode->taxon);
960
  return;
961
}
962

    
963
function cdm_dataportal_view_polytomousKey($polytomousKeyUuid){
964
  $polytomousKey = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, $polytomousKeyUuid);
965

    
966
  $sourcePager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "sources"));
967
  if(is_array($sourcePager->records)){
968
    $polytomousKey->sources =  $sourcePager->records;
969
    //$polytomousKey->sources->citation = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "sources"));
970
  }
971

    
972
  $annotationPager = cdm_ws_get(CDM_WS_POLYTOMOUSKEY, array($polytomousKeyUuid, "annotations"));
973
  if(is_array($annotationPager->records)){
974
    $polytomousKey->annotations = $annotationPager->records;
975
  }
976

    
977
  _load_polytomousKeySubGraph($polytomousKey->root);
978
  return theme('cdm_polytomousKey_page', $polytomousKey);
979
}
980

    
981
/**
982
 * The taxon page gives detailed information on a taxon, it shows:
983
 *  - Taxon name
984
 *  - Full list of synonyms homotypic synonyms on top, followed by the
985
 *    heterotypic and finally followed by misapplied names.
986
 *    The list is ordered historically.
987
 *  - All description associated with the taxon.
988
 *
989
 * @param $uuid
990
 * @param $chapter name of the part to display,
991
 *         valid values are: 'description', 'images', 'synonymy', 'specimens', 'all'
992
 * @return unknown_type
993
 */
994
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = null){
995
	// display the page for the taxon defined by $uuid
996
	set_last_taxon_page_tab(arg(3));
997
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
998
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
999
}
1000

    
1001
/**
1002
 * @param $uuid
1003
 * @param $chapter name of the part to display,
1004
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1005
 * @return unknown_type
1006
 */
1007
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = null){
1008
	$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1009
	if(!$taxon){
1010
		drupal_set_title(t('Taxon does not exist'));
1011
		return false;
1012
	}
1013

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

    
1016
	// check if the taxon id contained in the currently selected tree
1017
	$taxon_in_current_tree = taxon_in_current_tree($uuid);
1018
	$taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1019
	if(!$taxon_in_current_tree){
1020
		if(count($taxon_nodes) == 0){
1021
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained any classification.'
1022
			,'warning');
1023
		} else {
1024
			$trees = '';
1025
			foreach($taxon_nodes as $node){
1026
				$trees .= ($trees?', ':'').'<strong>'.$node->classification->titleCache.'</strong>';
1027

    
1028
			}
1029
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained in the currently chosen classification, but in '
1030
			.(count($taxon_nodes) > 1? ' one of these: ' : ' this one: ') . $trees
1031
			, 'warning');
1032
		}
1033
	}
1034

    
1035
	// render the taxon page
1036
	$taxonpage->content = theme('cdm_taxon_page', $taxon, $chapter);
1037

    
1038
	return $taxonpage;
1039
}
1040

    
1041
/**
1042
 * The function returns a name page as a drupal node ready to be renderized by drupal.
1043
 * The node page show the taxon name title and the list of taxon related with such taxon
1044
 * name on the tree already in used.
1045
 * @param $taxon_name_uuid A taxon name uuid
1046
 * @return The formatted name page as node
1047
 */
1048
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1049
	$taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1050
	return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
1051
}
1052

    
1053
/**
1054
 * The function genates a object ready to be transformated to a node
1055
 * in order to show as a drupal node
1056
 * @param $taxon_name_uuid
1057
 * @return the object with the page content and title
1058
 */
1059
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1060
	//getting the full taxonname object from the server
1061
	$taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1062
	if(!$taxon_name){
1063
		drupal_set_title(t('Taxon name does not exist'));
1064
		return false;
1065
	}
1066
	//searching for all the taxa connected with the taxon name on the tree in used
1067
	$name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1068
	$request_params = array();
1069
	$request_params['query'] = $name_cache;
1070
	$request_params['tree'] = get_taxonomictree_uuid_selected();
1071
	$request_params['doTaxa'] = 1;
1072
	$request_params['doSynonyms'] = 1;
1073
	$request_params['doTaxaByCommonNames'] = 0;
1074
	$request_params['matchMode'] = "EXACT";
1075
	$taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1076

    
1077
	//removing the name where we come from and
1078
	foreach($taxon_pager->records as $k=>&$taxon){
1079
		if($taxon->uuid == $taxon_to_hide_uuid){
1080
			unset($taxon_pager->records[$k]);
1081
		}
1082
	}
1083
	//show the taxa list or go to the singular taxon
1084
	if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
1085
		reset($taxon_pager->records);
1086
		$first_key = key($taxon_pager->records);
1087
		if($taxon_pager->records[$first_key]->class != "Taxon"){
1088
			$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($taxon_pager->records[$first_key]->uuid, get_taxonomictree_uuid_selected()));
1089
			if($synonym_uuid){
1090
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
1091
			}else{
1092
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid);
1093
			}
1094
		}else{
1095
			if($synonym_uuid){
1096
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid . '/synonymy',
1097
                      'highlite=' . $synonym_uuid);
1098
			}else{
1099
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1100
			}
1101
			//drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1102
		}
1103
	}else{ //more than one taxa case
1104
		$taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1105
		if($taxon_pager->records){
1106
			$taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1107
		}else{
1108
			$taxon_name_page->content = 'This name has no taxa';
1109
		}
1110
		return $taxon_name_page;
1111
	}
1112
}
1113

    
1114
function cdm_dataportal_view_search_advanced(){
1115

    
1116
	drupal_set_title(t('Advanced search'));
1117

    
1118
	$searchForm = cdm_dataportal_search_taxon_form(true);
1119

    
1120
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1121

    
1122
}
1123

    
1124
/**
1125
 *
1126
 * future extensions to meet palmweb mockup requirements:
1127
 *  - habitat
1128
 *  - uses
1129
 *  - conservation status
1130
 *  - locality / tdwg region
1131
 */
1132
function cdm_dataportal_view_search_taxon(){
1133

    
1134
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1135

    
1136
	$request_params = cdm_dataportal_search_form_request();
1137
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1138

    
1139
	$search_params = $_REQUEST;
1140
	unset($search_params['q']);
1141
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1142
}
1143

    
1144

    
1145
function cdm_view_xml2json(){
1146
	$file = arg(2);
1147
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1148
	return  xml2json::transformXmlStringToJson($datastr);
1149
}
1150

    
1151
/* ====================== other functions ====================== */
1152

    
1153

    
1154
/**
1155
 * Enter description here...
1156
 *
1157
 * @param String $uuid the UUID of the taxon
1158
 * @return the URL
1159
 */
1160
function path_to_taxon($uuid, $no_tab = false){
1161
	$tab = get_default_taxon_tab();
1162
	$values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1163

    
1164
	if(!$uuid) return false;
1165

    
1166
	if (!$tab){
1167
		return 'cdm_dataportal/taxon/'.$uuid;
1168
	}elseif(get_last_taxon_page_tab() &&
1169
	   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]){
1170
		return 'cdm_dataportal/taxon/'.$uuid . '/' . get_last_taxon_page_tab();
1171
	} else {
1172
		return 'cdm_dataportal/taxon/'.$uuid . '/' . strtolower($tab);
1173
	}
1174
}
1175

    
1176
function path_to_key($keyType, $keyUuid){
1177
	if(!$keyUuid || !$keyType) return false;
1178
	$keyType{0} = strtolower($keyType{0});
1179
  return "cdm_dataportal/".$keyType."/$keyUuid";
1180
}
1181

    
1182
function path_to_reference($uuid){
1183
	if(!$uuid) return false;
1184
	return 'cdm_dataportal/reference/'.$uuid;
1185
}
1186

    
1187
function path_to_name($name_uuid){
1188
	$res = false;
1189
	if($name_uuid){
1190
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1191
	}
1192
	return $res;
1193
}
1194

    
1195
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1196
	if(!$uuid) return false;
1197
	$out = 'cdm_dataportal/media/'.$uuid;
1198
	if($representaion_uuid){
1199
		$out .= '/'.$representaion_uuid;
1200
		if($partId !== false){
1201
			$out .= '/'.$partId;
1202
		}
1203
	}
1204
	return $out;
1205
}
1206

    
1207
/**
1208
 * Compares thisRank with thatRank.
1209
 * Returns a negative integer, zero, or a positive integer
1210
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1211
 * e.g:
1212
 * <ul>
1213
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1214
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1215
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1216
 * </ul>
1217
 * <p>
1218
 * This compare logic of the underlying webservice is the
1219
 * <b>inverse logic</b> of the the one implemented in
1220
 * java.lang.Comparable#compareTo(java.lang.Object)
1221
 * @param $thisRankUuid
1222
 * @param $thatRankUuid
1223
 * @return  a negative integer, zero, or a positive integer
1224
 * as the thisRank is lower than, equal to, or higher than thatRank
1225
 */
1226
function rank_compare($thisRankUuid, $thatRankUuid){
1227
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1228
	return $result->Integer;
1229
}
1230

    
1231
function theme_cdm_uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1232
	$acceptedPath = path_to_taxon($acceptedUuid, true);
1233
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid, $synonymUuid);
1234
}
1235

    
1236
/**
1237
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1238
 * If the taggename if empty the fullname will be returned.
1239
 *
1240
 * @param unknown_type $Name or TreeNode
1241
 * @return string
1242
 */
1243
function cdm_dataportal_shortname_of($name){
1244
	$nameStr = '';
1245
	// get all tagged text tokens of the scientific name
1246
	foreach($name->taggedTitle as $tagtxt){
1247
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1248
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1249
		}
1250
	}
1251
	$nameStr = trim($nameStr);
1252
	if($nameStr){
1253
		// do not return short names for these
1254
		//if (stristr(strtolower($nameStr), 'incertae sedis') !== FALSE ||
1255
		//	stristr(strtolower($nameStr), 'nomina excludenda') !== FALSE) {
1256
		if ($name->unplaced || $name->excluded){
1257
			return $nameStr;
1258
		}
1259
		if($pos = stripos($nameStr, ' ')){
1260
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1261
		} else {
1262
			return $nameStr;
1263
		}
1264
	} else {
1265
		return $name->titleCache;
1266
	}
1267
}
1268

    
1269

    
1270
/**
1271
 * Check if a taxon is accepted by the current taxonomic tree
1272
 *
1273
 * @param Taxon $taxon
1274
 * @return true if $taxon is accepted, false otherwise
1275
 */
1276

    
1277
function _cdm_dataportal_acceptedByCurrentView($taxon){
1278

    
1279
	$defaultTreeUuid = get_taxonomictree_uuid_selected();
1280
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1281
		foreach($taxon->taxonNodes as $node){
1282
			if($node->classification == $defaultTreeUuid) {
1283
				return true;
1284
			}
1285
		}
1286
	}
1287
	return false;
1288
}
1289

    
1290
/**@Deprecated
1291
 *
1292
 */
1293
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1294
	$pstr = '';
1295
	foreach($parameters as $key=>$value){
1296
		if(is_array($value)){
1297

    
1298
		} else {
1299
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1300
		}
1301
	}
1302
	return $pstr;
1303
}
1304

    
1305
/**
1306
 * workaround for missing original source type, idNamespace is always set in these cases
1307
 * @param unknown_type $source
1308
 * @return unknown_type
1309
 */
1310
function _is_original_source_type($source){
1311
	return !$source->idNamespace && strlen($source->idNamespace) == 0;
1312
}
1313

    
1314

    
1315

    
1316
/**
1317
 * The function read the metadata info such title or artist of a media file. The
1318
 * function tries at first to get all the info from the file metadata and if it is
1319
 * not avaible look at the media file info stored at the database.
1320
 * @param $media The media file
1321
 * @return array The array with the avilable specified metadata info.
1322
 * TODO rename to read_media_metadata() and move to *.module
1323
 */
1324
function cdm_read_media_metadata($media){
1325

    
1326
	$metadata_caption = array('title' => '',           //media_metadata and media
1327
                              'artist' => '',          //media_metadata and media
1328
                              'rights',                //media_metadata and media
1329
                              'location',              //media_metadata
1330
                              'filename' => '',        //media
1331
                              'mediacreated' => '',    //media
1332
                              'description' => '');    //media
1333

    
1334
	//getting the media metadata
1335
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1336
	$media_metadata_aux = (array) $media_metadata;
1337
	//title
1338
	//if ($media_metadata->Headline) {
1339
	if ($media_metadata->ObjectName) {
1340
		$metadata_caption['title'] = $media_metadata->ObjectName;
1341

    
1342
		//	} else if ($media->titleCache){
1343
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1344
	} else if ($media_metadata_aux['Object Name']){
1345
		$metadata_caption['title'] = $media_metadata_aux['Object Name'];
1346
	} else if ($media->title_L10n){
1347
		$metadata_caption['title'] = $media->title_L10n;
1348
	} else if ($media->titleCache){
1349
		$metadata_caption['title'] = $media->titleCache;
1350
	} else{ //if there is no title on the db and metadata get file title
1351
		$aux = $media->representations[0]->parts[0]->uri;
1352
		$aux = explode("/", $aux);
1353
		$aux = end($aux);
1354
		$metadata_caption['title'] = $aux;
1355
	}
1356

    
1357
	// append description to title
1358
	if ($media->description_L10n) {
1359
		$metadata_caption['title'] .= '<span class="media-description"> -' . $media->description_L10n . '<span>';
1360
	}
1361

    
1362
	//artist
1363
	if ($media_metadata->Artist){
1364
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1365
	}
1366
	elseif ($media->artist->titleCache){
1367
	 $metadata_caption['artist'] = $media->artist->titleCache;
1368
	}
1369

    
1370
	//copyright
1371
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1372
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1373
	if ($media_metadata->Copyright)
1374
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1375
	elseif ($media->rights){
1376
		foreach($media->rights as $right){
1377
			switch($right->term->uuid){
1378
				case UUID_RIGHTS_LICENCE:
1379
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1380
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1381
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1382
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1383
					break;
1384
				case UUID_RIGHTS_COPYRIGHT:
1385
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1386
					break;
1387
			}
1388
		}
1389
	}
1390
	else
1391
	$metadata_caption['rights']['agentNames'][] = '';
1392

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

    
1396
	//location
1397
	$metadata_caption['location'] = array();
1398
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1399
	$metadata_caption['location']['city'] = $media_metadata->City;
1400
	$metadata_caption['location']['province'] = $media_metadata->Province;
1401
	$metadata_caption['location']['country'] = $media_metadata->Country;
1402

    
1403
	//filename
1404
	if(isset($media->representations[0]->parts[0]->uri)){
1405
		$fileUri = $media->representations[0]->parts[0]->uri;
1406
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1407
		$metadata_caption['filename'] = $filename;
1408
	}
1409
	else{
1410
	 $metadata_caption['filename'] = '';
1411
	}
1412
	/*
1413
	 //creation date
1414
	 if($media_metadata["Modify Date"])
1415
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1416
	 else
1417
	 $metadata_caption['mediacreated'] = $media->created;
1418
	 */
1419
	//returned value
1420
	return $metadata_caption;
1421
}
1422

    
1423
/**
1424
 * This function collects all the media from a list of description elements
1425
 * and return them as an Array.
1426
 *
1427
 * @param $descriptionElementes The description elements
1428
 * @return Array The output with all the media
1429
 */
1430
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1431
	//variables
1432
	$outArrayOfMedia = array(); //return value
1433
	//implementation
1434
	if(is_array($descriptionElements)){//avoiding warning box in drupal for flora malesiana
1435
		foreach($descriptionElements as $descriptionElement){
1436
			if(is_array($descriptionElement->media)){
1437
				foreach($descriptionElement->media as $media){
1438
					if(is_object($media)){
1439
						$outArrayOfMedia[] = $media;
1440
					}
1441
				}
1442
			}
1443
		}
1444
	}
1445
	return $outArrayOfMedia;
1446
}
1447

    
1448
function cdm_annotations_as_footnotekeys($cdmBase, $footnote_list_key = array()){
1449
	$footNoteKeys = array();
1450
	//is argument cdmBase an array?
1451
	if (!is_array($cdmBase)){
1452
		$cdmBase_array = array();
1453
		$cdmBase_array[] = $cdmBase;
1454
	}else{
1455
		$cdmBase_array = $cdmBase;
1456
	}
1457
	//getting the key for the footnotemanager
1458
	if((bool) $footnote_list_key){
1459
		$footnoteListKey = $footnote_list_key;
1460
	}else{
1461
		$footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1462
	}
1463
	//adding the footnotes keys
1464
	foreach($cdmBase_array as $cdmBase_element){
1465
		$annotations = cdm_ws_getAnnotationsFor($cdmBase_element);
1466
		if(is_array($annotations)){
1467
			foreach($annotations as $annotation){
1468
					$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1469
      }
1470
    }
1471
	}
1472
	return $footNoteKeys;
1473
}
1474

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

    
1477
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cdm_dynabox.js');
1478

    
1479
	$cdm_proxy_url = url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
1480
	$out .= '<'. $enclosingtags[0]. ' class="dynabox"><a href="'.$content_url.'" class="label" alt="'.t($link_alt_text).'">'.$label.'</a>';
1481
	$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]. '>';
1482
	$out .= '</'. $enclosingtags[0]. '>';
1483
	return $out;
1484
}
1485

    
(6-6/12)