Project

General

Profile

Download (62 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), arg(3)),
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_SEARCH_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_SEARCH_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, $taxon_to_hide_uuid){
1236
  $taxonname_page = cdm_dataportal_name_view($taxon_name_uuid, $taxon_to_hide_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, $taxon_to_hide_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_PORTAL_TAXON_FIND, null, queryString($request_params));
1263
  
1264
  //removing the name where we come from and 
1265
  foreach($taxon_pager->records as $k=>&$taxon){
1266
  	if($taxon->uuid == $taxon_to_hide_uuid){
1267
  		unset($taxon_pager->records[$k]);
1268
  	}
1269
  }
1270
 
1271
  //show the taxa list or go to the singular taxon
1272
  if (sizeof($taxon_pager->records) == 1){ //sigle taxon case
1273
  	reset($taxon_pager->records);
1274
  	$first_key = key($taxon_pager->records);
1275
    if($taxon_pager->records[$first_key]->class != "Taxon"){
1276
        $taxon = cdm_ws_get(CDM_WS_PORTAL_TAXON_ACCEPTED, $taxon_pager->records[$first_key]->uuid);
1277
        drupal_goto('cdm_dataportal/taxon/' . $taxon[0]->uuid);
1278
    }else{
1279
  	   drupal_goto('cdm_dataportal/taxon/' . $taxon_pager->records[$first_key]->uuid);
1280
    }
1281
  }else{ //more than one taxa case
1282
    $taxon_name_page->title = theme('cdm_name_page_title', $taxon_name);
1283
    if($taxon_pager->records){
1284
      $taxon_name_page->content = theme_cdm_list_of_taxa($taxon_pager->records, false);
1285
    }else{
1286
      $taxon_name_page->content = 'This name has no taxa';
1287
    }
1288
    return $taxon_name_page; 
1289
  }
1290
}
1291

    
1292
function cdm_dataportal_view_search_advanced(){
1293

    
1294
	drupal_set_title(t('Advanced search'));
1295

    
1296
	$searchForm = cdm_dataportal_search_taxon_form(true);
1297

    
1298
	return drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
1299

    
1300
}
1301

    
1302
/**
1303
 *
1304
 * future extensions to meet palmweb mockup requirements:
1305
 *  - habitat
1306
 *  - uses
1307
 *  - conservation status
1308
 *  - locality / tdwg region
1309
 */
1310
function cdm_dataportal_view_search_taxon(){
1311

    
1312
	$_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
1313

    
1314
	$request_params = cdm_dataportal_search_form_request();
1315
	$taxonPager = cdm_ws_get(CDM_WS_PORTAL_TAXON_FIND, null, queryString($request_params));
1316

    
1317
	$search_params = $_REQUEST;
1318
	unset($search_params['q']);
1319
	return theme('cdm_search_results', $taxonPager, 'cdm_dataportal/search/taxon', $search_params);
1320
}
1321

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

    
1363
function cdm_view_xml2json(){
1364
	$file = arg(2);
1365
	$datastr = get_content(variable_get('cdm_webservice_url', '').$file);
1366
	return  xml2json::transformXmlStringToJson($datastr);
1367
}
1368

    
1369
/* ====================== other functions ====================== */
1370

    
1371
/**
1372
 * Enter description here...
1373
 *
1374
 * @param String $uuid the UUID of the taxon
1375
 * @return the URL
1376
 */
1377
function path_to_taxon($uuid){
1378
	if(!$uuid) return false;
1379
	return 'cdm_dataportal/taxon/'.$uuid;
1380
}
1381

    
1382
function path_to_reference($uuid){
1383
	if(!$uuid) return false;
1384
	return 'cdm_dataportal/reference/'.$uuid;
1385
}
1386

    
1387
function path_to_name($name_uuid){
1388
	$res = false;
1389
	if($name_uuid){
1390
	 $res = 'cdm_dataportal/name/'.$name_uuid;
1391
	}
1392
  return $res;
1393
}
1394

    
1395
function path_to_media($uuid, $representaion_uuid = false, $partId = false){
1396
	if(!$uuid) return false;
1397
	$out = 'cdm_dataportal/media/'.$uuid;
1398
	if($representaion_uuid){
1399
		$out .= '/'.$representaion_uuid;
1400
		if($partId !== false){
1401
			$out .= '/'.$partId;
1402
		}
1403
	}
1404
	return $out;
1405
}
1406

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

    
1431
function uri_to_synonym($synonymUuid, $acceptedUuid, $pagePart = null){
1432
	$acceptedPath = path_to_taxon($acceptedUuid);
1433
	return url($acceptedPath.($pagePart ? '/'.$pagePart : ''), 'highlite='.$synonymUuid.'&acceptedFor='.$synonymUuid);
1434
}
1435

    
1436
/**
1437
 * Creates a short taxonname by using the taggename field of NameSTO or NameTO instances.
1438
 * If the taggename if empty the fullname will be returned.
1439
 *
1440
 * @param unknown_type $Name or TreeNode
1441
 * @return string
1442
 */
1443
function cdm_dataportal_shortname_of($name){
1444

    
1445
	$nameStr = '';
1446
	// get all tagged text tokens of the scientific name
1447
	foreach($name->taggedTitle as $tagtxt){
1448
		if($tagtxt->type == 'name' || $tagtxt->type == 'rank'){
1449
			$nameStr .= ($nameStr ? ' ' : '').$tagtxt->text;
1450
		}
1451
	}
1452
	$nameStr = trim($nameStr);
1453
	if($nameStr){
1454
		// do not return short names for these
1455
		if($nameStr == 'Incertae sedis' || $nameStr ==  'Nomina excludenda'){
1456
			return $nameStr;
1457
		}
1458
		if($pos = stripos($nameStr, ' ')){
1459
			return substr($nameStr, 0, 1).'. '.substr($nameStr, $pos);
1460
		} else {
1461
			return $nameStr;
1462
		}
1463
	} else {
1464
		return $name->titleCache;
1465
	}
1466
}
1467

    
1468
/**
1469
 * TODO Add Comments. I don't get what
1470
 *
1471
 * @param UUID $secUuid
1472
 */
1473
function _cdm_dataportal_set_currentSecUuid($secUuid){
1474

    
1475
	// do not save in session but in database
1476

    
1477
	if(is_array($secUuid)){
1478
		$secUuid = $secUuid[0];
1479
	}
1480
	if(!$secUuid){
1481
		variable_set('cdm_currentSecRef', null);
1482
	} else {
1483
		$secRef = cdm_ws_get(CDM_WS_REFERENCE, $secUuid);
1484
		if(isset($secRef)){
1485
			variable_set('cdm_currentSecRef', (array)($secRef));
1486
		}
1487
	}
1488

    
1489
}
1490

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

    
1520
/**
1521
 * Check if a taxon is accepted by the current taxonomic tree
1522
 *
1523
 * @param Taxon $taxon
1524
 * @return true if $taxon is accepted, false otherwise
1525
 */
1526

    
1527
function _cdm_dataportal_acceptedByCurrentView($taxon){
1528

    
1529
	//FIXME $current_secref = _cdm_dataportal_currentSecRef_array();
1530
	$defaultTreeUuid = variable_get('cdm_taxonomictree_uuid', false);
1531
	if($taxon->class == "Taxon" && isset($taxon->taxonNodes)){
1532
		foreach($taxon->taxonNodes as $node){
1533
			if($node->taxonomicTree == $defaultTreeUuid) {
1534
				return true;
1535
			}
1536
		}
1537
	}
1538
	return false;
1539
}
1540

    
1541
/**@Deprecated
1542
 *
1543
 */
1544
function compose_url_prameterstr($parameters = array(), $parentPropertyName = false){
1545
	$pstr = '';
1546
	foreach($parameters as $key=>$value){
1547
		if(is_array($value)){
1548

    
1549
		} else {
1550
			$pstr .= ($pstr ? '&' :'').$key.'='.urlencode($value);
1551
		}
1552
	}
1553
	return $pstr;
1554
}
1555

    
1556
function _get_feature_trees(){
1557
	$feature_trees = array();
1558

    
1559
	// set tree that contains all features
1560
	$feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1561

    
1562
	// get features from database
1563
	$persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1564
	if(is_array($persisted_trees)){
1565
		foreach($persisted_trees as $featureTree){
1566

    
1567
			// do not add the DEFAULT_FEATURETREE again
1568
			if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1569
				continue;
1570
			}
1571
			$featureLabels = array();
1572
			foreach ($featureTree->root->children as $featureNode){
1573
				$featureLabels[] = $featureNode->feature->representation_L10n;
1574
			}
1575

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

    
1578
		}
1579
	}
1580
	return $feature_trees;
1581
}
1582

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

    
1592
function get_nameRenderTemplate($renderPath, $nameLink = NULL, $refenceLink = NULL){
1593
	//TODO implement admin user interface to replace swicth statement
1594
	//     preliminar solution: using themes
1595

    
1596
	$template = null;
1597
	// find best matching default RenderTemplate in theme
1598
	//echo "<br/><br/>RENDER PATH:  ".$renderPath;
1599
	//var_dump('RENDER PATH: ' . $renderPath);
1600
	while(!is_array($template) && strlen($renderPath) > 0){
1601
	   $template = theme('get_nameRenderTemplate', $renderPath);
1602
	   $renderPath = substr($renderPath, 0, strrpos($renderPath, '.'));
1603
//	   if(!is_array($template)){
1604
//	       echo "<br/>->".$renderPath;
1605
//	   }
1606
	}
1607
	
1608
	// otherwise get default RenderTemplate from theme 
1609
	if(!is_array($template)){
1610
	   $template = theme('get_nameRenderTemplate', '#DEFAULT');
1611
	}
1612
	// otherwise get system default RenderTemplate
1613
	if(!is_array($template)){
1614
		switch($renderPath){
1615
			case 'list_of_taxa':
1616
			case  'acceptedFor':
1617
			case 'taxon_page_synonymy':
1618
			case 'typedesignations':
1619
			case 'taxon_page_title':
1620
			case 'na': $template = array(
1621
			        'namePart' => array('#uri'=>true),
1622
			        //'authorshipPart' => true,
1623
				);
1624
				break;
1625
			case 'nar': $template = array(
1626
		          	'namePart' => array('#uri'=>true),
1627
					 //'authorshipPart' => true,
1628
		          	'referencePart' => array('#uri'=>true),
1629
		          	'microreferencePart' => true,
1630
				);
1631
				break;
1632
			default: $template = array(
1633
          'namePart' => array('#uri'=>true),
1634
          'authorshipPart' => true,
1635
          'referencePart' => array('#uri'=>true),
1636
          'microreferencePart' => true,
1637
          'statusPart' => true,
1638
          'descriptionPart' => true
1639
			);
1640
		}
1641
	}
1642

    
1643
	if($nameLink && isset($template['nameAuthorPart']['#uri'])){
1644
		$template['nameAuthorPart']['#uri'] = $nameLink;
1645
	} else{
1646
		unset($template['nameAuthorPart']['#uri']);
1647
	}
1648

    
1649
	if($nameLink && isset($template['namePart']['#uri'])){
1650
		$template['namePart']['#uri'] = $nameLink;
1651
	} else{
1652
		unset($template['namePart']['#uri']);
1653
	}
1654

    
1655
	if($refenceLink && isset($template['referencePart']['#uri'])){
1656
		$template['referencePart']['#uri'] = $refenceLink;
1657
	}else{
1658
		unset($template['referencePart']['#uri']);
1659
	}
1660
	
1661
	return $template;
1662
}
1663

    
1664
function get_partDefinition($taxonNameType){
1665
	//TODO implement admin user interface to allow specify the partdefinitions for any type
1666
	//     preliminar solution: using themes
1667

    
1668
	$partdef = theme('get_partDefinition', $taxonNameType);
1669

    
1670
	if(!is_array($partdef)){
1671
		switch($taxonNameType){
1672
			case 'ZoologicalName': $partdef = array(
1673
        'namePart' => array(
1674
          'name' => true,
1675
			),
1676
        'referencePart' => array(
1677
          'authorTeam' => true
1678
			),
1679
        'microreferencePart' => array(
1680
          'microreference' => true,
1681
			),
1682
        'statusPart' => array(
1683
          'status' => true,
1684
			),
1685
        'descriptionPart' => array(
1686
          'description' => true,
1687
			),
1688
			);
1689
			break;
1690
			case 'BotanicalName': $partdef = array(
1691
        'namePart' => array(
1692
          'name' => true
1693
			),
1694
        'authorTeamPart' => array(
1695
          'authorTeam' => true,   
1696
			),
1697
        'referencePart' => array(
1698
          'reference' => true      
1699
			),
1700
        'microreferencePart' => array(
1701
          'microreference' => true,
1702
			),
1703
        'statusPart' => array(
1704
          'status' => true,
1705
			),
1706
        'descriptionPart' => array(
1707
          'description' => true,
1708
			),
1709
			);
1710
			break;
1711
			default: $partdef = array(
1712
        'namePart' => array(
1713
          'name' => true,
1714
			),
1715
        'authorTeamPart' => array(
1716
          'authorTeam' => true,   
1717
			),
1718
        'referencePart' => array(
1719
          'reference' => true      
1720
			),
1721
        'microreferencePart' => array(
1722
          'microreference' => true,
1723
			),
1724
        'statusPart' => array(
1725
          'status' => true,
1726
			),
1727
        'descriptionPart' => array(
1728
          'description' => true,
1729
			),
1730
			);
1731
		}
1732
	}
1733
	return $partdef;
1734
}
1735

    
1736
/**
1737
 * The function read the metadata info such title or artist of a media file. The
1738
 * function tries at first to get all the info from the file metadata and if it is
1739
 * not avaible look at the media file info stored at the database.
1740
 * @param $media The media file
1741
 * @return array The array with the avilable specified metadata info.
1742
 * TODO rename to read_media_metadata() and move to *.module
1743
 */
1744
function cdm_read_media_metadata($media){
1745

    
1746
	$metadata_caption = array('title' => '',           //media_metadata and media
1747
                              'artist' => '',          //media_metadata and media
1748
                              'rights',                //media_metadata and media
1749
                              'location',              //media_metadata
1750
                              'filename' => '',        //media
1751
                              'mediacreated' => '',    //media
1752
                              'description' => '');    //media
1753

    
1754
	//getting the media metadata
1755
	$media_metadata = cdm_ws_get(CDM_WS_MEDIA_METADATA, array($media->uuid));
1756

    
1757
	//title
1758
	//if ($media_metadata->Headline) {
1759
	if ($media_metadata->ObjectName) {
1760
		$metadata_caption['title'] = $media_metadata->ObjectName;
1761
		//	} else if ($media->titleCache){
1762
		//		$metadata_caption['title'] = $media_metadata->ObjectName;
1763
	} else if ($media->titleCache){
1764
		$metadata_caption['title'] = $media->titleCache;
1765
		if ($media->description_L10n)
1766
		$metadata_caption['title'] .= ' - ' . $media->description_L10n;
1767
	}else{ //if there is no title on the db and metadata get file title
1768
    $aux = $media->representations[0]->parts[0]->uri;
1769
    $aux = explode("/", $aux);
1770
    $aux = end($aux);
1771
		$metadata_caption['title'] = $aux;		
1772
	}
1773

    
1774
	//artist
1775
	if ($media_metadata->Artist){
1776
	 $metadata_caption['artist'] = ($media_metadata->Artist ? ''.$media_metadata->Artist : '');
1777
	}
1778
	elseif ($media->artist->titleCache){
1779
	 $metadata_caption['artist'] = $media->artist->titleCache;
1780
	}
1781
	
1782
	//copyright
1783
	$metadata_caption['rights'] = array('copyright' => array('agentNames' => array()),
1784
                                      'license' => array('agentNames' => array(), 'types' => array(), 'abbreviatedTexts' => array(), 'uris' => array()));
1785
	if ($media_metadata->Copyright)
1786
	$metadata_caption['rights']['copyright']['agentNames'][] = $media_metadata->Copyright;
1787
	elseif ($media->rights){
1788
		foreach($media->rights as $right){
1789
			switch($right->term->uuid){
1790
				case UUID_RIGHTS_LICENCE:
1791
					$metadata_caption['rights']['license']['agentNames'][] = ($right->agent ? ''.$right->agent->firstname.' '.$right->agent->lastname : '');
1792
					$metadata_caption['rights']['license']['types'][] = ($right->representation_L10n ? ''.$right->representation_L10n : '');
1793
					$metadata_caption['rights']['license']['abbreviatedTexts'][] = ($right->abbreviatedText ? ''.$right->abbreviatedText : '');
1794
					$metadata_caption['rights']['license']['uris'][] = ($right->uri ? ''.$right->uri : '');
1795
					break;
1796
				case UUID_RIGHTS_COPYRIGHT:
1797
					$metadata_caption['rights']['copyright']['agentNames'][] = $right->agent->firstname . ' ' . $right->agent->lastname;
1798
					break;
1799
			}
1800
		}
1801
	}
1802
	else
1803
	$metadata_caption['rights']['agentNames'][] = '';
1804

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

    
1808
	//location
1809
	$metadata_caption['location'] = array();
1810
	$metadata_caption['location']['sublocation'] = $media_metadata->Sublocation;
1811
	$metadata_caption['location']['city'] = $media_metadata->City;
1812
	$metadata_caption['location']['province'] = $media_metadata->Province;
1813
	$metadata_caption['location']['country'] = $media_metadata->Country;
1814

    
1815
	//filename
1816
	if(isset($media->representations[0]->parts[0]->uri)){
1817
		$fileUri = $media->representations[0]->parts[0]->uri;
1818
		$filename = substr($fileUri, strrpos($fileUri, "/")+1);
1819
		$metadata_caption['filename'] = $filename;
1820
	}
1821
	else{
1822
	 $metadata_caption['filename'] = '';
1823
	}
1824
	/*
1825
	 //creation date
1826
	 if($media_metadata["Modify Date"])
1827
	 $metadata_caption['mediacreated'] = $media_metadata["Modify Date"];
1828
	 else
1829
	 $metadata_caption['mediacreated'] = $media->created;
1830
	 */
1831
	//returned value
1832
	return $metadata_caption;
1833
}
1834

    
1835
/**
1836
 * This function collects all the media from a list of description elements
1837
 * and return them as an Array.
1838
 *
1839
 * @param $descriptionElementes The description elements
1840
 * @return Array The output with all the media
1841
 */
1842
function cdm_dataportal_media_from_descriptionElements($descriptionElements){
1843
	//variables
1844
	$outArrayOfMedia = array(); //return value
1845
	//implementation
1846
	foreach($descriptionElements as $descriptionElement){
1847
		foreach($descriptionElement->media as $media){
1848
			if(isset($media)){
1849
			 $outArrayOfMedia[] = $media;
1850
			}
1851
	 }
1852
	}
1853
	return $outArrayOfMedia;
1854
}
1855

    
1856

    
(6-6/10)