Project

General

Profile

Download (63 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_TAXON_RELATIONSHIPS_DEFAULT', 1);
51
define('CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT', 1);
52
define('CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID', 'cdm_dataportal_featuretree_uuid');
53
define('CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID', 'cdm_dataportal_structdesc_featuretree_uuid');
54

    
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

    
62

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

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

    
80

    
81
/* ====================== hook implementations ====================== */
82

    
83
/**
84
 * Implementation of hook_help()
85
 *
86
 * Display help and module information
87
 * @param section which section of the site we're displaying help
88
 * @return help text for section
89
 */
90
function cdm_dataportal_help($section='') {
91

    
92
	$out = '';
93
	switch ($section) {
94
		case "admin/modules#description":
95
			$out = t("The dataportal publishes CDM data hosted in a CommunityStore on the web.");
96
			break;
97
	}
98
	return $out;
99
}
100

    
101

    
102
/**
103
 * Implementation of hook_perm()
104
 *
105
 * Valid permissions for this module
106
 * @return array An array of valid permissions for the portfolio module
107
 */
108
function cdm_dataportal_perm() {
109
	return array(
110
    	'administer cdm_dataportal',
111
      'cdm_dataportal view notes',
112
	//TODO which else permission are required? -> check the WP6 requirements document
113
	);
114
}
115

    
116

    
117
/**
118
 * Implementation of hook_menu()
119
 */
120
function cdm_dataportal_menu($may_cache) {
121
	$items = array();
122

    
123
	if ($may_cache) {
124

    
125
		$items[] = array(
126
      'path' => 'admin/settings/cdm_dataportal',
127
      'title' => t('CDM Dataportal'),
128
      'description' => t('Setting for the CDM DataPortal'),
129
      'access' => user_access('administer cdm_dataportal'),
130
      'callback' => 'drupal_get_form',
131
      'callback arguments' => 'cdm_dataportal_settings',
132
      'type' => MENU_NORMAL_ITEM,
133
		);
134

    
135
		$items[] = array(
136
      'path' => 'admin/settings/cdm_dataportal/general',
137
      'title' => t('General'),
138
      'description' => t('Setting for the CDM DataPortal'),
139
      'access' => user_access('administer cdm_dataportal'),
140
      'callback' => 'drupal_get_form',
141
      'callback arguments' => 'cdm_dataportal_settings',
142
	  'weight' => 0,
143
      'type' => MENU_LOCAL_TASK,
144
		);
145

    
146
		$items[] = array(
147
      'path' => 'admin/settings/cdm_dataportal/geo',
148
      'title' => t('Geo & Map'),
149
      'description' => t('Geo & Map'),
150
      'access' => user_access('administer cdm_dataportal'),
151
      'callback' => 'drupal_get_form',
152
      'callback arguments' => 'cdm_dataportal_settings_geo',
153
	  'weight' => 1,
154
      'type' => MENU_LOCAL_TASK,
155
		);
156

    
157
		$items[] = array(
158
      'path' => 'admin/settings/cdm_dataportal/layout',
159
      'title' => t('Layout'),
160
      'description' => t('Configure and adjust the layout of your DataPortal '),
161
      'access' => user_access('administer cdm_dataportal'),
162
      'callback' => 'drupal_get_form',
163
      'callback arguments' => 'cdm_dataportal_settings_layout',
164
      'weight' => 2,
165
      'type' => MENU_LOCAL_TASK,
166
		);
167

    
168
		$items[] = array(
169
      'path' => 'admin/settings/cdm_dataportal/cachesite',
170
      'title' => t('Cache'),
171
      'description' => t('Cache the whole CDM DataPortal site'),
172
      'access' => user_access('administer cdm_dataportal'),
173
      'callback' => 'cdm_dataportal_view_cache_site',
174
      'weight' => 10,
175
      'type' => MENU_LOCAL_TASK,
176
		);
177

    
178
		/*$items[] = array(
179
		 'path' => 'admin/settings/cdm_dataportal/ws',
180
		 'title' => t('Web Service'),
181
		 'description' => t('Setting for the CDM DataPortal'),
182
		 'access' => user_access('administer cdm_dataportal'),
183
		 'callback' => 'drupal_get_form',
184
		 'callback arguments' => 'cdm_dataportal_settings',
185
		 'weight' => 1,
186
		 'type' => MENU_DEFAULT_LOCAL_TASK,
187
		 );*/
188

    
189
		$items[] = array(
190
	    'path' => 'cdm_dataportal/names',
191
	    'callback' => 'cdm_dataportal_view_names',
192
	    'access' => true,
193
	    'type' => MENU_CALLBACK,
194
		);
195
		// optional callback arguments: page
196
			
197
		$items[] = array(
198
      'path' => 'cdm_dataportal/taxon',
199
      'callback' => 'cdm_dataportal_taxon_page_view',
200
      'access' => true,
201
      'type' => MENU_CALLBACK,
202
		// expected callback arguments: uuid
203
		);
204

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

    
213
		$items[] = array(
214
      'path' => 'cdm_dataportal/reference',
215
      'callback' => 'cdm_dataportal_view_reference',
216
      'access' => true,
217
      'type' => MENU_CALLBACK,
218
		// expected callback arguments: uuid
219
		);
220

    
221
		$items[] = array(
222
      'path' => 'cdm_dataportal/reference/list',
223
      'callback' => 'cdm_dataportal_view_reference_list',
224
      'access' => true,
225
      'type' => MENU_CALLBACK,
226
		// expected callback arguments: uuid
227
		);
228

    
229
		$items[] = array(
230
      'path' => 'cdm_dataportal/media',
231
      'callback' => 'cdm_dataportal_view_media',
232
      'access' => true,
233
      'type' => MENU_CALLBACK,
234
		// expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
235
		);
236

    
237
		$items[] = array(
238
      'path' => 'cdm_dataportal/search',
239
      'callback' => 'cdm_dataportal_view_search_advanced',
240
      'access' => true,
241
      'type' => MENU_CALLBACK,
242
		);
243

    
244
		$items[] = array(
245
      'path' => 'cdm_dataportal/search/taxon',
246
      'callback' => 'cdm_dataportal_view_search_taxon',
247
      'access' => true,
248
      'type' => MENU_CALLBACK,
249
		);
250

    
251
		$items[] = array(
252
      'path' => 'cdm/xml2json',
253
      'callback' => 'cdm_view_xml2json',
254
      'access' => true,
255
      'type' => MENU_CALLBACK,
256
		);
257

    
258
	} else {
259
		// may not cache
260
		// --- local tasks for Taxon
261
		$items[] = array(
262
      'path' => 'cdm_dataportal/name/'.arg(2),
263
		//'callback' => 'cdm_dataportal_view_name',
264
		  'callback' => 'cdm_dataportal_name_page_view',
265
      'callback arguments' => array(arg(2), arg(3), arg(4)),
266
      'access' => true,
267
      'type' => MENU_CALLBACK,
268
		);
269

    
270
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
271

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

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

    
294
			$items[] = array(
295
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/description',
296
      'title' => theme('cdm_taxonpage_tab', 'General'),
297
      'callback' => 'cdm_dataportal_taxon_page_view',
298
      'access' => true,
299
      'type' => MENU_DEFAULT_LOCAL_TASK,
300
      'weight' => 2,
301
      'callback arguments' => array(arg(2), "description")
302
			// expected callback arguments: name_uuid
303
			);
304

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

    
316
			$items[] = array(
317
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/images',
318
      'title' => theme('cdm_taxonpage_tab', 'Images'),
319
      'callback' => 'cdm_dataportal_taxon_page_view',
320
      'access' => true,
321
      'type' => MENU_LOCAL_TASK,
322
      'weight' => 4,
323
      'callback arguments' => array(arg(2), "images")
324
			// expected callback arguments: name_uuid
325
			);
326
		}
327
	}
328

    
329
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal.css');
330
	//drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_print.css', 'print');
331
	drupal_add_css(drupal_get_path('module', 'cdm_dataportal').'/cdm_dataportal_screen.css', 'screen');
332

    
333
	return $items;
334

    
335
}
336

    
337
/**
338
 * Implementation of hook_block()
339
 *
340
 * Provides the following blocks:
341
 *  0: list of links useful during development
342
 *
343
 * @param String $op
344
 * @param int $delta
345
 */
346
function cdm_dataportal_block($op='list', $delta=0) {
347
	// listing of blocks, such as on the admin/block page
348
	if ($op == "list") {
349
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
350
		//		$block[1]["info"] = t("CDM DataPortal Credits");
351
		$block[2]["info"] = t("CDM Search Taxa");
352
		//$block[3]["info"] = t("CDM Filters");
353
		$block[4]["info"] = t("CDM Dataportal Print");
354
		return $block;
355
	}
356
	else if ($op == 'view') {
357
		switch($delta){
358
			//			case 1:
359
			//				$block['subject'] = t('Credits');
360
			//				$block['content'] = theme('cdm_credits');
361
			//				return $block;
362
			case 2:
363
				$block['subject'] = t('Search taxa');
364
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
365
				$block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
366
				return $block;
367
			case 4:
368
				$block['subject'] = t('Print this page');
369
				$block['content'] = theme('cdm_print_button');;
370
				return $block;
371
		}
372
	}
373
}
374

    
375

    
376
/**
377
 * Implementation of hook_validate()
378
 *
379
 * @param $element
380
 */
381
function cdm_dataportal_settings_validate($form_id, $form_values){
382

    
383
	if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
384
		//form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
385
		$form_values['cdm_webservice_url'] .= '/';
386
	}
387

    
388
	//	$cdm_webservice_url_changed = variable_get('cdm_webservice_url', '') != $form_values['cdm_webservice_url'];
389

    
390
	//	if ($cdm_webservice_url_changed) {
391
	//
392
	//		//FIXME remove _cdm_dataportal_set_currentSecUuid($form_values['cdm_secUuid_default']);
393
	//		// reset all cdm related data stored in the session
394
	//		// cdm_dataportal_session_clear($form_values['cdm_webservice_url']); // cdm_webservice_url is not further stored here
395
	//		// clear the cdm webservice cache
396
	//		cache_clear_all(NULL, 'cache_cdm_ws');
397
	//		// better clear secref_cache since i can not be sure if the cache has not be used during this response
398
	//		cdm_api_secref_cache_clear();
399
	//	}
400
	if($form_values['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)){
401
		cache_clear_all(NULL, 'cache_cdm_ws');
402
		// better clear secref_cache since i can not be sure if the cache has not be used during this response
403
		cdm_api_secref_cache_clear();
404
	}
405

    
406
}
407

    
408
/*
409
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
410
 $_SESSION['cdm'] = null;
411
 if(is_string($cdm_ws_uri_update)){
412
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
413
 }
414
 }
415

    
416
 function cdm_dataportal_session_validate(){
417

    
418
 if(!isset($_SESSION['cdm']['ws_uri'])){
419
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
420
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
421
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
422
 }
423
 }
424
 */
425

    
426
function cdm_dataportal_search_taxon_form($advancedForm = false){
427

    
428
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
429
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
430
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
431
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
432
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
433
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
434

    
435
	$url = 'cdm_dataportal/search/taxon';
436
	$form['#method'] = 'get';
437
	$form['#process'] = array('cdm_dataportal_search_process' => array());
438
	$form['#action'] = url($url, NULL, NULL, true);
439

    
440
	$form['query'] = array(
441
    '#delta' => 0,
442
    '#type' => 'textfield',
443
    '#size' => 20,
444
    '#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')),
445
    '#value' => $preset_query,
446
	);
447

    
448
	$form['search'] = array(
449
      '#delta' => 1,
450
      '#tree' => true,
451
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
452
      '#title' => t('Options')
453
	);
454

    
455
	$form['search']['tree'] = array(
456
    '#delta' => -1,
457
    '#type' => 'hidden',
458
    '#value' => get_taxonomictree_uuid_selected()
459
	);
460

    
461

    
462
	// clean URL get forms breaks if we don't give it a 'q'.
463
	if (!(bool)variable_get('clean_url', '0')) {
464
		$form['search']['q'] = array(
465
      '#delta' => -1,
466
      '#type' => 'hidden',
467
      '#value' => $url,
468
      '#name' => 'q',
469
		);
470
	}
471

    
472
	$form['search']['pageSize'] = array(
473
      '#delta' => -1,
474
      '#type' => 'hidden',
475
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
476
	);
477

    
478
	if($advancedForm){
479
		// general search parameters
480
		$form['search']['doTaxa'] = array(
481
      '#delta' => 2,
482
      '#type' => 'checkbox',
483
      '#title' => t('Search for accepted taxa'),
484
      '#value' => $preset_doTaxa
485
		);
486
		$form['search']['doSynonyms'] = array(
487
      '#delta' => 3,
488
      '#type' => 'checkbox',
489
      '#title' => t('Search for synonyms'),
490
      '#value' => $preset_doSynonyms
491
		);
492
		$form['search']['doTaxaByCommonNames'] = array(
493
      '#delta' => 4,
494
      '#type' => 'checkbox',
495
      '#title' => t('Search for common names'),
496
      '#value' => $preset_doTaxaByCommonNames
497
		);
498
			
499
		// Geographic Range
500
		$form['search']['geographic_range'] = array(
501
      '#type' => 'fieldset',
502
      '#delta' => 5,
503
      '#tree' => true,
504
      '#title' => t('Geographic range'),
505
		);
506

    
507
		$form['search']['geographic_range']['tdwg_level_select'] = array(
508
    '#type' => 'radios',
509
    '#title' => t('Select a TDWG distribution level and code'),
510
    '#default_value' => $tdwg_level_select,
511
    '#options' => array(
512
		t('TDWG level-1, i.e. a continent'),
513
		t('TDWG level-2'),
514
		t('TDWG level-3, i.e. a country'),
515
		t('TDWG level-4')
516
		)
517
		);
518
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
519
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
520
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
521
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
522

    
523
		$tdwg_js = '';
524
		foreach($tdwg as $key=>$tdwg_level){
525
			$tdwgOptions = array();
526
			$tdwgOptionsSelected = array();
527
			foreach($tdwg_level as $area){
528
				$representation = $area->representations[0];
529
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
530
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
531
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
532
				}
533
			}
534
			asort($tdwgOptions);
535
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
536
        '#type' => 'select',
537
        '#title'         => t('TDWG level').' '.$key,
538
        '#default_value' => $tdwgOptionsSelected,
539
        '#multiple' => TRUE, 
540
        '#options' => $tdwgOptions
541
			);
542
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
543
		}
544

    
545
		drupal_add_js(
546
    "$(document).ready(function(){
547
    
548
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change( 
549
        function(event){
550
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
551
          var i;
552
          for(i = 0; i < 4; i++){
553
            if(selectId == i){
554
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
555
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
556
            } else {
557
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
558
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
559
            }
560
          }
561
        }
562
      );
563
      
564
      $tdwg_js
565
    });",
566
    'inline');
567

    
568
	} else {
569
		$form['search']['doTaxa'] = array(
570
	      '#delta' => -2,
571
	      '#type' => 'hidden',
572
	      '#value' => 1
573
		);
574
		$form['search']['doSynonyms'] = array(
575
	      '#delta' => -3,
576
	      '#type' => 'hidden',
577
	      '#value' => 1
578
		);
579
		$form['search']['doTaxaByCommonNames'] = array(
580
	      '#delta' => -4,
581
	      '#type' => 'hidden',
582
	      '#value' => 0
583
		);
584
	}
585

    
586
	$form['submit'] = array(
587
	  '#delta' => 9,
588
	  '#type' => 'submit',
589
	  '#name' => '',
590
	  '#value' => t('Search')
591
	);
592

    
593
	return $form;
594
}
595

    
596
function cdm_dataportal_search_taxon_form_advanced(){
597
	return cdm_dataportal_search_taxon_form(true);
598
}
599

    
600
function cdm_taxonomictree_selector(){
601
	_add_js_treeselector();
602

    
603
	$out = drupal_get_form('cdm_taxonomictree_selector_form');
604

    
605
	return $out;
606
}
607

    
608

    
609
function cdm_taxonomictree_selector_form(){
610

    
611
	$url = url('cdm_api/setvalue/session', null);
612
	$form['#action'] = $url;
613

    
614
	$form['var'] = array(
615
        '#delta' => -3,
616
        '#type' => 'hidden',
617
        '#value' => '[cdm][taxonomictree_uuid]'    
618
        );
619

    
620
        $form['destination'] = array(
621
        '#delta' => -3,
622
        '#type' => 'hidden',
623
        '#value' => substr(drupal_get_destination(), strlen('destination='))
624
        );
625

    
626
        $form['val'] = array(
627
	    '#type' => 'select',
628
	    '#title'         => t('Available classifications'),
629
	    '#default_value' => get_taxonomictree_uuid_selected(),
630
	    '#options' => cdm_get_taxontrees_as_options()
631
        );
632

    
633
        return $form;
634

    
635
}
636

    
637
/**
638
 * Implementation #process method call, see form_builder()
639
 * <p>
640
 * Removes Drupal internal form elements from query
641
 * @param $form
642
 * @return unknown_type
643
 */
644
function cdm_dataportal_search_process($form) {
645
	unset($form['form_id']);
646
	unset($form['form_token']);
647
	return $form;
648
}
649

    
650
/**
651
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
652
 * returns the processed request parameters submitted by the search form.
653
 */
654
function cdm_dataportal_search_form_request(){
655

    
656

    
657
	$form_params = array();
658
	array_deep_copy($_REQUEST['search'], $form_params);
659
	$form_params['query'] =  trim($_REQUEST['query']);
660

    
661
	// split of  geographic range
662
	if(isset($_REQUEST['search']['geographic_range'])){
663
		$geographicRange = $_REQUEST['search']['geographic_range'];
664
		// remove
665
		unset($form_params['geographic_range']);
666
	}
667

    
668
	// add geographic range
669
	if($geographicRange){
670
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
671
		for($i = 1; $i < 5; $i++){
672
			if(isset($geographicRange['tdwg_level_'.$i])){
673
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
674
			}
675
		}
676
	}
677

    
678
	// store in session
679
	$_SESSION['cdm']['search'] = $form_params;
680

    
681
	return $form_params;
682
}
683

    
684

    
685
/* UNREACHABLE since action of form directly links to view
686
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
687

    
688
 $_SESSION['cdm']['search'] = $form_values;
689
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
690
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
691
 //$paramstr = compose_url_prameterstr($form_values);
692
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
693
 }
694
 */
695
/* ====================== menu callback functions ====================== */
696

    
697
/**
698
 * Generate main administration form.
699
 *
700
 * @return
701
 *   An array containing form items to place on the module settings page.
702
 */
703
function cdm_dataportal_settings(){
704

    
705
	$form = cdm_api_settings_form();
706

    
707
	//TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
708
	$form['cdm_dataportal'] = array(
709
      '#type' => 'fieldset',
710
      '#title' => t('CDM DataPortal'),
711
      '#collapsible' => FALSE,
712
      '#collapsed' => TRUE,
713
	);
714

    
715
	$form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
716
    '#type' => 'select',
717
    '#title'         => t('Available classifications'),
718
    '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
719
    '#options' => cdm_get_taxontrees_as_options(),
720
    '#description'   => t('Select the default classification to be used.')
721
	);
722

    
723
	return system_settings_form($form);
724
}
725

    
726
function cdm_dataportal_form_alter($form_id, &$form) {
727

    
728
	static $comment_node_disabled =  0;
729
	static $comment_node_read_only =  1;
730
	static $comment_node_read_write =  2;
731
	 
732

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

    
747
/**
748
 * LAYOUT settings
749
 * @return unknown_type
750
 */
751
function cdm_dataportal_settings_layout(){
752

    
753
	$form = array();
754

    
755
  
756
	
757
	$form['cdm_taxonname_type'] = array(
758
    '#type' => 'select',
759
    '#title'         => t('Taxon name type'),
760
    '#default_value' => variable_get('cdm_taxonname_type', 'BotanicalName'),
761
    '#options' => array( 'BotanicalName'=>t('BotanicalName'), 'ZoologicalName'=>t('ZoologicalName')),
762
    '#description'   => t('')
763
	);
764

    
765
	$form['cdm_dataportal_nomref_in_title'] = array(
766
    '#type' => 'checkbox',
767
    '#title' => t('Show full nomenclatural reference in title'),
768
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
769
    '#description' => t('Uncheck this, if you want the title of a taxon page consisting of name and author plus publication year only.
770
                        If not checked, the first homotypic taxon is a repetition of the accepted taxon with
771
                        the full nomenclatural reference.')
772
	);
773

    
774
	$form[CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS] = array(
775
    '#type' => 'checkbox',
776
    '#title' => t('Show name relations of accepted taxa on taxon page'),
777
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT),
778
    '#description' => t('')
779
	);
780

    
781
	$form[CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
782
    '#type' => 'checkbox',
783
    '#title' => t('Show taxon relations of accepted taxa on taxon page'),
784
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
785
    '#description' => t('')
786
	);
787

    
788
	$form['cdm_dataportal_display_is_accepted_for'] = array(
789
    '#type' => 'checkbox',
790
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when coming from a synonym link.'),
791
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
792
    '#description' => t('')
793
	);
794

    
795
	$form['cdm_dataportal_name_relations_skiptype_basionym'] = array(
796
    '#type' => 'checkbox',
797
    '#title' => t('Exclude the basionym relationship type from the taxon page'),
798
    '#default_value' => variable_get('cdm_dataportal_name_relations_skiptype_basionym', 1),
799
    '#description' => t('')
800
	);
801

    
802
	$form['cdm_dataportal_taxonpage_tabs'] = array(
803
    '#type' => 'checkbox',
804
    '#title' => t('Tabbed taxon page'),
805
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
806
    '#description' => t('Split the taxon page into individual tabs for description, images, synonymy')
807
	);
808

    
809
	$form['cdm_dataportal_search_items_on_page'] = array(
810
    '#type' => 'textfield',
811
    '#title' => t('Search Page Size'),
812
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
813
    '#description' => t('Number of Names to display per page in search results.')
814
	);
815

    
816
	$form['cdm_dataportal_descriptions_separated'] = array(
817
    '#type' => 'checkbox',
818
    '#title' => t('Separate Descriptions'),
819
    '#default_value' => variable_get('cdm_dataportal_descriptions_separated', 0),
820
    '#description' => t('By default corresponding elements of different descriptions are joined together'
821
    .' into a common section per feature (i.e. type of description).'
822
    .' Check this box to allow displaying all descriptions separately.')
823
    );
824

    
825
    //------------------ FEATURE TREE --------------------//
826

    
827
	  $form['cdm_dataportal']['taxon_profile'] = array(
828
	    '#type' => 'fieldset',
829
	    '#title' => t('Taxon profile'),
830
	    '#description'   => t('This section covers setting related to the taxon profile tab, also known as the <strong>"General"</strong> tab.'),
831
	    '#collapsible' => TRUE,
832
	    '#collapsed' => FALSE,
833
	  );
834
	
835
	  $form['cdm_dataportal']['taxon_profile'][CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID] = array(
836
	    '#type' => 'radios',
837
	    '#title'         => t('Taxon profile elements'),                
838
	    '#default_value' => variable_get(CDM_DATAPORTAL_DEFAULT_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE),
839
	    '#options' => cdm_get_featureTrees_as_options(TRUE),
840
	    '#description'   => t('Select a FeatureTree to specify the elements to be displayd in the taxon profile.'
841
	    //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
842
	    )
843
	  );
844
	  
845
	  $form['cdm_dataportal']['taxon_profile'][CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID] = array(
846
	    '#type' => 'radios',
847
	    '#title'         => t('Natural language representation of structured descriptions'),                
848
	    '#default_value' => variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, null),
849
	    '#options' => cdm_get_featureTrees_as_options(),
850
	    '#description'   => t('Taxon descriptions can be stored in a highly structured form.'.
851
	      ' The feature tree selected here will be used to generate textual representation in natural language.'
852
	    //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
853
	    )
854
	  );
855
    
856
    //---- IMAGES ----//
857
    $form['images'] = array(
858
    '#type' => 'fieldset',
859
    '#title' => t('Images'),
860
    '#collapsible' => TRUE,
861
    '#collapsed' => TRUE,
862
    );
863
    $options = cdm_rankVocabulary_as_option();
864
    array_unshift($options, '-- DISABLED --');
865
    $form['images']['image_hide_rank'] =  array(
866
    '#type'          => 'select',
867
    '#title'         => t('Hide Images for Taxa above'),
868
    '#default_value' => variable_get('image_hide_rank', '0'),
869
    '#options'       => $options,
870
    '#description'   => t(''),
871
    );
872
    //show media
873
    $selectShowMedia = array(0 => "Show only taxon media",
874
    1 => "Show taxon and child taxon media");
875
    $form['images']['cdm_dataportal_show_media'] = array(
876
    '#type' => 'select',
877
    '#title' => t('Available media files'),
878
    '#default_value' => variable_get('cdm_dataportal_show_media', false),
879
    '#options' => $selectShowMedia,
880
    '#description'   => t('Select if a taxon should show only his media or also child media.')
881
    );
882

    
883
    // --- SEARCH TAXA GALLERY ---- //
884
    $collapsed = TRUE;
885
    $form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
886
    $form_tittle = 'Search Taxa';
887
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
888

    
889
    // --- FEATURE DESCRIPTION GALLERY ---- //
890
    $form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
891
    $form_tittle = 'Description elements gallery';
892
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
893

    
894
    // --- MEDIA GALLERY ---- //
895
    $form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
896
    $form_tittle = 'Media gallery';
897
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
898

    
899
    //-- DISTRIBUTION LAYOUT --//
900
    $form['distribution_layout'] = array(
901
        '#title' => t('Distribution layout'),
902
        '#collapsible' => TRUE,
903
        '#collapsed' => TRUE,
904
        '#type' => 'fieldset',
905
     );
906
    
907
    $form['distribution_layout']['distribution_sort'] =  array(
908
    '#type'          => 'radios',
909
    '#title'         => t('Sort'),
910
    '#default_value' => 0,
911
    '#options' => array(
912
            t('Standard (No sort)'),
913
            t('Sorted without TDWG Level 2'),
914
    ));
915

    
916
    return system_settings_form($form);
917
}
918

    
919
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed){
920

    
921
	$form[$form_name] = array(
922
    '#type' => 'fieldset',
923
    '#title' => t($form_tittle),
924
    '#collapsible' => TRUE,
925
    '#collapsed' => $collapsed,
926
    '#tree' => true,
927
	);
928

    
929
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
930
	$gallery_settings = variable_get($form_name, $default_values);
931

    
932
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
933
		$form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
934
      '#type' => 'checkbox',
935
      '#title' => t('Show media thumbnails for accepted taxa'),
936
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
937
      '#description' => t('')
938
		);
939

    
940
		$form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
941
      '#type' => 'checkbox',
942
      '#title' => t('Show media thumbnails for synonyms'),
943
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
944
      '#description' => t('')
945
		);
946
	}
947

    
948
	//$showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
949
	$form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
950
    '#type' => 'checkbox',
951
    '#title' => t('Show captions under thumbnails'),
952
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
953
    '#description' => t('')
954
	);
955

    
956
	$form[$form_name]['cdm_dataportal_media_maxextend'] = array(
957
    '#type' => 'textfield',
958
    '#title' => t('Maximum extend of Images'),
959
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
960
    '#description' => t('In the gallery neither width or height will exceed the maximum extend of images.')
961
	);
962

    
963
	$form[$form_name]['cdm_dataportal_media_cols'] = array(
964
    '#type' => 'textfield',
965
    '#title' => t('Number of columns'),
966
    '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
967
    '#description' => t('')
968
	);
969

    
970
	if($form_name == CDM_DATAPORTAL_SEARCH_GALLERY_NAME){
971
		$form[$form_name]['cdm_dataportal_media_maxRows'] = array(
972
      '#type' => 'textfield',
973
      '#title' => t('Maximum number of rows'),
974
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
975
      '#description' => t('If you want an unlimited number of rows please set to 0')
976
		);
977
	}
978

    
979
	return $form;
980
}
981

    
982
/**
983
 * GEOSERVICE and Map settings
984
 * @return unknown_type
985
 */
986
function cdm_dataportal_settings_geo(){
987

    
988
	$form = array();
989

    
990
	$form['cdm_dataportal_map_openlayers'] = array(
991
    '#type' => 'checkbox',
992
    '#title' => t('OpenLayers Viewer'),
993
    '#default_value' => variable_get('cdm_dataportal_map_openlayers', 1),
994
    '#description' => t('Display the maps in an interactive viewer which allows zooming and panning.')
995
	);
996

    
997
	$form['cdm_dataportal_geoservice_access_point'] = array(
998
    '#type' => 'textfield',
999
    '#title' => t('Geoservice Access Point'),
1000
    '#default_value' => variable_get('cdm_dataportal_geoservice_access_point', ''),
1001
    '#description' => t('Base URL of the geoservice to be used by this portal')
1002
	);
1003

    
1004
	$form['cdm_dataportal_geoservice_display_width'] = array(
1005
    '#type' => 'textfield',
1006
    '#title' => t('Geoservice Display Width'),
1007
    '#default_value' => variable_get('cdm_dataportal_geoservice_display_width', 390),
1008
    '#description' => t('Width of the image generated by geoservice')
1009
	);
1010

    
1011
	$form['cdm_dataportal_geoservice_bounding_box'] = array(
1012
    '#type' => 'textfield',
1013
    '#title' => t('Fixed Geoservice Bounding Box'),
1014
    '#default_value' => variable_get('cdm_dataportal_geoservice_bounding_box', '-180,-90,180,90'),
1015
    '#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.')
1016
	);
1017

    
1018
	//cdm_dataportal_geoservice_labels_on
1019
	$form['cdm_dataportal_geoservice_labels_on'] = array(
1020
    '#type' => 'checkbox',
1021
    '#title' => t('Display Country Labels'),
1022
    '#default_value' => variable_get('cdm_dataportal_geoservice_labels_on', FALSE),
1023
    '#description' => t('Check this if you like country names to be displayed in the maps. ')
1024
	);
1025

    
1026
	//cdm_dataportal_geoservice_legend_on
1027
	$form['cdm_dataportal_geoservice_map_caption'] = array(
1028
    '#type' => 'textfield',
1029
    '#title' => t('Map Caption'),
1030
    '#default_value' => variable_get('cdm_dataportal_geoservice_map_caption', ''),
1031
    '#description' => t('Define a caption for the map.')
1032
	);
1033

    
1034
	//cdm_dataportal_geoservice_map_legend
1035
	$form['cdm_dataportal_geoservice_map_legend'] = array(
1036
      '#type' => 'fieldset',
1037
      '#title' => t('Map Legend'),
1038
      '#collapsible' => FALSE,
1039
      '#collapsed' => TRUE,
1040
	);
1041

    
1042
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_on'] = array(
1043
    '#type' => 'checkbox',
1044
    '#title' => t('Display a map legend'),
1045
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
1046
    '#description' => t('Check this if you like a legend to be displayed with the maps. ')
1047
	);
1048

    
1049
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_size'] = array(
1050
    '#type' => 'textfield',
1051
    '#title' => t('Font size'),
1052
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_size', 10),
1053
    '#description' => t('Font size in pixels.')
1054
	);
1055

    
1056
	$fontStyles = array(0 => "plane", 1 => "italic");
1057
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_style'] = array(
1058
    '#type' => 'select',
1059
    '#title' => t('Available font styles'),
1060
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_style', false),
1061
    '#options' => $fontStyles,
1062
    '#description'   => t('Select a font style for the map legend.')
1063
	);
1064

    
1065
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_width'] = array(
1066
    '#type' => 'textfield',
1067
    '#title' => t('Icon width'),
1068
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_width', 35),
1069
    '#description' => t('Icon width in pixels.')
1070
	);
1071

    
1072
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_height'] = array(
1073
    '#type' => 'textfield',
1074
    '#title' => t('Icon height'),
1075
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_height', 15),
1076
    '#description' => t('Icon height in pixels.')
1077
	);
1078

    
1079
	return system_settings_form($form);
1080
}
1081

    
1082

    
1083
/**
1084
 * @return walk and cache all taxon pages
1085
 */
1086
function cdm_dataportal_view_cache_site(){
1087

    
1088
	_add_js_progressbar();
1089

    
1090
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cache_all_taxa.js');
1091

    
1092
	$out = '';
1093

    
1094
	$request_params = array();
1095
	$request_params['query'] = '%';
1096
	$request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false); //cache only the dafault classification
1097
	$request_params['doTaxa'] = 1;
1098
	$request_params['doSynonyms'] = 0;
1099
	$request_params['doTaxaByCommonNames'] = 0;
1100
	$search_url = cdm_compose_url(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1101
	$search_url = uri_uriByProxy($search_url);
1102
	$taxon_page_url = url('cdm_dataportal/taxon/');
1103

    
1104
	$out .= '<form id="cache_site">';
1105
	$out .= '<br /><h4>'.t('Cache all taxon pages').'</h4>';
1106
	$out .= 'Before  running the cache bot you have to empty the cache manually:<ul>'
1107
	.'<li>Navigate to "Site Configuration -> General"</li>'
1108
	.'<li>Uncheck "Enable Caching" checkbox</li>'
1109
	.'<li>Check "Enable Caching" checkbox</li>'
1110
	.'</ul>';
1111
	$out .= '<div>'.t('This caching process may take long time and could cause heavy load on your server').'</div>';
1112
	$out .= '<div id="progress"></div>';
1113
	$out .= '<input type="hidden" name="searchTaxaUrl" value="'.$search_url.'"/>';
1114
	$out .= '<input type="hidden" name="taxonPageUrl" value="'.$taxon_page_url.'"/>';
1115
	$out .= '<input type="button" name="start" value="'.t('Start').'"/>';
1116
	$out .= '<input type="button" name="stop" value="'.t('Stop').'"/>';
1117
	$out .= '</form>';
1118
	$out .= '</div>';
1119
	//  foreach($taxonPager->records as $taxon){
1120
	//    cdm_dataportal_taxon_view($uuid);
1121
	//  }
1122

    
1123
	return $out;
1124
}
1125

    
1126
/**
1127
 * Implementation of hook_elements().
1128
 */
1129
function cdm_dataportal_elements() {
1130
	$type['select_secuuid'] = array(
1131
    '#input' => TRUE,
1132
    '#process' => array('cdm_dataportal_select_secuuid_expand' => array()),
1133
	//'#validate' => array('cdm_dataportal_select_secuuid_validate' => array()),
1134
	//'#default_value' => array(),
1135
	);
1136
	return $type;
1137
}
1138

    
1139
/*
1140
 *
1141
 */
1142
function cdm_dataportal_select_secuuid_expand($element){
1143

    
1144
	$element['#tree'] = FALSE;
1145

    
1146
	// any value submitted?
1147
	if(isset($element['#post'][$element['#varname']])){
1148
		$selected_values = $element['#post'][$element['#varname']];
1149
	} else {
1150
		// use those store in drupal
1151
		$selected_values = variable_get( $element['#varname'], array());
1152
	}
1153
	if(!is_array($selected_values)){
1154
		$selected_values = array($selected_values);
1155
	}
1156
	$options = array();
1157
	foreach($selected_values as $secUuid){
1158
		$options[$secUuid] = cdm_taxontree_secRefTitle_for($secUuid);
1159
	}
1160

    
1161
	$element[$element['#varname']] =  array(
1162
    '#type' => 'select',
1163
    '#options' => $options,
1164
    '#default_value' => array_values($options),
1165
    '#size' => $element['#multiple'] ? 12 : 2,
1166
    '#multiple' => $element['#multiple'],
1167
	);
1168
	return $element;
1169
}
1170

    
1171

    
1172

    
1173
/**
1174
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
1175
 *
1176
 * TODO: parameters are still preliminar
1177
 * @param String $page page number to diplay defaults to page 1
1178
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
1179
 */
1180
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
1181

    
1182
	$request_params  = array(
1183
    'q' => $beginsWith,
1184
	//'sec' = '',
1185
	//'higherTaxa' => getFiters(),
1186
	// 'matchAnywhere' => false, // default is false
1187
    'page' => $page,
1188
    'onlyAccepted' => $onlyAccepted,
1189
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
1190

    
1191
	$taxonPager = cdm_ws_find(CDM_WS_PORTAL_TAXON_FIND, $request_params);
1192
	/*
1193
	 * FIXME the filter for accepted names will be a form element, thus this widget
1194
	 * should be generated via form api preferably as block
1195
	 */
1196
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1197
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1198
	$out .= theme('cdm_listof_taxa', $taxonPager);
1199
	return $out;
1200
}
1201

    
1202
function cdm_dataportal_view_reference($uuid, $arg2 = null){
1203
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1204
	return theme('cdm_reference_page', $reference);
1205
}
1206

    
1207
function cdm_dataportal_view_reference_list($pageNumber){
1208
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1209
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
1210
}
1211

    
1212
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
1213
	$media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1214
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
1215
}
1216

    
1217
/**
1218
 * The taxon page gives detailed information on a taxon, it shows:
1219
 *  - Taxon name
1220
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1221
 *    heterotypic and finally followed by misapplied names.
1222
 *    The list is ordered historically.
1223
 *  - All description associated with the taxon.
1224
 *
1225
 * @param $uuid
1226
 * @param $chapter name of the part to display,
1227
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1228
 * @return unknown_type
1229
 */
1230
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all'){
1231

    
1232
	// display the page for the taxon defined by $uuid
1233
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1234
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
1235
}
1236

    
1237
/**
1238
 * @param $uuid
1239
 * @param $chapter name of the part to display,
1240
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1241
 * @return unknown_type
1242
 */
1243
function cdm_dataportal_taxon_view($uuid, $chapter = 'all'){
1244

    
1245
	$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1246
	if(!$taxon){
1247
		drupal_set_title(t('Taxon does not exist'));
1248
		return false;
1249
	}
1250
	$taxonpage->title = theme('cdm_taxon_page_title', $taxon);
1251

    
1252
	// check if the taxon id contained in the currently selected tree
1253
	$taxon_nodes = cdm_ws_get(CDM_WS_PORTAL_TAXON_TAXONNODES, $uuid);
1254
	$taxon_in_current_tree = false;
1255
	foreach($taxon_nodes as $node){
1256
		if(get_taxonomictree_uuid_selected() == $node->taxonomicTree->uuid){
1257
			$taxon_in_current_tree = true;
1258
			break;
1259
		}
1260
	}
1261
	if(!$taxon_in_current_tree){
1262
		if(count($taxon_nodes) == 0){
1263
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained any classification.'
1264
			,'warning');
1265
		} else {
1266
			$trees = '';
1267
			foreach($taxon_nodes as $node){
1268
				$trees .= ($trees?', ':'').'<strong>'.$node->taxonomicTree->titleCache.'</strong>';
1269

    
1270
			}
1271
			drupal_set_message('This concept of the taxon '.theme('cdm_taxonName', $taxon->name).' is not contained in the currently chosen classification, but in '
1272
			.(count($taxon_nodes) > 1? ' one of these: ' : ' this one: ') . $trees
1273
			, 'warning');
1274
		}
1275
	}
1276

    
1277
	// render the taxon page
1278
	$taxonpage->content = theme('cdm_taxon_page_general', $taxon, $chapter);
1279

    
1280
	return $taxonpage;
1281
}
1282

    
1283
/**
1284
 * The function returns a name page as a drupal node ready to be renderized by drupal.
1285
 * The node page show the taxon name title and the list of taxon related with such taxon
1286
 * name on the tree already in used.
1287
 * @param $taxon_name_uuid A taxon name uuid
1288
 * @return The formatted name page as node
1289
 */
1290
function cdm_dataportal_name_page_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1291
	$taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid);
1292
	return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
1293
}
1294

    
1295
/**
1296
 * The function genates a object ready to be transformated to a node
1297
 * in order to show as a drupal node
1298
 * @param $taxon_name_uuid
1299
 * @return the object with the page content and title
1300
 */
1301
function cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_uuid, $synonym_uuid = null){
1302
	//getting the full taxonname object from the server
1303
	$taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1304
	if(!$taxon_name){
1305
		drupal_set_title(t('Taxon name does not exist'));
1306
		return false;
1307
	}
1308
	//searching for all the taxon connected with the taxon name on the tree in used
1309
	$name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1310
	$request_params = array();
1311
	$request_params['query'] = $name_cache;
1312
	$request_params['tree'] = get_taxonomictree_uuid_selected();
1313
	$request_params['doTaxa'] = 1;
1314
	$request_params['doSynonyms'] = 1;
1315
	$request_params['doTaxaByCommonNames'] = 0;
1316
	$request_params['matchMode'] = "EXACT";
1317
	$taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1318

    
1319
	//removing the name where we come from and
1320
	foreach($taxon_pager->records as $k=>&$taxon){
1321
		if($taxon->uuid == $taxon_to_hide_uuid){
1322
			unset($taxon_pager->records[$k]);
1323
		}
1324
	}
1325
	//show the taxa list or go to the singular taxon
1326
	if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
1327
		reset($taxon_pager->records);
1328
		$first_key = key($taxon_pager->records);
1329
		if($taxon_pager->records[$first_key]->class != "Taxon"){
1330
			$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, $taxon_pager->records[$first_key]->uuid);
1331
			if($synonym_uuid){
1332
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid . '/synonymy', 'highlite=' . $synonym_uuid);
1333
			}else{
1334
				drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid);
1335
			}
1336
		}else{
1337
			if($synonym_uuid){
1338
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid . '/synonymy',
1339
                      'highlite=' . $synonym_uuid);
1340
			}else{
1341
				drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1342
			}
1343
			//drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1344
		}
1345
	}else{ //more than one taxa case
1346
		$taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1347
		if($taxon_pager->records){
1348
			$taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1349
		}else{
1350
			$taxon_name_page->content = 'This name has no taxa';
1351
		}
1352
		return $taxon_name_page;
1353
	}
1354
}
1355

    
1356
function cdm_dataportal_view_search_advanced(){
1357

    
1358
	drupal_set_title(t('Advanced search'));
1359

    
1360
	$searchForm = cdm_dataportal_search_taxon_form(true);
1361

    
1362
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1363

    
1364
}
1365

    
1366
/**
1367
 *
1368
 * future extensions to meet palmweb mockup requirements:
1369
 *  - habitat
1370
 *  - uses
1371
 *  - conservation status
1372
 *  - locality / tdwg region
1373
 */
1374
function cdm_dataportal_view_search_taxon(){
1375

    
1376
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1377

    
1378
	$request_params = cdm_dataportal_search_form_request();
1379
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1380

    
1381
	$search_params = $_REQUEST;
1382
	unset($search_params['q']);
1383
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1384
}
1385

    
1386

    
1387
function cdm_view_xml2json(){
1388
	$file = arg(2);
1389
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1390
	return  xml2json::transformXmlStringToJson($datastr);
1391
}
1392

    
1393
/* ====================== other functions ====================== */
1394

    
1395
/**
1396
 * Enter description here...
1397
 *
1398
 * @param String $uuid the UUID of the taxon
1399
 * @return the URL
1400
 */
1401
function path_to_taxon($uuid){
1402
	if(!$uuid) return false;
1403
	return 'cdm_dataportal/taxon/'.$uuid;
1404
}
1405

    
1406
function path_to_reference($uuid){
1407
	if(!$uuid) return false;
1408
	return 'cdm_dataportal/reference/'.$uuid;
1409
}
1410

    
1411
function path_to_name($name_uuid){
1412
	$res = false;
1413
	if($name_uuid){
1414
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1415
	}
1416
	return $res;
1417
}
1418

    
1419
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1420
	if(!$uuid) return false;
1421
	$out = 'cdm_dataportal/media/'.$uuid;
1422
	if($representaion_uuid){
1423
		$out .= '/'.$representaion_uuid;
1424
		if($partId !== false){
1425
			$out .= '/'.$partId;
1426
		}
1427
	}
1428
	return $out;
1429
}
1430

    
1431
/**
1432
 * Compares thisRank with thatRank.
1433
 * Returns a negative integer, zero, or a positive integer
1434
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1435
 * e.g:
1436
 * <ul>
1437
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1438
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1439
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1440
 * </ul>
1441
 * <p>
1442
 * This compare logic of the underlying webservice is the
1443
 * <b>inverse logic</b> of the the one implemented in
1444
 * java.lang.Comparable#compareTo(java.lang.Object)
1445
 * @param $thisRankUuid
1446
 * @param $thatRankUuid
1447
 * @return  a negative integer, zero, or a positive integer
1448
 * as the thisRank is lower than, equal to, or higher than thatRank
1449
 */
1450
function rank_compare($thisRankUuid, $thatRankUuid){
1451
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1452
	return $result->Integer;
1453
}
1454

    
1455
function uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1456
	$acceptedPath = path_to_taxon($acceptedUuid);
1457
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid);
1458
}
1459

    
1460
/**
1461
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1462
 * If the taggename if empty the fullname will be returned.
1463
 *
1464
 * @param unknown_type $Name or TreeNode
1465
 * @return string
1466
 */
1467
function cdm_dataportal_shortname_of($name){
1468

    
1469
	$nameStr = '';
1470
	// get all tagged text tokens of the scientific name
1471
	foreach($name->taggedTitle as $tagtxt){
1472
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1473
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1474
		}
1475
	}
1476
	$nameStr = trim($nameStr);
1477
	if($nameStr){
1478
		// do not return short names for these
1479
		if($nameStr == 'Incertae sedis' || $nameStr ==  'Nomina excludenda'){
1480
			return $nameStr;
1481
		}
1482
		if($pos = stripos($nameStr, ' ')){
1483
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1484
		} else {
1485
			return $nameStr;
1486
		}
1487
	} else {
1488
		return $name->titleCache;
1489
	}
1490
}
1491

    
1492
/**
1493
 * TODO Add Comments. I don't get what
1494
 *
1495
 * @param UUID $secUuid
1496
 */
1497
function _cdm_dataportal_set_currentSecUuid($secUuid){
1498

    
1499
	// do not save in session but in database
1500

    
1501
	if(is_array($secUuid)){
1502
		$secUuid = $secUuid[0];
1503
	}
1504
	if(!$secUuid){
1505
		variable_set('cdm_currentSecRef', null);
1506
	} else {
1507
		$secRef = cdm_ws_get(CDM_WS_REFERENCE, $secUuid);
1508
		if(isset($secRef)){
1509
			variable_set('cdm_currentSecRef', (array)($secRef));
1510
		}
1511
	}
1512

    
1513
}
1514

    
1515
/**
1516
 * TODO
1517
 * This will not work with multiple instances of the dataportal running
1518
 * under the same host as there is only one session for all instances.
1519
 * In case you switch instances with the same client, you will definitely
1520
 * run into trouble.
1521
 * Also this is not handling multiple secs.
1522
 *
1523
 *
1524
 * returns the current secRef array.
1525
 * If the according session variable is not jet set the default
1526
 * as configured in the setting is used otherwise null.
1527
 *
1528
 * currentSecRef['uuid']
1529
 * currentSecRef[....
1530
 *
1531
 * @return array
1532
 */
1533
//FIXME function _cdm_dataportal_currentSecRef_array(){
1534
//
1535
//	// do not look in session but in database
1536
//	if( variable_get('cdm_currentSecRef', null) == null){
1537
//		$secUuid = variable_get('cdm_secUuid_default', null);
1538
//		_cdm_dataportal_set_currentSecUuid($secUuid);
1539
//	}
1540
//	return variable_get('cdm_currentSecRef', null);
1541
//
1542
//}
1543

    
1544
/**
1545
 * Check if a taxon is accepted by the current taxonomic tree
1546
 *
1547
 * @param Taxon $taxon
1548
 * @return true if $taxon is accepted, false otherwise
1549
 */
1550

    
1551
function _cdm_dataportal_acceptedByCurrentView($taxon){
1552

    
1553
	$defaultTreeUuid = get_taxonomictree_uuid_selected();
1554
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1555
		foreach($taxon->taxonNodes as $node){
1556
			if($node->taxonomicTree == $defaultTreeUuid) {
1557
				return true;
1558
			}
1559
		}
1560
	}
1561
	return false;
1562
}
1563

    
1564
/**@Deprecated
1565
 *
1566
 */
1567
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1568
	$pstr = '';
1569
	foreach($parameters as $key=>$value){
1570
		if(is_array($value)){
1571

    
1572
		} else {
1573
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1574
		}
1575
	}
1576
	return $pstr;
1577
}
1578

    
1579
/**
1580
 * workaround for missing original source type, idNamespace is always set in these cases
1581
 * @param unknown_type $source
1582
 * @return unknown_type
1583
 */
1584
function _is_original_source_type($source){
1585
	return !$source->idNamespace && strlen($source->idNamespace) == 0;
1586
}
1587

    
1588
function get_taxonomictree_uuid_selected(){
1589
	if(is_uuid($_SESSION['cdm']['taxonomictree_uuid']) ){
1590
		return $_SESSION['cdm']['taxonomictree_uuid'];
1591
	} else {
1592
		return variable_get('cdm_taxonomictree_uuid', false);
1593
	}
1594
}
1595

    
1596
function switch_to_taxonomictree_uuid($taxonomictree_uuid){
1597
	$_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
1598
}
1599

    
1600
function reset_taxonomictree_uuid($taxonomictree_uuid){
1601
	unset($_SESSION['cdm']['taxonomictree_uuid']);
1602
}
1603

    
1604

    
1605
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1606
	//TODO implement admin user interface to replace switch statement
1607
	//     preliminar solution: using themes
1608

    
1609
	$template = null;
1610
	// find best matching default RenderTemplate in theme
1611
	//echo "<br/><br/>RENDER PATH:  ".$renderPath;
1612
	//var_dump('RENDER PATH: ' . $renderPath);
1613
	while(!is_array($template) && strlen($renderPath) > 0){
1614
		$template = theme('get_nameRenderTemplate', $renderPath);
1615
		$renderPath = substr($renderPath, 0, strrpos($renderPath, '.'));
1616
		//	   if(!is_array($template)){
1617
		//	       echo "<br/>->".$renderPath;
1618
		//	   }
1619
	}
1620

    
1621
	// otherwise get default RenderTemplate from theme
1622
	if(!is_array($template)){
1623
		$template = theme('get_nameRenderTemplate', '#DEFAULT');
1624
	}
1625
	// otherwise get system default RenderTemplate
1626
	if(!is_array($template)){
1627
		switch($renderPath){
1628
			case 'list_of_taxa':
1629
			case  'acceptedFor':
1630
			case 'taxon_page_synonymy':
1631
			case 'typedesignations':
1632
			case 'taxon_page_title':
1633
			case 'na': $template = array(
1634
			        'namePart' => array('#uri'=>true),
1635
			//'authorshipPart' => true,
1636
			);
1637
			break;
1638
			case 'nar': $template = array(
1639
		          	'namePart' => array('#uri'=>true),
1640
			//'authorshipPart' => true,
1641
		          	'referencePart' => array('#uri'=>true),
1642
		          	'microreferencePart' => true,
1643
			);
1644
			break;
1645
			default: $template = array(
1646
          'namePart' => array('#uri'=>true),
1647
          'authorshipPart' => true,
1648
          'referencePart' => array('#uri'=>true),
1649
          'microreferencePart' => true,
1650
          'statusPart' => true,
1651
          'descriptionPart' => true
1652
			);
1653
		}
1654
	}
1655

    
1656
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1657
		$template['nameAuthorPart']['#uri'] = $nameLink;
1658
	} else{
1659
		unset($template['nameAuthorPart']['#uri']);
1660
	}
1661

    
1662
	if($nameLink && isset($template['namePart']['#uri'])){
1663
		$template['namePart']['#uri'] = $nameLink;
1664
	} else{
1665
		unset($template['namePart']['#uri']);
1666
	}
1667

    
1668
	if($refenceLink && isset($template['referencePart']['#uri'])){
1669
		$template['referencePart']['#uri'] = $refenceLink;
1670
	}else{
1671
		unset($template['referencePart']['#uri']);
1672
	}
1673

    
1674
	return $template;
1675
}
1676

    
1677
function get_partDefinition($taxonNameType){
1678
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1679
	//     preliminar solution: using themes
1680

    
1681
	$partdef = theme('get_partDefinition', $taxonNameType);
1682

    
1683
	if(!is_array($partdef)){
1684
		switch($taxonNameType){
1685
			case 'ZoologicalName': $partdef = array(
1686
        'namePart' => array(
1687
          'name' => true,
1688
			),
1689
        'referencePart' => array(
1690
          'authorTeam' => true
1691
			),
1692
        'microreferencePart' => array(
1693
          'microreference' => true,
1694
			),
1695
        'statusPart' => array(
1696
          'status' => true,
1697
			),
1698
        'descriptionPart' => array(
1699
          'description' => true,
1700
			),
1701
			);
1702
			break;
1703
			case 'BotanicalName': $partdef = array(
1704
        'namePart' => array(
1705
          'name' => true
1706
			),
1707
        'authorTeamPart' => array(
1708
          'authorTeam' => true,   
1709
			),
1710
        'referencePart' => array(
1711
          'reference' => true      
1712
			),
1713
        'microreferencePart' => array(
1714
          'microreference' => true,
1715
			),
1716
        'statusPart' => array(
1717
          'status' => true,
1718
			),
1719
        'descriptionPart' => array(
1720
          'description' => true,
1721
			),
1722
			);
1723
			break;
1724
			default: $partdef = array(
1725
        'namePart' => array(
1726
          'name' => true,
1727
			),
1728
        'authorTeamPart' => array(
1729
          'authorTeam' => true,   
1730
			),
1731
        'referencePart' => array(
1732
          'reference' => true      
1733
			),
1734
        'microreferencePart' => array(
1735
          'microreference' => true,
1736
			),
1737
        'statusPart' => array(
1738
          'status' => true,
1739
			),
1740
        'descriptionPart' => array(
1741
          'description' => true,
1742
			),
1743
			);
1744
		}
1745
	}
1746
	return $partdef;
1747
}
1748

    
1749
/**
1750
 * The function read the metadata info such title or artist of a media file. The
1751
 * function tries at first to get all the info from the file metadata and if it is
1752
 * not avaible look at the media file info stored at the database.
1753
 * @param $media The media file
1754
 * @return array The array with the avilable specified metadata info.
1755
 * TODO rename to read_media_metadata() and move to *.module
1756
 */
1757
function cdm_read_media_metadata($media){
1758

    
1759
	$metadata_caption = array('title' => '',           //media_metadata and media
1760
                              'artist' => '',          //media_metadata and media
1761
                              'rights',                //media_metadata and media
1762
                              'location',              //media_metadata
1763
                              'filename' => '',        //media
1764
                              'mediacreated' => '',    //media
1765
                              'description' => '');    //media
1766

    
1767
	//getting the media metadata
1768
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1769

    
1770
	//title
1771
	//if ($media_metadata->Headline) {
1772
	if ($media_metadata->ObjectName) {
1773
		$metadata_caption['title'] = $media_metadata->ObjectName;
1774
		//	} else if ($media->titleCache){
1775
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1776
	} else if ($media->titleCache){
1777
		$metadata_caption['title'] = $media->titleCache;
1778
		if ($media->description_L10n)
1779
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1780
	}else{ //if there is no title on the db and metadata get file title
1781
		$aux = $media->representations[0]->parts[0]->uri;
1782
		$aux = explode("/", $aux);
1783
		$aux = end($aux);
1784
		$metadata_caption['title'] = $aux;
1785
	}
1786

    
1787
	//artist
1788
	if ($media_metadata->Artist){
1789
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1790
	}
1791
	elseif ($media->artist->titleCache){
1792
	 $metadata_caption['artist'] = $media->artist->titleCache;
1793
	}
1794

    
1795
	//copyright
1796
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1797
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1798
	if ($media_metadata->Copyright)
1799
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1800
	elseif ($media->rights){
1801
		foreach($media->rights as $right){
1802
			switch($right->term->uuid){
1803
				case UUID_RIGHTS_LICENCE:
1804
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1805
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1806
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1807
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1808
					break;
1809
				case UUID_RIGHTS_COPYRIGHT:
1810
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1811
					break;
1812
			}
1813
		}
1814
	}
1815
	else
1816
	$metadata_caption['rights']['agentNames'][] = '';
1817

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

    
1821
	//location
1822
	$metadata_caption['location'] = array();
1823
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1824
	$metadata_caption['location']['city'] = $media_metadata->City;
1825
	$metadata_caption['location']['province'] = $media_metadata->Province;
1826
	$metadata_caption['location']['country'] = $media_metadata->Country;
1827

    
1828
	//filename
1829
	if(isset($media->representations[0]->parts[0]->uri)){
1830
		$fileUri = $media->representations[0]->parts[0]->uri;
1831
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1832
		$metadata_caption['filename'] = $filename;
1833
	}
1834
	else{
1835
	 $metadata_caption['filename'] = '';
1836
	}
1837
	/*
1838
	 //creation date
1839
	 if($media_metadata["Modify Date"])
1840
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1841
	 else
1842
	 $metadata_caption['mediacreated'] = $media->created;
1843
	 */
1844
	//returned value
1845
	return $metadata_caption;
1846
}
1847

    
1848
/**
1849
 * This function collects all the media from a list of description elements
1850
 * and return them as an Array.
1851
 *
1852
 * @param $descriptionElementes The description elements
1853
 * @return Array The output with all the media
1854
 */
1855
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1856
	//variables
1857
	$outArrayOfMedia = array(); //return value
1858
	//implementation
1859
	foreach($descriptionElements as $descriptionElement){
1860
		foreach($descriptionElement->media as $media){
1861
			if(isset($media)){
1862
			 $outArrayOfMedia[] = $media;
1863
			}
1864
	 }
1865
	}
1866
	return $outArrayOfMedia;
1867
}
1868

    
1869
function cdm_annotations_as_footnotekeys($cdmBase){
1870

    
1871
	$footNoteKeys = array();
1872
	$footnoteListKey = RenderHints::getFootnoteListKey() . '-annotations';
1873
	$annotationUrl = cdm_compose_annotations_url($cdmBase);
1874
	if($annotationUrl){
1875
		$annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
1876
		if($annotationPager->count > 0){
1877
			foreach($annotationPager->records as $annotation){
1878
				$footNoteKeys[] = FootnoteManager::addNewFootnote($footnoteListKey, $annotation->text);
1879
			}
1880
		}
1881
	}
1882
	return $footNoteKeys;
1883
}
1884

    
1885

    
1886

    
(6-6/10)