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/search',
207
      'callback' => 'cdm_dataportal_view_search_advanced',
208
      'access' => true,
209
      'type' => MENU_CALLBACK,
210
		);
211

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

    
219
		$items[] = array(
220
      'path' => 'cdm/xml2json',
221
      'callback' => 'cdm_view_xml2json',
222
      'access' => true,
223
      'type' => MENU_CALLBACK,
224
		);
225

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

    
248
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
249

    
250
			$items[] = array(
251
      'path' => 'cdm_dataportal/taxon/'.arg(2),
252
      'title' => theme('cdm_taxonpage_tab', 'General'),
253
      'callback' => 'cdm_dataportal_taxon_page_view',
254
      'access' => true,
255
      'type' => MENU_CALLBACK,
256
      'weight' => 1,
257
      'callback arguments' => array(arg(2), "description")
258
			// expected callback arguments: name_uuid
259
			);
260

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

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

    
283
			$items[] = array(
284
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
285
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
286
      'callback' => 'cdm_dataportal_taxon_page_view',
287
      'access' => true,
288
      'type' => MENU_LOCAL_TASK,
289
      'weight' => 4,
290
      'callback arguments' => array(arg(2), "synonymy", arg(4))
291
			// expected callback arguments: name_uuid
292
			);
293
			$items[] = array(
294
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
295
      'title' => theme('cdm_taxonpage_tab', 'Images'),
296
      'callback' => 'cdm_dataportal_taxon_page_view',
297
      'access' => true,
298
      'type' => MENU_LOCAL_TASK,
299
      'weight' => 5,
300
      'callback arguments' => array(arg(2), "images")
301
			// expected callback arguments: name_uuid
302
			);
303

    
304
		 $items[] = array(
305
		 'path' => 'cdm_dataportal/taxon/'.arg(2).'/specimens',
306
		 'title' => theme('cdm_taxonpage_tab', 'Specimens'),
307
		 'callback' => 'cdm_dataportal_taxon_page_view',
308
		 'access' => true,
309
		 'type' => MENU_LOCAL_TASK,
310
		 'weight' => 6,
311
		 'callback arguments' => array(arg(2), "specimens")
312
		 // expected callback arguments: name_uuid
313
		 );
314
		}
315
	}
316

    
317
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
318
	//drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
319
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
320

    
321
	return $items;
322

    
323
}
324
/**
325
 * The function generate form for own user cdm dataportal configurations
326
 */
327
function cdm_dataportal_user_form() {
328
	
329
	global $user;
330
    $checkbox_value = 'cdm_dataportal_' .$user->uid . '_default_tab_active';
331
    
332
	$form['check'] = array
333
    (
334
    '#type'            => 'checkbox',
335
    '#title'         => t('Activate user default configuration'),
336
    '#default_value'   => variable_get($checkbox_value, 0),
337
    '#description' => t('Check this if you want configure your own default tab from the below menu.')
338
    );
339
    
340
	$form['cdm_dataportal_user_form'] =  array(
341
      '#type'          => 'select',
342
      '#title'         => t('Default tab to display'),
343
	    '#default_value' => get_default_taxon_tab(true),
344
      '#options'       => unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB),
345
      '#description'   => t('<p>Select the default tab to display when visiting a taxon page. Only available if Tabbed Taxon Page is enable.</p>
346
              <strong>Note:</strong> After performing a search and clicking in any synonym, the taxon tab
347
              to be renderized will be the synonymy of the accepted taxon and not the above selected tab.'),
348
	);
349

    
350
	$form['submit'] = array(
351
	  '#type' => 'submit',
352
	  '#value' => t('Submit')
353
	);
354

    
355
	return $form;
356
}
357

    
358
/**
359
 * The function submit the user cdm dataportal configurations
360
 * @param unknown_type $form
361
 * @param unknown_type $form_values
362
 */
363
function cdm_dataportal_user_form_submit($form, $form_values) {
364
	global $user;
365
	$msg_type = 'status';
366
	$username = $user->name;
367
	$variable_to_use = 'cdm_dataportal_' .$user->uid . '_default_tab';
368

    
369
	//if is the right user the variables are setted
370
	if (arg(0)=='user' && ($uid=arg(1)) && is_numeric($uid) && $user->uid==$uid){
371
		$variable = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
372
		variable_set($variable_to_use . '_active', $form_values['check']);
373
		variable_set($variable_to_use, $form_values['cdm_dataportal_user_form']);
374
		if ($form_values['check']){
375
			drupal_set_message('The user default tab will be used for the next taxon site visit.');
376
			drupal_set_message('The user default tab have been changed to: '
377
            . $variable[variable_get($variable_to_use, 0)]
378
            . ' for the user ' . $username, $msg_type);
379
		}else{
380
			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.');
381
		}
382
	//problem with the user id => variables wont be saved
383
	}else{
384
		$msg_type = 'warning';
385
		drupal_set_message('Default tab have not been saved due to user id problems', $msg_type);
386
	}
387
}
388

    
389
/**
390
 * Implementation of hook_block()
391
 *
392
 * Provides the following blocks:
393
 *  0: list of links useful during development
394
 *
395
 * @param String $op
396
 * @param int $delta
397
 */
398
function cdm_dataportal_block($op='list', $delta=0) {
399
	// listing of blocks, such as on the admin/block page
400
	if ($op == "list") {
401
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
402
		//		$block[1]["info"] = t("CDM DataPortal Credits");
403
		$block[2]["info"] = t("CDM Search Taxa");
404
		//$block[3]["info"] = t("CDM Filters");
405
		$block[4]["info"] = t("CDM Dataportal Print");
406
		return $block;
407
	}
408
	else if ($op == 'view') {
409
		switch($delta){
410
			//			case 1:
411
			//				$block['subject'] = t('Credits');
412
			//				$block['content'] = theme('cdm_credits');
413
			//				return $block;
414
			case 2:
415
				$block['subject'] = t('Search taxa');
416
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
417
				if (variable_get('cdm_dataportal_show_advanced_search', 1)){
418
				    $block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
419
				}
420
				return $block;
421
			case 4:
422
				$block['subject'] = t('<none>');
423
				$block['content'] = theme('cdm_print_button');;
424
				return $block;
425
		}
426
	}
427
}
428

    
429

    
430

    
431
/*
432
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
433
 $_SESSION['cdm'] = null;
434
 if(is_string($cdm_ws_uri_update)){
435
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
436
 }
437
 }
438

    
439
 function cdm_dataportal_session_validate(){
440

    
441
 if(!isset($_SESSION['cdm']['ws_uri'])){
442
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
443
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
444
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
445
 }
446
 }
447
 */
448

    
449
function cdm_dataportal_search_taxon_form($advancedForm = false){
450

    
451
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
452
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
453
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
454
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
455
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
456
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
457

    
458
	$url = 'cdm_dataportal/search/taxon';
459
	$form['#method'] = 'get';
460
	$form['#process'] = array('cdm_dataportal_search_process' => array());
461
	$form['#action'] = url($url, NULL, NULL, true);
462

    
463
	$form['query'] = array(
464
    '#delta' => 0,
465
    '#type' => 'textfield',
466
    '#size' => 20,
467
    '#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')),
468
    '#value' => $preset_query,
469
	);
470

    
471
	$form['search'] = array(
472
      '#delta' => 1,
473
      '#tree' => true,
474
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
475
      '#title' => t('Options')
476
	);
477

    
478
	$form['search']['tree'] = array(
479
    '#delta' => -1,
480
    '#type' => 'hidden',
481
    '#value' => get_taxonomictree_uuid_selected()
482
	);
483

    
484

    
485
	// clean URL get forms breaks if we don't give it a 'q'.
486
	if (!(bool)variable_get('clean_url', '0')) {
487
		$form['search']['q'] = array(
488
      '#delta' => -1,
489
      '#type' => 'hidden',
490
      '#value' => $url,
491
      '#name' => 'q',
492
		);
493
	}
494

    
495
	$form['search']['pageSize'] = array(
496
      '#delta' => -1,
497
      '#type' => 'hidden',
498
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
499
	);
500

    
501
	if($advancedForm){
502
		// general search parameters
503
		$form['search']['doTaxa'] = array(
504
      '#delta' => 2,
505
      '#type' => 'checkbox',
506
      '#title' => t('Search for accepted taxa'),
507
      '#value' => $preset_doTaxa
508
		);
509
		$form['search']['doSynonyms'] = array(
510
      '#delta' => 3,
511
      '#type' => 'checkbox',
512
      '#title' => t('Search for synonyms'),
513
      '#value' => $preset_doSynonyms
514
		);
515
		$form['search']['doTaxaByCommonNames'] = array(
516
      '#delta' => 4,
517
      '#type' => 'checkbox',
518
      '#title' => t('Search for common names'),
519
      '#value' => $preset_doTaxaByCommonNames
520
		);
521

    
522
		// Geographic Range
523
		$form['search']['geographic_range'] = array(
524
      '#type' => 'fieldset',
525
      '#delta' => 5,
526
      '#tree' => true,
527
      '#title' => t('Geographic range'),
528
		);
529

    
530
		$form['search']['geographic_range']['tdwg_level_select'] = array(
531
    '#type' => 'radios',
532
    '#title' => t('Select a TDWG distribution level and code'),
533
    '#default_value' => $tdwg_level_select,
534
    '#options' => array(
535
		t('TDWG level-1, i.e. a continent'),
536
		t('TDWG level-2'),
537
		t('TDWG level-3, i.e. a country'),
538
		t('TDWG level-4')
539
		)
540
		);
541
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
542
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
543
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
544
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
545

    
546
		$tdwg_js = '';
547
		foreach($tdwg as $key=>$tdwg_level){
548
			$tdwgOptions = array();
549
			$tdwgOptionsSelected = array();
550
			foreach($tdwg_level as $area){
551
				$representation = $area->representations[0];
552
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
553
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
554
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
555
				}
556
			}
557
			asort($tdwgOptions);
558
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
559
        '#type' => 'select',
560
        '#title'         => t('TDWG level').' '.$key,
561
        '#default_value' => $tdwgOptionsSelected,
562
        '#multiple' => TRUE,
563
        '#options' => $tdwgOptions
564
			);
565
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
566
		}
567

    
568
		drupal_add_js(
569
    "$(document).ready(function(){
570

    
571
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change(
572
        function(event){
573
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
574
          var i;
575
          for(i = 0; i < 4; i++){
576
            if(selectId == i){
577
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
578
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
579
            } else {
580
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
581
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
582
            }
583
          }
584
        }
585
      );
586

    
587
      $tdwg_js
588
    });",
589
    'inline');
590

    
591
	} else {
592
		$form['search']['doTaxa'] = array(
593
	      '#delta' => -2,
594
	      '#type' => 'hidden',
595
	      '#value' => 1
596
		);
597
		$form['search']['doSynonyms'] = array(
598
	      '#delta' => -3,
599
	      '#type' => 'hidden',
600
	      '#value' => 1
601
		);
602
		$form['search']['doTaxaByCommonNames'] = array(
603
	      '#delta' => -4,
604
	      '#type' => 'hidden',
605
	      '#value' => 0
606
		);
607
	}
608

    
609
	$form['submit'] = array(
610
	  '#delta' => 9,
611
	  '#type' => 'submit',
612
	  '#name' => '',
613
	  '#value' => t('Search')
614
	);
615

    
616
	return $form;
617
}
618

    
619
function cdm_dataportal_search_taxon_form_advanced(){
620
	return cdm_dataportal_search_taxon_form(true);
621
}
622

    
623
function cdm_taxonomictree_selector(){
624
	_add_js_treeselector();
625

    
626
	$out = drupal_get_form('cdm_taxonomictree_selector_form');
627

    
628
	return $out;
629
}
630

    
631

    
632
function cdm_taxonomictree_selector_form(){
633

    
634
	$url = url('cdm_api/setvalue/session', null);
635
	$form['#action'] = $url;
636

    
637
	$form['var'] = array(
638
        '#delta' => -3,
639
        '#type' => 'hidden',
640
        '#value' => '[cdm][taxonomictree_uuid]'
641
        );
642

    
643
        $form['destination'] = array(
644
	   '#delta' => -3,
645
	   '#type' => 'hidden',
646
	   '#value' => substr(drupal_get_destination(), strlen('destination='))
647
        );
648

    
649
        $form['val'] = array(
650
      '#type' => 'select',
651
      '#title'         => t('Available classifications'),
652
      '#default_value' => get_taxonomictree_uuid_selected(),
653
      '#options' => cdm_get_taxontrees_as_options()
654
        );
655

    
656
        return $form;
657

    
658
}
659

    
660
/**
661
 * Implementation #process method call, see form_builder()
662
 * <p>
663
 * Removes Drupal internal form elements from query
664
 * @param $form
665
 * @return unknown_type
666
 */
667
function cdm_dataportal_search_process($form) {
668
	unset($form['form_id']);
669
	unset($form['form_token']);
670
	return $form;
671
}
672

    
673
/**
674
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
675
 * returns the processed request parameters submitted by the search form.
676
 */
677
function cdm_dataportal_search_form_request(){
678

    
679

    
680
	$form_params = array();
681
	array_deep_copy($_REQUEST['search'], $form_params);
682
	$form_params['query'] =  trim($_REQUEST['query']);
683

    
684
	// split of  geographic range
685
	if(isset($_REQUEST['search']['geographic_range'])){
686
		$geographicRange = $_REQUEST['search']['geographic_range'];
687
		// remove
688
		unset($form_params['geographic_range']);
689
	}
690

    
691
	// add geographic range
692
	if($geographicRange){
693
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
694
		for($i = 1; $i < 5; $i++){
695
			if(isset($geographicRange['tdwg_level_'.$i])){
696
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
697
			}
698
		}
699
	}
700

    
701
	// store in session
702
	$_SESSION['cdm']['search'] = $form_params;
703

    
704
	return $form_params;
705
}
706

    
707

    
708
/* UNREACHABLE since action of form directly links to view
709
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
710

    
711
 $_SESSION['cdm']['search'] = $form_values;
712
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
713
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
714
 //$paramstr = compose_url_prameterstr($form_values);
715
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
716
 }
717
 */
718
/* ====================== menu callback functions ====================== */
719

    
720

    
721

    
722
function cdm_dataportal_form_alter($form_id, &$form) {
723

    
724
	static $comment_node_disabled =  0;
725
	static $comment_node_read_only =  1;
726
	static $comment_node_read_write =  2;
727

    
728

    
729
	if ($form_id == 'node_type_form'
730
	&& isset($form['identity']['type'])
731
	&& array_key_exists($form['#node_type']->type, cdm_get_nodetypes())
732
	) {
733
		$form['workflow']['comment'] = array(
734
      '#type' => 'radios',
735
      '#title' => t('Default comment setting'),
736
      '#default_value' => variable_get('comment_'. $form['#node_type']->type, $comment_node_disabled),
737
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
738
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
739
		);
740
	}
741
}
742

    
743

    
744

    
745
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed, $form_description = ''){
746
//TODO move into settings.php
747
	$form[$form_name] = array(
748
    '#type' => 'fieldset',
749
    '#title' => t($form_tittle),
750
    '#collapsible' => TRUE,
751
    '#collapsed' => $collapsed,
752
    '#tree' => true,
753
	'#description' => t($form_description),
754
	);
755

    
756
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
757
	$gallery_settings = variable_get($form_name, $default_values);
758
	//$test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
759

    
760
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
761
		/* TODO: why cdm_dataportal_search_items_on_page does not save the value on $test???
762
		 $form[$form_name]['cdm_dataportal_search_items_on_page'] = array(
763
		 '#type' => 'textfield',
764
		 '#title' => t('Search Page Size'),
765
		 '#default_value' => $test,
766
		 '#description' => t('Number of Names to display per page in search results.')
767
		 );
768
		 */
769
		$form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
770
      '#type' => 'checkbox',
771
      '#title' => t('Show media thumbnails for accepted taxa'),
772
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
773
		);
774

    
775
		$form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
776
      '#type' => 'checkbox',
777
      '#title' => t('Show media thumbnails for synonyms'),
778
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
779
      '#description' => t('')
780
		);
781
	}
782

    
783
	//$showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
784
	$form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
785
    '#type' => 'checkbox',
786
    '#title' => t('Show captions under thumbnails'),
787
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
788
    '#description' => t('')
789
	);
790

    
791
	$form[$form_name]['cdm_dataportal_media_maxextend'] = array(
792
    '#type' => 'textfield',
793
    '#title' => t('Thumbnail size'),
794
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
795
    '#description' => t('Select the size of each individual thumbnail.')
796
	);
797

    
798
	if($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME){
799
	   $form[$form_name]['cdm_dataportal_media_cols'] = array(
800
        '#type' => 'textfield',
801
        '#title' => t('Number of columns'),
802
        '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
803
        '#description' => t('Group the thumbnails in columns: select how many columns should the gallery display.')
804
	   );
805
	}
806

    
807
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
808
		$form[$form_name]['cdm_dataportal_media_maxRows'] = array(
809
      '#type' => 'textfield',
810
      '#title' => t('Maximum number of rows'),
811
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
812
      '#description' => t('You can group the thumbnails in rows, select in how many rows should be the thumbnails grouped.<br>
813
                           <b>Note:</b> If you want an unlimited number of rows please set to 0')
814
		);
815
	}
816

    
817
	return $form;
818
}
819

    
820

    
821
/**
822
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
823
 *
824
 * TODO: parameters are still preliminar
825
 * @param String $page page number to diplay defaults to page 1
826
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
827
 */
828
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
829

    
830
	$request_params  = array(
831
    'q' => $beginsWith,
832
	//'sec' = '',
833
	//'higherTaxa' => getFiters(),
834
	// 'matchAnywhere' => false, // default is false
835
    'page' => $page,
836
    'onlyAccepted' => $onlyAccepted,
837
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
838

    
839
	$taxonPager = cdm_ws_find(CDM_WS_PORTAL_TAXON_FIND, $request_params);
840
	/*
841
	 * FIXME the filter for accepted names will be a form element, thus this widget
842
	 * should be generated via form api preferably as block
843
	 */
844
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
845
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
846
	$out .= theme('cdm_listof_taxa', $taxonPager);
847
	return $out;
848
}
849

    
850
function cdm_dataportal_view_reference($uuid, $arg2 = null){
851
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
852
	return theme('cdm_reference_page', $reference);
853
}
854

    
855
function cdm_dataportal_view_reference_list($pageNumber){
856
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
857
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
858
}
859

    
860
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
861
	$media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
862
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
863
}
864

    
865
/**
866
 * The taxon page gives detailed information on a taxon, it shows:
867
 *  - Taxon name
868
 *  - Full list of synonyms homotypic synonyms on top, followed by the
869
 *    heterotypic and finally followed by misapplied names.
870
 *    The list is ordered historically.
871
 *  - All description associated with the taxon.
872
 *
873
 * @param $uuid
874
 * @param $chapter name of the part to display,
875
 *         valid values are: 'description', 'images', 'synonymy', 'specimens', 'all'
876
 * @return unknown_type
877
 */
878
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all', $synonym_uuid = null){
879
	// display the page for the taxon defined by $uuid
880
	set_last_taxon_page_tab(arg(3));
881
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter, $synonym_uuid);
882
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
883
}
884

    
885
/**
886
 * @param $uuid
887
 * @param $chapter name of the part to display,
888
 *         valid values are: 'description', 'images', 'synonymy', 'all'
889
 * @return unknown_type
890
 */
891
function cdm_dataportal_taxon_view($uuid, $chapter = 'all', $synonym_uuid = null){
892
	$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
893
	if(!$taxon){
894
		drupal_set_title(t('Taxon does not exist'));
895
		return false;
896
	}
897

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

    
900
	// check if the taxon id contained in the currently selected tree
901
	$taxon_in_current_tree = taxon_in_current_tree($uuid);
902
	$taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
903
	if(!$taxon_in_current_tree){
904
		if(count($taxon_nodes) == 0){
905
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained any classification.'
906
			,'warning');
907
		} else {
908
			$trees = '';
909
			foreach($taxon_nodes as $node){
910
				$trees .= ($trees?', ':'').'<strong>'.$node->classification->titleCache.'</strong>';
911

    
912
			}
913
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained in the currently chosen classification, but in '
914
			.(count($taxon_nodes) > 1? ' one of these: ' : ' this one: ') . $trees
915
			, 'warning');
916
		}
917
	}
918

    
919
	// render the taxon page
920
	$taxonpage->content = theme('cdm_taxon_page_general', $taxon, $chapter);
921

    
922
	return $taxonpage;
923
}
924

    
925
/**
926
 * The function returns a name page as a drupal node ready to be renderized by drupal.
927
 * The node page show the taxon name title and the list of taxon related with such taxon
928
 * name on the tree already in used.
929
 * @param $taxon_name_uuid A taxon name uuid
930
 * @return The formatted name page as node
931
 */
932
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
933
	$taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
934
	return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
935
}
936

    
937
/**
938
 * The function genates a object ready to be transformated to a node
939
 * in order to show as a drupal node
940
 * @param $taxon_name_uuid
941
 * @return the object with the page content and title
942
 */
943
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
944
	//getting the full taxonname object from the server
945
	$taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
946
	if(!$taxon_name){
947
		drupal_set_title(t('Taxon name does not exist'));
948
		return false;
949
	}
950
	//searching for all the taxa connected with the taxon name on the tree in used
951
	$name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
952
	$request_params = array();
953
	$request_params['query'] = $name_cache;
954
	$request_params['tree'] = get_taxonomictree_uuid_selected();
955
	$request_params['doTaxa'] = 1;
956
	$request_params['doSynonyms'] = 1;
957
	$request_params['doTaxaByCommonNames'] = 0;
958
	$request_params['matchMode'] = "EXACT";
959
	$taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
960

    
961
	//removing the name where we come from and
962
	foreach($taxon_pager->records as $k=>&$taxon){
963
		if($taxon->uuid == $taxon_to_hide_uuid){
964
			unset($taxon_pager->records[$k]);
965
		}
966
	}
967
	//show the taxa list or go to the singular taxon
968
	if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
969
		reset($taxon_pager->records);
970
		$first_key = key($taxon_pager->records);
971
		if($taxon_pager->records[$first_key]->class != "Taxon"){
972
			$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, array($taxon_pager->records[$first_key]->uuid, get_taxonomictree_uuid_selected()));
973
			if($synonym_uuid){
974
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
975
			}else{
976
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid);
977
			}
978
		}else{
979
			if($synonym_uuid){
980
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid . '/synonymy',
981
                      'highlite=' . $synonym_uuid);
982
			}else{
983
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
984
			}
985
			//drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
986
		}
987
	}else{ //more than one taxa case
988
		$taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
989
		if($taxon_pager->records){
990
			$taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
991
		}else{
992
			$taxon_name_page->content = 'This name has no taxa';
993
		}
994
		return $taxon_name_page;
995
	}
996
}
997

    
998
function cdm_dataportal_view_search_advanced(){
999

    
1000
	drupal_set_title(t('Advanced search'));
1001

    
1002
	$searchForm = cdm_dataportal_search_taxon_form(true);
1003

    
1004
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1005

    
1006
}
1007

    
1008
/**
1009
 *
1010
 * future extensions to meet palmweb mockup requirements:
1011
 *  - habitat
1012
 *  - uses
1013
 *  - conservation status
1014
 *  - locality / tdwg region
1015
 */
1016
function cdm_dataportal_view_search_taxon(){
1017

    
1018
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1019

    
1020
	$request_params = cdm_dataportal_search_form_request();
1021
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1022

    
1023
	$search_params = $_REQUEST;
1024
	unset($search_params['q']);
1025
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1026
}
1027

    
1028

    
1029
function cdm_view_xml2json(){
1030
	$file = arg(2);
1031
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1032
	return  xml2json::transformXmlStringToJson($datastr);
1033
}
1034

    
1035
/* ====================== other functions ====================== */
1036

    
1037
/**
1038
 * Enter description here...
1039
 *
1040
 * @param String $uuid the UUID of the taxon
1041
 * @return the URL
1042
 */
1043
function path_to_taxon($uuid, $no_tab = false){
1044
	$tab = get_default_taxon_tab();
1045
	$values = unserialize(CDM_DATAPORTAL_DEFAULT_TAXON_TAB);
1046

    
1047
	if(!$uuid) return false;
1048

    
1049
	if (!$tab){
1050
		return 'cdm_dataportal/taxon/'.$uuid;
1051
	}elseif(get_last_taxon_page_tab() &&
1052
	   $tab == $values[CDM_DATAPORTAL_LAST_VISITED_TAB_ARRAY_INDEX]){
1053
		return 'cdm_dataportal/taxon/'.$uuid . '/' . get_last_taxon_page_tab();
1054
	} else {
1055
		return 'cdm_dataportal/taxon/'.$uuid . '/' . strtolower($tab);
1056
	}
1057
}
1058

    
1059
function path_to_reference($uuid){
1060
	if(!$uuid) return false;
1061
	return 'cdm_dataportal/reference/'.$uuid;
1062
}
1063

    
1064
function path_to_name($name_uuid){
1065
	$res = false;
1066
	if($name_uuid){
1067
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1068
	}
1069
	return $res;
1070
}
1071

    
1072
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1073
	if(!$uuid) return false;
1074
	$out = 'cdm_dataportal/media/'.$uuid;
1075
	if($representaion_uuid){
1076
		$out .= '/'.$representaion_uuid;
1077
		if($partId !== false){
1078
			$out .= '/'.$partId;
1079
		}
1080
	}
1081
	return $out;
1082
}
1083

    
1084
/**
1085
 * Compares thisRank with thatRank.
1086
 * Returns a negative integer, zero, or a positive integer
1087
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1088
 * e.g:
1089
 * <ul>
1090
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1091
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1092
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1093
 * </ul>
1094
 * <p>
1095
 * This compare logic of the underlying webservice is the
1096
 * <b>inverse logic</b> of the the one implemented in
1097
 * java.lang.Comparable#compareTo(java.lang.Object)
1098
 * @param $thisRankUuid
1099
 * @param $thatRankUuid
1100
 * @return  a negative integer, zero, or a positive integer
1101
 * as the thisRank is lower than, equal to, or higher than thatRank
1102
 */
1103
function rank_compare($thisRankUuid, $thatRankUuid){
1104
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1105
	return $result->Integer;
1106
}
1107

    
1108
function theme_cdm_uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1109
	$acceptedPath = path_to_taxon($acceptedUuid, true);
1110
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid, $synonymUuid);
1111
}
1112

    
1113
/**
1114
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1115
 * If the taggename if empty the fullname will be returned.
1116
 *
1117
 * @param unknown_type $Name or TreeNode
1118
 * @return string
1119
 */
1120
function cdm_dataportal_shortname_of($name){
1121
	$nameStr = '';
1122
	// get all tagged text tokens of the scientific name
1123
	foreach($name->taggedTitle as $tagtxt){
1124
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1125
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1126
		}
1127
	}
1128
	$nameStr = trim($nameStr);
1129
	if($nameStr){
1130
		// do not return short names for these
1131
		//if (stristr(strtolower($nameStr), 'incertae sedis') !== FALSE ||
1132
		//	stristr(strtolower($nameStr), 'nomina excludenda') !== FALSE) {
1133
		if ($name->unplaced || $name->excluded){
1134
			return $nameStr;
1135
		}
1136
		if($pos = stripos($nameStr, ' ')){
1137
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1138
		} else {
1139
			return $nameStr;
1140
		}
1141
	} else {
1142
		return $name->titleCache;
1143
	}
1144
}
1145

    
1146

    
1147
/**
1148
 * Check if a taxon is accepted by the current taxonomic tree
1149
 *
1150
 * @param Taxon $taxon
1151
 * @return true if $taxon is accepted, false otherwise
1152
 */
1153

    
1154
function _cdm_dataportal_acceptedByCurrentView($taxon){
1155

    
1156
	$defaultTreeUuid = get_taxonomictree_uuid_selected();
1157
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1158
		foreach($taxon->taxonNodes as $node){
1159
			if($node->classification == $defaultTreeUuid) {
1160
				return true;
1161
			}
1162
		}
1163
	}
1164
	return false;
1165
}
1166

    
1167
/**@Deprecated
1168
 *
1169
 */
1170
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1171
	$pstr = '';
1172
	foreach($parameters as $key=>$value){
1173
		if(is_array($value)){
1174

    
1175
		} else {
1176
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1177
		}
1178
	}
1179
	return $pstr;
1180
}
1181

    
1182
/**
1183
 * workaround for missing original source type, idNamespace is always set in these cases
1184
 * @param unknown_type $source
1185
 * @return unknown_type
1186
 */
1187
function _is_original_source_type($source){
1188
	return !$source->idNamespace && strlen($source->idNamespace) == 0;
1189
}
1190

    
1191

    
1192
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1193
	//TODO implement admin user interface to replace switch statement
1194
	//     preliminar solution: using themes
1195

    
1196
	$template = null;
1197
	// find best matching default RenderTemplate in theme
1198
	//echo "<br/><br/>RENDER PATH:  ".$renderPath;
1199
	//var_dump('RENDER PATH: ' . $renderPath);
1200
	while(!is_array($template) && strlen($renderPath) > 0){
1201
		$template = theme('get_nameRenderTemplate', $renderPath);
1202
		$renderPath = substr($renderPath, 0, strrpos($renderPath, '.'));
1203
		//	   if(!is_array($template)){
1204
		//	       echo "<br/>->".$renderPath;
1205
		//	   }
1206
	}
1207

    
1208
	// otherwise get default RenderTemplate from theme
1209
	if(!is_array($template)){
1210
		$template = theme('get_nameRenderTemplate', '#DEFAULT');
1211
	}
1212
	// otherwise get system default RenderTemplate
1213
	if(!is_array($template)){
1214
		switch($renderPath){
1215
			case 'list_of_taxa':
1216
			case  'acceptedFor':
1217
			case 'taxon_page_synonymy':
1218
			case 'typedesignations':
1219
			case 'taxon_page_title':
1220
			case 'na': $template = array(
1221
			        'namePart' => array('#uri'=>true),
1222
			//'authorshipPart' => true,
1223
			);
1224
			break;
1225
			case 'nar': $template = array(
1226
		          	'namePart' => array('#uri'=>true),
1227
			//'authorshipPart' => true,
1228
		          	'referencePart' => array('#uri'=>true),
1229
		          	'microreferencePart' => true,
1230
			);
1231
			break;
1232
			default: $template = array(
1233
          'namePart' => array('#uri'=>true),
1234
          'authorshipPart' => true,
1235
          'referencePart' => array('#uri'=>true),
1236
          'microreferencePart' => true,
1237
          'statusPart' => true,
1238
          'descriptionPart' => true
1239
			);
1240
		}
1241
	}
1242

    
1243
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1244
		$template['nameAuthorPart']['#uri'] = $nameLink;
1245
	} else{
1246
		unset($template['nameAuthorPart']['#uri']);
1247
	}
1248

    
1249
	if($nameLink && isset($template['namePart']['#uri'])){
1250
		$template['namePart']['#uri'] = $nameLink;
1251
	} else{
1252
		unset($template['namePart']['#uri']);
1253
	}
1254

    
1255
	if($refenceLink && isset($template['referencePart']['#uri'])){
1256
		$template['referencePart']['#uri'] = $refenceLink;
1257
	}else{
1258
		unset($template['referencePart']['#uri']);
1259
	}
1260

    
1261
	return $template;
1262
}
1263

    
1264
function get_partDefinition($taxonNameType){
1265
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1266
	//     preliminar solution: using themes
1267

    
1268
	$partdef = theme('get_partDefinition', $taxonNameType);
1269

    
1270
	if(!is_array($partdef)){
1271
		switch($taxonNameType){
1272
			case 'ZoologicalName': $partdef = array(
1273
        'namePart' => array(
1274
          'name' => true,
1275
			),
1276
        'referencePart' => array(
1277
          'authorTeam' => true
1278
			),
1279
        'microreferencePart' => array(
1280
          'microreference' => true,
1281
			),
1282
        'statusPart' => array(
1283
          'status' => true,
1284
			),
1285
        'descriptionPart' => array(
1286
          'description' => true,
1287
			),
1288
			);
1289
			break;
1290
			case 'BotanicalName': $partdef = array(
1291
        'namePart' => array(
1292
          'name' => true
1293
			),
1294
        'authorTeamPart' => array(
1295
          'authorTeam' => true,
1296
			),
1297
        'referencePart' => array(
1298
          'reference' => true
1299
			),
1300
        'microreferencePart' => array(
1301
          'microreference' => true,
1302
			),
1303
        'statusPart' => array(
1304
          'status' => true,
1305
			),
1306
        'descriptionPart' => array(
1307
          'description' => true,
1308
			),
1309
			);
1310
			break;
1311
			default: $partdef = array(
1312
        'namePart' => array(
1313
          'name' => true,
1314
			),
1315
        'authorTeamPart' => array(
1316
          'authorTeam' => true,
1317
			),
1318
        'referencePart' => array(
1319
          'reference' => true
1320
			),
1321
        'microreferencePart' => array(
1322
          'microreference' => true,
1323
			),
1324
        'statusPart' => array(
1325
          'status' => true,
1326
			),
1327
        'descriptionPart' => array(
1328
          'description' => true,
1329
			),
1330
			);
1331
		}
1332
	}
1333
	return $partdef;
1334
}
1335

    
1336
/**
1337
 * The function read the metadata info such title or artist of a media file. The
1338
 * function tries at first to get all the info from the file metadata and if it is
1339
 * not avaible look at the media file info stored at the database.
1340
 * @param $media The media file
1341
 * @return array The array with the avilable specified metadata info.
1342
 * TODO rename to read_media_metadata() and move to *.module
1343
 */
1344
function cdm_read_media_metadata($media){
1345

    
1346
	$metadata_caption = array('title' => '',           //media_metadata and media
1347
                              'artist' => '',          //media_metadata and media
1348
                              'rights',                //media_metadata and media
1349
                              'location',              //media_metadata
1350
                              'filename' => '',        //media
1351
                              'mediacreated' => '',    //media
1352
                              'description' => '');    //media
1353

    
1354
	//getting the media metadata
1355
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1356
	$media_metadata_aux = (array) $media_metadata;
1357
	//title
1358
	//if ($media_metadata->Headline) {
1359
	if ($media_metadata->ObjectName) {
1360
		$metadata_caption['title'] = $media_metadata->ObjectName;
1361

    
1362
		//	} else if ($media->titleCache){
1363
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1364
	} else if ($media_metadata_aux['Object Name']){
1365
		$metadata_caption['title'] = $media_metadata_aux['Object Name'];
1366
	} else if ($media->titleCache){
1367
		$metadata_caption['title'] = $media->titleCache;
1368
		if ($media->description_L10n)
1369
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1370
	}else{ //if there is no title on the db and metadata get file title
1371
		$aux = $media->representations[0]->parts[0]->uri;
1372
		$aux = explode("/", $aux);
1373
		$aux = end($aux);
1374
		$metadata_caption['title'] = $aux;
1375
	}
1376

    
1377
	//artist
1378
	if ($media_metadata->Artist){
1379
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1380
	}
1381
	elseif ($media->artist->titleCache){
1382
	 $metadata_caption['artist'] = $media->artist->titleCache;
1383
	}
1384

    
1385
	//copyright
1386
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1387
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1388
	if ($media_metadata->Copyright)
1389
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1390
	elseif ($media->rights){
1391
		foreach($media->rights as $right){
1392
			switch($right->term->uuid){
1393
				case UUID_RIGHTS_LICENCE:
1394
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1395
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1396
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1397
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1398
					break;
1399
				case UUID_RIGHTS_COPYRIGHT:
1400
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1401
					break;
1402
			}
1403
		}
1404
	}
1405
	else
1406
	$metadata_caption['rights']['agentNames'][] = '';
1407

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

    
1411
	//location
1412
	$metadata_caption['location'] = array();
1413
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1414
	$metadata_caption['location']['city'] = $media_metadata->City;
1415
	$metadata_caption['location']['province'] = $media_metadata->Province;
1416
	$metadata_caption['location']['country'] = $media_metadata->Country;
1417

    
1418
	//filename
1419
	if(isset($media->representations[0]->parts[0]->uri)){
1420
		$fileUri = $media->representations[0]->parts[0]->uri;
1421
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1422
		$metadata_caption['filename'] = $filename;
1423
	}
1424
	else{
1425
	 $metadata_caption['filename'] = '';
1426
	}
1427
	/*
1428
	 //creation date
1429
	 if($media_metadata["Modify Date"])
1430
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1431
	 else
1432
	 $metadata_caption['mediacreated'] = $media->created;
1433
	 */
1434
	//returned value
1435
	return $metadata_caption;
1436
}
1437

    
1438
/**
1439
 * This function collects all the media from a list of description elements
1440
 * and return them as an Array.
1441
 *
1442
 * @param $descriptionElementes The description elements
1443
 * @return Array The output with all the media
1444
 */
1445
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1446
	//variables
1447
	$outArrayOfMedia = array(); //return value
1448
	//implementation
1449
	if(is_array($descriptionElements)){//avoiding warning box in drupal for flora malesiana
1450
		foreach($descriptionElements as $descriptionElement){
1451
			if(is_array($descriptionElement->media)){
1452
				foreach($descriptionElement->media as $media){
1453
					if(isset($media)){
1454
						$outArrayOfMedia[] = $media;
1455
					}
1456
				}
1457
			}
1458
		}
1459
	}
1460
	return $outArrayOfMedia;
1461
}
1462

    
1463
function cdm_annotations_as_footnotekeys($cdmBase, $footnote_list_key = array()){
1464
	$footNoteKeys = array();
1465
	//is argument cdmBase an array?
1466
	if (!is_array($cdmBase)){
1467
		$cdmBase_array = array();
1468
		$cdmBase_array[] = $cdmBase;
1469
	}else{
1470
		$cdmBase_array = $cdmBase;
1471
	}
1472
	//getting the key for the footnotemanager
1473
	if((bool) $footnote_list_key){
1474
		$footnoteListKey = $footnote_list_key;
1475
	}else{
1476
		$footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1477
	}
1478
	//adding the footnotes keys
1479
	foreach($cdmBase_array as $cdmBase_element){
1480
		$annotationUrl = cdm_compose_annotations_url($cdmBase_element);
1481
		if($annotationUrl){
1482
			$annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
1483
			if($annotationPager->count > 0){
1484
				foreach($annotationPager->records as $annotation){
1485
					$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1486
				}
1487
			}
1488
		}
1489
	}
1490
	return $footNoteKeys;
1491
	/*
1492
	 $footNoteKeys = array();
1493
	 $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1494
	 $annotationUrl = cdm_compose_annotations_url($cdmBase);
1495
	 if($annotationUrl){
1496
		$annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
1497
		if($annotationPager->count > 0){
1498
		foreach($annotationPager->records as $annotation){
1499
		$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1500
		}
1501
		}
1502
		}
1503
		return $footNoteKeys;
1504
		*/
1505
}
1506

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

    
1509
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cdm_dynabox.js');
1510

    
1511
	$cdm_proxy_url = url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
1512
	$out .= '<'. $enclosingtags[0]. ' class="dynabox"><a href="'.$content_url.'" class="label" alt="'.t($link_alt_text).'">'.$label.'</a>';
1513
	$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]. '>';
1514
	$out .= '</'. $enclosingtags[0]. '>';
1515
	return $out;
1516
}
1517

    
(6-6/12)