Project

General

Profile

Download (61.2 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/renderhints.php');
30

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

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

    
53

    
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

    
68
/* ====================== hook implementations ====================== */
69

    
70
/**
71
 * Implementation of hook_help()
72
 *
73
 * Display help and module information
74
 * @param section which section of the site we're displaying help
75
 * @return help text for section
76
 */
77
function cdm_dataportal_help($section='') {
78

    
79
	$out = '';
80
	switch ($section) {
81
		case "admin/modules#description":
82
			$out = t("The dataportal publishes CDM data hosted in a CommunityStore on the web.");
83
			break;
84
	}
85
	return $out;
86
}
87

    
88

    
89
/**
90
 * Implementation of hook_perm()
91
 *
92
 * Valid permissions for this module
93
 * @return array An array of valid permissions for the portfolio module
94
 */
95
function cdm_dataportal_perm() {
96
	return array(
97
    	'administer cdm_dataportal',
98
      'cdm_dataportal view notes',
99
	//TODO which else permission are required? -> check the WP6 requirements document
100
	);
101
}
102

    
103

    
104
/**
105
 * Implementation of hook_menu()
106
 */
107
function cdm_dataportal_menu($may_cache) {
108
	$items = array();
109

    
110
	if ($may_cache) {
111

    
112
		$items[] = array(
113
      'path' => 'admin/settings/cdm_dataportal',
114
      'title' => t('CDM Dataportal'),
115
      'description' => t('Setting for the CDM DataPortal'),
116
      'access' => user_access('administer cdm_dataportal'),
117
      'callback' => 'drupal_get_form',
118
      'callback arguments' => 'cdm_dataportal_settings',
119
      'type' => MENU_NORMAL_ITEM,
120
		);
121

    
122
		$items[] = array(
123
      'path' => 'admin/settings/cdm_dataportal/general',
124
      'title' => t('General'),
125
      'description' => t('Setting for the CDM DataPortal'),
126
      'access' => user_access('administer cdm_dataportal'),
127
      'callback' => 'drupal_get_form',
128
      'callback arguments' => 'cdm_dataportal_settings',
129
	  'weight' => 0,
130
      'type' => MENU_LOCAL_TASK,
131
		);
132

    
133
		$items[] = array(
134
      'path' => 'admin/settings/cdm_dataportal/geo',
135
      'title' => t('Geo & Map'),
136
      'description' => t('Geo & Map'),
137
      'access' => user_access('administer cdm_dataportal'),
138
      'callback' => 'drupal_get_form',
139
      'callback arguments' => 'cdm_dataportal_settings_geo',
140
	  'weight' => 1,
141
      'type' => MENU_LOCAL_TASK,
142
		);
143

    
144
		$items[] = array(
145
      'path' => 'admin/settings/cdm_dataportal/layout',
146
      'title' => t('Layout'),
147
      'description' => t('Configure and adjust the layout of your DataPortal '),
148
      'access' => user_access('administer cdm_dataportal'),
149
      'callback' => 'drupal_get_form',
150
      'callback arguments' => 'cdm_dataportal_settings_layout',
151
      'weight' => 2,
152
      'type' => MENU_LOCAL_TASK,
153
		);
154

    
155
		$items[] = array(
156
      'path' => 'admin/settings/cdm_dataportal/cachesite',
157
      'title' => t('Cache'),
158
      'description' => t('Cache the whole CDM DataPortal site'),
159
      'access' => user_access('administer cdm_dataportal'),
160
      'callback' => 'cdm_dataportal_view_cache_site',
161
      'weight' => 10,
162
      'type' => MENU_LOCAL_TASK,
163
		);
164

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

    
176
		$items[] = array(
177
	    'path' => 'cdm_dataportal/names',
178
	    'callback' => 'cdm_dataportal_view_names',
179
	    'access' => true,
180
	    'type' => MENU_CALLBACK,
181
		);
182
		// optional callback arguments: page
183
			
184
		$items[] = array(
185
      'path' => 'cdm_dataportal/taxon',
186
      'callback' => 'cdm_dataportal_taxon_page_view',
187
      'access' => true,
188
      'type' => MENU_CALLBACK,
189
		// expected callback arguments: uuid
190
		);
191
		
192
		$items[] = array(
193
      'path' => 'cdm_dataportal/name',
194
      'callback' => 'cdm_dataportal_name_page_view',
195
      'access' => true,
196
      'type' => MENU_CALLBACK,
197
    // expected callback arguments: uuid
198
    );
199

    
200
		$items[] = array(
201
      'path' => 'cdm_dataportal/reference',
202
      'callback' => 'cdm_dataportal_view_reference',
203
      'access' => true,
204
      'type' => MENU_CALLBACK,
205
		// expected callback arguments: uuid
206
		);
207

    
208
		$items[] = array(
209
      'path' => 'cdm_dataportal/reference/list',
210
      'callback' => 'cdm_dataportal_view_reference_list',
211
      'access' => true,
212
      'type' => MENU_CALLBACK,
213
		// expected callback arguments: uuid
214
		);
215

    
216
		$items[] = array(
217
      'path' => 'cdm_dataportal/media',
218
      'callback' => 'cdm_dataportal_view_media',
219
      'access' => true,
220
      'type' => MENU_CALLBACK,
221
		// expected callback arguments: uuid, mediarepresentation_uuid, part_uuid or part#
222
		);
223

    
224
		$items[] = array(
225
      'path' => 'cdm_dataportal/search',
226
      'callback' => 'cdm_dataportal_view_search_advanced',
227
      'access' => true,
228
      'type' => MENU_CALLBACK,
229
		);
230

    
231
		$items[] = array(
232
      'path' => 'cdm_dataportal/search/taxon',
233
      'callback' => 'cdm_dataportal_view_search_taxon',
234
      'access' => true,
235
      'type' => MENU_CALLBACK,
236
		);
237
		
238
		$items[] = array(
239
      'path' => 'cdm/xml2json',
240
      'callback' => 'cdm_view_xml2json',
241
      'access' => true,
242
      'type' => MENU_CALLBACK,
243
		);
244

    
245
	} else {
246
		// may not cache
247
		// --- local tasks for Taxon
248
		$items[] = array(
249
      'path' => 'cdm_dataportal/name/'.arg(2),
250
      //'callback' => 'cdm_dataportal_view_name',
251
		  'callback' => 'cdm_dataportal_name_page_view',
252
      'callback arguments' => array(arg(2)),
253
      'access' => true,
254
      'type' => MENU_CALLBACK,
255
    );
256
    
257
		if(variable_get('cdm_dataportal_taxonpage_tabs', 1)) {
258

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

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

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

    
292
			$items[] = array(
293
      'path' => 'cdm_dataportal/taxon/'.arg(2).'/synonymy',
294
      'title' => theme('cdm_taxonpage_tab', 'Synonymy'),
295
      'callback' => 'cdm_dataportal_taxon_page_view',
296
      'access' => true,
297
      'type' => MENU_LOCAL_TASK,
298
      'weight' => 3,
299
      'callback arguments' => array(arg(2), "synonymy")
300
			// expected callback arguments: name_uuid
301
			);
302

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

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

    
320
	return $items;
321

    
322
}
323

    
324
/**
325
 * Implementation of hook_block()
326
 *
327
 * Provides the following blocks:
328
 *  0: list of links useful during development
329
 *
330
 * @param String $op
331
 * @param int $delta
332
 */
333
function cdm_dataportal_block($op='list', $delta=0) {
334
	// listing of blocks, such as on the admin/block page
335
	if ($op == "list") {
336
		//$block[0]["info"] = t("CDM DataPortal DevLinks");
337
//		$block[1]["info"] = t("CDM DataPortal Credits");
338
		$block[2]["info"] = t("CDM Search Taxa");
339
		//$block[3]["info"] = t("CDM Filters");
340
		$block[4]["info"] = t("CDM Dataportal Print");
341
		return $block;
342
	}
343
	else if ($op == 'view') {
344
		switch($delta){
345
//			case 1:
346
//				$block['subject'] = t('Credits');
347
//				$block['content'] = theme('cdm_credits');
348
//				return $block;
349
			case 2:
350
				$block['subject'] = t('Search Taxa');
351
				$block['content'] = drupal_get_form('cdm_dataportal_search_taxon_form');
352
				$block['content'] .= '<div>'.l('Advanced Search', '/cdm_dataportal/search').'</div>';
353
				return $block;
354
			case 4:
355
				$block['subject'] = t('Print this page');
356
				$block['content'] = theme('cdm_print_button');;
357
				return $block;
358
		}
359
	}
360
}
361

    
362

    
363
/**
364
 * Implementation of hook_validate()
365
 *
366
 * @param $element
367
 */
368
function cdm_dataportal_settings_validate($form_id, $form_values){
369

    
370
	if (!str_endsWith($form_values['cdm_webservice_url'], '/')) {
371
		//form_set_error('cdm_webservice_url', t("The URL to the CDM Web Service must end with a slash: '/'."));
372
		$form_values['cdm_webservice_url'] .= '/';
373
	}
374

    
375
//	$cdm_webservice_url_changed = variable_get('cdm_webservice_url', '') != $form_values['cdm_webservice_url'];
376

    
377
//	if ($cdm_webservice_url_changed) {
378
//
379
//		//FIXME remove _cdm_dataportal_set_currentSecUuid($form_values['cdm_secUuid_default']);
380
//		// reset all cdm related data stored in the session
381
//		// cdm_dataportal_session_clear($form_values['cdm_webservice_url']); // cdm_webservice_url is not further stored here
382
//		// clear the cdm webservice cache
383
//		cache_clear_all(NULL, 'cache_cdm_ws');
384
//		// better clear secref_cache since i can not be sure if the cache has not be used during this response
385
//		cdm_api_secref_cache_clear();
386
//	}
387
	if($form_values['cdm_webservice_cache'] != variable_get('cdm_webservice_cache', 1)){
388
		cache_clear_all(NULL, 'cache_cdm_ws');
389
		// better clear secref_cache since i can not be sure if the cache has not be used during this response
390
		cdm_api_secref_cache_clear();
391
	}
392

    
393
}
394

    
395
/*
396
 function cdm_dataportal_session_clear($cdm_ws_uri_update = false){
397
 $_SESSION['cdm'] = null;
398
 if(is_string($cdm_ws_uri_update)){
399
 $_SESSION['cdm'] = array('ws_uri'=>$cdm_ws_uri_update);
400
 }
401
 }
402

    
403
 function cdm_dataportal_session_validate(){
404

    
405
 if(!isset($_SESSION['cdm']['ws_uri'])){
406
 $_SESSION['cdm'] = array('ws_uri'=>variable_get('cdm_webservice_url', false));
407
 } else if($_SESSION['cdm']['ws_uri'] != variable_get('cdm_webservice_url', false)){
408
 cdm_dataportal_session_clear(variable_get('cdm_webservice_url', false));
409
 }
410
 }
411
 */
412

    
413
function cdm_dataportal_search_taxon_form($advancedForm = false){
414

    
415
	$preset_query = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
416
	$preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
417
	$preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
418
	$preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
419
	$tdwg_level_select =  (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
420
	$selected_areas =  (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : false);
421

    
422
	$url = 'cdm_dataportal/search/taxon';
423
	$form['#method'] = 'get';
424
	$form['#process'] = array('cdm_dataportal_search_process' => array());
425
	$form['#action'] = url($url, NULL, NULL, true);
426

    
427
	$form['query'] = array(
428
    '#delta' => 0,
429
    '#type' => 'textfield',
430
    '#size' => 20,
431
    '#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')),
432
    '#value' => $preset_query,
433
	);
434

    
435
	$form['search'] = array(
436
      '#delta' => 1,
437
      '#tree' => true,
438
	//'#type' => $advancedForm ? 'fieldset': 'hidden',
439
      '#title' => t('Options')
440
	);
441

    
442
	$form['search']['tree'] = array(
443
    '#delta' => -1,
444
    '#type' => 'hidden',
445
    '#value' => variable_get('cdm_taxonomictree_uuid', false)
446
	);
447

    
448

    
449
	// clean URL get forms breaks if we don't give it a 'q'.
450
	if (!(bool)variable_get('clean_url', '0')) {
451
		$form['search']['q'] = array(
452
      '#delta' => -1,
453
      '#type' => 'hidden',
454
      '#value' => $url,
455
      '#name' => 'q',
456
		);
457
	}
458

    
459
	$form['search']['pageSize'] = array(
460
      '#delta' => -1,
461
      '#type' => 'hidden',
462
      '#value' => variable_get('cdm_dataportal_search_items_on_page', 25)
463
	);
464

    
465
	if($advancedForm){
466
		// general search parameters
467
		$form['search']['doTaxa'] = array(
468
      '#delta' => 2,
469
      '#type' => 'checkbox',
470
      '#title' => t('Search for accepted taxa'),
471
      '#value' => $preset_doTaxa
472
		);
473
		$form['search']['doSynonyms'] = array(
474
      '#delta' => 3,
475
      '#type' => 'checkbox',
476
      '#title' => t('Search for synonyms'),
477
      '#value' => $preset_doSynonyms
478
		);
479
		$form['search']['doTaxaByCommonNames'] = array(
480
      '#delta' => 4,
481
      '#type' => 'checkbox',
482
      '#title' => t('Search for common names'),
483
      '#value' => $preset_doTaxaByCommonNames
484
		);
485
			
486
		// Geographic Range
487
		$form['search']['geographic_range'] = array(
488
      '#type' => 'fieldset',
489
      '#delta' => 5,
490
      '#tree' => true,
491
      '#title' => t('Geographic range'),
492
		);
493

    
494
		$form['search']['geographic_range']['tdwg_level_select'] = array(
495
    '#type' => 'radios',
496
    '#title' => t('Select a TDWG distribution level and code'),
497
    '#default_value' => $tdwg_level_select,
498
    '#options' => array(
499
		t('TDWG level-1, i.e. a continent'),
500
		t('TDWG level-2'),
501
		t('TDWG level-3, i.e. a country'),
502
		t('TDWG level-4')
503
		)
504
		);
505
		$tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
506
		$tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
507
		$tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
508
		$tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
509

    
510
		$tdwg_js = '';
511
		foreach($tdwg as $key=>$tdwg_level){
512
			$tdwgOptions = array();
513
			$tdwgOptionsSelected = array();
514
			foreach($tdwg_level as $area){
515
				$representation = $area->representations[0];
516
				$tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
517
				if(is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)){
518
					$tdwgOptionsSelected[] = $representation->abbreviatedLabel; //$area->uuid;
519
				}
520
			}
521
			asort($tdwgOptions);
522
			$form['search']['geographic_range']['tdwg_level_'.$key] = array(
523
        '#type' => 'select',
524
        '#title'         => t('TDWG level').' '.$key,
525
        '#default_value' => $tdwgOptionsSelected,
526
        '#multiple' => TRUE, 
527
        '#options' => $tdwgOptions
528
			);
529
			$tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()".($tdwg_level_select + 1 == $key ?  '.show()' : '.hide()'). ";\n";
530
		}
531

    
532
		drupal_add_js(
533
    "$(document).ready(function(){
534
    
535
      $(\"input[@name='search[geographic_range][tdwg_level_select]']\").change( 
536
        function(event){
537
          var selectId = $(\"input[@name='search[geographic_range][tdwg_level_select]']:checked\").val();
538
          var i;
539
          for(i = 0; i < 4; i++){
540
            if(selectId == i){
541
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
542
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
543
            } else {
544
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
545
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
546
            }
547
          }
548
        }
549
      );
550
      
551
      $tdwg_js
552
    });",
553
    'inline');
554

    
555
	} else {
556
		$form['search']['doTaxa'] = array(
557
      '#delta' => -2,
558
      '#type' => 'hidden',
559
      '#value' => 1
560
		);
561
		$form['search']['doSynonyms'] = array(
562
      '#delta' => -3,
563
      '#type' => 'hidden',
564
      '#value' => 1
565
		);
566
		$form['search']['doTaxaByCommonNames'] = array(
567
      '#delta' => -4,
568
      '#type' => 'hidden',
569
      '#value' => 1
570
		);
571
	}
572

    
573
	$form['submit'] = array(
574
  '#delta' => 9,
575
  '#type' => 'submit',
576
  '#name' => '',
577
  '#value' => t('Search')
578
	);
579

    
580
	return $form;
581
}
582

    
583
function cdm_dataportal_search_taxon_form_advanced(){
584
	return cdm_dataportal_search_taxon_form(true);
585
}
586

    
587
/**
588
 * Implementation #process method call, see form_builder()
589
 * <p>
590
 * Removes Drupal internal form elements from query
591
 * @param $form
592
 * @return unknown_type
593
 */
594
function cdm_dataportal_search_process($form) {
595
	unset($form['form_id']);
596
	unset($form['form_token']);
597
	return $form;
598
}
599

    
600
/**
601
 * Filters $_REQUEST by a list of valid request  parameters and also sets defaults if required.
602
 * returns the processed request parameters submitted by the search form.
603
 */
604
function cdm_dataportal_search_form_request(){
605

    
606

    
607
	$form_params = array();
608
	array_deep_copy($_REQUEST['search'], $form_params);
609
	$form_params['query'] =  trim($_REQUEST['query']);
610

    
611
	// split of  geographic range
612
	if(isset($_REQUEST['search']['geographic_range'])){
613
		$geographicRange = $_REQUEST['search']['geographic_range'];
614
		// remove
615
		unset($form_params['geographic_range']);
616
	}
617

    
618
	// add geographic range
619
	if($geographicRange){
620
		$form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
621
		for($i = 1; $i < 5; $i++){
622
			if(isset($geographicRange['tdwg_level_'.$i])){
623
				$form_params['area'] = $geographicRange['tdwg_level_'.$i];
624
			}
625
		}
626
	}
627

    
628
	// store in session
629
	$_SESSION['cdm']['search'] = $form_params;
630

    
631
	return $form_params;
632
}
633

    
634

    
635
/* UNREACHABLE since action of form directly links to view
636
 function cdm_dataportal_search_taxon_form_submit($form_id, $form_values) {
637

    
638
 $_SESSION['cdm']['search'] = $form_values;
639
 //return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['vernacular']?'1':'0').'/'.$form_values['language'];
640
 return '/cdm_dataportal/search/taxon/'.$form_values['queryString'].'/'.($form_values['onlyAccepted']?'1':'0');
641
 //$paramstr = compose_url_prameterstr($form_values);
642
 //return url('/cdm_dataportal/search/taxon/', $paramstr);
643
 }
644
 */
645
/* ====================== menu callback functions ====================== */
646

    
647
/**
648
 * Generate main administration form.
649
 *
650
 * @return
651
 *   An array containing form items to place on the module settings page.
652
 */
653
function cdm_dataportal_settings(){
654

    
655
	$form = cdm_api_settings_form();
656

    
657
	//TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
658
	$form['cdm_dataportal'] = array(
659
      '#type' => 'fieldset',
660
      '#title' => t('CDM DataPortal'),
661
      '#collapsible' => FALSE,
662
      '#collapsed' => TRUE,
663
	);
664

    
665
	//  $form['cdm_dataportal']['secuuid_widget'] = array(
666
	//    '#type' => 'select_secuuid', // => will be themed by theme_select_secuuid(...)
667
	//    '#title' => t('Default Concept References'),
668
	//    '#description'   => t('The default \'sensu\' reference to start the CDM DataPortal with. Per user choices are possible and may override this value.'),
669
	//    '#varname' => 'cdm_secUuid_default',
670
	//    '#multiple' => false
671
	//  );
672

    
673
	$taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
674
	foreach($taxonTrees as $tree){
675
		$taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
676
	}
677
	$form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
678
    '#type' => 'select',
679
    '#title'         => t('Available taxonomic views'),
680
    '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
681
    '#options' => $taxonomicTreeOptions,
682
    '#description'   => t('Select a taxonomic view for this webservice.')
683
	);
684

    
685
	//  $form['cdm_dataportal']['DEBUG']= array(
686
	//    '#value' => '<pre>'.print_r($taxonTrees, true).'</pre>'
687
	//  );
688

    
689

    
690
	//------------------ FEATURE TREE --------------------//
691

    
692
	$form['cdm_dataportal']['feature_tree'] = array(
693
    '#type' => 'fieldset',
694
    '#title' => t('Feature Tree'),
695
    '#collapsible' => TRUE,
696
    '#collapsed' => TRUE,
697
	);
698

    
699
	$form['cdm_dataportal']['feature_tree'][CDM_DATAPORTAL_FEATURETREE_UUID] = array(
700
    '#type' => 'select',
701
    '#title'         => t('Available FeatureTrees'),
702
    '#default_value' => variable_get(CDM_DATAPORTAL_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE),
703
	  '#options' => _get_feature_trees(),
704
    '#description'   => t('Select a FeatureTree for this webservice.'
705
    //.' If there is no applicable FeatureTree you can create a new one using the <a href="">FeatureTreeManager</a>'
706
	)
707
	);
708

    
709
	return system_settings_form($form);
710
}
711

    
712
function cdm_dataportal_form_alter($form_id, &$form) {
713
    
714
static $comment_node_disabled =  0;
715
static $comment_node_read_only =  1;
716
static $comment_node_read_write =  2;
717
   
718
    
719
  if ($form_id == 'node_type_form' 
720
    && isset($form['identity']['type']) 
721
    && array_key_exists($form['#node_type']->type, cdm_dataportal_get_nodetypes()) 
722
    ) {
723
    $form['workflow']['comment'] = array(
724
      '#type' => 'radios',
725
      '#title' => t('Default comment setting'),
726
      '#default_value' => variable_get('comment_'. $form['#node_type']->type, $comment_node_disabled),
727
      '#options' => array(t('Disabled'), t('Read only'), t('Read/Write')),
728
      '#description' => t('Users with the <em>administer comments</em> permission will be able to override this setting.'),
729
    );
730
  }
731
}
732

    
733
/**
734
 * LAYOUT settings
735
 * @return unknown_type
736
 */
737
function cdm_dataportal_settings_layout(){
738

    
739
	$form = array();
740

    
741

    
742
	$form['cdm_taxonname_type'] = array(
743
    '#type' => 'select',
744
    '#title'         => t('Taxon name type'),
745
    '#default_value' => variable_get('cdm_taxonname_type', 'BotanicalName'),
746
    '#options' => array( 'BotanicalName'=>t('BotanicalName'), 'ZoologicalName'=>t('ZoologicalName')),
747
    '#description'   => t('')
748
	);
749

    
750
	$form['cdm_dataportal_nomref_in_title'] = array(
751
    '#type' => 'checkbox',
752
    '#title' => t('Show full nomenclatural reference in title'),
753
    '#default_value' => variable_get('cdm_dataportal_nomref_in_title', CDM_DATAPORTAL_NOMREF_IN_TITLE),
754
    '#description' => t('Uncheck this, if you want the title of a taxon page consisting of name and author plus publication year only.
755
                        If not checked, the first homotypic taxon is a repetition of the accepted taxon with
756
                        the full nomenclatural reference.')
757
	);
758

    
759
	$form[CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS] = array(
760
    '#type' => 'checkbox',
761
    '#title' => t('Show name relations of accepted taxa on taxon page'),
762
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_NAME_RELATIONSHIPS_DEFAULT),
763
    '#description' => t('')
764
	);
765
	
766
	$form[CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS] = array(
767
    '#type' => 'checkbox',
768
    '#title' => t('Show taxon relations of accepted taxa on taxon page'),
769
    '#default_value' => variable_get(CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS, CDM_DATAPORTAL_DISPLAY_TAXON_RELATIONSHIPS_DEFAULT),
770
    '#description' => t('')
771
    );
772

    
773
	$form['cdm_dataportal_display_is_accepted_for'] = array(
774
    '#type' => 'checkbox',
775
    '#title' => t('Display <em>is accepted for ...</em> on taxon pages when coming from a synonym link.'),
776
    '#default_value' => variable_get('cdm_dataportal_display_is_accepted_for', CDM_DATAPORTAL_DISPLAY_IS_ACCEPTED_FOR),
777
    '#description' => t('')
778
	);
779

    
780
	$form['cdm_dataportal_name_relations_skiptype_basionym'] = array(
781
    '#type' => 'checkbox',
782
    '#title' => t('Exclude the basionym relationship type from the taxon page'),
783
    '#default_value' => variable_get('cdm_dataportal_name_relations_skiptype_basionym', 1),
784
    '#description' => t('')
785
	);
786

    
787
	$form['cdm_dataportal_taxonpage_tabs'] = array(
788
    '#type' => 'checkbox',
789
    '#title' => t('Tabbed taxon page'),
790
    '#default_value' => variable_get('cdm_dataportal_taxonpage_tabs', 1),
791
    '#description' => t('Split the taxon page into individual tabs for description, images, synonymy')
792
	);
793

    
794
	$form['cdm_dataportal_search_items_on_page'] = array(
795
    '#type' => 'textfield',
796
    '#title' => t('Search Page Size'),
797
    '#default_value' => variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE),
798
    '#description' => t('Number of Names to display per page in search results.')
799
	);
800

    
801
	$form['cdm_dataportal_descriptions_separated'] = array(
802
    '#type' => 'checkbox',
803
    '#title' => t('Separate Descriptions'),
804
    '#default_value' => variable_get('cdm_dataportal_descriptions_separated', 0),
805
    '#description' => t('By default corresponding elements of different descriptions are joined together'
806
    .' into a common section per feature (i.e. type of description).'
807
    .' Check this box to allow displaying all descriptions separately.')
808
    );
809

    
810
    //---- IMAGES ----//
811
    $form['images'] = array(
812
    '#type' => 'fieldset',
813
    '#title' => t('Images'),
814
    '#collapsible' => TRUE,
815
    '#collapsed' => FALSE,
816
    );
817
    $options = cdm_rankVocabulary_as_option();
818
    array_unshift($options, '-- DISABLED --');
819
    $form['images']['image_hide_rank'] =  array(
820
    '#type'          => 'select',
821
    '#title'         => t('Hide Images for Taxa above'),
822
    '#default_value' => variable_get('image_hide_rank', '0'),
823
    '#options'       => $options,
824
    '#description'   => t(''),
825
    );
826
    //show media
827
    $selectShowMedia = array(0 => "Show only taxon media",
828
    1 => "Show taxon and child taxon media");
829
    $form['images']['cdm_dataportal_show_media'] = array(
830
    '#type' => 'select',
831
    '#title' => t('Available media files'),
832
    '#default_value' => variable_get('cdm_dataportal_show_media', false),
833
    '#options' => $selectShowMedia,
834
    '#description'   => t('Select if a taxon should show only his media or also child media.')
835
    );
836

    
837
    // --- SEARCH TAXA GALLERY ---- //
838
    $collapsed = TRUE;
839
    $form_name = CDM_DATAPORTAL_SEARCH_GALLERY_NAME;
840
    $form_tittle = 'Search Taxa';
841
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
842

    
843
    // --- FEATURE DESCRIPTION GALLERY ---- //
844
    $form_name = CDM_DATAPORTAL_DESCRIPTION_GALLERY_NAME;
845
    $form_tittle = 'Description elements gallery';
846
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
847

    
848
    // --- MEDIA GALLERY ---- //
849
    $form_name = CDM_DATAPORTAL_MEDIA_GALLERY_NAME;
850
    $form_tittle = 'Media gallery';
851
    $form[] = cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed);
852

    
853
    return system_settings_form($form);
854
}
855

    
856
function cdm_dataportal_create_gallery_settings_form($form_name, $form_tittle, $collapsed){
857

    
858
	$form[$form_name] = array(
859
    '#type' => 'fieldset',
860
    '#title' => t($form_tittle),
861
    '#collapsible' => TRUE,
862
    '#collapsed' => $collapsed,
863
    '#tree' => true,
864
	);
865

    
866
	$default_values = unserialize(CDM_DATAPORTAL_GALLERY_SETTINGS);
867
	$gallery_settings = variable_get($form_name, $default_values);
868

    
869
  if($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME){
870
    $form[$form_name]['cdm_dataportal_show_taxon_thumbnails'] = array(
871
      '#type' => 'checkbox',
872
      '#title' => t('Show media thumbnails for accepted taxa'),
873
      '#default_value' => $gallery_settings['cdm_dataportal_show_taxon_thumbnails'],
874
      '#description' => t('')
875
    );
876

    
877
    $form[$form_name]['cdm_dataportal_show_synonym_thumbnails'] = array(
878
      '#type' => 'checkbox',
879
      '#title' => t('Show media thumbnails for synonyms'),
880
      '#default_value' => $gallery_settings['cdm_dataportal_show_synonym_thumbnails'],
881
      '#description' => t('')
882
    );
883
  }
884
  
885
	//$showCaption = variable_get('cdm_dataportal_findtaxa_show_thumbnail_captions', 0);
886
	$form[$form_name]['cdm_dataportal_show_thumbnail_captions'] = array(
887
    '#type' => 'checkbox',
888
    '#title' => t('Show captions under thumbnails'),
889
    '#default_value' => $gallery_settings['cdm_dataportal_show_thumbnail_captions'],
890
    '#description' => t('')
891
	);
892

    
893
	$form[$form_name]['cdm_dataportal_media_maxextend'] = array(
894
    '#type' => 'textfield',
895
    '#title' => t('Maximum extend of Images'),
896
    '#default_value' => $gallery_settings['cdm_dataportal_media_maxextend'],
897
    '#description' => t('In the gallery neither width or height will exceed the maximum extend of images.')
898
	);
899

    
900
	$form[$form_name]['cdm_dataportal_media_cols'] = array(
901
    '#type' => 'textfield',
902
    '#title' => t('Number of columns'),
903
    '#default_value' => $gallery_settings['cdm_dataportal_media_cols'],
904
    '#description' => t('')
905
	);
906

    
907
  if($form_name != CDM_DATAPORTAL_MEDIA_GALLERY_NAME){
908
    $form[$form_name]['cdm_dataportal_media_maxRows'] = array(
909
      '#type' => 'textfield',
910
      '#title' => t('Maximum number of rows'),
911
      '#default_value' => $gallery_settings['cdm_dataportal_media_maxRows'],
912
      '#description' => t('If you want an unlimited number of rows please set to 0')
913
    );
914
  }
915

    
916
	return $form;
917
}
918

    
919
/**
920
 * GEOSERVICE and Map settings
921
 * @return unknown_type
922
 */
923
function cdm_dataportal_settings_geo(){
924

    
925
	$form = array();
926

    
927
	$form['cdm_dataportal_map_openlayers'] = array(
928
    '#type' => 'checkbox',
929
    '#title' => t('OpenLayers Viewer'),
930
    '#default_value' => variable_get('cdm_dataportal_map_openlayers', 1),
931
    '#description' => t('Display the maps in an interactive viewer which allows zooming and panning.')
932
	);
933

    
934
	$form['cdm_dataportal_geoservice_access_point'] = array(
935
    '#type' => 'textfield',
936
    '#title' => t('Geoservice Access Point'),
937
    '#default_value' => variable_get('cdm_dataportal_geoservice_access_point', ''),
938
    '#description' => t('Base URL of the geoservice to be used by this portal')
939
	);
940

    
941
	$form['cdm_dataportal_geoservice_display_width'] = array(
942
    '#type' => 'textfield',
943
    '#title' => t('Geoservice Display Width'),
944
    '#default_value' => variable_get('cdm_dataportal_geoservice_display_width', 390),
945
    '#description' => t('Width of the image generated by geoservice')
946
	);
947

    
948
	$form['cdm_dataportal_geoservice_bounding_box'] = array(
949
    '#type' => 'textfield',
950
    '#title' => t('Fixed Geoservice Bounding Box'),
951
    '#default_value' => variable_get('cdm_dataportal_geoservice_bounding_box', '-180,-90,180,90'),
952
    '#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.')
953
	);
954

    
955
	//cdm_dataportal_geoservice_labels_on
956
	$form['cdm_dataportal_geoservice_labels_on'] = array(
957
    '#type' => 'checkbox',
958
    '#title' => t('Display Country Labels'),
959
    '#default_value' => variable_get('cdm_dataportal_geoservice_labels_on', FALSE),
960
    '#description' => t('Check this if you like country names to be displayed in the maps. ')
961
	);
962

    
963
	//cdm_dataportal_geoservice_legend_on
964
	$form['cdm_dataportal_geoservice_map_caption'] = array(
965
    '#type' => 'textfield',
966
    '#title' => t('Map Caption'),
967
    '#default_value' => variable_get('cdm_dataportal_geoservice_map_caption', ''),
968
    '#description' => t('Define a caption for the map.')
969
	);
970

    
971
	/*
972
	 //cdm_dataportal_geoservice_legend_on
973
	 $form['cdm_dataportal_geoservice_legend_on'] = array(
974
	 '#type' => 'checkbox',
975
	 '#title' => t('Display a map legend'),
976
	 '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
977
	 '#description' => t('Check this if you like a legend to be displayed with the maps. ')
978
	 );
979
	 */
980

    
981
	//cdm_dataportal_geoservice_map_legend
982
	$form['cdm_dataportal_geoservice_map_legend'] = array(
983
      '#type' => 'fieldset',
984
      '#title' => t('Map Legend'),
985
      '#collapsible' => FALSE,
986
      '#collapsed' => TRUE,
987
	);
988

    
989
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_on'] = array(
990
    '#type' => 'checkbox',
991
    '#title' => t('Display a map legend'),
992
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_on', TRUE),
993
    '#description' => t('Check this if you like a legend to be displayed with the maps. ')
994
	);
995

    
996
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_size'] = array(
997
    '#type' => 'textfield',
998
    '#title' => t('Font size'),
999
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_size', 10),
1000
    '#description' => t('Font size in pixels.')
1001
	);
1002

    
1003
	$fontStyles = array(0 => "plane", 1 => "italic");
1004
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_font_style'] = array(
1005
    '#type' => 'select',
1006
    '#title' => t('Available font styles'),
1007
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_font_style', false),
1008
    '#options' => $fontStyles,
1009
    '#description'   => t('Select a font style for the map legend.')
1010
	);
1011

    
1012
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_width'] = array(
1013
    '#type' => 'textfield',
1014
    '#title' => t('Icon width'),
1015
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_width', 35),
1016
    '#description' => t('Icon width in pixels.')
1017
	);
1018

    
1019
	$form['cdm_dataportal_geoservice_map_legend']['cdm_dataportal_geoservice_legend_icon_height'] = array(
1020
    '#type' => 'textfield',
1021
    '#title' => t('Icon height'),
1022
    '#default_value' => variable_get('cdm_dataportal_geoservice_legend_icon_height', 15),
1023
    '#description' => t('Icon height in pixels.')
1024
	);
1025

    
1026
	/* variable_get('cdm_dataportal_findtaxa_media_maxextend', 120),
1027
	 *  $form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
1028
	 '#type' => 'select',
1029
	 '#title'         => t('Available taxonomic views'),
1030
	 '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
1031
	 '#options' => $taxonomicTreeOptions,
1032
	 '#description'   => t('Select a taxonomic view for this webservice.')
1033
	 );
1034

    
1035
	 $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1036
	 foreach($taxonTrees as $tree){
1037
	 $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
1038
	 }
1039
	 $form['cdm_dataportal']['cdm_taxonomictree_uuid'] = array(
1040
	 '#type' => 'select',
1041
	 '#title'         => t('Available taxonomic views'),
1042
	 '#default_value' => variable_get('cdm_taxonomictree_uuid', false),
1043
	 '#options' => $taxonomicTreeOptions,
1044
	 '#description'   => t('Select a taxonomic view for this webservice.')
1045
	 );
1046
	 */
1047

    
1048
	return system_settings_form($form);
1049

    
1050
}
1051

    
1052

    
1053
/**
1054
 * @return walk and cache all taxon pages
1055
 */
1056
function cdm_dataportal_view_cache_site(){
1057

    
1058
	_add_js_progressbar();
1059

    
1060
	drupal_add_js(drupal_get_path('module', 'cdm_dataportal').'/js/cache_all_taxa.js');
1061

    
1062
	$out = '';
1063

    
1064
	$request_params = array();
1065
	$request_params['query'] = '%';
1066
	$request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false);
1067
	$request_params['doTaxa'] = 1;
1068
	$request_params['doSynonyms'] = 0;
1069
	$request_params['doTaxaByCommonNames'] = 0;
1070
	$search_url = cdm_compose_url(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1071
	$search_url = uri_uriByProxy($search_url);
1072
	$taxon_page_url = url('cdm_dataportal/taxon/');
1073

    
1074
	$out .= '<form id="cache_site">';
1075
	$out .= '<br /><h4>'.t('Cache all taxon pages').'</h4>';
1076
	$out .= 'Before  running the cache bot you have to empty the cache manually:<ul>' 
1077
            .'<li>Navigate to "Site Configuration -> General"</li>'
1078
            .'<li>Uncheck "Enable Caching" checkbox</li>'
1079
            .'<li>Check "Enable Caching" checkbox</li>'
1080
	        .'</ul>';
1081
	$out .= '<div>'.t('This caching process may take long time and could cause heavy load on your server').'</div>';
1082
	$out .= '<div id="progress"></div>';
1083
	$out .= '<input type="hidden" name="searchTaxaUrl" value="'.$search_url.'"/>';
1084
	$out .= '<input type="hidden" name="taxonPageUrl" value="'.$taxon_page_url.'"/>';
1085
	$out .= '<input type="button" name="start" value="'.t('Start').'"/>';
1086
	$out .= '<input type="button" name="stop" value="'.t('Stop').'"/>';
1087
	$out .= '</form>';
1088
	$out .= '</div>';
1089
	//  foreach($taxonPager->records as $taxon){
1090
	//    cdm_dataportal_taxon_view($uuid);
1091
	//  }
1092

    
1093
	return $out;
1094
}
1095

    
1096
/**
1097
 * Implementation of hook_elements().
1098
 */
1099
function cdm_dataportal_elements() {
1100
	$type['select_secuuid'] = array(
1101
    '#input' => TRUE,
1102
    '#process' => array('cdm_dataportal_select_secuuid_expand' => array()),
1103
	//'#validate' => array('cdm_dataportal_select_secuuid_validate' => array()),
1104
	//'#default_value' => array(),
1105
	);
1106
	return $type;
1107
}
1108

    
1109
/*
1110
 *
1111
 */
1112
function cdm_dataportal_select_secuuid_expand($element){
1113

    
1114
	$element['#tree'] = FALSE;
1115

    
1116
	// any value submitted?
1117
	if(isset($element['#post'][$element['#varname']])){
1118
		$selected_values = $element['#post'][$element['#varname']];
1119
	} else {
1120
		// use those store in drupal
1121
		$selected_values = variable_get( $element['#varname'], array());
1122
	}
1123
	if(!is_array($selected_values)){
1124
		$selected_values = array($selected_values);
1125
	}
1126
	$options = array();
1127
	foreach($selected_values as $secUuid){
1128
		$options[$secUuid] = cdm_taxontree_secRefTitle_for($secUuid);
1129
	}
1130

    
1131
	$element[$element['#varname']] =  array(
1132
    '#type' => 'select',
1133
    '#options' => $options,
1134
    '#default_value' => array_values($options),
1135
    '#size' => $element['#multiple'] ? 12 : 2,
1136
    '#multiple' => $element['#multiple'],
1137
	);
1138
	return $element;
1139
}
1140

    
1141

    
1142

    
1143
/**
1144
 * Displays a list of the known taxonomic names. Long lists are split up into multiple pages
1145
 *
1146
 * TODO: parameters are still preliminar
1147
 * @param String $page page number to diplay defaults to page 1
1148
 * @param boolean $hide_unaccepted whether to hide nams which are not accepted by the current view
1149
 */
1150
function cdm_dataportal_view_names($beginsWith = 'A', $page = 1, $onlyAccepted = false ){
1151

    
1152
	$request_params  = array(
1153
    'q' => $beginsWith,
1154
	//'sec' = '',
1155
	//'higherTaxa' => getFiters(),
1156
	// 'matchAnywhere' => false, // default is false
1157
    'page' => $page,
1158
    'onlyAccepted' => $onlyAccepted,
1159
    'pagesize' => 20  /*$_SESSION['cdm']['namelist_pagesize'] */);
1160

    
1161
	$taxonPager = cdm_ws_find(CDM_WS_PORTAL_TAXON_FIND, $request_params);
1162
	/*
1163
	 * FIXME the filter for accepted names will be a form element, thus this widget
1164
	 * should be generated via form api preferably as block
1165
	 */
1166
	//$out  = theme('cdm_dataportal_widget_filter_accepted', $onlyAccepted);
1167
	//$out .= theme('cdm_dataportal_widget_names_list', $names, $page);
1168
	$out .= theme('cdm_listof_taxa', $taxonPager);
1169
	return $out;
1170
}
1171

    
1172
function cdm_dataportal_view_reference($uuid, $arg2 = null){
1173
	$reference = cdm_ws_get(CDM_WS_REFERENCE, $uuid);
1174
	return theme('cdm_reference_page', $reference);
1175
}
1176

    
1177
function cdm_dataportal_view_reference_list($pageNumber){
1178
	$referencePager = cdm_ws_page(CDM_WS_REFERENCE, variable_get('cdm_dataportal_search_items_on_page', CDM_DATAPORTAL_SEARCH_ITEMS_ON_PAGE), $pageNumber);
1179
	return theme('cdm_reference_pager', $referencePager, 'cdm_dataportal/reference/list/');
1180
}
1181

    
1182
function cdm_dataportal_view_media($mediaUuid, $mediarepresentation_uuid = false, $part = 0){
1183
	$media = cdm_ws_get(CDM_WS_PORTAL_MEDIA, $mediaUuid);
1184
	return theme('cdm_media_page', $media, $mediarepresentation_uuid, $part);
1185
}
1186

    
1187
/**
1188
 * The taxon page gives detailed information on a taxon, it shows:
1189
 *  - Taxon name
1190
 *  - Full list of synonyms homotypic synonyms on top, followed by the
1191
 *    heterotypic and finally followed by misapplied names.
1192
 *    The list is ordered historically.
1193
 *  - All description associated with the taxon.
1194
 *
1195
 * @param $uuid
1196
 * @param $chapter name of the part to display,
1197
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1198
 * @return unknown_type
1199
 */
1200
function cdm_dataportal_taxon_page_view($uuid, $chapter = 'all'){
1201

    
1202
	// display the page for the taxon defined by $uuid
1203
	$taxonpage = cdm_dataportal_taxon_view($uuid, $chapter);
1204
	return cdm_node_show(NODETYPE_TAXON, $uuid, $taxonpage->title , $taxonpage->content);
1205
}
1206

    
1207
/**
1208
 * @param $uuid
1209
 * @param $chapter name of the part to display,
1210
 *         valid values are: 'description', 'images', 'synonymy', 'all'
1211
 * @return unknown_type
1212
 */
1213
function cdm_dataportal_taxon_view($uuid, $chapter = 'all'){
1214

    
1215
	$taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON, $uuid);
1216
	if(!$taxon){
1217
		drupal_set_title(t('Taxon does not exist'));
1218
		return false;
1219
	}
1220
	//FIXME remove _cdm_dataportal_set_currentSecUuid($taxon->sec->uuid);
1221

    
1222
	$taxonpage->title = theme('cdm_taxon_page_title', $taxon);
1223
	$taxonpage->content = theme('cdm_taxon_page_general', $taxon, $chapter);
1224

    
1225
	return $taxonpage;
1226
}
1227

    
1228
/**
1229
 * The function returns a name page as a drupal node ready to be renderized by drupal.
1230
 * The node page show the taxon name title and the list of taxon related with such taxon 
1231
 * name on the tree already in used. 
1232
 * @param $taxon_name_uuid A taxon name uuid
1233
 * @return The formatted name page as node
1234
 */
1235
function cdm_dataportal_name_page_view($taxon_name_uuid){
1236
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid);
1237
  return cdm_node_show(NODETYPE_NAME, $taxon_name_uuid, $taxonname_page->title , $taxonname_page->content);
1238
}
1239

    
1240
/**
1241
 * The function genates a object ready to be transformated to a node 
1242
 * in order to show as a drupal node
1243
 * @param $taxon_name_uuid
1244
 * @return the object with the page content and title  
1245
 */
1246
function cdm_dataportal_name_view($taxon_name_uuid){
1247
	//getting the full taxonname object from the server  
1248
  $taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1249
  if(!$taxon_name){
1250
    drupal_set_title(t('Taxon name does not exist'));
1251
    return false;
1252
  }
1253
  //searching for all the taxon connected with the taxon name on the tree in used
1254
  $name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1255
  $request_params = array();
1256
  $request_params['query'] = $name_cache;
1257
  $request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false);
1258
  $request_params['doTaxa'] = 1;
1259
  $request_params['doSynonyms'] = 1;
1260
  $request_params['doTaxaByCommonNames'] = 0;
1261
  $request_params['matchMode'] = "EXACT";
1262
  //$taxon_pager = cdm_ws_get(CDM_WS_FIND_TAXA, null, queryString($request_params));
1263
  $taxon_pager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1264
  
1265
  if (sizeof($taxon_pager->records) == 1){
1266
  	drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[0]->uuid);
1267
  }else{
1268
    $taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1269
    if($taxon_pager->records){
1270
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1271
    }else{
1272
      $taxon_name_page->content = 'This name has no taxa';
1273
    }
1274
    return $taxon_name_page; 
1275
  }
1276
  
1277
  //_cdm_dataportal_set_currentSecUuid($taxon->sec->uuid);
1278
  
1279
  //generating the returned object
1280

    
1281
}
1282

    
1283
function cdm_dataportal_view_search_advanced(){
1284

    
1285
	drupal_set_title(t('Advanced Search'));
1286

    
1287
	$searchForm = cdm_dataportal_search_taxon_form(true);
1288

    
1289
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1290

    
1291
}
1292

    
1293
/**
1294
 *
1295
 * future extensions to meet palmweb mockup requirements:
1296
 *  - habitat
1297
 *  - uses
1298
 *  - conservation status
1299
 *  - locality / tdwg region
1300
 */
1301
function cdm_dataportal_view_search_taxon(){
1302

    
1303
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1304

    
1305
	$request_params = cdm_dataportal_search_form_request();
1306
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1307

    
1308
	$search_params = $_REQUEST;
1309
	unset($search_params['q']);
1310
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1311
}
1312

    
1313
///**
1314
// * 
1315
// * @return unknown_type
1316
// */
1317
//function cdm_dataportal_view_name($taxon_name_uuid){
1318
//
1319
//	$taxon_name = cdm_ws_get(CDM_WS_NAME, array($taxon_name_uuid));
1320
//	/*
1321
//	$name_cache = cdm_ws_get(CDM_WS_NAME_NAMECAHE, array($taxon_name_uuid));
1322
//	$records = array();
1323
//	foreach ($taxon_name->taxonBases as $taxon_base){
1324
//		$taxon = cdm_ws_get(CDM_WS_TAXON, array($taxon_base->uuid));
1325
//		$records[] = $taxon;
1326
//	}
1327
//	
1328
//	$out  = "Taxon name: " . $taxon_name->titleCache . "<br/>";
1329
//	$out .= theme_cdm_list_of_taxa($records, false);
1330
//	*/
1331
//	
1332
//	$request_params = array();
1333
//  $request_params['query'] = $name_cache;
1334
//  $request_params['tree'] = variable_get('cdm_taxonomictree_uuid', false);
1335
//  $request_params['doTaxa'] = 1;
1336
//  $request_params['doSynonyms'] = 1;
1337
//  $request_params['doTaxaByCommonNames'] = 0;
1338
//  //$request_params['matchMode'] = "EXACT";
1339
//  
1340
//  $taxon_pager = cdm_ws_get(CDM_WS_FIND_TAXA, null, queryString($request_params));
1341
//  //var_dump($taxon_pager->records);
1342
//  //$out = theme_cdm_taxonname_page_title($taxon_name);
1343
//  $out = theme_cdm_list_of_taxa($taxon_pager->records, false);
1344
//  
1345
///*
1346
//  $out  = "Taxon name: " . $taxon_name->titleCache . "<br/>";
1347
//  $out .= "Taxon name uuid: " . $taxon_name_uuid  . "<br/>";
1348
//  $out .= "Taxon name records: "  . "<br/>" . $records_names_out; 
1349
//*/
1350
//  //$out  = "Taxon name: " . $taxon_name->titleCache . "<br/>";
1351
//	return $out;
1352
//}
1353

    
1354
function cdm_view_xml2json(){
1355
	$file = arg(2);
1356
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1357
	return  xml2json::transformXmlStringToJson($datastr);
1358
}
1359

    
1360
/* ====================== other functions ====================== */
1361

    
1362
/**
1363
 * Enter description here...
1364
 *
1365
 * @param String $uuid the UUID of the taxon
1366
 * @return the URL
1367
 */
1368
function path_to_taxon($uuid){
1369
	if(!$uuid) return false;
1370
	return 'cdm_dataportal/taxon/'.$uuid;
1371
}
1372

    
1373
function path_to_reference($uuid){
1374
	if(!$uuid) return false;
1375
	return 'cdm_dataportal/reference/'.$uuid;
1376
}
1377

    
1378
function path_to_name($name_uuid){
1379
	$res = false;
1380
	if($name_uuid){
1381
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1382
	}
1383
  return $res;
1384
}
1385

    
1386
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1387
	if(!$uuid) return false;
1388
	$out = 'cdm_dataportal/media/'.$uuid;
1389
	if($representaion_uuid){
1390
		$out .= '/'.$representaion_uuid;
1391
		if($partId !== false){
1392
			$out .= '/'.$partId;
1393
		}
1394
	}
1395
	return $out;
1396
}
1397

    
1398
/**
1399
 * Compares thisRank with thatRank.
1400
 * Returns a negative integer, zero, or a positive integer
1401
 * as the of thisRank is higher than, equal to, or lower than thatRank.
1402
 * e.g:
1403
 * <ul>
1404
 * <li>rank_compare({species_uuid}, {genus_uuid}) = -1</li>
1405
 * <li>rank_compare({genus_uuid}, {genus_uuid}) = 0</li>
1406
 * <li>rank_compare({genus_uuid}, {tribus_uuid}) = 1</li>
1407
 * </ul>
1408
 * <p>
1409
 * This compare logic of the underlying webservice is the
1410
 * <b>inverse logic</b> of the the one implemented in
1411
 * java.lang.Comparable#compareTo(java.lang.Object)
1412
 * @param $thisRankUuid
1413
 * @param $thatRankUuid
1414
 * @return  a negative integer, zero, or a positive integer
1415
 * as the thisRank is lower than, equal to, or higher than thatRank
1416
 */
1417
function rank_compare($thisRankUuid, $thatRankUuid){
1418
	$result = cdm_ws_get(CDM_WS_TERM_COMPARE, array($thisRankUuid, $thatRankUuid));
1419
	return $result->Integer;
1420
}
1421

    
1422
function uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1423
	$acceptedPath = path_to_taxon($acceptedUuid);
1424
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid);
1425
}
1426

    
1427
/**
1428
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1429
 * If the taggename if empty the fullname will be returned.
1430
 *
1431
 * @param unknown_type $Name or TreeNode
1432
 * @return string
1433
 */
1434
function cdm_dataportal_shortname_of($name){
1435

    
1436
	$nameStr = '';
1437
	// get all tagged text tokens of the scientific name
1438
	foreach($name->taggedTitle as $tagtxt){
1439
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1440
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1441
		}
1442
	}
1443
	$nameStr = trim($nameStr);
1444
	if($nameStr){
1445
		// do not return short names for these
1446
		if($nameStr == 'Incertae sedis' || $nameStr ==  'Nomina excludenda'){
1447
			return $nameStr;
1448
		}
1449
		if($pos = stripos($nameStr, ' ')){
1450
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1451
		} else {
1452
			return $nameStr;
1453
		}
1454
	} else {
1455
		return $name->titleCache;
1456
	}
1457
}
1458

    
1459
/**
1460
 * TODO Add Comments. I don't get what
1461
 *
1462
 * @param UUID $secUuid
1463
 */
1464
function _cdm_dataportal_set_currentSecUuid($secUuid){
1465

    
1466
	// do not save in session but in database
1467

    
1468
	if(is_array($secUuid)){
1469
		$secUuid = $secUuid[0];
1470
	}
1471
	if(!$secUuid){
1472
		variable_set('cdm_currentSecRef', null);
1473
	} else {
1474
		$secRef = cdm_ws_get(CDM_WS_REFERENCE, $secUuid);
1475
		if(isset($secRef)){
1476
			variable_set('cdm_currentSecRef', (array)($secRef));
1477
		}
1478
	}
1479

    
1480
}
1481

    
1482
/**
1483
 * TODO
1484
 * This will not work with multiple instances of the dataportal running
1485
 * under the same host as there is only one session for all instances.
1486
 * In case you switch instances with the same client, you will definitely
1487
 * run into trouble.
1488
 * Also this is not handling multiple secs.
1489
 *
1490
 *
1491
 * returns the current secRef array.
1492
 * If the according session variable is not jet set the default
1493
 * as configured in the setting is used otherwise null.
1494
 *
1495
 * currentSecRef['uuid']
1496
 * currentSecRef[....
1497
 *
1498
 * @return array
1499
 */
1500
//FIXME function _cdm_dataportal_currentSecRef_array(){
1501
//
1502
//	// do not look in session but in database
1503
//	if( variable_get('cdm_currentSecRef', null) == null){
1504
//		$secUuid = variable_get('cdm_secUuid_default', null);
1505
//		_cdm_dataportal_set_currentSecUuid($secUuid);
1506
//	}
1507
//	return variable_get('cdm_currentSecRef', null);
1508
//
1509
//}
1510

    
1511
/**
1512
 * Check if a taxon is accepted by the current taxonomic tree
1513
 *
1514
 * @param Taxon $taxon
1515
 * @return true if $taxon is accepted, false otherwise
1516
 */
1517

    
1518
function _cdm_dataportal_acceptedByCurrentView($taxon){
1519

    
1520
	//FIXME $current_secref = _cdm_dataportal_currentSecRef_array();
1521
	$defaultTreeUuid = variable_get('cdm_taxonomictree_uuid', false);
1522
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1523
		foreach($taxon->taxonNodes as $node){
1524
			if($node->taxonomicTree == $defaultTreeUuid) {
1525
				return true;
1526
			}
1527
		}
1528
	}
1529
	return false;
1530
}
1531

    
1532
/**@Deprecated
1533
 *
1534
 */
1535
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1536
	$pstr = '';
1537
	foreach($parameters as $key=>$value){
1538
		if(is_array($value)){
1539

    
1540
		} else {
1541
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1542
		}
1543
	}
1544
	return $pstr;
1545
}
1546

    
1547
function _get_feature_trees(){
1548
	$feature_trees = array();
1549

    
1550
	// set tree that contains all features
1551
	$feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1552

    
1553
	// get features from database
1554
	$persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1555
	if(is_array($persisted_trees)){
1556
		foreach($persisted_trees as $featureTree){
1557

    
1558
			// do not add the DEFAULT_FEATURETREE again
1559
			if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1560
				continue;
1561
			}
1562
			$featureLabels = array();
1563
			foreach ($featureTree->root->children as $featureNode){
1564
				$featureLabels[] = $featureNode->feature->representation_L10n;
1565
			}
1566

    
1567
			$feature_trees[$featureTree->uuid] = implode(", ", $featureLabels);
1568

    
1569
		}
1570
	}
1571
	return $feature_trees;
1572
}
1573

    
1574

    
1575
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1576
	//TODO implement admin user interface to replace swicth statement
1577
	//     preliminar solution: using themes
1578

    
1579
	$template = null;
1580
	// find best matching default RenderTemplate in theme
1581
	//echo "<br/><br/>RENDER PATH:  ".$renderPath;
1582
	//var_dump('RENDER PATH: ' . $renderPath);
1583
	while(!is_array($template) && strlen($renderPath) > 0){
1584
	   $template = theme('get_nameRenderTemplate', $renderPath);
1585
	   $renderPath = substr($renderPath, 0, strrpos($renderPath, '.'));
1586
//	   if(!is_array($template)){
1587
//	       echo "<br/>->".$renderPath;
1588
//	   }
1589
	}
1590
	
1591
	// otherwise get default RenderTemplate from theme 
1592
	if(!is_array($template)){
1593
	   $template = theme('get_nameRenderTemplate', '#DEFAULT');
1594
	}
1595
	// otherwise get system default RenderTemplate
1596
	if(!is_array($template)){
1597
		switch($renderPath){
1598
			case 'list_of_taxa':
1599
			case  'acceptedFor':
1600
			case 'taxon_page_synonymy':
1601
			case 'typedesignations':
1602
			case 'taxon_page_title':
1603
			case 'na': $template = array(
1604
			        'namePart' => array('#uri'=>true),
1605
			        //'authorshipPart' => true,
1606
				);
1607
				break;
1608
			case 'nar': $template = array(
1609
		          	'namePart' => array('#uri'=>true),
1610
					 //'authorshipPart' => true,
1611
		          	'referencePart' => array('#uri'=>true),
1612
		          	'microreferencePart' => true,
1613
				);
1614
				break;
1615
			default: $template = array(
1616
          'namePart' => array('#uri'=>true),
1617
          'authorshipPart' => true,
1618
          'referencePart' => array('#uri'=>true),
1619
          'microreferencePart' => true,
1620
          'statusPart' => true,
1621
          'descriptionPart' => true
1622
			);
1623
		}
1624
	}
1625

    
1626
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1627
		$template['nameAuthorPart']['#uri'] = $nameLink;
1628
	} else{
1629
		unset($template['nameAuthorPart']['#uri']);
1630
	}
1631

    
1632
	if($nameLink && isset($template['namePart']['#uri'])){
1633
		$template['namePart']['#uri'] = $nameLink;
1634
	} else{
1635
		unset($template['namePart']['#uri']);
1636
	}
1637

    
1638
	if($refenceLink && isset($template['referencePart']['#uri'])){
1639
		$template['referencePart']['#uri'] = $refenceLink;
1640
	}else{
1641
		unset($template['referencePart']['#uri']);
1642
	}
1643
	
1644
	return $template;
1645
}
1646

    
1647
function get_partDefinition($taxonNameType){
1648
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1649
	//     preliminar solution: using themes
1650

    
1651
	$partdef = theme('get_partDefinition', $taxonNameType);
1652

    
1653
	if(!is_array($partdef)){
1654
		switch($taxonNameType){
1655
			case 'ZoologicalName': $partdef = array(
1656
        'namePart' => array(
1657
          'name' => true,
1658
			),
1659
        'referencePart' => array(
1660
          'authorTeam' => true
1661
			),
1662
        'microreferencePart' => array(
1663
          'microreference' => true,
1664
			),
1665
        'statusPart' => array(
1666
          'status' => true,
1667
			),
1668
        'descriptionPart' => array(
1669
          'description' => true,
1670
			),
1671
			);
1672
			break;
1673
			case 'BotanicalName': $partdef = array(
1674
        'namePart' => array(
1675
          'name' => true
1676
			),
1677
        'authorTeamPart' => array(
1678
          'authorTeam' => true,   
1679
			),
1680
        'referencePart' => array(
1681
          'reference' => true      
1682
			),
1683
        'microreferencePart' => array(
1684
          'microreference' => true,
1685
			),
1686
        'statusPart' => array(
1687
          'status' => true,
1688
			),
1689
        'descriptionPart' => array(
1690
          'description' => true,
1691
			),
1692
			);
1693
			break;
1694
			default: $partdef = array(
1695
        'namePart' => array(
1696
          'name' => true,
1697
			),
1698
        'authorTeamPart' => array(
1699
          'authorTeam' => true,   
1700
			),
1701
        'referencePart' => array(
1702
          'reference' => true      
1703
			),
1704
        'microreferencePart' => array(
1705
          'microreference' => true,
1706
			),
1707
        'statusPart' => array(
1708
          'status' => true,
1709
			),
1710
        'descriptionPart' => array(
1711
          'description' => true,
1712
			),
1713
			);
1714
		}
1715
	}
1716
	return $partdef;
1717
}
1718

    
1719
/**
1720
 * The function read the metadata info such title or artist of a media file. The
1721
 * function tries at first to get all the info from the file metadata and if it is
1722
 * not avaible look at the media file info stored at the database.
1723
 * @param $media The media file
1724
 * @return array The array with the avilable specified metadata info.
1725
 * TODO rename to read_media_metadata() and move to *.module
1726
 */
1727
function cdm_read_media_metadata($media){
1728

    
1729
	$metadata_caption = array('title' => '',           //media_metadata and media
1730
                              'artist' => '',          //media_metadata and media
1731
                              'rights',                //media_metadata and media
1732
                              'location',              //media_metadata
1733
                              'filename' => '',        //media
1734
                              'mediacreated' => '',    //media
1735
                              'description' => '');    //media
1736

    
1737
	//getting the media metadata
1738
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1739

    
1740
	//title
1741
	//if ($media_metadata->Headline) {
1742
	if ($media_metadata->ObjectName) {
1743
		$metadata_caption['title'] = $media_metadata->ObjectName;
1744
		//	} else if ($media->titleCache){
1745
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1746
	} else if ($media->titleCache){
1747
		$metadata_caption['title'] = $media->titleCache;
1748
		if ($media->description_L10n)
1749
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1750
	}else{ //if there is no title on the db and metadata get file title
1751
    $aux = $media->representations[0]->parts[0]->uri;
1752
    $aux = explode("/", $aux);
1753
    $aux = end($aux);
1754
		$metadata_caption['title'] = $aux;		
1755
	}
1756

    
1757
	//artist
1758
	if ($media_metadata->Artist){
1759
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1760
	}
1761
	elseif ($media->artist->titleCache){
1762
	 $metadata_caption['artist'] = $media->artist->titleCache;
1763
	}
1764
	
1765
	//copyright
1766
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1767
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1768
	if ($media_metadata->Copyright)
1769
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1770
	elseif ($media->rights){
1771
		foreach($media->rights as $right){
1772
			switch($right->term->uuid){
1773
				case UUID_RIGHTS_LICENCE:
1774
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1775
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1776
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1777
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1778
					break;
1779
				case UUID_RIGHTS_COPYRIGHT:
1780
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1781
					break;
1782
			}
1783
		}
1784
	}
1785
	else
1786
	$metadata_caption['rights']['agentNames'][] = '';
1787

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

    
1791
	//location
1792
	$metadata_caption['location'] = array();
1793
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1794
	$metadata_caption['location']['city'] = $media_metadata->City;
1795
	$metadata_caption['location']['province'] = $media_metadata->Province;
1796
	$metadata_caption['location']['country'] = $media_metadata->Country;
1797

    
1798
	//filename
1799
	if(isset($media->representations[0]->parts[0]->uri)){
1800
		$fileUri = $media->representations[0]->parts[0]->uri;
1801
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1802
		$metadata_caption['filename'] = $filename;
1803
	}
1804
	else{
1805
	 $metadata_caption['filename'] = '';
1806
	}
1807
	/*
1808
	 //creation date
1809
	 if($media_metadata["Modify Date"])
1810
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1811
	 else
1812
	 $metadata_caption['mediacreated'] = $media->created;
1813
	 */
1814
	//returned value
1815
	return $metadata_caption;
1816
}
1817

    
1818
/**
1819
 * This function collects all the media from a list of description elements
1820
 * and return them as an Array.
1821
 *
1822
 * @param $descriptionElementes The description elements
1823
 * @return Array The output with all the media
1824
 */
1825
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1826
	//variables
1827
	$outArrayOfMedia = array(); //return value
1828
	//implementation
1829
	foreach($descriptionElements as $descriptionElement){
1830
		foreach($descriptionElement->media as $media){
1831
			if(isset($media)){
1832
			 $outArrayOfMedia[] = $media;
1833
			}
1834
	 }
1835
	}
1836
	return $outArrayOfMedia;
1837
}
1838

    
1839

    
(6-6/10)