Project

General

Profile

Download (37.9 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
// $Id$
3

    
4
/**
5
 * @file
6
 * Functions which are required or useful when accessing and processing CDM Data Store Webservices
7
 *
8
 * Naming conventions:
9
 * ----------------------
10
 *
11
 *  - all webservice access methods are prefixed with cdm_ws
12
 *
13
 *
14
 * Copyright (C) 2007 EDIT
15
 * European Distributed Institute of Taxonomy
16
 * http://www.e-taxonomy.eu
17
 */
18
require_once ('xml2json.php');
19
require_once ('commons.php');
20
require_once ('uuids.php');
21
require_once ('webservice_uris.php');
22
require_once ('cdm_node.php');
23

    
24
define('DEFAULT_TAXONTREE_RANKLIMIT', '1b11c34c-48a8-4efa-98d5-84f7f66ef43a');//TODO Genus UUID
25
define('CDM_TAXONOMICTREE_UUID', 'cdm_taxonomictree_uuid');
26

    
27

    
28
/**
29
 * Implementation of hook_requirements()
30
 */
31
function cdm_api_requirements() {
32

    
33
  $requirements['cdm_api'] = array(
34
    'title' => t('CDM API')
35
  );
36

    
37
  if( function_exists('curl_init') ){
38
    $requirements['cdm_api']['description'] = ''; // description below title is not jet in use
39
    $requirements['cdm_api']['value'] =  'CURL php extension is available and will be used by the cdm api. HTTP requests thus will be up to 20x faster';
40
  } else {
41
    $requirements['cdm_api']['value'] =  'CURL php extension is missing. If CURL lib is installed HTTP requests will be up to 20x faster';
42
  }
43

    
44
  //FIXME: once _get_content_fsockopen is implemented change  severity to  REQUIREMENT_WARNING,
45
  $requirements['cdm_api']['severity'] =  (function_exists('curl_init') ? REQUIREMENT_OK : REQUIREMENT_INFO);
46

    
47
  return $requirements;
48
}
49

    
50

    
51
/**
52
 * Implementation of hook_menu()
53
 */
54
function cdm_api_menu($may_cache) {
55
  $items = array();
56
  if ($may_cache) {
57
    $items[] = array(
58
    // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
59
      'path' => 'cdm_api/proxy',
60
      'callback' => 'proxy_content',
61
      'access' => true,
62
      'type' => MENU_CALLBACK,
63
    );
64

    
65
    $items[] = array(
66
    // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
67
      'path' => 'cdm_api/setvalue/session',
68
      'callback' => 'setvalue_session',
69
      'access' => true,
70
      'type' => MENU_CALLBACK,
71
    );
72

    
73
  }
74

    
75
  return $items;
76
}
77

    
78
/**
79
 * Configures the settings form for the CDM-API module.
80
 *
81
 * @return Array Drupal settings form
82
 */
83
function cdm_api_settings_form(){
84

    
85
  $form['cdm_webservice'] = array(
86
      '#type' => 'fieldset',
87
      '#title' => t('CDM Web Service'),
88
      '#collapsible' => FALSE,
89
      '#collapsed' => FALSE,
90
  );
91

    
92
  $form['cdm_webservice']['cdm_webservice_url'] =  array(
93
    '#type' => 'textfield',
94
    '#title'         => t('CDM Web Service URL'),
95
    '#description'   => t('The URL of CDM Webservice which delivers the data to be published.'),
96
    '#default_value' => variable_get('cdm_webservice_url', NULL),
97
  );
98

    
99
  $form['cdm_webservice']['taxontree_ranklimit'] =  array(
100
    '#type'          => 'select',
101
    '#title'         => t('Rank of highest displayed taxon'),
102
    '#default_value' => variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT), //before DEFAULT_TAXONTREE_RANKLIMIT_UUID
103
    '#options'       => cdm_rankVocabulary_as_option(),
104
    '#description'   => t('The rank of the highest displayed taxon in the taxontree.'),
105
  );
106

    
107
  $form['cdm_webservice']['cdm_webservice_cache'] =  array(
108
    '#type' => 'checkbox',
109
    '#title'         => t('Enable Caching'),
110
    '#default_value' => variable_get('cdm_webservice_cache', 1),
111
    '#description'   => t('Enable caching of webservice responses on simple requests, '
112
    .'that is requests which only have one parameter generally a UUID or a concatenation of UUIDs')
113
    );
114

    
115
    $form['cdm_webservice']['proxy'] = array(
116
      '#type' => 'fieldset',
117
      '#title' => t('Proxy'),
118
      '#collapsible' => TRUE,
119
      '#collapsed' => TRUE
120
    );
121

    
122
    $form['cdm_webservice']['proxy']['cdm_webservice_proxy_url'] =  array(
123
    '#type' => 'textfield',
124
    '#title'         => t('Proxy URL'),
125
    '#description'   => t('If this proxy url is set the cdm api tries
126
    to connect the web service over the given proxy server.
127
    Otherwise proxy usage is deactivated.'),
128
    '#default_value' => variable_get('cdm_webservice_proxy_url', false),
129
    );
130

    
131
    $form['cdm_webservice']['proxy']['cdm_webservice_proxy_port'] =  array(
132
    '#type' => 'textfield',
133
    '#title'         => t('Proxy Port'),
134
    '#default_value' => variable_get('cdm_webservice_proxy_port', '80'),
135
    );
136

    
137
    $form['cdm_webservice']['proxy']['cdm_webservice_proxy_usr'] =  array(
138
    '#type' => 'textfield',
139
    '#title'         => t('Login'),
140
    '#default_value' => variable_get('cdm_webservice_proxy_usr', false),
141
    );
142

    
143
    $form['cdm_webservice']['proxy']['cdm_webservice_proxy_pwd'] =  array(
144
    '#type' => 'textfield',
145
    '#title'         => t('Password'),
146
    '#default_value' => variable_get('cdm_webservice_proxy_pwd', false),
147
    );
148

    
149
    $form['cdm_webservice']['cdm_webservice_debug'] =  array(
150
    '#type' => 'checkbox',
151
    '#title'         => t('Debug CDM Web Service'),
152
    '#default_value' => variable_get('cdm_webservice_debug', 1),
153
    '#description'   => t('Enable CDM Web Service debugging messages. Only visible for the super administrator or for users having the permission <em>administer cdm_api</em>!')
154
    );
155

    
156
    //TODO: settings are still incomplete, compare with trunk/dataportal/inc/config_default.php.inc
157
    $form['cdm_dataportal'] = array(
158
      '#type' => 'fieldset',
159
      '#title' => t('CDM DataPortal'),
160
      '#collapsible' => FALSE,
161
      '#collapsed' => TRUE,
162
    );
163

    
164
	  $form['cdm_dataportal'][CDM_TAXONOMICTREE_UUID] = array(
165
	    '#type' => 'select',
166
	    '#title'         => t('Available classifications'),
167
	    '#default_value' => variable_get(CDM_TAXONOMICTREE_UUID, false),
168
	    '#options' => cdm_get_taxontrees_as_options(),
169
	    '#description'   => t('Select the default classification to be used.')
170
	  );
171

    
172
    return $form;
173
}
174

    
175
/**
176
 * Implementation of hook_cron().
177
 *
178
 * Expire outdated cache entries
179
 */
180
function cdm_api_cron() {
181
  cache_clear_all(NULL, 'cache_cdm_ws');
182
}
183

    
184
function cdm_api_perm() {
185
  return array(
186
      'administer cdm_api'
187
      );
188
}
189

    
190
// ----------------------------------------------------------- //
191

    
192

    
193
/**
194
 * Converts an array of TagedText items into a sequence of corresponding html tags whereas
195
 * each item will provided with a class attribute which set to the key of the TaggedText item.
196
 *
197
 * @param array $taggedtxt
198
 * @param String $tag
199
 * @param String $glue the string by which the chained text tokens are concatenated together.
200
 *       Default is a blank character
201
 * @return String of HTML
202
 */
203
function cdm_taggedtext2html(array &$taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()){
204
  $out = '';
205
  $i = 0;
206
  foreach($taggedtxt as $tt){
207
    if(!in_array($tt->type, $skiptags) && strlen($tt->text) > 0){
208
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt)? $glue : '').'<'.$tag.' class="'.$tt->type.'">'.t($tt->text).'</'.$tag.'>';
209
    }
210
  }
211
  return $out;
212
}
213

    
214
/**
215
 * Finds the text tagged with $$tag_type in an array of taggedText instances
216
 *
217
 * @param array $taggedtxt
218
 * @param string $tag_type
219
 * @return the text mapped by $tag_type or an empty string
220
 */
221
function cdm_taggedtext_value(array &$taggedtxt = array(), $tag_type){
222
  foreach($taggedtxt as $tagtxt){
223
    if($tagtxt->type == $tag_type)
224
    return $tagtxt->text;
225
  }
226
  return '';
227
}
228

    
229
function get_taxonomictree_uuid_selected(){
230
  if(is_uuid($_SESSION['cdm']['taxonomictree_uuid']) ){
231
    return $_SESSION['cdm']['taxonomictree_uuid'];
232
  } else {
233
    return variable_get(CDM_TAXONOMICTREE_UUID, false);
234
  }
235
}
236

    
237
function switch_to_taxonomictree_uuid($taxonomictree_uuid){
238
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
239
}
240

    
241
function reset_taxonomictree_uuid($taxonomictree_uuid){
242
  unset($_SESSION['cdm']['taxonomictree_uuid']);
243
}
244

    
245
function set_last_taxon_page_tab($taxonPageTab){
246
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
247
}
248

    
249
function get_last_taxon_page_tab(){
250
	if(isset($_SESSION['cdm']['taxon_page_tab'])){
251
    return $_SESSION['cdm']['taxon_page_tab'];
252
	} else {
253
		return false;
254
	}
255
}
256

    
257

    
258
/**
259
 * media Array [4]
260
 *   representations Array [3]
261
 *       mimeType  image/jpeg
262
 *       representationParts Array [1]
263
 *           duration  0
264
 *           heigth  0
265
 *           size  0
266
 *           uri http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
267
 *           uuid  15c687f1-f79d-4b79-992f-7ba0f55e610b
268
 *           width 0
269
 *       suffix  jpg
270
 *       uuid  930b7d51-e7b6-4350-b21e-8124b14fe29b
271
 *   title
272
 *   uuid  17e514f1-7a8e-4daa-87ea-8f13f8742cf9
273
 *
274
 * @param unknown_type $media
275
 * @param array $mimeTypes
276
 * @param unknown_type $width
277
 * @param unknown_type $height
278
 * @return unknown
279
 */
280
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300){
281
  /**
282

    
283
  *
284
  */
285
  $prefRepr = array();
286
  if(!isset($media->representations[0])){
287
    return $prefRepr;
288
  }
289

    
290
  while(count($mimeTypes) > 0){
291
    // getRepresentationByMimeType
292
    $mimeType = array_shift($mimeTypes);
293

    
294
    foreach($media->representations as $representation){
295

    
296
    	//if the mimetype is not known, try inferring it
297
    	if(!$representation->mimeType){
298
    		if(isset($representation->parts[0])){
299
    		  $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
300
    		}
301
    	}
302

    
303
      if($representation->mimeType == $mimeType){
304
        // preffered mimetype found -> erase all remaining mimetypes to end loop
305
        $mimeTypes = array();
306
        $dwa = 0;
307
        // look for part with the best matching size
308
        foreach($representation->parts as $part){
309
          $dw = $part->width * $part->height - $height * $width;
310
          if($dw < 0){
311
            $dw *= -1;
312
          }
313
          $dwa+= $dw;
314
        }
315
        $dwa = (count($representation->parts)>0) ? $dwa / count($representation->parts) : 0;
316
        $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
317
      }
318

    
319
    }
320

    
321
  }
322
  // sort
323
  krsort($prefRepr);
324
  // return
325
  return $prefRepr;
326
}
327

    
328
/**
329
 * Infers the mime type of a file using the filename extension.
330
 * @param $filepath the path to the respective file.
331
 *        The filename extension will be used to infer the mime type.
332
 * @return the mimetype to the file or false if the according mime type could not be found
333
 */
334
function infer_mime_type($filepath){
335
	static $mimemap = null;
336
	if(!$mimemap){
337
		$mimemap = array(
338
			'jpg'=>'image/jpeg',
339
		  'jpeg'=>'image/jpeg',
340
		  'png'=>'image/png',
341
		  'gif'=>'image/gif',
342
		  'giff'=>'image/gif',
343
		  'tif'=>'image/tif',
344
      'tiff'=>'image/tif',
345
		  'pdf'=>'application/pdf',
346
		  'html'=>'text/html',
347
		  'htm'=>'text/html'
348
		);
349
	}
350
	$extension = substr($filepath, strrpos($filepath, '.') + 1);
351
	if(isset($mimemap[$extension])){
352
		return $mimemap[$extension];
353
	} else {
354
		false;
355
	}
356
}
357

    
358
/**
359
 * expects an ISO 8601 time representations of a org.joda.time.Partial
360
 * of the form yyyy-MM-dd and returns the year as String.
361
 * In case the year is unknown (= ????) null is returned.
362
 *
363
 * @param ISO 8601 time representations of a org.joda.time.Partial
364
 * @return String
365
 */
366
function partialToYear($partial){
367
  if(is_string($partial)){
368
    $year = substr($partial, 0, 4);
369
    if($year != '??'){
370
      return $year;
371
    }
372
  }
373
  return;
374
}
375
/**
376
 * expects an ISO 8601 time representations of a org.joda.time.Partial
377
 * of the form yyyy-MM-dd and returns the month as String.
378
 * In case the month is unknown (= ???) null is returned.
379
 *
380
 * @param ISO 8601 time representations of a org.joda.time.Partial
381
 * @return String
382
 */
383
function partialToMonth($partial){
384
  if(is_string($partial)){
385
    $month = substr($partial, 5, 2);
386
    if($month != '??'){
387
      return $month;
388
    }
389
  }
390
  return;
391
}
392
/**
393
 * expects an ISO 8601 time representations of a org.joda.time.Partial
394
 * of the form yyyy-MM-dd and returns the day as String.
395
 * In case the day is unknown (= ???) null is returned.
396
 *
397
 * @param ISO 8601 time representations of a org.joda.time.Partial
398
 * @return String
399
 */
400
function partialToDay($partial){
401
  if(is_string($partial)){
402
    $day = substr($partial, 7, 2);
403
    if($day != '??'){
404
      return $day;
405
    }
406
  }
407
  return;
408
}
409

    
410
/**
411
 *
412
 * @param $uri_pattern
413
 * @param $pathParameters an array of path elements, or a single element
414
 * @param $query  A query string to append to the URL.
415
 * @return unknown_type
416
 */
417
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL ){
418

    
419
  $request_params = '';
420
  $path_params = '';
421

    
422
  /* (1)
423
   * substitute all place holders ($0, $1, ..) in the
424
   * $uri_pattern by the according element of the $pathParameters array
425
   */
426
  static $helperArray = array();
427
  if($pathParameters && !is_array($pathParameters)){
428
    $helperArray[0] = $pathParameters;
429
    $pathParameters = $helperArray;
430
  }
431

    
432
  $i = 0;
433
  while(strpos($uri_pattern, "$".$i) !== FALSE){
434
    if(count($pathParameters) <= $i && user_access('administer')){
435
      drupal_set_message('cdm_compose_url(): missing pathParameters', 'debug');
436
    }
437
    $uri_pattern = str_replace("$".$i, rawurlencode($pathParameters[$i]), $uri_pattern);
438
    ++$i;
439
  }
440

    
441
  /* (2)
442
   * Append all remaining element of the $pathParameters array as path elements
443
   */
444
  if(count($pathParameters) > $i){
445
    // strip trailing slashes
446
    if(strrchr($uri_pattern, '/') == strlen($uri_pattern)){
447
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
448
    }
449
    while(count($pathParameters) > $i){
450
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
451
      ++$i;
452
    }
453
  }
454

    
455
  /* (3)
456
   * Append the query string supplied by $query
457
   */
458
  if (isset($query)) {
459
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
460
  }
461

    
462
  $path = $ws_name.$uri_pattern;
463

    
464
  $uri = variable_get('cdm_webservice_url', '').$path;
465
  return $uri;
466
}
467

    
468

    
469
function proxy_content($uri, $theme = null){
470

    
471
  $args = func_get_args();
472

    
473
  $uriEncoded = array_shift($args);
474
  $uri = urldecode($uriEncoded);
475
  $theme = array_shift($args);
476

    
477
  //find comma sepatated string in all args
478
  foreach($args as &$arg){
479
  	if(strpos($arg, ',')){
480
  		$arg = explode(',', $arg);
481
  	}
482
  }
483

    
484
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
485

    
486
  if($request_method == "POST"){
487

    
488
    $parameters = $_POST;
489

    
490
    $post_data = array();
491
    foreach ($parameters as $k=>$v)
492
    {
493
      $post_data[] = "$k=".utf8_encode($v);
494
    }
495
    $post_data = implode(',', $post_data);
496

    
497
    // testing
498
    $data = cdm_http_request($uri, "POST", $post_data);
499
    print $data;
500

    
501
  }else if(strpos($theme, '/') > 0){ // must be a mimetype
502
    header('Content-Type: '.$theme);
503
    $data = _http_request_binary($uri);
504
    print $data;
505
    exit;
506
  } else {
507
    // in all other cases perform a simple get request
508
    //TODO reconsider caching logic in this function
509
    if(!$theme){
510
      // print out JSON, the cache cannot be used since it contains objects
511
      $data = cdm_http_request($uri);
512
      print $data;
513
      exit;
514
    } else {
515
      $obj = cdm_ws_get($uri, null, null, null, TRUE);
516
      array_unshift($args, $theme, $obj);
517
      print call_user_func_array('theme', $args);
518
    }
519
  }
520
}
521

    
522
function setvalue_session(){
523

    
524
  if( $_REQUEST['var'] && strlen( $_REQUEST['var']) > 4){
525
  	$keys = substr( $_REQUEST['var'], 1, strlen( $_REQUEST['var']) - 2);
526
    $keys = explode('][', $keys);
527
  } else {
528
  	return;
529
  }
530
  $val =  $_REQUEST['val'] ?  $_REQUEST['val'] : null;
531

    
532
  // prevent from malicous tags
533
  $val = strip_tags($val);
534

    
535
  $var = &$_SESSION;
536
  $i = 0;
537
  foreach($keys as $key){
538
    $hasMoreKeys = ++$i < count($var);
539
    if($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))){
540
      $var[$key] = array();
541
    }
542
    $var = &$var[$key];
543
  }
544
  $var = $val;
545
  drupal_goto($_REQUEST['destination']);
546
}
547

    
548
function uri_uriByProxy($uri, $theme = false){
549
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
550
  return url('cdm_api/proxy/'.urlencode($uri).($theme?"/$theme":''));
551
}
552

    
553
function cdm_compose_annotations_url($cdmBase){
554

    
555
    if(!$cdmBase->uuid){
556
        return;
557
    }
558

    
559
	$ws_base_uri = null;
560
    switch($cdmBase->class){
561
        case 'TaxonBase':
562
        case 'Taxon':
563
        case 'Synonym':
564
            $ws_base_uri = CDM_WS_TAXON;
565
            break;
566
        case 'TaxonNameBase':
567
        case 'NonViralName':
568
        case 'BacterialName':
569
        case 'BotanicalName':
570
        case 'CultivarPlantName':
571
        case 'ZoologicalName':
572
        case 'ViralName':
573
            $ws_base_uri = CDM_WS_NAME;
574
            break;
575
        case 'Media':
576
            $ws_base_uri = CDM_WS_MEDIA;
577
            break;
578
        case 'ReferenceBase':
579
            $ws_base_uri = CDM_WS_REFERENCE;
580
            break;
581
        case 'Distribution':
582
        case 'TextData':
583
        case 'TaxonInteraction':
584
        case 'QuantitativeData':
585
        case 'IndividualsAssociation':
586
        case 'Distribution':
587
        case 'CommonTaxonName':
588
        case 'CategoricalData':
589
        	$ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
590
        	break;
591
        default:  trigger_error('Unsupported CDM Class - no annotations available for ' . $cdmBase->class, E_USER_ERROR);
592
            return;
593
    }
594
    return  cdm_compose_url($ws_base_uri, array($cdmBase->uuid, 'annotation'));
595
}
596

    
597
/**
598
 * Enter description here...
599
 *
600
 * @param String $resourceURI
601
 * @param pageSize
602
 *            the maximum number of entities returned per page (can be null
603
 *            to return all entities in a single page)
604
 * @param pageNumber
605
 *            the number of the page to be returned, the first page has the
606
 *            pageNumber = 1
607
 * @return unknown
608
 */
609
function cdm_ws_page($resourceURI, $pageSize, $pageNumber){
610
  return cdm_ws_get($resourceURI, null, queryString(array("page" => $pageNumber, 'pageSize'=>$pageSize)));
611
}
612

    
613
//function cdm_ws_taxonomy_compose_resourcePath($path = null){
614
//  $viewrank =  _cdm_taxonomy_compose_viewrank();
615
//  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
616
//}
617

    
618

    
619
/**
620
 * Enter description here...
621
 *
622
 * @param unknown_type $secUuid
623
 * @param unknown_type $path
624
 * @return unknown
625
 */
626
function cdm_compose_taxonomy_path($taxonUuid = false){
627

    
628
	$viewUuid = get_taxonomictree_uuid_selected();
629
	$rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
630

    
631
	if($taxonUuid){
632
		return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array($viewUuid, $taxonUuid));
633
	} else {
634
		if($rankUuid){
635
			return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array($viewUuid, $rankUuid));
636
		} else {
637
			return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY, array($viewUuid));
638
		}
639
	}
640
}
641

    
642
function cdm_ws_taxonomy($taxonUuid = null){
643

    
644
    $response = null;
645
    $response = cdm_ws_get(cdm_compose_taxonomy_path($taxonUuid), null, null, null, TRUE);
646

    
647
	  if($response == null){
648
	    // error handing
649
	    if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
650
	      // delete the session value and try again with the default
651
	      unset($_SESSION['cdm']['taxonomictree_uuid']);
652
	      return cdm_ws_taxonomy($taxonUuid);
653
	    } else {
654
	    	// check if taxonomictree_uuid is valid
655
	    	$test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
656
        if($test == null){
657
	    	  print ($_SESSION['cdm']['taxonomictree_uuid']);
658
          // the default set by the admin seems to be invalid or is not even set
659
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
660
	    	}
661
	    }
662
	  }
663

    
664
    return $response;
665
}
666

    
667
/**
668
 * Enter description here...
669
 *
670
 * @param UUID $secUuid
671
 * @param String $path
672
 * @return unknown
673
 */
674
function cdm_ws_taxonomy_pathFromRoot($taxonUuid){
675

    
676
  $viewUuid = get_taxonomictree_uuid_selected();
677
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
678

    
679
  $response = null;
680
  if($rankUuid){
681
  	$response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array($viewUuid, $taxonUuid, $rankUuid));
682
  } else {
683
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array($viewUuid, $taxonUuid));
684
  }
685

    
686
  if($response == null){
687
  	// error handing
688
	  if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
689
		  // delete the session value and try again with the default
690
	  	unset($_SESSION['cdm']['taxonomictree_uuid']);
691
	  	return cdm_ws_taxonomy_pathFromRoot($taxonUuid);
692
	  } else {
693
	  	  // check if taxonomictree_uuid is valid
694
        $test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
695
        if($test == null){
696
			  	// the default set by the admin seems to be invalid or is not even set
697
          print ($_SESSION['cdm']['taxonomictree_uuid']);
698
          // the default set by the admin seems to be invalid or is not even set
699
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
700
        }
701
	  }
702
  }
703

    
704
  return $response;
705
}
706

    
707
function cdm_rankVocabulary_as_option(){
708
  global $rankVocabularyOptions;
709
  if(!$rankVocabularyOptions){
710
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, UUID_RANK);
711
    $rankVocabularyOptions = array();
712
    foreach($vocab->terms as $term){
713
      $rankVocabularyOptions[$term->uuid] = t($term->representation_L10n);
714
    }
715
    array_reverse($rankVocabularyOptions);
716
  }
717
  return $rankVocabularyOptions;
718
}
719

    
720

    
721
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
722

    
723
  if(!$featureTree){
724
    drupal_set_message('No \'FeatureTree\' has been set so far. '
725
    .'In order to see the species profiles of your taxa, please select a \'FeatureTree\' in the '.l('CDM Dataportal Settings', 'admin/settings/cdm_dataportal/general'), 'warning');
726
    return false;
727
  }
728

    
729
  $mergedTrees = array();
730

    
731
  if($isDescriptionsSeparated){
732
    // merge any description into a sparate feature tree
733
    foreach($descriptions as $desc){
734
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
735

    
736
      $mergedTree = clone $featureTree;
737
      $mergedTree->root->children = $mergedNodes;
738
      $mergedTrees[] = $mergedTree;
739
    }
740
  } else {
741
    // combine all descripions into one feature tree
742
    foreach($descriptions as $desc){
743
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
744
      $featureTree->root->children = $mergedNodes;
745
    }
746
    $mergedTrees[] = $featureTree;
747
  }
748

    
749
  return $mergedTrees;
750
}
751

    
752
function _mergeFeatureTreeDesciptions($featureNodes, $descriptionElements){
753

    
754
  foreach($featureNodes as &$node){
755

    
756
    // append corresponding elements to an additional node field: $node->descriptionElements
757
    foreach($descriptionElements as $element){
758
      if($element->feature->uuid == $node->feature->uuid){
759
        if(!isset($node->descriptionElements)){
760
          $node->descriptionElements = array();
761
        }
762
        $node->descriptionElements[] = $element;
763
      }
764
    }
765

    
766
    // recurse into node children
767
    if(is_array($node->children)){
768
    	/*
769
    	var_dump('++++++++++++++++++++');
770
    	var_dump($node->children);
771
    	var_dump('####################');
772

    
773
      foreach($node->children as $nodes){
774
        $mergedChildNodes = _mergeFeatureTreeDesciptions($nodes, $descriptionElements);
775
        $node->children = $mergedChildNodes;
776
      }
777
      */
778
    	$mergedChildNodes = _mergeFeatureTreeDesciptions($node->children, $descriptionElements);
779
      $node->children = $mergedChildNodes;
780
    }
781

    
782
  }
783
  return $featureNodes;
784
}
785

    
786

    
787
/**
788
 * Send a HTTP GET request to the RESTService and deserializes
789
 * and returns the response as object.
790
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
791
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
792
 *
793
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
794
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
795
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
796
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
797
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
798
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
799
 *
800
 * @param $uri
801
 * @param $pathParameters an array of path parameters
802
 * @param $query  A query string to be appended to the URL.
803
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
804
 * @param $absoluteURI
805
 * @return unknown_type
806
 */
807
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
808

    
809
  static $cacheL1;
810
  if(!isset($cacheL1)){
811
    $cacheL1 = array();
812
  }
813

    
814
  // transform the given uri path or patthern into a proper webservice uri
815
  if(!$absoluteURI){
816
    $uri = cdm_compose_url($uri, $pathParameters, $query);
817
  }
818

    
819
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
820
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
821

    
822
  $cacheL1_obj = $cacheL1[$uri];
823
  //print $cacheL1_obj;
824
  $set_cacheL1 = false;
825
  if($is_cdm_ws_uri && !$cacheL1_obj){
826
    $set_cacheL1 = true;
827
  }
828

    
829
  // only cache cdm webservice URIs
830
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
831
  $cacheL2_entry = false;
832

    
833
  if($use_cacheL2){
834
    // try to get object from cacheL2
835
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
836
  }
837

    
838
  if($cacheL1_obj){
839
      //
840
      // The object has been found in the L1 cache
841
      //
842
      $obj = $cacheL1_obj;
843
      _add_debugMessageStr('Using cacheL1 for: '.$uri);
844
    } else if($cacheL2_entry) {
845
      //
846
      // The object has been found in the L2 cache
847
      //
848
      $obj = unserialize($cacheL2_entry->data);
849
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
850
        _add_status_message_toggler();
851
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
852
      }
853
    } else {
854
      //
855
      // Get the object from the webservice and cache it
856
      //
857
      $time_get_start = microtime(true);
858
      // request data from webservice JSON or XML
859
      $datastr = cdm_http_request($uri, $method);
860
      $time_get = microtime(true) - $time_get_start;
861

    
862
      $time_parse_start = microtime(true);
863
      // parse data and create object
864
      $obj = cdm_load_obj($datastr);
865

    
866
      $time_parse = microtime(true) - $time_parse_start;
867
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
868
        $success_msg = $obj || $datastr == "[]" ? 'valid':'invalid';
869
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
870
      }
871
      if($set_cacheL2) {
872
        // store the object in cacheL2
873
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
874
      }
875

    
876
  }
877
  if($obj){
878
    // store the object in cacheL1
879
    if($set_cacheL1) {
880
      $cacheL1[$uri] = $obj;
881
    }
882
  }
883

    
884
  return $obj;
885
}
886
function _add_debugMessageStr($msg){
887
  _add_status_message_toggler();
888
  drupal_set_message($message, 'debug');
889

    
890
}
891
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
892

    
893
  static $cummulated_time_parse;
894
  static $cummulated_time_get;
895
  _add_status_message_toggler();
896

    
897
  $cummulated_time_get += $time_get;
898
  $cummulated_time_parse += $time_parse;
899

    
900
  // decompose uri into path and query element
901
  $uri_parts = explode("?", $uri);
902
  if(count($uri_parts) == 2){
903
    $path = $uri_parts[0];
904
    $query = $uri_parts[1];
905
  } else {
906
    $path = $uri;
907
  }
908

    
909
  $message = '<span class="uri">'.$uri.'</span><br />';
910
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
911
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
912
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
913
  if(_is_cdm_ws_uri($path)){
914
	  $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>,';
915
	  $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>';
916
  } else {
917
  	  $message .= '<a href="'.url($path, $query).'" target="data" class="'.$success_msg.'">open</a>';
918
  }
919
  $message .= '] ';
920
  drupal_set_message($message, 'debug');
921

    
922
}
923

    
924

    
925
function cdm_load_obj($datastr){
926

    
927
  // NOTICE: the cdm dataportal currently does not support xml so the line below are commented out
928
  /*
929
   // if the web service delivers XML convert it into json
930
   if(variable_get('cdm_webservice_type', 'json') == 'xml'){
931
   $datastr = xml2json::transformXmlStringToJson($datastr);
932
   }
933
   */
934

    
935
  $obj = json_decode($datastr);
936

    
937
  if(!(is_object($obj) || is_array($obj)) ){
938
    ob_start();
939
    $obj_dump = ob_get_contents();
940
    ob_clean();
941
    return false;
942
  }
943

    
944
  return $obj;
945
}
946

    
947
/**
948
 *
949
 * @param $uri
950
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
951
 *        false or any invalid value is supplied.
952
 * @param $parameters
953
 * @param $header
954
 * @return the response data
955
 */
956
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
957

    
958
  static $acceptLanguage = null;
959

    
960
  if(!$acceptLanguage) {
961
  	$headers = getallheaders();
962
  	if($headers['Accept-Language']){
963
  		$acceptLanguage = $headers['Accept-Language'];
964
  	} else {
965
  		$acceptLanguage = "en"; // DEFAULT TODO make configurable
966
  	}
967
  }
968

    
969
  if($method != "GET" && $method != "POST"){
970
    $method  = "GET";
971
  }
972

    
973
  $header = array();
974
  if(!$header && _is_cdm_ws_uri($uri)){
975
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
976
    $header['Accept-Language'] = $acceptLanguage;
977
    $header['Accept-Charset'] = 'UTF-8';
978
  }
979

    
980
  if(false && function_exists('curl_init')){
981
  	// !!!!! CURL Disabled due to problems with forllowing redirects (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
982
    // use the CURL lib if installed it is supposed to be 20x faster
983
    return _http_request_using_curl($uri, $header, $method, $parameters);
984
  } else {
985
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
986
  }
987
}
988

    
989
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
990
 $response = drupal_http_request($uri, $header, $method);
991
 return $response->data;
992
}
993

    
994

    
995
/**
996
 * Return string content from a remote file
997
 *
998
 * @param string $uri
999
 * @return string
1000
 *
1001
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
1002
 */
1003
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
1004
{
1005
  $ch = curl_init();
1006

    
1007
  curl_setopt ($ch, CURLOPT_URL, $uri);
1008
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
1009
  curl_setopt ($ch, CURLOPT_MAXREDIRS, 5);
1010

    
1011
  // set proxy settings
1012
  if(variable_get('cdm_webservice_proxy_url', false)){
1013
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
1014
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
1015
    if(variable_get('cdm_webservice_proxy_usr', false)){
1016
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
1017
    }
1018
  }
1019

    
1020
  // modify headers array to be used by curl
1021
  foreach($headers as $header_key=>$header_val){
1022
    $curl_headers[] = $header_key.': '.$header_val;
1023
  }
1024
  if(isset($curl_headers)){
1025
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
1026
  }
1027

    
1028
  // set method if not default
1029
  if($method != "GET"){
1030
    if($method == "POST"){
1031

    
1032
      curl_setopt ($ch, CURLOPT_POST, 1);
1033
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
1034

    
1035
    }else{
1036
      // other obscure http methods get passed to curl directly
1037
      // TODO generic parameter/body handling
1038
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
1039
    }
1040
  }
1041

    
1042
  ob_start();
1043
  curl_exec($ch);
1044
  $info = curl_getinfo($ch);
1045
  if(curl_errno($ch)){
1046
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
1047
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
1048
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
1049
    }
1050
  }
1051
  curl_close ($ch);
1052
  $string = ob_get_contents();
1053
  ob_end_clean();
1054

    
1055
  return $string;
1056
}
1057

    
1058
function _featureTree_elements_toString($rootNode, $separator = ', '){
1059
	$out = '';
1060
	$featureLabels = array();
1061
  foreach ($rootNode->children as $featureNode){
1062
  	$out .= ($out ? $separator : '');
1063
    $out .= $featureNode->feature->representation_L10n;
1064
    if (is_array($featureNode->children)){
1065
    	$childlabels = '';
1066
    	foreach ($featureNode->children as $childNode)
1067
    	$childlabels .= ($childlabels ? $separator : '');
1068
    	$childlabels .= _featureTree_elements_toString($childNode);
1069
    }
1070
    if($childlabels){
1071
    	$out .= '['.$childlabels.' ]';
1072
    }
1073
  }
1074
  return $out;
1075
}
1076

    
1077
function cdm_get_featureTrees_as_options($addDefaultFeatureTree = false){
1078
    $feature_trees = array();
1079

    
1080
    // set tree that contains all features
1081
    if($addDefaultFeatureTree){
1082
      $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1083
    }
1084

    
1085
    // get features from database
1086
    $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1087
    if(is_array($persisted_trees)){
1088

    
1089
        foreach($persisted_trees as $featureTree){
1090

    
1091
            // do not add the DEFAULT_FEATURETREE again
1092
            if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1093
                continue;
1094
            }
1095
            $treeRepresentation = $featureTree->titleCache;
1096
            $treeRepresentation .= '<div class="featuretree_structure">'
1097
              ._featureTree_elements_toString($featureTree->root)
1098
              .'</div>';
1099
            $feature_trees[$featureTree->uuid] = $treeRepresentation;
1100
        }
1101

    
1102
    }
1103
    return $feature_trees;
1104
}
1105

    
1106
function cdm_get_taxontrees_as_options(){
1107
   $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1108
    foreach($taxonTrees as $tree){
1109
        $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
1110
    }
1111
    return $taxonomicTreeOptions;
1112
}
1113

    
1114

    
1115
function cdm_api_secref_cache_prefetch(&$secUuids){
1116
  global $secref_cache;
1117
  if(!is_array($secref_cache)){
1118
    $secref_cache = array();
1119
  }
1120
  $uniqueUuids = array_unique($secUuids);
1121
  $i = 0;
1122
  $param = '';
1123
  while($i++ < count($uniqueUuids)){
1124
    $param .= $secUuids[$i].',';
1125
    if(strlen($param) + 37 > 2000){
1126
      _cdm_api_secref_cache_add($param);
1127
      $param = '';
1128
    }
1129
  }
1130
  if($param){
1131
    _cdm_api_secref_cache_add($param);
1132
  }
1133
}
1134

    
1135
function cdm_api_secref_cache_get($secUuid){
1136
  global $secref_cache;
1137
  if(!is_array($secref_cache)){
1138
    $secref_cache = array();
1139
  }
1140
  if(!array_key_exists($secUuid, $secref_cache)){
1141
    _cdm_api_secref_cache_add($secUuid);
1142
  }
1143
  return $secref_cache[$secUuid];
1144
}
1145

    
1146
function cdm_api_secref_cache_clear(){
1147
  global $secref_cache;
1148
  $secref_cache = array();
1149
}
1150

    
1151
function is_uuid($str){
1152
	return isset($str) && strlen($str) == 36 && strpos($str, '-');
1153
}
1154

    
1155
function _cdm_api_secref_cache_add($secUuidsStr){
1156
  global $secref_cache;
1157
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1158
  // batch fetching not jet reimplemented thus:
1159
  /*$assocRefSTOs = array();
1160
   if($refSTOs) {
1161
   foreach($refSTOs as $ref){
1162
   $assocRefSTOs[$ref->uuid] = $ref;
1163
   }
1164
   $secref_cache = array_merge($secref_cache, $assocRefSTOs);
1165
   }*/
1166
  $secref_cache[$ref->uuid] = $ref;
1167
}
1168

    
1169
function _is_cdm_ws_uri($uri){
1170
	return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1171
}
1172

    
1173
function queryString($elements) {
1174
  $query = '';
1175
  foreach($elements as $key=>$value){
1176
    if(is_array($value)){
1177
      foreach($value as $v){
1178
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
1179
      }
1180
    } else{
1181
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
1182
    }
1183
  }
1184
  return $query;
1185
}
1186

    
1187
/**
1188
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
1189
 */
1190
function __clone(){
1191
  foreach($this as $name => $value){
1192
    if(gettype($value)=='object' || gettype($value)=='array'){
1193
      $this->$name= clone($this->$name);
1194
    }
1195
  }
1196
}
1197

    
1198
/**
1199
 * Make a complete deep copy of an array replacing
1200
 * references with deep copies until a certain depth is reached
1201
 * ($maxdepth) whereupon references are copied as-is...
1202
 * [From http://us3.php.net/manual/en/ref.array.php]
1203
 * @param $array
1204
 * @param $copy
1205
 * @param $maxdepth
1206
 * @param $depth
1207
 * @return unknown_type
1208
 */
1209
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
1210
  if($depth > $maxdepth) { $copy = $array; return; }
1211
  if(!is_array($copy)) $copy = array();
1212
  foreach($array as $k => &$v) {
1213
    if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
1214
    } else {
1215
      $copy[$k] = $v;
1216
    }
1217
  }
1218
}
1219

    
1220
/**
1221
 * Implementation of theme_status_messages($display = NULL)
1222
 * @see includes/theme.inc
1223
 *
1224
 * @param $display
1225
 * @return unknown_type
1226
 */
1227
function _add_status_message_toggler() {
1228
  static $isAdded;
1229
  if(!$isAdded){
1230

    
1231
    drupal_add_js(
1232
          '$(document).ready(function(){
1233

    
1234
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
1235
            $(\'.messages_toggler\').click(function(){
1236
              $(this).next().slideToggle(\'fast\');
1237
                return false;
1238
            }).next().hide();
1239

    
1240
          });'
1241
          , 'inline');
1242
          $isAdded = TRUE;
1243
  }
1244
}
1245

    
1246
function _no_classfication_uuid_message(){
1247
	return
1248
	t('This DataPortal is not configured properly.')
1249
      . l(t('Please choose a valid classification'), 'admin/settings/cdm_dataportal/general')
1250
      . t(', or contact the maintainer of this DataPortal.');
1251
}
(4-4/9)