Project

General

Profile

Download (51 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
 */
13

    
14
require_once('node_types.php');
15
require_once('cdm_dataportal.theme.php');
16

    
17

    
18
define(CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE, 25);
19
define(CDM_DATAPORTAL_NOMREF_IN_TITLE, 1);
20

    
21
function _add_js_progressbar(){
22
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/jquery.progressbar/js/jquery.progressbar.js');
23
}
24

    
25

    
26
/* ====================== hook implementations ====================== */
27

    
28
/**
29
 * Implementation of hook_help()
30
 *
31
 * Display help and module information
32
 * @param section which section of the site we're displaying help
33
 * @return help text for section
34
 */
35
function cdm_dataportal_help($section='') {
36

    
37
	$out = '';
38
	switch ($section) {
39
		case "admin/modules#description":
40
			$out = t("The dataportal publishes CDM data hosted in a CommunityStore on the web.");
41
			break;
42
	}
43
	return $out;
44
}
45

    
46

    
47
/**
48
 * Implementation of hook_perm()
49
 *
50
 * Valid permissions for this module
51
 * @return array An array of valid permissions for the portfolio module
52
 */
53
function cdm_dataportal_perm() {
54
	return array(
55
    	'administer cdm_dataportal',
56
      'cdm_dataportal view notes',
57
	//TODO which else permission are required? -> check the WP6 requirements document
58
	);
59
}
60

    
61

    
62
/**
63
 * Implementation of hook_menu()
64
 */
65
function cdm_dataportal_menu($may_cache) {
66
	$items = array();
67

    
68
	if ($may_cache) {
69

    
70
		$items[] = array(
71
      'path' => 'admin/settings/cdm_dataportal',
72
      'title' => t('CDM Dataportal'),
73
      'description' => t('Setting for the CDM DataPortal'),
74
      'access' => user_access('administer cdm_dataportal'),
75
      'callback' => 'drupal_get_form',
76
      'callback arguments' => 'cdm_dataportal_settings',
77
      'type' => MENU_NORMAL_ITEM,
78
    );
79
    
80
    $items[] = array(
81
      'path' => 'admin/settings/cdm_dataportal/general',
82
      'title' => t('General'),
83
      'description' => t('Setting for the CDM DataPortal'),
84
      'access' => user_access('administer cdm_dataportal'),
85
      'callback' => 'drupal_get_form',
86
      'callback arguments' => 'cdm_dataportal_settings',
87
      'type' => MENU_LOCAL_TASK,
88
    );
89
    
90
    $items[] = array(
91
      'path' => 'admin/settings/cdm_dataportal/geo',
92
      'title' => t('Geo & Map'),
93
      'description' => t('Geo & Map'),
94
      'access' => user_access('administer cdm_dataportal'),
95
      'callback' => 'drupal_get_form',
96
      'callback arguments' => 'cdm_dataportal_settings_geo',
97
      'type' => MENU_LOCAL_TASK,
98
    );
99
    
100
    $items[] = array(
101
      'path' => 'admin/settings/cdm_dataportal/layout',
102
      'title' => t('Layout'),
103
      'description' => t('Configure and adjust the layout of your DataPortal '),
104
      'access' => user_access('administer cdm_dataportal'),
105
      'callback' => 'drupal_get_form',
106
      'callback arguments' => 'cdm_dataportal_settings_layout',
107
      'type' => MENU_LOCAL_TASK,
108
    );
109
    
110
    $items[] = array(
111
      'path' => 'admin/settings/cdm_dataportal/cachesite',
112
      'title' => t('Cache Site'),
113
      'description' => t('Cache the whole CDM DataPortal site'),
114
      'access' => user_access('administer cdm_dataportal'),
115
      'callback' => 'cdm_dataportal_view_cache_site',
116
      'type' => MENU_LOCAL_TASK,
117
    );
118
    
119
    /*$items[] = array(
120
      'path' => 'admin/settings/cdm_dataportal/ws',
121
      'title' => t('Web Service'),
122
      'description' => t('Setting for the CDM DataPortal'),
123
      'access' => user_access('administer cdm_dataportal'),
124
      'callback' => 'drupal_get_form',
125
      'callback arguments' => 'cdm_dataportal_settings',
126
      'weight' => 1,
127
      'type' => MENU_DEFAULT_LOCAL_TASK,
128
    );*/
129
    
130
    $items[] = array(
131
	    'path' => 'cdm_dataportal/names',
132
	    'callback' => 'cdm_dataportal_view_names',
133
	    'access' => true,
134
	    'type' => MENU_CALLBACK,
135
		);
136
		// optional callback arguments: page
137
		 
138
		$items[] = array(
139
      'path' => 'cdm_dataportal/taxon',
140
      'callback' => 'cdm_dataportal_taxon_page_view',
141
      'access' => true,
142
      'type' => MENU_CALLBACK,
143
		// expected callback arguments: uuid
144
		);
145

    
146
		$items[] = array(
147
      'path' => 'cdm_dataportal/reference',
148
      'callback' => 'cdm_dataportal_view_reference',
149
      'access' => true,
150
      'type' => MENU_CALLBACK,
151
		// expected callback arguments: uuid
152
		);
153

    
154
		$items[] = array(
155
      'path' => 'cdm_dataportal/reference/list',
156
      'callback' => 'cdm_dataportal_view_reference_list',
157
      'access' => true,
158
      'type' => MENU_CALLBACK,
159
		// expected callback arguments: uuid
160
		);
161

    
162
		$items[] = array(
163
      'path' => 'cdm_dataportal/media',
164
      'callback' => 'cdm_dataportal_view_media',
165
      'access' => true,
166
      'type' => MENU_CALLBACK,
167
		// expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
168
		);
169

    
170
		$items[] = array(
171
      'path' => 'cdm_dataportal/search',
172
      'callback' => 'cdm_dataportal_view_search_advanced',
173
      'access' => true,
174
      'type' => MENU_CALLBACK,
175
		);
176

    
177
		$items[] = array(
178
      'path' => 'cdm_dataportal/search/taxon',
179
      'callback' => 'cdm_dataportal_view_search_taxon',
180
      'access' => true,
181
      'type' => MENU_CALLBACK,
182
		);
183

    
184
		$items[] = array(
185
      'path' => 'cdm/xml2json',
186
      'callback' => 'cdm_view_xml2json',
187
      'access' => true,
188
      'type' => MENU_CALLBACK,
189
		);
190

    
191

    
192
	} else {
193
		// may not cache
194
		// --- local tasks for Taxon
195
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
196

    
197
			$items[] = array(
198
      'path' => 'cdm_dataportal/taxon/'.arg(2),
199
      'title' => theme('cdm_taxonpage_tab', 'General'),
200
      'callback' => 'cdm_dataportal_taxon_page_view',
201
      'access' => true,
202
      'type' => MENU_CALLBACK,
203
      'weight' => 1,
204
      'callback arguments' => array(arg(2), "description")
205
			// expected callback arguments: name_uuid
206
			);
207

    
208
			$items[] = array(
209
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/all',
210
      'title' => theme('cdm_taxonpage_tab', 'General'),
211
      'callback' => 'cdm_dataportal_taxon_page_view',
212
      'access' => true,
213
      'type' => MENU_CALLBACK,
214
      'weight' => 2,
215
      'callback arguments' => array(arg(2), "all")
216
      // expected callback arguments: name_uuid
217
      );
218
      
219
      $items[] = array(
220
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/description',
221
      'title' => theme('cdm_taxonpage_tab', 'General'),
222
      'callback' => 'cdm_dataportal_taxon_page_view',
223
      'access' => true,
224
      'type' => MENU_DEFAULT_LOCAL_TASK,
225
      'weight' => 2,
226
      'callback arguments' => array(arg(2), "description")
227
			// expected callback arguments: name_uuid
228
			);
229

    
230
			$items[] = array(
231
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
232
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
233
      'callback' => 'cdm_dataportal_taxon_page_view',
234
      'access' => true,
235
      'type' => MENU_LOCAL_TASK,
236
      'weight' => 3,
237
      'callback arguments' => array(arg(2), "synonymy")
238
			// expected callback arguments: name_uuid
239
			);
240

    
241
			$items[] = array(
242
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
243
      'title' => theme('cdm_taxonpage_tab', 'Images'),
244
      'callback' => 'cdm_dataportal_taxon_page_view',
245
      'access' => true,
246
      'type' => MENU_LOCAL_TASK,
247
      'weight' => 4,
248
      'callback arguments' => array(arg(2), "images")
249
			// expected callback arguments: name_uuid
250
			);
251
		}
252
	}
253

    
254
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
255
	//drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
256
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
257

    
258
	return $items;
259

    
260
}
261

    
262
/**
263
 * Implementation of hook_block()
264
 *
265
 * Provides the following blocks:
266
 *  0: list of links useful during development
267
 *
268
 * @param String $op
269
 * @param int $delta
270
 */
271
function cdm_dataportal_block($op='list', $delta=0) {
272
	// listing of blocks, such as on the admin/block page
273
	if ($op == "list") {
274
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
275
		$block[1]["info"] = t("CDM DataPortal Credits");
276
		$block[2]["info"] = t("CDM Search Taxa");
277
		//$block[3]["info"] = t("CDM Filters");
278
		$block[4]["info"] = t("CDM Dataportal Print");
279
		return $block;
280
	}
281
	else if ($op == 'view') {
282
		switch($delta){
283
			case 1:
284
				$block['subject'] = t('Credits');
285
				$block['content'] = theme('cdm_credits');
286
				return $block;
287
			case 2:
288
				$block['subject'] = t('Search Taxa');
289
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
290
				$block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
291
				return $block;
292
			case 4:
293
				$block['subject'] = t('Print this page');
294
				$block['content'] = theme('cdm_print_button');;
295
				return $block;
296
		}
297
	}
298
}
299

    
300

    
301
/**
302
 * Implementation of hook_validate()
303
 *
304
 * @param $element
305
 */
306
function cdm_dataportal_settings_validate($form_id, $form_values){
307

    
308
	if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
309
		form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
310
	}
311

    
312
	$cdm_webservice_url_changed = variable_get('cdm_webservice_url', '') != $form_values['cdm_webservice_url'];
313

    
314
	$cdm_secUuid_default_changed = variable_get('cdm_secUuid_default', '') != $form_values['cdm_secUuid_default'];
315

    
316
	if ($cdm_webservice_url_changed || $cdm_secUuid_default_changed) {
317

    
318
		_cdm_dataportal_set_currentSecUuid($form_values['cdm_secUuid_default']);
319
		// reset all cdm related data stored in the session
320
		// cdm_dataportal_session_clear($form_values['cdm_webservice_url']); // cdm_webservice_url is not further stored here
321
		// clear the cdm webservice cache
322
		cache_clear_all(NULL, 'cache_cdm_ws');
323
		// better clear secref_cache since i can not be sure if the cache has not be used during this response
324
		cdm_api_secref_cache_clear();
325
	}
326
	if($form_values['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)){
327
		cache_clear_all(NULL, 'cache_cdm_ws');
328
		// better clear secref_cache since i can not be sure if the cache has not be used during this response
329
		cdm_api_secref_cache_clear();
330
	}
331

    
332
}
333

    
334
/*
335
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
336
 $_SESSION['cdm'] = null;
337
 if(is_string($cdm_ws_uri_update)){
338
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
339
 }
340
 }
341

    
342
 function cdm_dataportal_session_validate(){
343

    
344
 if(!isset($_SESSION['cdm']['ws_uri'])){
345
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
346
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
347
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
348
 }
349
 }
350
 */
351

    
352
function cdm_dataportal_search_taxon_form($advancedForm = false){
353

    
354
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
355
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
356
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
357
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
358
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
359
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
360

    
361
	$url = 'cdm_dataportal/search/taxon';
362
	$form['#method'] = 'get';
363
	$form['#process'] = array('cdm_dataportal_search_process' => array());
364
	$form['#action'] = url($url, NULL, NULL, true);
365

    
366
	$form['query'] = array(
367
    '#delta' => 0,
368
    '#type' => 'textfield',
369
    '#size' => 20,
370
    '#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')),
371
    '#value' => $preset_query,
372
	);
373

    
374
	$form['search'] = array(
375
      '#delta' => 1,
376
      '#tree' => true,
377
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
378
      '#title' => t('Options')
379
	);
380

    
381
	$form['search']['tree'] = array(
382
    '#delta' => -1,
383
    '#type' => 'hidden',
384
    '#value' => variable_get('cdm_taxonomictree_uuid', false)
385
	);
386

    
387

    
388
	// clean URL get forms breaks if we don't give it a 'q'.
389
	if (!(bool)variable_get('clean_url', '0')) {
390
		$form['search']['q'] = array(
391
      '#delta' => -1,
392
      '#type' => 'hidden',
393
      '#value' => $url,
394
      '#name' => 'q',
395
		);
396
	}
397

    
398
	$form['search']['pageSize'] = array(
399
      '#delta' => -1,
400
      '#type' => 'hidden',
401
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
402
	);
403

    
404
	if($advancedForm){
405
		// general search parameters
406
		$form['search']['doTaxa'] = array(
407
      '#delta' => 2,
408
      '#type' => 'checkbox',
409
      '#title' => t('Search for accepted taxa'),
410
      '#value' => $preset_doTaxa
411
		);
412
		$form['search']['doSynonyms'] = array(
413
      '#delta' => 3,
414
      '#type' => 'checkbox',
415
      '#title' => t('Search for synonyms'),
416
      '#value' => $preset_doSynonyms
417
		);
418
		$form['search']['doTaxaByCommonNames'] = array(
419
      '#delta' => 4,
420
      '#type' => 'checkbox',
421
      '#title' => t('Search for common names'),
422
      '#value' => $preset_doTaxaByCommonNames
423
		);
424
		 
425
		// Geographic Range
426
		$form['search']['geographic_range'] = array(
427
      '#type' => 'fieldset',
428
      '#delta' => 5,
429
      '#tree' => true,
430
      '#title' => t('Geographic range'),
431
		);
432

    
433
		$form['search']['geographic_range']['tdwg_level_select'] = array(
434
    '#type' => 'radios',
435
    '#title' => t('Select a TDWG distribution level and code'),
436
    '#default_value' => $tdwg_level_select,
437
    '#options' => array(
438
		t('TDWG level-1, i.e. a continent'),
439
		t('TDWG level-2'),
440
		t('TDWG level-3, i.e. a country'),
441
		t('TDWG level-4')
442
		)
443
		);
444
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
445
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
446
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
447
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
448

    
449
		$tdwg_js = '';
450
		foreach($tdwg as $key=>$tdwg_level){
451
			$tdwgOptions = array();
452
			$tdwgOptionsSelected = array();
453
			foreach($tdwg_level as $area){
454
				$representation = $area->representations[0];
455
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
456
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
457
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
458
				}
459
			}
460
			asort($tdwgOptions);
461
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
462
        '#type' => 'select',
463
        '#title'         => t('TDWG level').' '.$key,
464
        '#default_value' => $tdwgOptionsSelected,
465
        '#multiple' => TRUE, 
466
        '#options' => $tdwgOptions
467
			);
468
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
469
		}
470

    
471
		drupal_add_js(
472
    "$(document).ready(function(){
473
    
474
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change( 
475
        function(event){
476
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
477
          var i;
478
          for(i = 0; i < 4; i++){
479
            if(selectId == i){
480
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
481
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
482
            } else {
483
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
484
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
485
            }
486
          }
487
        }
488
      );
489
      
490
      $tdwg_js
491
    });",
492
    'inline');
493

    
494
	} else {
495
		$form['search']['doTaxa'] = array(
496
      '#delta' => -2,
497
      '#type' => 'hidden',
498
      '#value' => 1
499
		);
500
		$form['search']['doSynonyms'] = array(
501
      '#delta' => -3,
502
      '#type' => 'hidden',
503
      '#value' => 1
504
		);
505
		$form['search']['doTaxaByCommonNames'] = array(
506
      '#delta' => -4,
507
      '#type' => 'hidden',
508
      '#value' => 1
509
		);
510
	}
511

    
512
	$form['submit'] = array(
513
  '#delta' => 9,
514
  '#type' => 'submit',
515
  '#name' => '',
516
  '#value' => t('Search')
517
	);
518

    
519
	return $form;
520
}
521

    
522
function cdm_dataportal_search_taxon_form_advanced(){
523
	return cdm_dataportal_search_taxon_form(true);
524
}
525

    
526
/**
527
 * Implementation #process method call, see form_builder()
528
 * <p>
529
 * Removes Drupal internal form elements from query
530
 * @param $form
531
 * @return unknown_type
532
 */
533
function cdm_dataportal_search_process($form) {
534
	unset($form['form_id']);
535
	unset($form['form_token']);
536
	return $form;
537
}
538

    
539
/**
540
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
541
 * returns the processed request parameters submitted by the search form.
542
 */
543
function cdm_dataportal_search_form_request(){
544

    
545

    
546
	$form_params = array();
547
	array_deep_copy($_REQUEST['search'], $form_params);
548
	$form_params['query'] =  trim($_REQUEST['query']);
549

    
550
	// split of  geographic range
551
	if(isset($_REQUEST['search']['geographic_range'])){
552
		$geographicRange = $_REQUEST['search']['geographic_range'];
553
		// remove
554
		unset($form_params['geographic_range']);
555
	}
556

    
557
	// add geographic range
558
	if($geographicRange){
559
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
560
		for($i = 1; $i < 5; $i++){
561
			if(isset($geographicRange['tdwg_level_'.$i])){
562
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
563
			}
564
		}
565
	}
566

    
567
	// store in session
568
	$_SESSION['cdm']['search'] = $form_params;
569

    
570
	return $form_params;
571
}
572

    
573

    
574
/* UNREACHABLE since action of form directly links to view
575
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
576

    
577
 $_SESSION['cdm']['search'] = $form_values;
578
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
579
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
580
 //$paramstr = compose_url_prameterstr($form_values);
581
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
582
 }
583
 */
584
/* ====================== menu callback functions ====================== */
585

    
586
/**
587
 * Generate main administration form.
588
 *
589
 * @return
590
 *   An array containing form items to place on the module settings page.
591
 */
592
function cdm_dataportal_settings(){
593

    
594
	$form = cdm_api_settings_form();
595

    
596
	//TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
597
	$form['cdm_dataportal'] = array(
598
      '#type' => 'fieldset',
599
      '#title' => t('CDM DataPortal'),
600
      '#collapsible' => FALSE,
601
      '#collapsed' => TRUE,
602
	);
603

    
604
	//  $form['cdm_dataportal']['secuuid_widget'] = array(
605
	//    '#type' => 'select_secuuid', // => will be themed by theme_select_secuuid(...)
606
	//    '#title' => t('Default Concept References'),
607
	//    '#description'   => t('The default \'sensu\' reference to start the CDM DataPortal with. Per user choices are possible and may override this value.'),
608
	//    '#varname' => 'cdm_secUuid_default',
609
	//    '#multiple' => false
610
	//  );
611

    
612
	$taxonTrees = cdm_ws_get(CDM_WS_TAXONOMY);
613
	foreach($taxonTrees as $tree){
614
		$taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
615
	}
616
	$form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
617
    '#type' => 'select',
618
    '#title'         => t('Available taxonomic views'),
619
    '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
620
    '#options' => $taxonomicTreeOptions,
621
    '#description'   => t('Select a taxonomic view for this webservice.')
622
	);
623

    
624
	//  $form['cdm_dataportal']['DEBUG']= array(
625
	//    '#value' => '<pre>'.print_r($taxonTrees, true).'</pre>'
626
	//  );
627

    
628

    
629
	//------------------ FEATURE TREE --------------------//
630

    
631
	$form['cdm_dataportal']['feature_tree'] = array(
632
    '#type' => 'fieldset',
633
    '#title' => t('Feature Tree'),
634
    '#collapsible' => TRUE,
635
    '#collapsed' => TRUE,
636
	);
637

    
638
	$form['cdm_dataportal']['feature_tree']['cdm_dataportal_featuretree_uuid'] = array(
639
    '#type' => 'select',
640
    '#title'         => t('Available FeatureTrees'),
641
    '#default_value' => variable_get('cdm_dataportal_featuretree_uuid', UUID_DEFAULT_FEATURETREE),
642
	  '#options' => _get_feature_trees(),
643
    '#description'   => t('Select a FeatureTree for this webservice.'
644
    //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
645
	)
646
	);
647

    
648
    return system_settings_form($form);
649
}
650

    
651
/**
652
 * LAYOUT settings
653
 * @return unknown_type
654
 */
655
function cdm_dataportal_settings_layout(){
656
	
657
	$form = array();
658

    
659

    
660
    $form['cdm_taxonname_type'] = array(
661
    '#type' => 'select',
662
    '#title'         => t('Taxon name type'),
663
    '#default_value' => variable_get('cdm_taxonname_type', 'BotanicalName'),
664
    '#options' => array( 'BotanicalName'=>t('BotanicalName'), 'ZoologicalName'=>t('ZoologicalName')),
665
    '#description'   => t('')
666
    );
667

    
668
    $form['cdm_dataportal_nomref_in_title'] = array(
669
    '#type' => 'checkbox',
670
    '#title' => t('Show full nomenclatural reference in title'),
671
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
672
    '#description' => t('Uncheck this, if you want the title of a taxon page consisting of name and author plus publication year only.
673
                        If not checked, the first homotypic taxon is a repetition of the accepted taxon with
674
                        the full nomenclatural reference.')
675
    );
676

    
677
    $form['cdm_dataportal_display_name_relations'] = array(
678
    '#type' => 'checkbox',
679
    '#title' => t('Show name relations of accepted taxa on taxon page'),
680
    '#default_value' => variable_get('cdm_dataportal_display_name_relations', 1),
681
    '#description' => t('')
682
    );
683

    
684
    $form['cdm_dataportal_name_relations_skiptype_basionym'] = array(
685
    '#type' => 'checkbox',
686
    '#title' => t('Exclude the basionym relationship type from the taxon page'),
687
    '#default_value' => variable_get('cdm_dataportal_name_relations_skiptype_basionym', 1),
688
    '#description' => t('')
689
    );
690

    
691
    $form['cdm_dataportal_taxonpage_tabs'] = array(
692
    '#type' => 'checkbox',
693
    '#title' => t('Tabbed taxon page'),
694
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
695
    '#description' => t('Split the taxon page into individual tabs for description, images, synonymy')
696
    );
697

    
698
    $form['cdm_dataportal_search_items_on_page'] = array(
699
    '#type' => 'textfield',
700
    '#title' => t('Search Page Size'),
701
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
702
    '#description' => t('Number of Names to display per page in search results.')
703
    );
704

    
705
    $form['cdm_dataportal_descriptions_separated'] = array(
706
    '#type' => 'checkbox',
707
    '#title' => t('Separate Descriptions'),
708
    '#default_value' => variable_get('cdm_dataportal_descriptions_separated', 0),
709
    '#description' => t('By default corresponding elements of different descriptions are joined together'
710
    .' into a common section per feature (i.e. type of description).'
711
    .' Check this box to allow displaying all descriptions separately.')
712
    );
713

    
714
    //---- IMAGES ----//
715
    $form['images'] = array(
716
    '#type' => 'fieldset',
717
    '#title' => t('Images'),
718
    '#collapsible' => TRUE,
719
    '#collapsed' => FALSE,
720
    );
721
    $options = cdm_rankVocabulary_as_option();
722
    array_unshift($options, '-- DISABLED --');
723
    $form['images']['image_hide_rank'] =  array(
724
    '#type'          => 'select',
725
    '#title'         => t('Hide Images for Taxa above'),
726
    '#default_value' => variable_get('image_hide_rank', '0'),
727
    '#options'       => $options,
728
    '#description'   => t(''),
729
    );
730
    //show media
731
    $selectShowMedia = array(0 => "Show only taxon media",
732
                             1 => "Show taxon and child taxon media");
733
    $form['images']['cdm_dataportal_show_media'] = array(
734
    '#type' => 'select',
735
    '#title' => t('Available media files'),
736
    '#default_value' => variable_get('cdm_dataportal_show_media', false),
737
    '#options' => $selectShowMedia,
738
    '#description'   => t('Select if a taxon should show only his media or also child media.')
739
    );
740

    
741
    // --- find taxa ---- //
742
    $form['findtaxa'] = array(
743
    '#type' => 'fieldset',
744
    '#title' => t('Search Taxa'),
745
    '#collapsible' => TRUE,
746
    '#collapsed' => FALSE,
747
    );
748

    
749
    //variable_get('', 1);
750
    $form['findtaxa']['cdm_dataportal_findtaxa_show_taxon_thumbnails'] = array(
751
    '#type' => 'checkbox',
752
    '#title' => t('Show media thumbnails for accepted taxa'),
753
    '#default_value' => variable_get('cdm_dataportal_findtaxa_show_taxon_thumbnails', 1),
754
    '#description' => t('')
755
    );
756

    
757
    $form['findtaxa']['cdm_dataportal_findtaxa_show_synonym_thumbnails'] = array(
758
    '#type' => 'checkbox',
759
    '#title' => t('Show media thumbnails for synonyms'),
760
    '#default_value' => variable_get('cdm_dataportal_findtaxa_show_synonym_thumbnails', 0),
761
    '#description' => t('')
762
    );
763

    
764
    //   $showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
765
    $form['findtaxa']['cdm_dataportal_findtaxa_show_thumbnail_captions'] = array(
766
    '#type' => 'checkbox',
767
    '#title' => t('Show captions under thumbnails'),
768
    '#default_value' => variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 1),
769
    '#description' => t('')
770
    );
771

    
772
    $form['findtaxa']['cdm_dataportal_findtaxa_media_maxextend'] = array(
773
    '#type' => 'textfield',
774
    '#title' => t('Maximum extend of Images'),
775
    '#default_value' => variable_get('cdm_dataportal_findtaxa_media_maxextend', 120),
776
    '#description' => t('')
777
    );
778

    
779
    $form['findtaxa']['cdm_dataportal_findtaxa_media_cols'] = array(
780
    '#type' => 'textfield',
781
    '#title' => t('Number of columns'),
782
    '#default_value' => variable_get('cdm_dataportal_findtaxa_media_cols', 3),
783
    '#description' => t('')
784
    );
785

    
786
    $form['findtaxa']['cdm_dataportal_findtaxa_media_maxRows'] = array(
787
    '#type' => 'textfield',
788
    '#title' => t('Maximum number of rows'),
789
    '#default_value' => variable_get('cdm_dataportal_findtaxa_media_maxRows', 1),
790
    '#description' => t('')
791
    );
792
    
793
	return system_settings_form($form);
794
	
795
}
796

    
797
/**
798
 * GEOSERVICE and Map settings
799
 * @return unknown_type
800
 */
801
function cdm_dataportal_settings_geo(){
802
	
803
	$form = array();
804

    
805
    $form['cdm_dataportal_map_openlayers'] = array(
806
    '#type' => 'checkbox',
807
    '#title' => t('OpenLayers Viewer'),
808
    '#default_value' => variable_get('cdm_dataportal_map_openlayers', 1),
809
    '#description' => t('Display the maps in an interactive viewer which allows zooming and panning.')
810
    );
811

    
812
    $form['cdm_dataportal_geoservice_access_point'] = array(
813
    '#type' => 'textfield',
814
    '#title' => t('Geoservice Access Point'),
815
    '#default_value' => variable_get('cdm_dataportal_geoservice_access_point', ''),
816
    '#description' => t('Base URL of the geoservice to be used by this portal')
817
    );
818

    
819
    $form['cdm_dataportal_geoservice_display_width'] = array(
820
    '#type' => 'textfield',
821
    '#title' => t('Geoservice Display Width'),
822
    '#default_value' => variable_get('cdm_dataportal_geoservice_display_width', 390),
823
    '#description' => t('Width of the image generated by geoservice')
824
    );
825

    
826
    $form['cdm_dataportal_geoservice_bounding_box'] = array(
827
    '#type' => 'textfield',
828
    '#title' => t('Fixed Geoservice Bounding Box'),
829
    '#default_value' => variable_get('cdm_dataportal_geoservice_bounding_box', '-180,-90,180,90'),
830
    '#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.')
831
    );
832

    
833
    //cdm_dataportal_geoservice_labels_on
834
    $form['cdm_dataportal_geoservice_labels_on'] = array(
835
    '#type' => 'checkbox',
836
    '#title' => t('Display Country Labels'),
837
    '#default_value' => variable_get('cdm_dataportal_geoservice_labels_on', FALSE),
838
    '#description' => t('Check this if you like country names to be displayed in the maps. ')
839
    );
840

    
841
    //cdm_dataportal_geoservice_legend_on
842
    $form['cdm_dataportal_geoservice_map_caption'] = array(
843
    '#type' => 'textfield',
844
    '#title' => t('Map Caption'),
845
    '#default_value' => variable_get('cdm_dataportal_geoservice_map_caption', ''),
846
    '#description' => t('Define a caption for the map.')
847
    );
848
    
849
/*
850
    //cdm_dataportal_geoservice_legend_on
851
    $form['cdm_dataportal_geoservice_legend_on'] = array(
852
    '#type' => 'checkbox',
853
    '#title' => t('Display a map legend'),
854
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
855
    '#description' => t('Check this if you like a legend to be displayed with the maps. ')
856
    );
857
*/
858
    
859
    //cdm_dataportal_geoservice_map_legend
860
    $form['cdm_dataportal_geoservice_map_legend'] = array(
861
      '#type' => 'fieldset',
862
      '#title' => t('Map Legend'),
863
      '#collapsible' => FALSE,
864
      '#collapsed' => TRUE,
865
    );
866
    
867
    $form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_on'] = array(
868
    '#type' => 'checkbox',
869
    '#title' => t('Display a map legend'),
870
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
871
    '#description' => t('Check this if you like a legend to be displayed with the maps. ')
872
    );
873
    
874
    $form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_size'] = array(
875
    '#type' => 'textfield',
876
    '#title' => t('Font size'),
877
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_size', 10),
878
    '#description' => t('Font size in pixels.')
879
    );
880
    
881
    $fontStyles = array(0 => "plane", 1 => "italic");
882
    $form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_style'] = array(
883
    '#type' => 'select',
884
    '#title' => t('Available font styles'),
885
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_style', false),
886
    '#options' => $fontStyles,
887
    '#description'   => t('Select a font style for the map legend.')
888
    );
889
    
890
    $form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_width'] = array(
891
    '#type' => 'textfield',
892
    '#title' => t('Icon width'),
893
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_width', 35),
894
    '#description' => t('Icon width in pixels.')
895
    );
896
    
897
    $form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_height'] = array(
898
    '#type' => 'textfield',
899
    '#title' => t('Icon height'),
900
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_height', 15),
901
    '#description' => t('Icon height in pixels.')
902
    );
903
    
904
    /* variable_get('cdm_dataportal_findtaxa_media_maxextend', 120),
905
     *  $form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
906
    '#type' => 'select',
907
    '#title'         => t('Available taxonomic views'),
908
    '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
909
    '#options' => $taxonomicTreeOptions,
910
    '#description'   => t('Select a taxonomic view for this webservice.')
911
    );
912
    
913
        $taxonTrees = cdm_ws_get(CDM_WS_TAXONOMY);
914
    foreach($taxonTrees as $tree){
915
        $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
916
    }
917
    $form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
918
    '#type' => 'select',
919
    '#title'         => t('Available taxonomic views'),
920
    '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
921
    '#options' => $taxonomicTreeOptions,
922
    '#description'   => t('Select a taxonomic view for this webservice.')
923
    );
924
     */
925

    
926
    return system_settings_form($form);
927
	
928
}
929

    
930

    
931
/**
932
 * @return walk and cache all taxon pages 
933
 */
934
function cdm_dataportal_view_cache_site(){
935
  
936
  _add_js_progressbar();
937
  
938
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cache_all_taxa.js');
939
  
940
  $out = '';
941
  
942
  $request_params = array();
943
  $request_params['query'] = '%';
944
  $request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false);
945
  $request_params['doTaxa'] = 1;
946
  $request_params['doSynonyms'] = 0;
947
  $request_params['doTaxaByCommonNames'] = 0;
948
  $search_url = cdm_compose_url(CDM_WS_FIND_TAXA, null, queryString($request_params));
949
  $search_url = uri_uriByProxy($search_url);
950
  $taxon_page_url = url('cdm_dataportal/taxon/');
951
  
952
  $out .= '<form id="cache_site">';
953
  $out .= '<br /><h4>'
954
    .t('Cache all taxon pages')
955
    .'</h4>';
956
  $out .= '<div>'.t('This caching process may take long time and could cause heavy load on your server').'</div>';
957
  $out .= '<div id="progress"></div>';
958
  $out .= '<input type="hidden" name="searchTaxaUrl" value="'.$search_url.'"/>';
959
  $out .= '<input type="hidden" name="taxonPageUrl" value="'.$taxon_page_url.'"/>';
960
  $out .= '<input type="button" name="start" value="'.t('Start').'"/>';
961
  $out .= '<input type="button" name="stop" value="'.t('Stop').'"/>';
962
  $out .= '</form>';
963
  $out .= '</div>';
964
//  foreach($taxonPager->records as $taxon){
965
//    cdm_dataportal_taxon_view($uuid); 
966
//  }
967
  
968
  return $out;
969
}
970

    
971
/**
972
 * Implementation of hook_elements().
973
 */
974
function cdm_dataportal_elements() {
975
	$type['select_secuuid'] = array(
976
    '#input' => TRUE,
977
    '#process' => array('cdm_dataportal_select_secuuid_expand' => array()),
978
	//'#validate' => array('cdm_dataportal_select_secuuid_validate' => array()),
979
	//'#default_value' => array(),
980
	);
981
	return $type;
982
}
983

    
984
/*
985
 *
986
 */
987
function cdm_dataportal_select_secuuid_expand($element){
988

    
989
	$element['#tree'] = FALSE;
990

    
991
	// any value submitted?
992
	if(isset($element['#post'][$element['#varname']])){
993
		$selected_values = $element['#post'][$element['#varname']];
994
	} else {
995
		// use those store in drupal
996
		$selected_values = variable_get( $element['#varname'], array());
997
	}
998
	if(!is_array($selected_values)){
999
		$selected_values = array($selected_values);
1000
	}
1001
	$options = array();
1002
	foreach($selected_values as $secUuid){
1003
		$options[$secUuid] = cdm_taxontree_secRefTitle_for($secUuid);
1004
	}
1005

    
1006
	$element[$element['#varname']] =  array(
1007
    '#type' => 'select',
1008
    '#options' => $options,
1009
    '#default_value' => array_values($options),
1010
    '#size' => $element['#multiple'] ? 12 : 2,
1011
    '#multiple' => $element['#multiple'],
1012
	);
1013
	return $element;
1014
}
1015

    
1016

    
1017

    
1018
/**
1019
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
1020
 *
1021
 * TODO: parameters are still preliminar
1022
 * @param String $page page number to diplay defaults to page 1
1023
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
1024
 */
1025
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
1026

    
1027
	$request_params  = array(
1028
    'q' => $beginsWith,
1029
	//'sec' = '',
1030
	//'higherTaxa' => getFiters(),
1031
	// 'matchAnywhere' => false, // default is false
1032
    'page' => $page,
1033
    'onlyAccepted' => $onlyAccepted,
1034
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
1035

    
1036
	$taxonPager = cdm_ws_find(CDM_WS_FIND_TAXA, $request_params);
1037
	/*
1038
	 * FIXME the filter for accepted names will be a form element, thus this widget
1039
	 * should be generated via form api preferably as block
1040
	 */
1041
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1042
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1043
	$out .= theme('cdm_listof_taxa', $taxonPager);
1044
	return $out;
1045
}
1046

    
1047
function cdm_dataportal_view_reference($uuid, $arg2 = null){
1048
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1049
	return theme('cdm_reference_page', $reference);
1050
}
1051

    
1052
function cdm_dataportal_view_reference_list($pageNumber){
1053
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1054
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
1055
}
1056

    
1057
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
1058
	$media = cdm_ws_get(CDM_WS_MEDIA, $mediaUuid);
1059
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
1060
}
1061

    
1062
/**
1063
 * The taxon page gives detailed information on a taxon, it shows:
1064
 *  - Taxon name
1065
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1066
 *    heterotypic and finally followed by misapplied names.
1067
 *    The list is ordered historically.
1068
 *  - All description associated with the taxon.
1069
 *
1070
 * @param $uuid
1071
 * @param $chapter name of the part to display,
1072
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1073
 * @return unknown_type
1074
 */
1075
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all'){
1076

    
1077
	// display the page for the taxon defined by $uuid
1078
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1079
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
1080
}
1081

    
1082
/**
1083
 * @param $uuid
1084
 * @param $chapter name of the part to display,
1085
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1086
 * @return unknown_type
1087
 */
1088
function cdm_dataportal_taxon_view($uuid, $chapter = 'all'){
1089

    
1090
	$taxon = cdm_ws_get(CDM_WS_TAXON, $uuid);
1091
	if(!$taxon){
1092
		drupal_set_title(t('Taxon does not exist'));
1093
		return false;
1094
	}
1095
	_cdm_dataportal_set_currentSecUuid($taxon->sec->uuid);
1096

    
1097
	$taxonpage->title = theme('cdm_taxon_page_title', $taxon);
1098
	$taxonpage->content = theme('cdm_taxon_page_general', $taxon, $chapter);
1099

    
1100
	return $taxonpage;
1101
}
1102

    
1103

    
1104
function cdm_dataportal_view_search_advanced(){
1105

    
1106
	drupal_set_title(t('Advanced Search'));
1107

    
1108
	$searchForm = cdm_dataportal_search_taxon_form(true);
1109

    
1110
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1111

    
1112
}
1113

    
1114
/**
1115
 *
1116
 * future extensions to meet palmweb mockup requirements:
1117
 *  - habitat
1118
 *  - uses
1119
 *  - conservation status
1120
 *  - locality / tdwg region
1121
 */
1122
function cdm_dataportal_view_search_taxon(){
1123

    
1124
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1125

    
1126
	$request_params = cdm_dataportal_search_form_request();
1127
	$taxonPager = cdm_ws_get(CDM_WS_FIND_TAXA, null, queryString($request_params));
1128

    
1129
	$search_params = $_REQUEST;
1130
	unset($search_params['q']);
1131
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1132
}
1133

    
1134
function cdm_view_xml2json(){
1135
	$file = arg(2);
1136
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1137
	return  xml2json::transformXmlStringToJson($datastr);
1138
}
1139

    
1140
/* ====================== other functions ====================== */
1141

    
1142
/**
1143
 * Enter description here...
1144
 *
1145
 * @param String $uuid the UUID of the taxon
1146
 * @return the URL
1147
 */
1148
function path_to_taxon($uuid){
1149
	if(!$uuid) return false;
1150
	return 'cdm_dataportal/taxon/'.$uuid;
1151
}
1152

    
1153
function path_to_reference($uuid){
1154
	if(!$uuid) return false;
1155
	return 'cdm_dataportal/reference/'.$uuid;
1156
}
1157

    
1158
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1159
	if(!$uuid) return false;
1160
	$out = 'cdm_dataportal/media/'.$uuid;
1161
	if($representaion_uuid){
1162
		$out .= '/'.$representaion_uuid;
1163
		if($partId !== false){
1164
			$out .= '/'.$partId;
1165
		}
1166
	}
1167
	return $out;
1168
}
1169

    
1170
/**
1171
 * Compares thisRank with thatRank.
1172
 * Returns a negative integer, zero, or a positive integer
1173
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1174
 * e.g:
1175
 * <ul>
1176
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1177
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1178
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1179
 * </ul>
1180
 * <p>
1181
 * This compare logic of the underlying webservice is the
1182
 * <b>inverse logic</b> of the the one implemented in
1183
 * java.lang.Comparable#compareTo(java.lang.Object)
1184
 * @param $thisRankUuid
1185
 * @param $thatRankUuid
1186
 * @return  a negative integer, zero, or a positive integer
1187
 * as the thisRank is lower than, equal to, or higher than thatRank
1188
 */
1189
function rank_compare($thisRankUuid, $thatRankUuid){
1190
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1191
	return $result->Integer;
1192
}
1193

    
1194
function uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1195
	$acceptedPath = path_to_taxon($acceptedUuid);
1196
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid);
1197
}
1198

    
1199
/**
1200
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1201
 * If the taggename if empty the fullname will be returned.
1202
 *
1203
 * @param unknown_type $Name or TreeNode
1204
 * @return string
1205
 */
1206
function cdm_dataportal_shortname_of($name){
1207

    
1208
	$nameStr = '';
1209
	// get all tagged text tokens of the scientific name
1210
	foreach($name->taggedTitle as $tagtxt){
1211
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1212
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1213
		}
1214
	}
1215
	$nameStr = trim($nameStr);
1216
	if($nameStr){
1217
		// do not return short names for these
1218
		if($nameStr == 'Incertae sedis' || $nameStr ==  'Nomina excludenda'){
1219
			return $nameStr;
1220
		}
1221
		if($pos = stripos($nameStr, ' ')){
1222
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1223
		} else {
1224
			return $nameStr;
1225
		}
1226
	} else {
1227
		return $name->titleCache;
1228
	}
1229
}
1230

    
1231
/**
1232
 * TODO Add Comments. I don't get what
1233
 *
1234
 * @param UUID $secUuid
1235
 */
1236
function _cdm_dataportal_set_currentSecUuid($secUuid){
1237

    
1238
	// do not save in session but in database
1239

    
1240
	if(is_array($secUuid)){
1241
		$secUuid = $secUuid[0];
1242
	}
1243
	if(!$secUuid){
1244
		variable_set('cdm_currentSecRef', null);
1245
	} else {
1246
		$secRef = cdm_ws_get(CDM_WS_REFERENCE, $secUuid);
1247
		if(isset($secRef)){
1248
			variable_set('cdm_currentSecRef', (array)($secRef));
1249
		}
1250
	}
1251

    
1252
}
1253

    
1254
/**
1255
 * TODO
1256
 * This will not work with multiple instances of the dataportal running
1257
 * under the same host as there is only one session for all instances.
1258
 * In case you switch instances with the same client, you will definitely
1259
 * run into trouble.
1260
 * Also this is not handling multiple secs.
1261
 *
1262
 *
1263
 * returns the current secRef array.
1264
 * If the according session variable is not jet set the default
1265
 * as configured in the setting is used otherwise null.
1266
 *
1267
 * currentSecRef['uuid']
1268
 * currentSecRef[....
1269
 *
1270
 * @return array
1271
 */
1272
function _cdm_dataportal_currentSecRef_array(){
1273

    
1274
	// do not look in session but in database
1275
	if( variable_get('cdm_currentSecRef', null) == null){
1276
		$secUuid = variable_get('cdm_secUuid_default', null);
1277
		_cdm_dataportal_set_currentSecUuid($secUuid);
1278
	}
1279
	return variable_get('cdm_currentSecRef', null);
1280

    
1281
}
1282

    
1283
/**
1284
 * Check if a taxon is accepted by the current taxonomic tree
1285
 *
1286
 * @param Taxon $taxon
1287
 * @return true if $taxon is accepted, false otherwise
1288
 */
1289

    
1290
function _cdm_dataportal_acceptedByCurrentView($taxon){
1291

    
1292
	//$current_secref = _cdm_dataportal_currentSecRef_array();
1293
	$defaultTreeUuid = variable_get('cdm_taxonomictree_uuid', false);
1294
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1295
		foreach($taxon->taxonNodes as $node){
1296
			if($node->taxonomicTree == $defaultTreeUuid) {
1297
				return true;
1298
			}
1299
		}
1300
	}
1301
	return false;
1302
}
1303

    
1304
/**@Deprecated
1305
 *
1306
 */
1307
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1308
	$pstr = '';
1309
	foreach($parameters as $key=>$value){
1310
		if(is_array($value)){
1311

    
1312
		} else {
1313
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1314
		}
1315
	}
1316
	return $pstr;
1317
}
1318

    
1319
function _get_feature_trees(){
1320
	$feature_trees = array();
1321
	 
1322
	// set tree that contains all features
1323
	$feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1324
	 
1325
	// get features from database
1326
	$persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1327
	if(is_array($persisted_trees)){
1328
		foreach($persisted_trees as $featureTree){
1329
			 
1330
			// do not add the DEFAULT_FEATURETREE again
1331
			if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1332
				continue;
1333
			}
1334
			$featureLabels = array();
1335
			foreach ($featureTree->root->children as $featureNode){
1336
				$featureLabels[] = $featureNode->feature->representation_L10n;
1337
			}
1338
			 
1339
			$feature_trees[$featureTree->uuid] = implode(", ", $featureLabels);
1340
			 
1341
		}
1342
	}
1343
	return $feature_trees;
1344
}
1345

    
1346

    
1347
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1348
	//TODO implement admin user interface to replace swicth statement
1349
	//     preliminar solution: using themes
1350

    
1351
	$template = theme('get_nameRenderTemplate', $renderPath);
1352

    
1353
	if(!is_array($template)){
1354
		switch($renderPath){
1355
			case 'list_of_taxa':
1356
			case  'acceptedFor':
1357
			case 'taxon_page_synonymy':
1358
			case 'typedesignations':
1359
			case 'taxon_page_title':
1360
			case 'na': $template = array(
1361
          'namePart' => array('#uri'=>true),
1362
			//'authorshipPart' => true,
1363
			);
1364
			break;
1365
			case 'nar': $template = array(
1366
          'namePart' => array('#uri'=>true),
1367
			//'authorshipPart' => true,
1368
          'referencePart' => array('#uri'=>true),
1369
          'microreferencePart' => true,
1370
			);
1371
			break;
1372
			default: $template = array(
1373
          'namePart' => array('#uri'=>true),
1374
          'authorshipPart' => true,
1375
          'referencePart' => array('#uri'=>true),
1376
          'microreferencePart' => true,
1377
          'statusPart' => true,
1378
          'descriptionPart' => true
1379
			);
1380
		}
1381
	}
1382

    
1383
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1384
		$template['nameAuthorPart']['#uri'] = $nameLink;
1385
	} else{
1386
		unset($template['nameAuthorPart']['#uri']);
1387
	}
1388

    
1389
	if($nameLink && isset($template['namePart']['#uri'])){
1390
		$template['namePart']['#uri'] = $nameLink;
1391
	} else{
1392
		unset($template['namePart']['#uri']);
1393
	}
1394

    
1395
	if($refenceLink && isset($template['referencePart']['#uri'])){
1396
		$template['referencePart']['#uri'] = $refenceLink;
1397
	}else{
1398
		unset($template['referencePart']['#uri']);
1399
	}
1400

    
1401
	return $template;
1402
}
1403

    
1404
function get_partDefinition($taxonNameType){
1405
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1406
	//     preliminar solution: using themes
1407

    
1408
	$partdef = theme('get_partDefinition', $taxonNameType);
1409

    
1410
	if(!is_array($partdef)){
1411
		switch($taxonNameType){
1412
			case 'ZoologicalName': $partdef = array(
1413
        'namePart' => array(
1414
          'name' => true,
1415
			),
1416
        'referencePart' => array(
1417
          'authorTeam' => true
1418
			),
1419
        'microreferencePart' => array(
1420
          'microreference' => true,
1421
			),
1422
        'statusPart' => array(
1423
          'status' => true,
1424
			),
1425
        'descriptionPart' => array(
1426
          'description' => true,
1427
			),
1428
			);
1429
			break;
1430
			case 'BotanicalName': $partdef = array(
1431
        'namePart' => array(
1432
          'name' => true
1433
			),
1434
        'authorTeamPart' => array(
1435
          'authorTeam' => true,   
1436
			),
1437
        'referencePart' => array(
1438
          'reference' => true      
1439
			),
1440
        'microreferencePart' => array(
1441
          'microreference' => true,
1442
			),
1443
        'statusPart' => array(
1444
          'status' => true,
1445
			),
1446
        'descriptionPart' => array(
1447
          'description' => true,
1448
			),
1449
			);
1450
			break;
1451
			default: $partdef = array(
1452
        'namePart' => array(
1453
          'name' => true,
1454
			),
1455
        'authorTeamPart' => array(
1456
          'authorTeam' => true,   
1457
			),
1458
        'referencePart' => array(
1459
          'reference' => true      
1460
			),
1461
        'microreferencePart' => array(
1462
          'microreference' => true,
1463
			),
1464
        'statusPart' => array(
1465
          'status' => true,
1466
			),
1467
        'descriptionPart' => array(
1468
          'description' => true,
1469
			),
1470
			);
1471
		}
1472
	}
1473
	return $partdef;
1474
}
1475

    
1476
/**
1477
 *
1478
 * @param $media
1479
 * @param $priority
1480
 * @return unknown_type
1481
 * TODO rename to read_media_metadata() and move to *.module
1482
 */
1483
function cdm_read_media_metadata($media){
1484

    
1485
	$metadata_caption = array('title' => '',           //media_metadata and media
1486
                              'artist' => '',          //media_metadata and media
1487
                              'rights',                //media_metadata and media
1488
                              'location',              //media_metadata
1489
                              'filename' => '',        //media
1490
                              'mediacreated' => '',    //media
1491
                              'description' => '');    //media
1492

    
1493
	//getting the media metadata
1494
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1495

    
1496
	//filling the title, artist, copyright depending on the priority 1=>files 2=>CDM
1497
	//filling the title
1498
	//if ($media_metadata->Headline) {
1499
    if ($media_metadata->ObjectName) {
1500
		$metadata_caption['title'] = $media_metadata->ObjectName;
1501
//	} else if ($media->titleCache){
1502
//		$metadata_caption['title'] = $media_metadata->ObjectName;
1503
	} else if ($media->titleCache){
1504
		$metadata_caption['title'] = $media->titleCache;
1505
		if ($media->description_L10n)
1506
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1507
	}
1508

    
1509
	//filling the artist
1510
	if ($media_metadata->Artist)
1511
	   $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1512
	elseif ($media->artist->titleCache)
1513
	   $metadata_caption['artist'] = $media->artist->titleCache;
1514

    
1515
	//filling the copyright info
1516
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1517
                                                'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1518
	if ($media_metadata->Copyright)
1519
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1520
	elseif ($media->rights){
1521
		foreach($media->rights as $right){
1522
			switch($right->term->uuid){
1523
				case UUID_RIGHTS_LICENCE:
1524
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1525
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1526
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1527
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1528
					break;
1529
				case UUID_RIGHTS_COPYRIGHT:
1530
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1531
					break;
1532
			}
1533
		}
1534
	}
1535
	else
1536
	$metadata_caption['rights']['agentNames'][] = '';
1537

    
1538

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

    
1542
	//filling the location
1543
	$metadata_caption['location'] = array();
1544
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1545
	$metadata_caption['location']['city'] = $media_metadata->City;
1546
	$metadata_caption['location']['province'] = $media_metadata->Province;
1547
	$metadata_caption['location']['country'] = $media_metadata->Country;
1548

    
1549

    
1550
	//filling the filename
1551
	if(isset($media->representations[0]->parts[0]->uri)){
1552
		$fileUri = $media->representations[0]->parts[0]->uri;
1553
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1554
		$metadata_caption['filename'] = $filename;
1555
	}
1556
	else
1557
	   $metadata_caption['filename'] = '';
1558
/*
1559
	//filling the creation date
1560
	if($media_metadata["Modify Date"])
1561
	   $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1562
	else
1563
	   $metadata_caption['mediacreated'] = $media->created;
1564
*/
1565
	//returned value
1566
	return $metadata_caption;
1567
}
(5-5/10)