Project

General

Profile

Download (67.5 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

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

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

    
32
define('CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE', 25);
33
define('CDM_DATAPORTAL_NOMREF_IN_TITLE', 1);
34
define('CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR', 0);
35

    
36
/* gallery variables */
37
$gallery_settings = array(
38
    "cdm_dataportal_show_taxon_thumbnails" => 1,
39
    "cdm_dataportal_show_synonym_thumbnails" => 0,
40
    "cdm_dataportal_show_thumbnail_captions" => 1,
41
    "cdm_dataportal_media_maxextend" => 120,
42
    "cdm_dataportal_media_cols" => 3,
43
    "cdm_dataportal_media_maxRows" => 1);
44
define('CDM_DATAPORTAL_GALLERY_SETTINGS', serialize($gallery_settings));
45
define('CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME', "description_gallery");
46
define('CDM_DATAPORTAL_MEDIA_GALLERY_NAME', "media_gallery");
47
define('CDM_DATAPORTAL_SEARCH_GALLERY_NAME', "search_gallery");
48
define('CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS', 'cdm_dataportal_display_taxon_relationships');
49
define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS', 'cdm_dataportal_display_name_relations');
50
//define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_2', array("default" => t('Display all')));
51
define('CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT', 1);
52
define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT', 1);
53
define('CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID', 'cdm_dataportal_featuretree_uuid');
54
define('CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID', 'cdm_dataportal_structdesc_featuretree_uuid');
55

    
56
function getGallerySettings($gallery_config_form_name){
57
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
58
	return variable_get($gallery_config_form_name, $default_values);
59
}
60

    
61
function _add_js_progressbar(){
62
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/jquery.progressbar/js/jquery.progressbar.js');
63
}
64

    
65
function _add_js_treeselector(){
66
	//drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/treeselector.js');
67
	drupal_add_js("
68
		if (Drupal.jsEnabled) {
69
		  $(document).ready(function() {
70
		      $('#cdm-taxonomictree-selector-form #edit-val').change(function () {
71
		          $('#cdm-taxonomictree-selector-form').submit();
72
		      });
73

    
74
		  });
75
		}", 'inline');
76
}
77

    
78

    
79
function get_openlayers_map($width, $occurrenceQuery = false, $distributionQuery = false, $legendFormatQuery = false, $map_caption = false ){
80

    
81
      _add_js_openlayers_map();
82

    
83
      $out = '<div id="openlayers">';
84
      $out .= '<div id="openlayers_map" class="smallmap"';
85
      $out .= ' style="width: ' . $width . 'px; height:'.( $width / 2).'px"';
86
      if($occurrenceQuery){
87

    
88
      	//fix $occurrenceQuery
89
      	$occurrenceQuery .= '&ms=400,350';
90
      	$occurrenceQuery .= '&l=v%3Aatbi%2Ce_w_0';
91
      	$occurrenceQuery .= '&legend=0'; //TODO add to cdm service?
92

    
93
      	$out .= ' occurrenceQuery="'.$occurrenceQuery.'"';
94
      }
95
      if($distributionQuery){
96
        $out .= ' distributionQuery="'.$distributionQuery.'"';
97
      }
98
      if($legendFormatQuery){
99
         $out .= ' legendFormatQuery="'.$legendFormatQuery.'"';
100
      }
101
      $out .= '></div></div>';
102

    
103
      // showing map caption
104
      if($map_caption){
105
        $out .= '<div class="distribution_map_caption">' . $map_caption . '</div>' . '<br />'; //FIXME: replace <br> by according css style
106
        $out .= '</div>';
107
      }
108
      return $out;
109
}
110

    
111
/* ====================== hook implementations ====================== */
112

    
113
/**
114
 * Implementation of hook_help()
115
 *
116
 * Display help and module information
117
 * @param section which section of the site we're displaying help
118
 * @return help text for section
119
 */
120
function cdm_dataportal_help($section='') {
121

    
122
	$out = '';
123
	switch ($section) {
124
		case "admin/modules#description":
125
			$out = t("The dataportal publishes CDM data hosted in a CommunityStore on the web.");
126
			break;
127
	}
128
	return $out;
129
}
130

    
131

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

    
146

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

    
153
	if ($may_cache) {
154

    
155
		$items[] = array(
156
      'path' => 'admin/settings/cdm_dataportal',
157
      'title' => t('CDM Dataportal'),
158
      'description' => t('Setting for the CDM DataPortal'),
159
      'access' => user_access('administer cdm_dataportal'),
160
      'callback' => 'drupal_get_form',
161
      'callback arguments' => 'cdm_dataportal_settings',
162
      'type' => MENU_NORMAL_ITEM,
163
		);
164

    
165
		$items[] = array(
166
      'path' => 'admin/settings/cdm_dataportal/general',
167
      'title' => t('General'),
168
      'description' => t('Setting for the CDM DataPortal'),
169
      'access' => user_access('administer cdm_dataportal'),
170
      'callback' => 'drupal_get_form',
171
      'callback arguments' => 'cdm_dataportal_settings',
172
	  'weight' => 0,
173
      'type' => MENU_LOCAL_TASK,
174
		);
175

    
176
		$items[] = array(
177
      'path' => 'admin/settings/cdm_dataportal/geo',
178
      'title' => t('Geo & Map'),
179
      'description' => t('Geo & Map'),
180
      'access' => user_access('administer cdm_dataportal'),
181
      'callback' => 'drupal_get_form',
182
      'callback arguments' => 'cdm_dataportal_settings_geo',
183
	    'weight' => 1,
184
      'type' => MENU_LOCAL_TASK,
185
		);
186

    
187
		$items[] = array(
188
      'path' => 'admin/settings/cdm_dataportal/layout',
189
      'title' => t('Layout'),
190
      'description' => t('Configure and adjust the layout of your DataPortal '),
191
      'access' => user_access('administer cdm_dataportal'),
192
      'callback' => 'drupal_get_form',
193
      'callback arguments' => 'cdm_dataportal_settings_layout',
194
      'weight' => 2,
195
      'type' => MENU_LOCAL_TASK,
196
		);
197

    
198
		$items[] = array(
199
      'path' => 'admin/settings/cdm_dataportal/cachesite',
200
      'title' => t('Cache'),
201
      'description' => t('Cache the whole CDM DataPortal site'),
202
      'access' => user_access('administer cdm_dataportal'),
203
      'callback' => 'cdm_dataportal_view_cache_site',
204
      'weight' => 10,
205
      'type' => MENU_LOCAL_TASK,
206
		);
207

    
208
		/*$items[] = array(
209
		 'path' => 'admin/settings/cdm_dataportal/ws',
210
		 'title' => t('Web Service'),
211
		 'description' => t('Setting for the CDM DataPortal'),
212
		 'access' => user_access('administer cdm_dataportal'),
213
		 'callback' => 'drupal_get_form',
214
		 'callback arguments' => 'cdm_dataportal_settings',
215
		 'weight' => 1,
216
		 'type' => MENU_DEFAULT_LOCAL_TASK,
217
		 );*/
218

    
219
		$items[] = array(
220
	    'path' => 'cdm_dataportal/names',
221
	    'callback' => 'cdm_dataportal_view_names',
222
	    'access' => true,
223
	    'type' => MENU_CALLBACK,
224
		);
225
		// optional callback arguments: page
226

    
227
		$items[] = array(
228
      'path' => 'cdm_dataportal/taxon',
229
      'callback' => 'cdm_dataportal_taxon_page_view',
230
      'access' => true,
231
      'type' => MENU_CALLBACK,
232
		// expected callback arguments: uuid
233
		);
234

    
235
		$items[] = array(
236
      'path' => 'cdm_dataportal/name',
237
      'callback' => 'cdm_dataportal_name_page_view',
238
      'access' => true,
239
      'type' => MENU_CALLBACK,
240
		// expected callback arguments: uuid
241
		);
242

    
243
		$items[] = array(
244
      'path' => 'cdm_dataportal/reference',
245
      'callback' => 'cdm_dataportal_view_reference',
246
      'access' => true,
247
      'type' => MENU_CALLBACK,
248
		// expected callback arguments: uuid
249
		);
250

    
251
		$items[] = array(
252
      'path' => 'cdm_dataportal/reference/list',
253
      'callback' => 'cdm_dataportal_view_reference_list',
254
      'access' => true,
255
      'type' => MENU_CALLBACK,
256
		// expected callback arguments: uuid
257
		);
258

    
259
		$items[] = array(
260
      'path' => 'cdm_dataportal/media',
261
      'callback' => 'cdm_dataportal_view_media',
262
      'access' => true,
263
      'type' => MENU_CALLBACK,
264
		// expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
265
		);
266

    
267
		$items[] = array(
268
      'path' => 'cdm_dataportal/search',
269
      'callback' => 'cdm_dataportal_view_search_advanced',
270
      'access' => true,
271
      'type' => MENU_CALLBACK,
272
		);
273

    
274
		$items[] = array(
275
      'path' => 'cdm_dataportal/search/taxon',
276
      'callback' => 'cdm_dataportal_view_search_taxon',
277
      'access' => true,
278
      'type' => MENU_CALLBACK,
279
		);
280

    
281
		$items[] = array(
282
      'path' => 'cdm/xml2json',
283
      'callback' => 'cdm_view_xml2json',
284
      'access' => true,
285
      'type' => MENU_CALLBACK,
286
		);
287

    
288
	} else {
289
		// may not cache
290
		// --- local tasks for Taxon
291
		$items[] = array(
292
      'path' => 'cdm_dataportal/name/'.arg(2),
293
		//'callback' => 'cdm_dataportal_view_name',
294
		  'callback' => 'cdm_dataportal_name_page_view',
295
      'callback arguments' => array(arg(2), arg(3), arg(4)),
296
      'access' => true,
297
      'type' => MENU_CALLBACK,
298
		);
299

    
300
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
301

    
302
			$items[] = array(
303
      'path' => 'cdm_dataportal/taxon/'.arg(2),
304
      'title' => theme('cdm_taxonpage_tab', 'General'),
305
      'callback' => 'cdm_dataportal_taxon_page_view',
306
      'access' => true,
307
      'type' => MENU_CALLBACK,
308
      'weight' => 1,
309
      'callback arguments' => array(arg(2), "description")
310
			// expected callback arguments: name_uuid
311
			);
312

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

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

    
335
			$items[] = array(
336
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
337
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
338
      'callback' => 'cdm_dataportal_taxon_page_view',
339
      'access' => true,
340
      'type' => MENU_LOCAL_TASK,
341
      'weight' => 3,
342
      'callback arguments' => array(arg(2), "synonymy")
343
			// expected callback arguments: name_uuid
344
			);
345

    
346
			$items[] = array(
347
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
348
      'title' => theme('cdm_taxonpage_tab', 'Images'),
349
      'callback' => 'cdm_dataportal_taxon_page_view',
350
      'access' => true,
351
      'type' => MENU_LOCAL_TASK,
352
      'weight' => 4,
353
      'callback arguments' => array(arg(2), "images")
354
			// expected callback arguments: name_uuid
355
			);
356
		 $items[] = array(
357
		 'path' => 'cdm_dataportal/taxon/'.arg(2).'/specimens',
358
		 'title' => theme('cdm_taxonpage_tab', 'Specimens'),
359
		 'callback' => 'cdm_dataportal_taxon_page_view',
360
		 'access' => true,
361
		 'type' => MENU_LOCAL_TASK,
362
		 'weight' => 5,
363
		 'callback arguments' => array(arg(2), "specimens")
364
		 // expected callback arguments: name_uuid
365
		 );
366

    
367
		}
368
	}
369

    
370
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
371
	//drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
372
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
373

    
374
	return $items;
375

    
376
}
377

    
378
/**
379
 * Implementation of hook_block()
380
 *
381
 * Provides the following blocks:
382
 *  0: list of links useful during development
383
 *
384
 * @param String $op
385
 * @param int $delta
386
 */
387
function cdm_dataportal_block($op='list', $delta=0) {
388
	// listing of blocks, such as on the admin/block page
389
	if ($op == "list") {
390
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
391
		//		$block[1]["info"] = t("CDM DataPortal Credits");
392
		$block[2]["info"] = t("CDM Search Taxa");
393
		//$block[3]["info"] = t("CDM Filters");
394
		$block[4]["info"] = t("CDM Dataportal Print");
395
		return $block;
396
	}
397
	else if ($op == 'view') {
398
		switch($delta){
399
			//			case 1:
400
			//				$block['subject'] = t('Credits');
401
			//				$block['content'] = theme('cdm_credits');
402
			//				return $block;
403
			case 2:
404
				$block['subject'] = t('Search taxa');
405
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
406
				$block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
407
				return $block;
408
			case 4:
409
				$block['subject'] = t('Print this page');
410
				$block['content'] = theme('cdm_print_button');;
411
				return $block;
412
		}
413
	}
414
}
415

    
416

    
417
/**
418
 * Implementation of hook_validate()
419
 *
420
 * @param $element
421
 */
422
function cdm_dataportal_settings_validate($form_id, $form_values){
423

    
424
	if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
425
		//form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
426
		$form_values['cdm_webservice_url'] .= '/';
427
	}
428

    
429
	//	$cdm_webservice_url_changed = variable_get('cdm_webservice_url', '') != $form_values['cdm_webservice_url'];
430

    
431
	//	if ($cdm_webservice_url_changed) {
432
	//
433
	//		//FIXME remove _cdm_dataportal_set_currentSecUuid($form_values['cdm_secUuid_default']);
434
	//		// reset all cdm related data stored in the session
435
	//		// cdm_dataportal_session_clear($form_values['cdm_webservice_url']); // cdm_webservice_url is not further stored here
436
	//		// clear the cdm webservice cache
437
	//		cache_clear_all(NULL, 'cache_cdm_ws');
438
	//		// better clear secref_cache since i can not be sure if the cache has not be used during this response
439
	//		cdm_api_secref_cache_clear();
440
	//	}
441
	if($form_values['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)){
442
		cache_clear_all(NULL, 'cache_cdm_ws');
443
		// better clear secref_cache since i can not be sure if the cache has not be used during this response
444
		cdm_api_secref_cache_clear();
445
	}
446

    
447
}
448

    
449
/*
450
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
451
 $_SESSION['cdm'] = null;
452
 if(is_string($cdm_ws_uri_update)){
453
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
454
 }
455
 }
456

    
457
 function cdm_dataportal_session_validate(){
458

    
459
 if(!isset($_SESSION['cdm']['ws_uri'])){
460
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
461
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
462
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
463
 }
464
 }
465
 */
466

    
467
function cdm_dataportal_search_taxon_form($advancedForm = false){
468

    
469
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
470
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
471
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
472
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
473
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
474
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
475

    
476
	$url = 'cdm_dataportal/search/taxon';
477
	$form['#method'] = 'get';
478
	$form['#process'] = array('cdm_dataportal_search_process' => array());
479
	$form['#action'] = url($url, NULL, NULL, true);
480

    
481
	$form['query'] = array(
482
    '#delta' => 0,
483
    '#type' => 'textfield',
484
    '#size' => 20,
485
    '#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')),
486
    '#value' => $preset_query,
487
	);
488

    
489
	$form['search'] = array(
490
      '#delta' => 1,
491
      '#tree' => true,
492
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
493
      '#title' => t('Options')
494
	);
495

    
496
	$form['search']['tree'] = array(
497
    '#delta' => -1,
498
    '#type' => 'hidden',
499
    '#value' => get_taxonomictree_uuid_selected()
500
	);
501

    
502

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

    
513
	$form['search']['pageSize'] = array(
514
      '#delta' => -1,
515
      '#type' => 'hidden',
516
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
517
	);
518

    
519
	if($advancedForm){
520
		// general search parameters
521
		$form['search']['doTaxa'] = array(
522
      '#delta' => 2,
523
      '#type' => 'checkbox',
524
      '#title' => t('Search for accepted taxa'),
525
      '#value' => $preset_doTaxa
526
		);
527
		$form['search']['doSynonyms'] = array(
528
      '#delta' => 3,
529
      '#type' => 'checkbox',
530
      '#title' => t('Search for synonyms'),
531
      '#value' => $preset_doSynonyms
532
		);
533
		$form['search']['doTaxaByCommonNames'] = array(
534
      '#delta' => 4,
535
      '#type' => 'checkbox',
536
      '#title' => t('Search for common names'),
537
      '#value' => $preset_doTaxaByCommonNames
538
		);
539

    
540
		// Geographic Range
541
		$form['search']['geographic_range'] = array(
542
      '#type' => 'fieldset',
543
      '#delta' => 5,
544
      '#tree' => true,
545
      '#title' => t('Geographic range'),
546
		);
547

    
548
		$form['search']['geographic_range']['tdwg_level_select'] = array(
549
    '#type' => 'radios',
550
    '#title' => t('Select a TDWG distribution level and code'),
551
    '#default_value' => $tdwg_level_select,
552
    '#options' => array(
553
		t('TDWG level-1, i.e. a continent'),
554
		t('TDWG level-2'),
555
		t('TDWG level-3, i.e. a country'),
556
		t('TDWG level-4')
557
		)
558
		);
559
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
560
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
561
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
562
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
563

    
564
		$tdwg_js = '';
565
		foreach($tdwg as $key=>$tdwg_level){
566
			$tdwgOptions = array();
567
			$tdwgOptionsSelected = array();
568
			foreach($tdwg_level as $area){
569
				$representation = $area->representations[0];
570
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
571
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
572
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
573
				}
574
			}
575
			asort($tdwgOptions);
576
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
577
        '#type' => 'select',
578
        '#title'         => t('TDWG level').' '.$key,
579
        '#default_value' => $tdwgOptionsSelected,
580
        '#multiple' => TRUE,
581
        '#options' => $tdwgOptions
582
			);
583
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
584
		}
585

    
586
		drupal_add_js(
587
    "$(document).ready(function(){
588

    
589
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change(
590
        function(event){
591
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
592
          var i;
593
          for(i = 0; i < 4; i++){
594
            if(selectId == i){
595
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
596
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
597
            } else {
598
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
599
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
600
            }
601
          }
602
        }
603
      );
604

    
605
      $tdwg_js
606
    });",
607
    'inline');
608

    
609
	} else {
610
		$form['search']['doTaxa'] = array(
611
	      '#delta' => -2,
612
	      '#type' => 'hidden',
613
	      '#value' => 1
614
		);
615
		$form['search']['doSynonyms'] = array(
616
	      '#delta' => -3,
617
	      '#type' => 'hidden',
618
	      '#value' => 1
619
		);
620
		$form['search']['doTaxaByCommonNames'] = array(
621
	      '#delta' => -4,
622
	      '#type' => 'hidden',
623
	      '#value' => 0
624
		);
625
	}
626

    
627
	$form['submit'] = array(
628
	  '#delta' => 9,
629
	  '#type' => 'submit',
630
	  '#name' => '',
631
	  '#value' => t('Search')
632
	);
633

    
634
	return $form;
635
}
636

    
637
function cdm_dataportal_search_taxon_form_advanced(){
638
	return cdm_dataportal_search_taxon_form(true);
639
}
640

    
641
function cdm_taxonomictree_selector(){
642
	_add_js_treeselector();
643

    
644
	$out = drupal_get_form('cdm_taxonomictree_selector_form');
645

    
646
	return $out;
647
}
648

    
649

    
650
function cdm_taxonomictree_selector_form(){
651

    
652
	$url = url('cdm_api/setvalue/session', null);
653
	$form['#action'] = $url;
654

    
655
	$form['var'] = array(
656
        '#delta' => -3,
657
        '#type' => 'hidden',
658
        '#value' => '[cdm][taxonomictree_uuid]'
659
        );
660

    
661
   $form['destination'] = array(
662
	   '#delta' => -3,
663
	   '#type' => 'hidden',
664
	   '#value' => substr(drupal_get_destination(), strlen('destination='))
665
    );
666

    
667
    $form['val'] = array(
668
      '#type' => 'select',
669
      '#title'         => t('Available classifications'),
670
      '#default_value' => get_taxonomictree_uuid_selected(),
671
      '#options' => cdm_get_taxontrees_as_options()
672
    );
673

    
674
        return $form;
675

    
676
}
677

    
678
/**
679
 * Implementation #process method call, see form_builder()
680
 * <p>
681
 * Removes Drupal internal form elements from query
682
 * @param $form
683
 * @return unknown_type
684
 */
685
function cdm_dataportal_search_process($form) {
686
	unset($form['form_id']);
687
	unset($form['form_token']);
688
	return $form;
689
}
690

    
691
/**
692
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
693
 * returns the processed request parameters submitted by the search form.
694
 */
695
function cdm_dataportal_search_form_request(){
696

    
697

    
698
	$form_params = array();
699
	array_deep_copy($_REQUEST['search'], $form_params);
700
	$form_params['query'] =  trim($_REQUEST['query']);
701

    
702
	// split of  geographic range
703
	if(isset($_REQUEST['search']['geographic_range'])){
704
		$geographicRange = $_REQUEST['search']['geographic_range'];
705
		// remove
706
		unset($form_params['geographic_range']);
707
	}
708

    
709
	// add geographic range
710
	if($geographicRange){
711
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
712
		for($i = 1; $i < 5; $i++){
713
			if(isset($geographicRange['tdwg_level_'.$i])){
714
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
715
			}
716
		}
717
	}
718

    
719
	// store in session
720
	$_SESSION['cdm']['search'] = $form_params;
721

    
722
	return $form_params;
723
}
724

    
725

    
726
/* UNREACHABLE since action of form directly links to view
727
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
728

    
729
 $_SESSION['cdm']['search'] = $form_values;
730
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
731
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
732
 //$paramstr = compose_url_prameterstr($form_values);
733
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
734
 }
735
 */
736
/* ====================== menu callback functions ====================== */
737

    
738
/**
739
 * Generate main administration form.
740
 *
741
 * @return
742
 *   An array containing form items to place on the module settings page.
743
 */
744
function cdm_dataportal_settings(){
745

    
746
	$form = cdm_api_settings_form();
747

    
748

    
749
	return system_settings_form($form);
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
 * LAYOUT settings
775
 * @return unknown_type
776
 */
777
function cdm_dataportal_settings_layout(){
778

    
779
	$form = array();
780
	/*
781
	 $form['cdm_taxonname_type'] = array(
782
	 '#type' => 'select',
783
	 '#title'         => t('Taxon name type'),
784
	 '#default_value' => variable_get('cdm_taxonname_type', 'BotanicalName'),
785
	 '#options' => array( 'BotanicalName'=>t('BotanicalName'), 'ZoologicalName'=>t('ZoologicalName')),
786
	 '#description'   => t('')
787
	 );
788
	 */
789
	
790
	$form['cdm_dataportal_taxonpage_tabs'] = array(
791
    '#type' => 'checkbox',
792
    '#title' => t('Tabbed taxon page'),
793
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
794
    '#description' => t('Split the taxon page into individual tabs for description, images, synonymy')
795
  );
796
	
797
	//---- SYNONYMY ----//
798
	$form['synonymy'] = array(
799
      '#type' => 'fieldset',
800
      '#title' => t('Synonymy'),
801
      '#collapsible' => TRUE,
802
      '#collapsed' => TRUE,
803
	);
804

    
805
	$form['synonymy']['cdm_dataportal_nomref_in_title'] = array(
806
    '#type' => 'checkbox',
807
    '#title' => t('Show accepted taxon on top of the synonymy'),
808
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
809
    '#description' => t('If checked, the first homotypic taxon is a repetition of the accepted taxon most likely
810
                        with the full nomenclatural reference (depending on the currently chosen theme).')
811
	);
812

    
813
	$form['synonymy']['cdm_dataportal_display_is_accepted_for'] = array(
814
    '#type' => 'checkbox',
815
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when coming from a synonym link.'),
816
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
817
    '#description' => t('Check this if after doing a search and clicking on a synonym you want to see the "accept of" text for the accepted synonym.')
818
	);
819

    
820
	$name_relationships_terms = cdm_ws_get(CDM_WS_TERMVOCABULARY, UUID_NAME_RELATIONSHIP_TYPE);
821
  $name_rel_options = array();
822
  //$name_rel_options['default'] = 'Show all';
823
  foreach ($name_relationships_terms->terms as $element){
824
    $name_rel_options[$element->uuid] = t('Show "' . $element->titleCache . '" relationships'); 
825
  } 
826
  
827
	$name_relationships_form['name_relationships_to_show']= array(
828
  '#type' => 'checkboxes',
829
  '#title' => t('Display name relationships'),
830
  '#default_value' => variable_get('name_relationships_to_show', 0),
831
  '#options' => $name_rel_options,
832
  '#description' => t('Select the name relationships you want to show for the accepted taxa.'),
833
  );
834
    
835
  $form['synonymy']['name_relationships'] = $name_relationships_form;
836
/*
837
	$form['synonymy'][CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS] = array(
838
    '#type' => 'checkbox',
839
    '#title' => t('Show name relations of accepted taxa on taxon page'),
840
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT),
841
    //'#description' => t('Check this if you want the synonymy list to show all the name relationships where other names implies the accepted taxa.')
842
	  '#description' => t('Check this if you want the synonymy list to show all the name relationships of accepted taxa.')
843
	);
844
*/
845
	$form['synonymy'][CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
846
    '#type' => 'checkbox',
847
    '#title' => t('Show taxon relations of accepted taxa on taxon page'),
848
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
849
    '#description' => t('Check this if you want the synonymy list to show the <em>"Misapplied Name for"</em> and <em>"Invalid Designation for"</em> relationships of accepted taxa.')
850
	);
851

    
852
/*
853
	$form['synonymy']['cdm_dataportal_name_relations_skiptype_basionym'] = array(
854
    '#type' => 'checkbox',
855
    '#title' => t('Exclude the basionym relationship type from the taxon page'),
856
    '#default_value' => variable_get('cdm_dataportal_name_relations_skiptype_basionym', 1),
857
    '#description' => t('')
858
	);
859
*/
860

    
861
	/*
862
	 $form['cdm_dataportal_descriptions_separated'] = array(
863
	 '#type' => 'checkbox',
864
	 '#title' => t('Separate Descriptions'),
865
	 '#default_value' => variable_get('cdm_dataportal_descriptions_separated', 0),
866
	 '#description' => t('By default corresponding elements of different descriptions are joined together'
867
	 .' into a common section per feature (i.e. type of description).'
868
	 .' Check this box to allow displaying all descriptions separately.')
869
	 );
870
	 */
871
	//------------------ FEATURE TREE --------------------//
872

    
873
	$form['cdm_dataportal']['taxon_profile'] = array(
874
	    '#type' => 'fieldset',
875
	    '#title' => t('Taxon profile'),
876
	    '#description'   => t('This section covers setting related to the taxon profile tab, also known as the <strong>"General"</strong> tab.'),
877
	    '#collapsible' => TRUE,
878
	    '#collapsed' => TRUE,
879
	);
880

    
881
	$form['cdm_dataportal']['taxon_profile'][CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID] = array(
882
	    '#type' => 'radios',
883
	    '#title'         => t('Taxon profile elements'),
884
	    '#default_value' => variable_get(CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE),
885
	    '#options' => cdm_get_featureTrees_as_options(TRUE),
886
	    '#description'   => t('Select a FeatureTree to specify the elements to be displayd in the taxon profile.'
887
	    //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
888
	)
889
	);
890

    
891
	$form['cdm_dataportal']['taxon_profile'][CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID] = array(
892
	    '#type' => 'radios',
893
	    '#title'         => t('Natural language representation of structured descriptions'),
894
	    '#default_value' => variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, null),
895
	    '#options' => cdm_get_featureTrees_as_options(),
896
	    '#description'   => t('Taxon descriptions can be stored in a highly structured form.'.
897
	      ' The feature tree selected here will be used to generate textual representation in natural language.'
898
	      //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
899
	)
900
	);
901

    
902
	//---- IMAGES ----//
903
	$form['images'] = array(
904
	    '#type' => 'fieldset',
905
	    '#title' => t('Images'),
906
	    '#collapsible' => TRUE,
907
	    '#collapsed' => TRUE,
908
	);
909
	$options = cdm_rankVocabulary_as_option();
910
	array_unshift($options, '-- DISABLED --');
911
	$form['images']['image_hide_rank'] =  array(
912
	    '#type'          => 'select',
913
	    '#title'         => t('Hide Images for Taxa above'),
914
	    '#default_value' => variable_get('image_hide_rank', '0'),
915
	    '#options'       => $options,
916
	    '#description'   => t(''),
917
	);
918
	//show media
919
	$selectShowMedia = array(0 => "Show only taxon media",
920
	1 => "Show taxon and child taxon media");
921
	$form['images']['cdm_dataportal_show_media'] = array(
922
	    '#type' => 'select',
923
	    '#title' => t('Available media files'),
924
	    '#default_value' => variable_get('cdm_dataportal_show_media', false),
925
	    '#options' => $selectShowMedia,
926
	    '#description'   => t('Select if a taxon should show only his media or also child media.')
927
	);
928
	$selectShowMedia = array(0 => "Show only taxon media",
929
	1 => "Show taxon and child taxon media");
930
	$form['images']['cdm_dataportal_show_default_image'] = array(
931
      '#type' => 'checkbox',
932
      '#title' => t('Show default image'),
933
      '#default_value' => variable_get('cdm_dataportal_show_default_image', false),
934
      '#description'   => t('Select if the taxon profile page should display the default image if no image is available for the chosen taxon.')
935
	);
936
	
937
	//------------------ SEARCH --------------------// 
938
  $form['search'] = array(
939
      '#type' => 'fieldset',
940
      '#title' => t('Search'),
941
      '#collapsible' => TRUE,
942
      '#collapsed' => TRUE,
943
  );
944
  $form['search']['cdm_dataportal_search_items_on_page'] = array(
945
    '#type' => 'textfield',
946
    '#title' => t('Search Page Size'),
947
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
948
    '#description' => t('Number of Names to display per page in search results.')
949
  );
950

    
951
	// --- SEARCH TAXA GALLERY ---- //
952
	$items = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
953
	$collapsed = TRUE;
954
	$form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
955
	$form_tittle = 'Search Taxa';
956
	$form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
957

    
958
	// --- FEATURE DESCRIPTION GALLERY ---- //
959
	$form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
960
	$form_tittle = 'Description elements gallery';
961
	$form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
962

    
963
	// --- MEDIA GALLERY ---- //
964
	$form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
965
	$form_tittle = 'Media gallery';
966
	$form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
967

    
968
	//-- DISTRIBUTION LAYOUT --//
969
	$form['distribution_layout'] = array(
970
        '#title' => t('Distribution layout'),
971
        '#collapsible' => TRUE,
972
        '#collapsed' => TRUE,
973
        '#type' => 'fieldset',
974
	);
975

    
976
	$form['distribution_layout']['distribution_sort'] =  array(
977
    '#type'          => 'radios',
978
    '#title'         => t('Sort'),
979
    '#default_value' => 0,
980
    '#options' => array(
981
	t('Standard (No sort)'),
982
	t('Sorted without TDWG Level 2'),
983
	));
984

    
985
	return system_settings_form($form);
986
}
987

    
988
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed){
989

    
990
	$form[$form_name] = array(
991
    '#type' => 'fieldset',
992
    '#title' => t($form_tittle),
993
    '#collapsible' => TRUE,
994
    '#collapsed' => $collapsed,
995
    '#tree' => true,
996
	);
997

    
998
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
999
	$gallery_settings = variable_get($form_name, $default_values);
1000
	//$test = variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE);
1001

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

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

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

    
1034
	$form[$form_name]['cdm_dataportal_media_maxextend'] = array(
1035
    '#type' => 'textfield',
1036
    '#title' => t('Maximum extend of Images'),
1037
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
1038
    '#description' => t('In the gallery neither width or height will exceed the maximum extend of images.')
1039
	);
1040

    
1041
	$form[$form_name]['cdm_dataportal_media_cols'] = array(
1042
    '#type' => 'textfield',
1043
    '#title' => t('Number of columns'),
1044
    '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
1045
    '#description' => t('')
1046
	);
1047

    
1048
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
1049
		$form[$form_name]['cdm_dataportal_media_maxRows'] = array(
1050
      '#type' => 'textfield',
1051
      '#title' => t('Maximum number of rows'),
1052
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
1053
      '#description' => t('If you want an unlimited number of rows please set to 0')
1054
		);
1055
	}
1056

    
1057
	return $form;
1058
}
1059

    
1060
/**
1061
 * GEOSERVICE and Map settings
1062
 * @return unknown_type
1063
 */
1064
function cdm_dataportal_settings_geo(){
1065

    
1066
	$form = array();
1067

    
1068
	$form['cdm_dataportal_map_openlayers'] = array(
1069
    '#type' => 'checkbox',
1070
    '#title' => t('OpenLayers Viewer'),
1071
    '#default_value' => variable_get('cdm_dataportal_map_openlayers', 1),
1072
    '#description' => t('Display the maps in an interactive viewer which allows zooming and panning.')
1073
	);
1074

    
1075
	$form['cdm_dataportal_geoservice_access_point'] = array(
1076
    '#type' => 'textfield',
1077
    '#title' => t('Geoservice Access Point'),
1078
    '#default_value' => variable_get('cdm_dataportal_geoservice_access_point', ''),
1079
    '#description' => t('Base URL of the geoservice to be used by this portal')
1080
	);
1081

    
1082
	$form['cdm_dataportal_geoservice_display_width'] = array(
1083
    '#type' => 'textfield',
1084
    '#title' => t('Geoservice Display Width'),
1085
    '#default_value' => variable_get('cdm_dataportal_geoservice_display_width', 390),
1086
    '#description' => t('Width of the image generated by geoservice')
1087
	);
1088

    
1089
	$form['cdm_dataportal_geoservice_bounding_box'] = array(
1090
    '#type' => 'textfield',
1091
    '#title' => t('Fixed Geoservice Bounding Box'),
1092
    '#default_value' => variable_get('cdm_dataportal_geoservice_bounding_box', '-180,-90,180,90'),
1093
    '#description' => t('Define urrounding of area to be displayed in maps. Use "-180,-90,180,90" for the whole world. Leave <strong>empty</strong> to let the map <strong>automatically zoom</strong> to the distribution area.')
1094
	);
1095

    
1096
	//cdm_dataportal_geoservice_labels_on
1097
	$form['cdm_dataportal_geoservice_labels_on'] = array(
1098
    '#type' => 'checkbox',
1099
    '#title' => t('Display Country Labels'),
1100
    '#default_value' => variable_get('cdm_dataportal_geoservice_labels_on', FALSE),
1101
    '#description' => t('Check this if you like country names to be displayed in the maps. ')
1102
	);
1103

    
1104
	//cdm_dataportal_geoservice_legend_on
1105
	$form['cdm_dataportal_geoservice_map_caption'] = array(
1106
    '#type' => 'textfield',
1107
    '#title' => t('Map Caption'),
1108
    '#default_value' => variable_get('cdm_dataportal_geoservice_map_caption', ''),
1109
    '#description' => t('Define a caption for the map.')
1110
	);
1111

    
1112
	//cdm_dataportal_geoservice_map_legend
1113
	$form['cdm_dataportal_geoservice_map_legend'] = array(
1114
      '#type' => 'fieldset',
1115
      '#title' => t('Map Legend'),
1116
      '#collapsible' => FALSE,
1117
      '#collapsed' => TRUE,
1118
	);
1119

    
1120
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_on'] = array(
1121
    '#type' => 'checkbox',
1122
    '#title' => t('Display a map legend'),
1123
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
1124
    '#description' => t('Check this if you like a legend to be displayed with the maps. ')
1125
	);
1126

    
1127
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_size'] = array(
1128
    '#type' => 'textfield',
1129
    '#title' => t('Font size'),
1130
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_size', 10),
1131
    '#description' => t('Font size in pixels.')
1132
	);
1133

    
1134
	$fontStyles = array(0 => "plane", 1 => "italic");
1135
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_style'] = array(
1136
    '#type' => 'select',
1137
    '#title' => t('Available font styles'),
1138
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_style', false),
1139
    '#options' => $fontStyles,
1140
    '#description'   => t('Select a font style for the map legend.')
1141
	);
1142

    
1143
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_width'] = array(
1144
    '#type' => 'textfield',
1145
    '#title' => t('Icon width'),
1146
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_width', 35),
1147
    '#description' => t('Icon width in pixels.')
1148
	);
1149

    
1150
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_height'] = array(
1151
    '#type' => 'textfield',
1152
    '#title' => t('Icon height'),
1153
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_height', 15),
1154
    '#description' => t('Icon height in pixels.')
1155
	);
1156

    
1157
	return system_settings_form($form);
1158
}
1159

    
1160

    
1161
/**
1162
 * @return walk and cache all taxon pages
1163
 */
1164
function cdm_dataportal_view_cache_site(){
1165

    
1166
	_add_js_progressbar();
1167

    
1168
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cache_all_taxa.js');
1169

    
1170
	$out = '';
1171

    
1172
	$request_params = array();
1173
	$request_params['query'] = '%';
1174
	$request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false); //cache only the dafault classification
1175
	$request_params['doTaxa'] = 1;
1176
	$request_params['doSynonyms'] = 0;
1177
	$request_params['doTaxaByCommonNames'] = 0;
1178
	$search_url = cdm_compose_url(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1179
	$search_url = uri_uriByProxy($search_url);
1180
	$taxon_page_url = url('cdm_dataportal/taxon/');
1181

    
1182
	$out .= '<form id="cache_site">';
1183
	$out .= '<br /><h4>'.t('Cache all taxon pages').'</h4>';
1184
	$out .= 'Before  running the cache bot you have to empty the cache manually:<ul>'
1185
	.'<li>Navigate to "Site Configuration -> General"</li>'
1186
	.'<li>Uncheck "Enable Caching" checkbox</li>'
1187
	.'<li>Check "Enable Caching" checkbox</li>'
1188
	.'</ul>';
1189
	$out .= '<div>'.t('This caching process may take long time and could cause heavy load on your server').'</div>';
1190
	$out .= '<div id="progress"></div>';
1191
	$out .= '<input type="hidden" name="searchTaxaUrl" value="'.$search_url.'"/>';
1192
	$out .= '<input type="hidden" name="taxonPageUrl" value="'.$taxon_page_url.'"/>';
1193
	$out .= '<input type="button" name="start" value="'.t('Start').'"/>';
1194
	$out .= '<input type="button" name="stop" value="'.t('Stop').'"/>';
1195
	$out .= '</form>';
1196
	$out .= '</div>';
1197
	//  foreach($taxonPager->records as $taxon){
1198
	//    cdm_dataportal_taxon_view($uuid);
1199
	//  }
1200

    
1201
	return $out;
1202
}
1203

    
1204
/**
1205
 * Implementation of hook_elements().
1206
 */
1207
function cdm_dataportal_elements() {
1208
	$type['select_secuuid'] = array(
1209
    '#input' => TRUE,
1210
    '#process' => array('cdm_dataportal_select_secuuid_expand' => array()),
1211
	//'#validate' => array('cdm_dataportal_select_secuuid_validate' => array()),
1212
	//'#default_value' => array(),
1213
	);
1214
	return $type;
1215
}
1216

    
1217
/*
1218
 *
1219
 */
1220
function cdm_dataportal_select_secuuid_expand($element){
1221

    
1222
	$element['#tree'] = FALSE;
1223

    
1224
	// any value submitted?
1225
	if(isset($element['#post'][$element['#varname']])){
1226
		$selected_values = $element['#post'][$element['#varname']];
1227
	} else {
1228
		// use those store in drupal
1229
		$selected_values = variable_get( $element['#varname'], array());
1230
	}
1231
	if(!is_array($selected_values)){
1232
		$selected_values = array($selected_values);
1233
	}
1234
	$options = array();
1235
	foreach($selected_values as $secUuid){
1236
		$options[$secUuid] = cdm_taxontree_secRefTitle_for($secUuid);
1237
	}
1238

    
1239
	$element[$element['#varname']] =  array(
1240
    '#type' => 'select',
1241
    '#options' => $options,
1242
    '#default_value' => array_values($options),
1243
    '#size' => $element['#multiple'] ? 12 : 2,
1244
    '#multiple' => $element['#multiple'],
1245
	);
1246
	return $element;
1247
}
1248

    
1249

    
1250

    
1251
/**
1252
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
1253
 *
1254
 * TODO: parameters are still preliminar
1255
 * @param String $page page number to diplay defaults to page 1
1256
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
1257
 */
1258
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
1259

    
1260
	$request_params  = array(
1261
    'q' => $beginsWith,
1262
	//'sec' = '',
1263
	//'higherTaxa' => getFiters(),
1264
	// 'matchAnywhere' => false, // default is false
1265
    'page' => $page,
1266
    'onlyAccepted' => $onlyAccepted,
1267
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
1268

    
1269
	$taxonPager = cdm_ws_find(CDM_WS_PORTAL_TAXON_FIND, $request_params);
1270
	/*
1271
	 * FIXME the filter for accepted names will be a form element, thus this widget
1272
	 * should be generated via form api preferably as block
1273
	 */
1274
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1275
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1276
	$out .= theme('cdm_listof_taxa', $taxonPager);
1277
	return $out;
1278
}
1279

    
1280
function cdm_dataportal_view_reference($uuid, $arg2 = null){
1281
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1282
	return theme('cdm_reference_page', $reference);
1283
}
1284

    
1285
function cdm_dataportal_view_reference_list($pageNumber){
1286
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1287
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
1288
}
1289

    
1290
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
1291
	$media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1292
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
1293
}
1294

    
1295
/**
1296
 * The taxon page gives detailed information on a taxon, it shows:
1297
 *  - Taxon name
1298
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1299
 *    heterotypic and finally followed by misapplied names.
1300
 *    The list is ordered historically.
1301
 *  - All description associated with the taxon.
1302
 *
1303
 * @param $uuid
1304
 * @param $chapter name of the part to display,
1305
 *         valid values are: 'description', 'images', 'synonymy', 'specimens', 'all'
1306
 * @return unknown_type
1307
 */
1308
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all'){
1309
	// display the page for the taxon defined by $uuid
1310
	set_last_taxon_page_tab(arg(3));
1311
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1312
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
1313
}
1314

    
1315
/**
1316
 * @param $uuid
1317
 * @param $chapter name of the part to display,
1318
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1319
 * @return unknown_type
1320
 */
1321
function cdm_dataportal_taxon_view($uuid, $chapter = 'all'){
1322

    
1323
	$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1324
	if(!$taxon){
1325
		drupal_set_title(t('Taxon does not exist'));
1326
		return false;
1327
	}
1328
	$taxonpage->title = theme('cdm_taxon_page_title', $taxon);
1329

    
1330
	// check if the taxon id contained in the currently selected tree
1331
	$taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1332
	$taxon_in_current_tree = false;
1333
	foreach($taxon_nodes as $node){
1334
		if(get_taxonomictree_uuid_selected() == $node->taxonomicTree->uuid){
1335
			$taxon_in_current_tree = true;
1336
			break;
1337
		}
1338
	}
1339
	if(!$taxon_in_current_tree){
1340
		if(count($taxon_nodes) == 0){
1341
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained any classification.'
1342
			,'warning');
1343
		} else {
1344
			$trees = '';
1345
			foreach($taxon_nodes as $node){
1346
				$trees .= ($trees?', ':'').'<strong>'.$node->taxonomicTree->titleCache.'</strong>';
1347

    
1348
			}
1349
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained in the currently chosen classification, but in '
1350
			.(count($taxon_nodes) > 1? ' one of these: ' : ' this one: ') . $trees
1351
			, 'warning');
1352
		}
1353
	}
1354

    
1355
	// render the taxon page
1356
	$taxonpage->content = theme('cdm_taxon_page_general', $taxon, $chapter);
1357

    
1358
	return $taxonpage;
1359
}
1360

    
1361
/**
1362
 * The function returns a name page as a drupal node ready to be renderized by drupal.
1363
 * The node page show the taxon name title and the list of taxon related with such taxon
1364
 * name on the tree already in used.
1365
 * @param $taxon_name_uuid A taxon name uuid
1366
 * @return The formatted name page as node
1367
 */
1368
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1369
	$taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1370
	return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
1371
}
1372

    
1373
/**
1374
 * The function genates a object ready to be transformated to a node
1375
 * in order to show as a drupal node
1376
 * @param $taxon_name_uuid
1377
 * @return the object with the page content and title
1378
 */
1379
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1380
	//getting the full taxonname object from the server
1381
	$taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1382
	if(!$taxon_name){
1383
		drupal_set_title(t('Taxon name does not exist'));
1384
		return false;
1385
	}
1386
	//searching for all the taxa connected with the taxon name on the tree in used
1387
	$name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1388
	$request_params = array();
1389
	$request_params['query'] = $name_cache;
1390
	$request_params['tree'] = get_taxonomictree_uuid_selected();
1391
	$request_params['doTaxa'] = 1;
1392
	$request_params['doSynonyms'] = 1;
1393
	$request_params['doTaxaByCommonNames'] = 0;
1394
	$request_params['matchMode'] = "EXACT";
1395
	$taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1396

    
1397
	//removing the name where we come from and
1398
	foreach($taxon_pager->records as $k=>&$taxon){
1399
		if($taxon->uuid == $taxon_to_hide_uuid){
1400
			unset($taxon_pager->records[$k]);
1401
		}
1402
	}
1403
	//show the taxa list or go to the singular taxon
1404
	if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
1405
		reset($taxon_pager->records);
1406
		$first_key = key($taxon_pager->records);
1407
		if($taxon_pager->records[$first_key]->class != "Taxon"){
1408
			$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, $taxon_pager->records[$first_key]->uuid);
1409
			if($synonym_uuid){
1410
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
1411
			}else{
1412
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid);
1413
			}
1414
		}else{
1415
			if($synonym_uuid){
1416
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid . '/synonymy',
1417
                      'highlite=' . $synonym_uuid);
1418
			}else{
1419
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1420
			}
1421
			//drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1422
		}
1423
	}else{ //more than one taxa case
1424
		$taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1425
		if($taxon_pager->records){
1426
			$taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1427
		}else{
1428
			$taxon_name_page->content = 'This name has no taxa';
1429
		}
1430
		return $taxon_name_page;
1431
	}
1432
}
1433

    
1434
function cdm_dataportal_view_search_advanced(){
1435

    
1436
	drupal_set_title(t('Advanced search'));
1437

    
1438
	$searchForm = cdm_dataportal_search_taxon_form(true);
1439

    
1440
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1441

    
1442
}
1443

    
1444
/**
1445
 *
1446
 * future extensions to meet palmweb mockup requirements:
1447
 *  - habitat
1448
 *  - uses
1449
 *  - conservation status
1450
 *  - locality / tdwg region
1451
 */
1452
function cdm_dataportal_view_search_taxon(){
1453

    
1454
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1455

    
1456
	$request_params = cdm_dataportal_search_form_request();
1457
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1458

    
1459
	$search_params = $_REQUEST;
1460
	unset($search_params['q']);
1461
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1462
}
1463

    
1464

    
1465
function cdm_view_xml2json(){
1466
	$file = arg(2);
1467
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1468
	return  xml2json::transformXmlStringToJson($datastr);
1469
}
1470

    
1471
/* ====================== other functions ====================== */
1472

    
1473
/**
1474
 * Enter description here...
1475
 *
1476
 * @param String $uuid the UUID of the taxon
1477
 * @return the URL
1478
 */
1479
function path_to_taxon($uuid){
1480
	if(!$uuid) return false;
1481
	if(get_last_taxon_page_tab()){
1482
		return 'cdm_dataportal/taxon/'.$uuid . '/' . get_last_taxon_page_tab();
1483
	} else {
1484
		 return 'cdm_dataportal/taxon/'.$uuid ;
1485
	}
1486
}
1487

    
1488
function path_to_reference($uuid){
1489
	if(!$uuid) return false;
1490
	return 'cdm_dataportal/reference/'.$uuid;
1491
}
1492

    
1493
function path_to_name($name_uuid){
1494
	$res = false;
1495
	if($name_uuid){
1496
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1497
	}
1498
	return $res;
1499
}
1500

    
1501
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1502
	if(!$uuid) return false;
1503
	$out = 'cdm_dataportal/media/'.$uuid;
1504
	if($representaion_uuid){
1505
		$out .= '/'.$representaion_uuid;
1506
		if($partId !== false){
1507
			$out .= '/'.$partId;
1508
		}
1509
	}
1510
	return $out;
1511
}
1512

    
1513
/**
1514
 * Compares thisRank with thatRank.
1515
 * Returns a negative integer, zero, or a positive integer
1516
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1517
 * e.g:
1518
 * <ul>
1519
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1520
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1521
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1522
 * </ul>
1523
 * <p>
1524
 * This compare logic of the underlying webservice is the
1525
 * <b>inverse logic</b> of the the one implemented in
1526
 * java.lang.Comparable#compareTo(java.lang.Object)
1527
 * @param $thisRankUuid
1528
 * @param $thatRankUuid
1529
 * @return  a negative integer, zero, or a positive integer
1530
 * as the thisRank is lower than, equal to, or higher than thatRank
1531
 */
1532
function rank_compare($thisRankUuid, $thatRankUuid){
1533
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1534
	return $result->Integer;
1535
}
1536

    
1537
function uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1538
	$acceptedPath = path_to_taxon($acceptedUuid);
1539
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid, $synonymUuid);
1540
}
1541

    
1542
/**
1543
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1544
 * If the taggename if empty the fullname will be returned.
1545
 *
1546
 * @param unknown_type $Name or TreeNode
1547
 * @return string
1548
 */
1549
function cdm_dataportal_shortname_of($name){
1550

    
1551
	$nameStr = '';
1552
	// get all tagged text tokens of the scientific name
1553
	foreach($name->taggedTitle as $tagtxt){
1554
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1555
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1556
		}
1557
	}
1558
	$nameStr = trim($nameStr);
1559
	/*
1560
	 if (stristr(strtolower($nameStr), 'incertae sedis') !== FALSE ||
1561
	 stristr(strtolower($nameStr), 'nomina excludenda') !== FALSE){
1562
	 var_dump($nameStr);
1563
	 }
1564
	 */
1565
	if($nameStr){
1566
		// do not return short names for these
1567
		//if(strtolower($nameStr) == 'incertae sedis' || $nameStr ==  'nomina excludenda'){
1568
		if (stristr(strtolower($nameStr), 'incertae sedis') !== FALSE ||
1569
		stristr(strtolower($nameStr), 'nomina excludenda') !== FALSE){
1570
			return $nameStr;
1571
		}
1572
		if($pos = stripos($nameStr, ' ')){
1573
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1574
		} else {
1575
			return $nameStr;
1576
		}
1577
	} else {
1578
		return $name->titleCache;
1579
	}
1580
}
1581

    
1582
/**
1583
 * TODO Add Comments. I don't get what
1584
 *
1585
 * @param UUID $secUuid
1586
 */
1587
function _cdm_dataportal_set_currentSecUuid($secUuid){
1588

    
1589
	// do not save in session but in database
1590

    
1591
	if(is_array($secUuid)){
1592
		$secUuid = $secUuid[0];
1593
	}
1594
	if(!$secUuid){
1595
		variable_set('cdm_currentSecRef', null);
1596
	} else {
1597
		$secRef = cdm_ws_get(CDM_WS_REFERENCE, $secUuid);
1598
		if(isset($secRef)){
1599
			variable_set('cdm_currentSecRef', (array)($secRef));
1600
		}
1601
	}
1602

    
1603
}
1604

    
1605
/**
1606
 * TODO
1607
 * This will not work with multiple instances of the dataportal running
1608
 * under the same host as there is only one session for all instances.
1609
 * In case you switch instances with the same client, you will definitely
1610
 * run into trouble.
1611
 * Also this is not handling multiple secs.
1612
 *
1613
 *
1614
 * returns the current secRef array.
1615
 * If the according session variable is not jet set the default
1616
 * as configured in the setting is used otherwise null.
1617
 *
1618
 * currentSecRef['uuid']
1619
 * currentSecRef[....
1620
 *
1621
 * @return array
1622
 */
1623
//FIXME function _cdm_dataportal_currentSecRef_array(){
1624
//
1625
//	// do not look in session but in database
1626
//	if( variable_get('cdm_currentSecRef', null) == null){
1627
//		$secUuid = variable_get('cdm_secUuid_default', null);
1628
//		_cdm_dataportal_set_currentSecUuid($secUuid);
1629
//	}
1630
//	return variable_get('cdm_currentSecRef', null);
1631
//
1632
//}
1633

    
1634
/**
1635
 * Check if a taxon is accepted by the current taxonomic tree
1636
 *
1637
 * @param Taxon $taxon
1638
 * @return true if $taxon is accepted, false otherwise
1639
 */
1640

    
1641
function _cdm_dataportal_acceptedByCurrentView($taxon){
1642

    
1643
	$defaultTreeUuid = get_taxonomictree_uuid_selected();
1644
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1645
		foreach($taxon->taxonNodes as $node){
1646
			if($node->taxonomicTree == $defaultTreeUuid) {
1647
				return true;
1648
			}
1649
		}
1650
	}
1651
	return false;
1652
}
1653

    
1654
/**@Deprecated
1655
 *
1656
 */
1657
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1658
	$pstr = '';
1659
	foreach($parameters as $key=>$value){
1660
		if(is_array($value)){
1661

    
1662
		} else {
1663
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1664
		}
1665
	}
1666
	return $pstr;
1667
}
1668

    
1669
/**
1670
 * workaround for missing original source type, idNamespace is always set in these cases
1671
 * @param unknown_type $source
1672
 * @return unknown_type
1673
 */
1674
function _is_original_source_type($source){
1675
	return !$source->idNamespace && strlen($source->idNamespace) == 0;
1676
}
1677

    
1678

    
1679
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1680
	//TODO implement admin user interface to replace switch statement
1681
	//     preliminar solution: using themes
1682

    
1683
	$template = null;
1684
	// find best matching default RenderTemplate in theme
1685
	//echo "<br/><br/>RENDER PATH:  ".$renderPath;
1686
	//var_dump('RENDER PATH: ' . $renderPath);
1687
	while(!is_array($template) && strlen($renderPath) > 0){
1688
		$template = theme('get_nameRenderTemplate', $renderPath);
1689
		$renderPath = substr($renderPath, 0, strrpos($renderPath, '.'));
1690
		//	   if(!is_array($template)){
1691
		//	       echo "<br/>->".$renderPath;
1692
		//	   }
1693
	}
1694

    
1695
	// otherwise get default RenderTemplate from theme
1696
	if(!is_array($template)){
1697
		$template = theme('get_nameRenderTemplate', '#DEFAULT');
1698
	}
1699
	// otherwise get system default RenderTemplate
1700
	if(!is_array($template)){
1701
		switch($renderPath){
1702
			case 'list_of_taxa':
1703
			case  'acceptedFor':
1704
			case 'taxon_page_synonymy':
1705
			case 'typedesignations':
1706
			case 'taxon_page_title':
1707
			case 'na': $template = array(
1708
			        'namePart' => array('#uri'=>true),
1709
			//'authorshipPart' => true,
1710
			);
1711
			break;
1712
			case 'nar': $template = array(
1713
		          	'namePart' => array('#uri'=>true),
1714
			//'authorshipPart' => true,
1715
		          	'referencePart' => array('#uri'=>true),
1716
		          	'microreferencePart' => true,
1717
			);
1718
			break;
1719
			default: $template = array(
1720
          'namePart' => array('#uri'=>true),
1721
          'authorshipPart' => true,
1722
          'referencePart' => array('#uri'=>true),
1723
          'microreferencePart' => true,
1724
          'statusPart' => true,
1725
          'descriptionPart' => true
1726
			);
1727
		}
1728
	}
1729

    
1730
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1731
		$template['nameAuthorPart']['#uri'] = $nameLink;
1732
	} else{
1733
		unset($template['nameAuthorPart']['#uri']);
1734
	}
1735

    
1736
	if($nameLink && isset($template['namePart']['#uri'])){
1737
		$template['namePart']['#uri'] = $nameLink;
1738
	} else{
1739
		unset($template['namePart']['#uri']);
1740
	}
1741

    
1742
	if($refenceLink && isset($template['referencePart']['#uri'])){
1743
		$template['referencePart']['#uri'] = $refenceLink;
1744
	}else{
1745
		unset($template['referencePart']['#uri']);
1746
	}
1747

    
1748
	return $template;
1749
}
1750

    
1751
function get_partDefinition($taxonNameType){
1752
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1753
	//     preliminar solution: using themes
1754

    
1755
	$partdef = theme('get_partDefinition', $taxonNameType);
1756

    
1757
	if(!is_array($partdef)){
1758
		switch($taxonNameType){
1759
			case 'ZoologicalName': $partdef = array(
1760
        'namePart' => array(
1761
          'name' => true,
1762
			),
1763
        'referencePart' => array(
1764
          'authorTeam' => true
1765
			),
1766
        'microreferencePart' => array(
1767
          'microreference' => true,
1768
			),
1769
        'statusPart' => array(
1770
          'status' => true,
1771
			),
1772
        'descriptionPart' => array(
1773
          'description' => true,
1774
			),
1775
			);
1776
			break;
1777
			case 'BotanicalName': $partdef = array(
1778
        'namePart' => array(
1779
          'name' => true
1780
			),
1781
        'authorTeamPart' => array(
1782
          'authorTeam' => true,
1783
			),
1784
        'referencePart' => array(
1785
          'reference' => true
1786
			),
1787
        'microreferencePart' => array(
1788
          'microreference' => true,
1789
			),
1790
        'statusPart' => array(
1791
          'status' => true,
1792
			),
1793
        'descriptionPart' => array(
1794
          'description' => true,
1795
			),
1796
			);
1797
			break;
1798
			default: $partdef = array(
1799
        'namePart' => array(
1800
          'name' => true,
1801
			),
1802
        'authorTeamPart' => array(
1803
          'authorTeam' => true,
1804
			),
1805
        'referencePart' => array(
1806
          'reference' => true
1807
			),
1808
        'microreferencePart' => array(
1809
          'microreference' => true,
1810
			),
1811
        'statusPart' => array(
1812
          'status' => true,
1813
			),
1814
        'descriptionPart' => array(
1815
          'description' => true,
1816
			),
1817
			);
1818
		}
1819
	}
1820
	return $partdef;
1821
}
1822

    
1823
/**
1824
 * The function read the metadata info such title or artist of a media file. The
1825
 * function tries at first to get all the info from the file metadata and if it is
1826
 * not avaible look at the media file info stored at the database.
1827
 * @param $media The media file
1828
 * @return array The array with the avilable specified metadata info.
1829
 * TODO rename to read_media_metadata() and move to *.module
1830
 */
1831
function cdm_read_media_metadata($media){
1832

    
1833
	$metadata_caption = array('title' => '',           //media_metadata and media
1834
                              'artist' => '',          //media_metadata and media
1835
                              'rights',                //media_metadata and media
1836
                              'location',              //media_metadata
1837
                              'filename' => '',        //media
1838
                              'mediacreated' => '',    //media
1839
                              'description' => '');    //media
1840

    
1841
	//getting the media metadata
1842
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1843

    
1844
	//title
1845
	//if ($media_metadata->Headline) {
1846
	if ($media_metadata->ObjectName) {
1847
		$metadata_caption['title'] = $media_metadata->ObjectName;
1848
		//	} else if ($media->titleCache){
1849
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1850
	} else if ($media->titleCache){
1851
		$metadata_caption['title'] = $media->titleCache;
1852
		if ($media->description_L10n)
1853
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1854
	}else{ //if there is no title on the db and metadata get file title
1855
		$aux = $media->representations[0]->parts[0]->uri;
1856
		$aux = explode("/", $aux);
1857
		$aux = end($aux);
1858
		$metadata_caption['title'] = $aux;
1859
	}
1860

    
1861
	//artist
1862
	if ($media_metadata->Artist){
1863
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1864
	}
1865
	elseif ($media->artist->titleCache){
1866
	 $metadata_caption['artist'] = $media->artist->titleCache;
1867
	}
1868

    
1869
	//copyright
1870
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1871
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1872
	if ($media_metadata->Copyright)
1873
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1874
	elseif ($media->rights){
1875
		foreach($media->rights as $right){
1876
			switch($right->term->uuid){
1877
				case UUID_RIGHTS_LICENCE:
1878
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1879
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1880
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1881
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1882
					break;
1883
				case UUID_RIGHTS_COPYRIGHT:
1884
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1885
					break;
1886
			}
1887
		}
1888
	}
1889
	else
1890
	$metadata_caption['rights']['agentNames'][] = '';
1891

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

    
1895
	//location
1896
	$metadata_caption['location'] = array();
1897
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1898
	$metadata_caption['location']['city'] = $media_metadata->City;
1899
	$metadata_caption['location']['province'] = $media_metadata->Province;
1900
	$metadata_caption['location']['country'] = $media_metadata->Country;
1901

    
1902
	//filename
1903
	if(isset($media->representations[0]->parts[0]->uri)){
1904
		$fileUri = $media->representations[0]->parts[0]->uri;
1905
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1906
		$metadata_caption['filename'] = $filename;
1907
	}
1908
	else{
1909
	 $metadata_caption['filename'] = '';
1910
	}
1911
	/*
1912
	 //creation date
1913
	 if($media_metadata["Modify Date"])
1914
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1915
	 else
1916
	 $metadata_caption['mediacreated'] = $media->created;
1917
	 */
1918
	//returned value
1919
	return $metadata_caption;
1920
}
1921

    
1922
/**
1923
 * This function collects all the media from a list of description elements
1924
 * and return them as an Array.
1925
 *
1926
 * @param $descriptionElementes The description elements
1927
 * @return Array The output with all the media
1928
 */
1929
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1930
	//variables
1931
	$outArrayOfMedia = array(); //return value
1932
	//implementation
1933
	if(is_array($descriptionElements)){//avoiding warning box in drupal for flora malesiana
1934
		foreach($descriptionElements as $descriptionElement){
1935
			if(is_array($descriptionElement->media)){
1936
				foreach($descriptionElement->media as $media){
1937
					if(isset($media)){
1938
						$outArrayOfMedia[] = $media;
1939
					}
1940
				}
1941
			}
1942
		}
1943
	}
1944
	return $outArrayOfMedia;
1945
}
1946

    
1947
function cdm_annotations_as_footnotekeys($cdmBase, $footnote_list_key = array()){
1948
	$footNoteKeys = array();
1949
	//is argument cdmBase an array?
1950
	if (!is_array($cdmBase)){
1951
		$cdmBase_array = array();
1952
		$cdmBase_array[] = $cdmBase;
1953
	}else{
1954
		$cdmBase_array = $cdmBase;
1955
	}
1956
	//getting the key for the footnotemanager
1957
	if((bool) $footnote_list_key){
1958
		$footnoteListKey = $footnote_list_key;
1959
	}else{
1960
		$footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1961
	}
1962
	//adding the footnotes keys
1963
	foreach($cdmBase_array as $cdmBase_element){
1964
		$annotationUrl = cdm_compose_annotations_url($cdmBase_element);
1965
		if($annotationUrl){
1966
			$annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
1967
			if($annotationPager->count > 0){
1968
				foreach($annotationPager->records as $annotation){
1969
					$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1970
				}
1971
			}
1972
		}
1973
	}
1974
	return $footNoteKeys;
1975
	/*
1976
	 $footNoteKeys = array();
1977
	 $footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1978
	 $annotationUrl = cdm_compose_annotations_url($cdmBase);
1979
	 if($annotationUrl){
1980
		$annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
1981
		if($annotationPager->count > 0){
1982
		foreach($annotationPager->records as $annotation){
1983
		$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1984
		}
1985
		}
1986
		}
1987
		return $footNoteKeys;
1988
		*/
1989
}
1990

    
1991

    
1992

    
(6-6/10)