Project

General

Profile

Download (38.2 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
/**
25
 * Implementation of hook_requirements()
26
 */
27
function cdm_api_requirements() {
28

    
29
  $requirements['cdm_api'] = array(
30
    'title' => t('CDM API')
31
  );
32

    
33
  if( function_exists('curl_init') ){
34
    $requirements['cdm_api']['description'] = ''; // description below title is not jet in use
35
    $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';
36
  } else {
37
    $requirements['cdm_api']['value'] =  'CURL php extension is missing. If CURL lib is installed HTTP requests will be up to 20x faster';
38
  }
39

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

    
43
  return $requirements;
44
}
45

    
46

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

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

    
69
  }
70

    
71
  return $items;
72
}
73

    
74

    
75
/**
76
 * Implementation of hook_cron().
77
 *
78
 * Expire outdated cache entries
79
 */
80
function cdm_api_cron() {
81
  cache_clear_all(NULL, 'cache_cdm_ws');
82
}
83

    
84
function cdm_api_perm() {
85
  return array(
86
      'administer cdm_api'
87
      );
88
}
89

    
90
// ----------------------------------------------------------- //
91

    
92

    
93
/**
94
 * Converts an array of TagedText items into a sequence of corresponding html tags whereas
95
 * each item will provided with a class attribute which set to the key of the TaggedText item.
96
 *
97
 * @param array $taggedtxt
98
 * @param String $tag
99
 * @param String $glue the string by which the chained text tokens are concatenated together.
100
 *       Default is a blank character
101
 * @return String of HTML
102
 */
103
function cdm_taggedtext2html(array &$taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()){
104
  $out = '';
105
  $i = 0;
106
  foreach($taggedtxt as $tt){
107
    if(!in_array($tt->type, $skiptags) && strlen($tt->text) > 0){
108
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt)? $glue : '').'<'.$tag.' class="'.$tt->type.'">'.t($tt->text).'</'.$tag.'>';
109
    }
110
  }
111
  return $out;
112
}
113

    
114
/**
115
 * Finds the text tagged with $tag_type in an array of taggedText instances
116
 *
117
 * @param array $taggedtxt
118
 * @param string $tag_type
119
 * @return an array with the texts mapped by $tag_type
120
 */
121
function cdm_taggedtext_values(array &$taggedtxt = array(), $tag_type){
122
  $tokens = array();
123
  foreach($taggedtxt as $tagtxt){
124
    if($tagtxt->type == $tag_type)
125
    $tokens[] = $tagtxt->text;
126
  }
127
  return $tokens;
128
}
129

    
130
/**
131
 * Returns the currently classification tree in use
132
 */
133
function get_taxonomictree_uuid_selected(){
134
  if(is_uuid($_SESSION['cdm']['taxonomictree_uuid']) ){
135
    return $_SESSION['cdm']['taxonomictree_uuid'];
136
  } else {
137
    return variable_get(CDM_TAXONOMICTREE_UUID, false);
138
  }
139
}
140

    
141
function switch_to_taxonomictree_uuid($taxonomictree_uuid){
142
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
143
}
144

    
145
function reset_taxonomictree_uuid($taxonomictree_uuid){
146
  unset($_SESSION['cdm']['taxonomictree_uuid']);
147
}
148

    
149
function set_last_taxon_page_tab($taxonPageTab){
150
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
151
}
152

    
153
function get_last_taxon_page_tab(){
154
  if(isset($_SESSION['cdm']['taxon_page_tab'])){
155
    return $_SESSION['cdm']['taxon_page_tab'];
156
  } else {
157
    return false;
158
  }
159
}
160

    
161

    
162
/**
163
 * media Array [4]
164
 *   representations Array [3]
165
 *       mimeType  image/jpeg
166
 *       representationParts Array [1]
167
 *           duration  0
168
 *           heigth  0
169
 *           size  0
170
 *           uri http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
171
 *           uuid  15c687f1-f79d-4b79-992f-7ba0f55e610b
172
 *           width 0
173
 *       suffix  jpg
174
 *       uuid  930b7d51-e7b6-4350-b21e-8124b14fe29b
175
 *   title
176
 *   uuid  17e514f1-7a8e-4daa-87ea-8f13f8742cf9
177
 *
178
 * @param unknown_type $media
179
 * @param array $mimeTypes
180
 * @param unknown_type $width
181
 * @param unknown_type $height
182
 * @return unknown
183
 */
184
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300){
185

    
186
  $prefRepr = array();
187
  if(!isset($media->representations[0])){
188
    return $prefRepr;
189
  }
190

    
191
  while(count($mimeTypes) > 0){
192
    // getRepresentationByMimeType
193
    $mimeType = array_shift($mimeTypes);
194

    
195
    foreach($media->representations as &$representation){
196

    
197
      //if the mimetype is not known, try inferring it
198
      if(!$representation->mimeType){
199
        if(isset($representation->parts[0])){
200
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
201
        }
202
      }
203

    
204
      if($representation->mimeType == $mimeType){
205
        // preffered mimetype found -> erase all remaining mimetypes to end loop
206
        $mimeTypes = array();
207
        $dwa = 0;
208
        // look for part with the best matching size
209
        foreach($representation->parts as $part){
210
          $dw = $part->width * $part->height - $height * $width;
211
          if($dw < 0){
212
            $dw *= -1;
213
          }
214
          $dwa+= $dw;
215
        }
216
        $dwa = (count($representation->parts)>0) ? $dwa / count($representation->parts) : 0;
217
        $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
218
      }
219

    
220
    }
221

    
222
  }
223
  // sort
224
  krsort($prefRepr);
225
  // return
226
  return $prefRepr;
227
}
228

    
229
/**
230
 * Infers the mime type of a file using the filename extension.
231
 * @param $filepath the path to the respective file.
232
 *        The filename extension will be used to infer the mime type.
233
 * @return the mimetype to the file or false if the according mime type could not be found
234
 */
235
function infer_mime_type($filepath){
236
  static $mimemap = null;
237
  if(!$mimemap){
238
    $mimemap = array(
239
      'jpg'=>'image/jpeg',
240
      'jpeg'=>'image/jpeg',
241
      'png'=>'image/png',
242
      'gif'=>'image/gif',
243
      'giff'=>'image/gif',
244
      'tif'=>'image/tif',
245
      'tiff'=>'image/tif',
246
      'pdf'=>'application/pdf',
247
      'html'=>'text/html',
248
      'htm'=>'text/html'
249
    );
250
  }
251
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
252
  if(isset($mimemap[$extension])){
253
    return $mimemap[$extension];
254
  } else {
255
    return 'text/html'; //FIXME remove this hack just return false;
256
  }
257
}
258

    
259
/**
260
 * expects an ISO 8601 time representations of a org.joda.time.Partial
261
 * of the form yyyy-MM-dd and returns the year as String.
262
 * In case the year is unknown (= ????) null is returned.
263
 *
264
 * @param ISO 8601 time representations of a org.joda.time.Partial
265
 * @return String
266
 */
267
function partialToYear($partial){
268
  if(is_string($partial)){
269
    $year = substr($partial, 0, 4);
270
    if($year != '??'){
271
      return $year;
272
    }
273
  }
274
  return;
275
}
276
/**
277
 * expects an ISO 8601 time representations of a org.joda.time.Partial
278
 * of the form yyyy-MM-dd and returns the month as String.
279
 * In case the month is unknown (= ???) null is returned.
280
 *
281
 * @param ISO 8601 time representations of a org.joda.time.Partial
282
 * @return String
283
 */
284
function partialToMonth($partial){
285
  if(is_string($partial)){
286
    $month = substr($partial, 5, 2);
287
    if($month != '??'){
288
      return $month;
289
    }
290
  }
291
  return;
292
}
293
/**
294
 * expects an ISO 8601 time representations of a org.joda.time.Partial
295
 * of the form yyyy-MM-dd and returns the day as String.
296
 * In case the day is unknown (= ???) null is returned.
297
 *
298
 * @param ISO 8601 time representations of a org.joda.time.Partial
299
 * @return String
300
 */
301
function partialToDay($partial){
302
  if(is_string($partial)){
303
    $day = substr($partial, 7, 2);
304
    if($day != '??'){
305
      return $day;
306
    }
307
  }
308
  return;
309
}
310

    
311
/**
312
 *
313
 * @param $uri_pattern
314
 * @param $pathParameters an array of path elements, or a single element
315
 * @param $query  A query string to append to the URL.
316
 * @return unknown_type
317
 */
318
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL ){
319

    
320
  if(!isset($pathParameters)){
321
    $pathParameters = array();
322
  }
323

    
324
  $request_params = '';
325
  $path_params = '';
326

    
327
  /* (1)
328
   * substitute all place holders ($0, $1, ..) in the
329
   * $uri_pattern by the according element of the $pathParameters array
330
   */
331
  static $helperArray = array();
332
  if($pathParameters && !is_array($pathParameters)){
333
    $helperArray[0] = $pathParameters;
334
    $pathParameters = $helperArray;
335
  }
336

    
337
  $i = 0;
338
  while(strpos($uri_pattern, "$".$i) !== FALSE){
339
    if(count($pathParameters) <= $i){
340
      //if(drupal_check_module("user") && user_access('administer')){
341
    	if(true){
342
        drupal_set_message('cdm_compose_url(): missing pathParameters', 'debug');
343
      }
344
      break;
345
    }
346
    $uri_pattern = str_replace("$".$i, rawurlencode($pathParameters[$i]), $uri_pattern);
347
    ++$i;
348
  }
349

    
350
  /* (2)
351
   * Append all remaining element of the $pathParameters array as path elements
352
   */
353
  if(count($pathParameters) > $i){
354
    // strip trailing slashes
355
    if(strrchr($uri_pattern, '/') == strlen($uri_pattern)){
356
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
357
    }
358
    while(count($pathParameters) > $i){
359
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
360
      ++$i;
361
    }
362
  }
363

    
364
  /* (3)
365
   * Append the query string supplied by $query
366
   */
367
  if (isset($query)) {
368
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
369
  }
370

    
371
  $path = $ws_name.$uri_pattern;
372

    
373
  $uri = variable_get('cdm_webservice_url', '').$path;
374
  return $uri;
375
}
376

    
377

    
378
function proxy_content($uri, $theme = null){
379

    
380
  $args = func_get_args();
381

    
382
  $uriEncoded = array_shift($args);
383
  $uri = urldecode($uriEncoded);
384
  $theme = array_shift($args);
385

    
386
  // find and deserialize arrays
387
    foreach($args as &$arg){
388
      if( strpos($arg, "a:") === 0){ //FIXME use regex to find serialized arrays
389
        $arg = unserialize($arg);
390
      }
391
      //find comma sepatated string in all args
392
//  	if(strpos($arg, ',')){
393
//  		$arg = explode(',', $arg);
394
//  	}
395
  }
396

    
397

    
398
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
399

    
400
  if($request_method == "POST"){
401

    
402
    $parameters = $_POST;
403

    
404
    $post_data = array();
405
    foreach ($parameters as $k=>$v)
406
    {
407
      $post_data[] = "$k=".utf8_encode($v);
408
    }
409
    $post_data = implode(',', $post_data);
410

    
411
    // testing
412
    $data = drupal_http_request($uri, "POST", $post_data);
413
    print $data;
414

    
415
  }else if(strpos($theme, '/') > 0){ // must be a mimetype
416
    header('Content-Type: '.$theme);
417
    $data = _http_request_binary($uri);
418
    print $data;
419
    exit;
420
  } else {
421
    // in all other cases perform a simple get request
422
    //TODO reconsider caching logic in this function
423
    if(!$theme){
424
      // print out JSON, the cache cannot be used since it contains objects
425
      $http_response = drupal_http_request($uri);
426
      foreach($http_response->headers as $hname=>$hvalue) {
427
        drupal_set_header($hname . ":" . $hvalue);
428
      }
429
      print $http_response->data;
430
      exit;
431
    } else {
432
      $obj = cdm_ws_get($uri, null, null, null, TRUE);
433
      array_unshift($args, $theme, $obj);
434
      print call_user_func_array('theme', $args);
435
    }
436
  }
437
}
438

    
439
function setvalue_session(){
440

    
441
  if( $_REQUEST['var'] && strlen( $_REQUEST['var']) > 4){
442
    $keys = substr( $_REQUEST['var'], 1, strlen( $_REQUEST['var']) - 2);
443
    $keys = explode('][', $keys);
444
  } else {
445
    return;
446
  }
447
  $val =  $_REQUEST['val'] ?  $_REQUEST['val'] : null;
448

    
449
  // prevent from malicous tags
450
  $val = strip_tags($val);
451

    
452
  $var = &$_SESSION;
453
  $i = 0;
454
  foreach($keys as $key){
455
    $hasMoreKeys = ++$i < count($var);
456
    if($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))){
457
      $var[$key] = array();
458
    }
459
    $var = &$var[$key];
460
  }
461
  $var = $val;
462
  drupal_goto($_REQUEST['destination']);
463
}
464

    
465
function uri_uriByProxy($uri, $theme = false){
466
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
467
  return url('cdm_api/proxy/'.urlencode($uri).($theme?"/$theme":''));
468
}
469

    
470
function cdm_compose_annotations_url($cdmBase){
471

    
472
    if(!$cdmBase->uuid){
473
        return;
474
    }
475

    
476
    $ws_base_uri = null;
477
    switch($cdmBase->class){
478
        case 'TaxonBase':
479
        case 'Taxon':
480
        case 'Synonym':
481
            $ws_base_uri = CDM_WS_TAXON;
482
            break;
483
        case 'TaxonNameBase':
484
        case 'NonViralName':
485
        case 'BacterialName':
486
        case 'BotanicalName':
487
        case 'CultivarPlantName':
488
        case 'ZoologicalName':
489
        case 'ViralName':
490
            $ws_base_uri = CDM_WS_NAME;
491
            break;
492
        case 'Media':
493
            $ws_base_uri = CDM_WS_MEDIA;
494
            break;
495
        case 'ReferenceBase':
496
            $ws_base_uri = CDM_WS_REFERENCE;
497
            break;
498
        case 'Distribution':
499
        case 'TextData':
500
        case 'TaxonInteraction':
501
        case 'QuantitativeData':
502
        case 'IndividualsAssociation':
503
        case 'Distribution':
504
        case 'CommonTaxonName':
505
        case 'CategoricalData':
506
          $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
507
          break;
508
        case 'PolytomousKey':
509
        case 'MediaKey':
510
        case 'MultiAccessKey':
511
          $ws_base_uri = $cdmBase->class;
512
          $ws_base_uri{0} = strtolower($ws_base_uri{0});
513
          break;
514
        default:  trigger_error('Unsupported CDM Class - no annotations available for ' . $cdmBase->class, E_USER_ERROR);
515
            return;
516
    }
517
    return  cdm_compose_url($ws_base_uri, array($cdmBase->uuid, 'annotations'));
518
}
519

    
520
/**
521
 * Enter description here...
522
 *
523
 * @param String $resourceURI
524
 * @param pageSize
525
 *            the maximum number of entities returned per page (can be null
526
 *            to return all entities in a single page)
527
 * @param pageNumber
528
 *            the number of the page to be returned, the first page has the
529
 *            pageNumber = 1
530
 * @return unknown
531
 */
532
function cdm_ws_page($resourceURI, $pageSize, $pageNumber){
533
  return cdm_ws_get($resourceURI, null, queryString(array("page" => $pageNumber, 'pageSize'=>$pageSize)));
534
}
535

    
536
//function cdm_ws_taxonomy_compose_resourcePath($path = null){
537
//  $viewrank =  _cdm_taxonomy_compose_viewrank();
538
//  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
539
//}
540

    
541

    
542
/**
543
 * Enter description here...
544
 *
545
 * @param unknown_type $secUuid
546
 * @param unknown_type $path
547
 * @return unknown
548
 */
549
function cdm_compose_taxonomy_path($taxonUuid = false){
550

    
551
  $viewUuid = get_taxonomictree_uuid_selected();
552
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
553

    
554
  if($taxonUuid){
555
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array($viewUuid, $taxonUuid));
556
  } else {
557
    if($rankUuid){
558
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array($viewUuid, $rankUuid));
559
    } else {
560
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY, array($viewUuid));
561
    }
562
  }
563
}
564

    
565
function cdm_ws_taxonomy($taxonUuid = null){
566

    
567
    $response = null;
568
    $response = cdm_ws_get(cdm_compose_taxonomy_path($taxonUuid), null, null, null, TRUE);
569

    
570
    if($response == null){
571
      // error handing
572
      if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
573
        // delete the session value and try again with the default
574
        unset($_SESSION['cdm']['taxonomictree_uuid']);
575
        return cdm_ws_taxonomy($taxonUuid);
576
      } else {
577
        // check if taxonomictree_uuid is valid
578
        $test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
579
        if($test == null){
580
          // the default set by the admin seems to be invalid or is not even set
581
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
582
        }
583
      }
584
    }
585

    
586
    return $response;
587
}
588

    
589
/**
590
 * Enter description here...
591
 *
592
 * @param UUID $secUuid
593
 * @param String $path
594
 * @return unknown
595
 */
596
function cdm_ws_taxonomy_pathFromRoot($taxonUuid){
597

    
598
  $viewUuid = get_taxonomictree_uuid_selected();
599
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
600

    
601
  $response = null;
602
  if($rankUuid){
603
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array($viewUuid, $taxonUuid, $rankUuid));
604
  } else {
605
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array($viewUuid, $taxonUuid));
606
  }
607

    
608
  if($response == null){
609
    // error handing
610
    if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
611
      // delete the session value and try again with the default
612
      unset($_SESSION['cdm']['taxonomictree_uuid']);
613
      return cdm_ws_taxonomy_pathFromRoot($taxonUuid);
614
    } else {
615
        // check if taxonomictree_uuid is valid
616
        $test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
617
        if($test == null){
618
          // the default set by the admin seems to be invalid or is not even set
619
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
620
        }
621
    }
622
  }
623

    
624
  return $response;
625
}
626

    
627
function cdm_rankVocabulary_as_option() {
628
  return cdm_Vocabulary_as_option(UUID_RANK);
629
}
630

    
631
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = null){
632
  static $vocabularyOptions;
633

    
634
  if(!$rankVocabularyOptions){
635
    $vocabularyOptions = array();
636
    if(!isset($vocabularyOptions[$vocabularyUuid])){
637
      $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
638
      $vocabularyOptions[$vocabularyUuid] = array();
639
      if($vocab){
640
        foreach($vocab->terms as $term){
641
          if($term_label_callback && function_exists($term_label_callback)){
642
            $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
643
          } else {
644
	        $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
645
          }
646
        }
647
        array_reverse($vocabularyOptions[$vocabularyUuid]);
648
      }
649
    }
650
  }
651
  return $vocabularyOptions[$vocabularyUuid];
652
}
653

    
654
function _cdm_relationship_type_term_label_callback($term){
655
  if(isset($term->representation_L10n_abbreviatedLabel)) {
656
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
657
  } else {
658
    return t($term->representation_L10n);
659
  }
660
}
661

    
662

    
663
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
664

    
665
  if(!$featureTree){
666
    drupal_set_message('No \'FeatureTree\' has been set so far. '
667
    .'In order to see the species profiles of your taxa, please select a \'FeatureTree\' in the '.l('CDM Dataportal Settings', 'admin/settings/cdm_dataportal/layout'), 'warning');
668
    return false;
669
  }
670

    
671
  $mergedTrees = array();
672

    
673
  if($isDescriptionsSeparated){
674
    // merge any description into a sparate feature tree
675
    foreach($descriptions as $desc){
676
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
677

    
678
      $mergedTree = clone $featureTree;
679
      $mergedTree->root->children = $mergedNodes;
680
      $mergedTrees[] = $mergedTree;
681
    }
682
  } else {
683
    // combine all descripions into one feature tree
684
    foreach($descriptions as $desc){
685
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
686
      $featureTree->root->children = $mergedNodes;
687
    }
688
    $mergedTrees[] = $featureTree;
689
  }
690

    
691
  return $mergedTrees;
692
}
693

    
694
/**
695
 * @param $cdmBase
696
 * @return an array or empty
697
 */
698
function cdm_ws_getAnnotationsFor($cdmBase, $includeTypes = false){
699
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
700
    if($annotationUrl){
701
      $annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
702
      if(is_array($annotationPager->records)){
703
        $annotations = array();
704
        foreach($annotationPager->records as $annotation){
705
          if($includeTypes) {
706
            if( (isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, true))
707
              || ($annotation->annotationType === null && in_array('NULL_VALUE', $includeTypes, true))){
708
              $annotations[] = $annotation;
709
            }
710
          }
711
        }
712
        return $annotations;
713
      }
714
    }
715
}
716

    
717
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements){
718

    
719
  foreach($featureNodes as &$node){
720

    
721
    // append corresponding elements to an additional node field: $node->descriptionElements
722
    foreach($descriptionElements as $element) {
723
      if($element->feature->uuid == $node->feature->uuid) {
724
        if(!isset($node->descriptionElements)) {
725
          $node->descriptionElements = array();
726
        }
727
        $node->descriptionElements[] = $element;
728
      }
729
    }
730

    
731
    // recurse into node children
732
    if(is_array($node->children)){
733
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
734
      $node->children = $mergedChildNodes;
735
    }
736

    
737
  }
738
  return $featureNodes;
739
}
740

    
741

    
742
/**
743
 * Send a HTTP GET request to the RESTService and deserializes
744
 * and returns the response as object.
745
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
746
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
747
 *
748
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
749
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
750
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
751
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
752
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
753
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
754
 *
755
 * @param $uri
756
 * @param $pathParameters an array of path parameters
757
 * @param $query  A query string to be appended to the URL.
758
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
759
 * @param $absoluteURI
760
 * @return unknown_type
761
 */
762
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
763

    
764
  static $cacheL1;
765
  if(!isset($cacheL1)){
766
    $cacheL1 = array();
767
  }
768

    
769
  // transform the given uri path or patthern into a proper webservice uri
770
  if(!$absoluteURI){
771
    $uri = cdm_compose_url($uri, $pathParameters, $query);
772
  }
773

    
774
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
775
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
776

    
777
  if(array_key_exists($uri, $cacheL1)){
778
    $cacheL1_obj = $cacheL1[$uri];
779
  }
780
  //print $cacheL1_obj;
781
  $set_cacheL1 = false;
782
  if($is_cdm_ws_uri && !$cacheL1_obj){
783
    $set_cacheL1 = true;
784
  }
785

    
786
  // only cache cdm webservice URIs
787
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
788
  $cacheL2_entry = false;
789

    
790
  if($use_cacheL2){
791
    // try to get object from cacheL2
792
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
793
  }
794

    
795
  if($cacheL1_obj){
796
      //
797
      // The object has been found in the L1 cache
798
      //
799
      $obj = $cacheL1_obj;
800
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
801
        _add_status_message_toggler();
802
        _add_debugMessageStr('Using cacheL1 for: '.$uri);
803
      }
804
    } else if($cacheL2_entry) {
805
      //
806
      // The object has been found in the L2 cache
807
      //
808
      $obj = unserialize($cacheL2_entry->data);
809
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
810
        _add_status_message_toggler();
811
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
812
      }
813
    } else {
814
      //
815
      // Get the object from the webservice and cache it
816
      //
817
      $time_get_start = microtime(true);
818
      // request data from webservice JSON or XML
819
      $datastr = cdm_http_request($uri, $method);
820
      $time_get = microtime(true) - $time_get_start;
821

    
822
      $time_parse_start = microtime(true);
823
      // parse data and create object
824
      $obj = cdm_load_obj($datastr);
825

    
826
      $time_parse = microtime(true) - $time_parse_start;
827
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
828
        if($obj || $datastr == "[]" ){
829
          $success_msg = 'valid';
830
        } else {
831
          $success_msg = 'invalid';
832
        }
833
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
834
      }
835
      if($set_cacheL2) {
836
        // store the object in cacheL2
837
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
838
      }
839

    
840
  }
841
  if($obj){
842
    // store the object in cacheL1
843
    if($set_cacheL1) {
844
      $cacheL1[$uri] = $obj;
845
    }
846
  }
847

    
848
  return $obj;
849
}
850
function _add_debugMessageStr($message){
851
  _add_status_message_toggler();
852
  drupal_set_message($message, 'debug');
853
}
854

    
855
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
856

    
857
  static $cummulated_time_parse;
858
  static $cummulated_time_get;
859
  _add_status_message_toggler();
860

    
861
  $cummulated_time_get += $time_get;
862
  $cummulated_time_parse += $time_parse;
863

    
864
  // decompose uri into path and query element
865
  $uri_parts = explode("?", $uri);
866
  if(count($uri_parts) == 2){
867
    $path = $uri_parts[0];
868
    $query = $uri_parts[1];
869
  } else {
870
    $path = $uri;
871
  }
872

    
873
  $message = '<span class="uri">'.$uri.'</span><br />';
874
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
875
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
876
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
877
  if(_is_cdm_ws_uri($path)){
878
    $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>-';
879
    $message .= '<a href="'.url('cdm_api/proxy/'.urlencode(url($path.'.xml', $query))).'" target="data" class="'.$success_msg.'">proxied</a>,';
880
    $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>-';
881
    $message .= '<a href="'.url('cdm_api/proxy/'.urlencode(url($path.'.json', $query))).'" target="data" class="'.$success_msg.'">proxied</a>';
882
  } else {
883
      $message .= '<a href="'.url($path, $query).'" target="data" class="'.$success_msg.'">open</a>';
884
  }
885
  $message .= '] ';
886
  drupal_set_message($message, 'debug');
887

    
888
}
889

    
890

    
891
function cdm_load_obj($datastr){
892

    
893
  $obj = json_decode($datastr);
894

    
895
  if(!(is_object($obj) || is_array($obj)) ){
896
    ob_start();
897
    $obj_dump = ob_get_contents();
898
    ob_clean();
899
    return false;
900
  }
901

    
902
  return $obj;
903
}
904

    
905
/**
906
 *
907
 * @param $uri
908
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
909
 *        false or any invalid value is supplied.
910
 * @param $parameters
911
 * @param $header
912
 * @return the response data
913
 */
914
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
915

    
916
  static $acceptLanguage = null;
917

    
918
  if(!$acceptLanguage) {
919
    if(function_exists('apache_request_headers')){
920
      $headers = apache_request_headers();
921
      if($headers['Accept-Language']){
922
        $acceptLanguage = $headers['Accept-Language'];
923
      }
924
    }
925
    if( !$acceptLanguage ) {
926
      $acceptLanguage = "en"; // DEFAULT TODO make configurable
927
    }
928
  }
929

    
930
  if($method != "GET" && $method != "POST"){
931
    $method  = "GET";
932
  }
933

    
934
  $header = array();
935
  if(!$header && _is_cdm_ws_uri($uri)){
936
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
937
    $header['Accept-Language'] = $acceptLanguage;
938
    $header['Accept-Charset'] = 'UTF-8';
939
  }
940

    
941
  if(false && function_exists('curl_init')){
942
    // !!!!! CURL Disabled due to problems with forllowing redirects (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
943
    // use the CURL lib if installed it is supposed to be 20x faster
944
    return _http_request_using_curl($uri, $header, $method, $parameters);
945
  } else {
946
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
947
  }
948
}
949

    
950
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
951
 $response = drupal_http_request($uri, $header, $method);
952
 return $response->data;
953
}
954

    
955

    
956
/**
957
 * Return string content from a remote file
958
 *
959
 * @param string $uri
960
 * @return string
961
 *
962
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
963
 */
964
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
965
{
966
  $ch = curl_init();
967

    
968
  curl_setopt ($ch, CURLOPT_URL, $uri);
969
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
970
  curl_setopt ($ch, CURLOPT_MAXREDIRS, 5);
971

    
972
  // set proxy settings
973
  if(variable_get('cdm_webservice_proxy_url', false)){
974
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
975
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
976
    if(variable_get('cdm_webservice_proxy_usr', false)){
977
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
978
    }
979
  }
980

    
981
  // modify headers array to be used by curl
982
  foreach($headers as $header_key=>$header_val){
983
    $curl_headers[] = $header_key.': '.$header_val;
984
  }
985
  if(isset($curl_headers)){
986
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
987
  }
988

    
989
  // set method if not default
990
  if($method != "GET"){
991
    if($method == "POST"){
992

    
993
      curl_setopt ($ch, CURLOPT_POST, 1);
994
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
995

    
996
    }else{
997
      // other obscure http methods get passed to curl directly
998
      // TODO generic parameter/body handling
999
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
1000
    }
1001
  }
1002

    
1003
  ob_start();
1004
  curl_exec($ch);
1005
  $info = curl_getinfo($ch);
1006
  if(curl_errno($ch)){
1007
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
1008
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
1009
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
1010
    }
1011
  }
1012
  curl_close ($ch);
1013
  $string = ob_get_contents();
1014
  ob_end_clean();
1015

    
1016
  return $string;
1017
}
1018

    
1019
function _featureTree_elements_toString($rootNode, $separator = ', '){
1020
  $out = '';
1021
  $featureLabels = array();
1022
  foreach ($rootNode->children as $featureNode){
1023
    $out .= ($out ? $separator : '');
1024
    $out .= $featureNode->feature->representation_L10n;
1025
    if (is_array($featureNode->children)){
1026
      $childlabels = '';
1027
      foreach ($featureNode->children as $childNode)
1028
      $childlabels .= ($childlabels ? $separator : '');
1029
      $childlabels .= _featureTree_elements_toString($childNode);
1030
    }
1031
    if($childlabels){
1032
      $out .= '['.$childlabels.' ]';
1033
    }
1034
  }
1035
  return $out;
1036
}
1037

    
1038
function cdm_get_featureTrees_as_options($addDefaultFeatureTree = false){
1039
    $feature_trees = array();
1040

    
1041
    // set tree that contains all features
1042
    if($addDefaultFeatureTree){
1043
      $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1044
    }
1045

    
1046
    // get features from database
1047
    $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1048
    if(is_array($persisted_trees)){
1049

    
1050
        foreach($persisted_trees as $featureTree){
1051
            // do not add the DEFAULT_FEATURETREE again
1052
            if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1053
                continue;
1054
            }
1055

    
1056
            $treeRepresentation = $featureTree->titleCache;
1057

    
1058
            if(is_array($featureTree->root->children) && count($featureTree->root->children) > 0){
1059

    
1060
              // render the hierarchic tree structure
1061
              $treeDetails = '<div class="featuretree_structure">'
1062
                //._featureTree_elements_toString($featureTree->root)
1063
                .theme('featureTree_hierarchy', $featureTree->uuid)
1064
                .'</div>';
1065

    
1066
              $form = array();
1067
              $form['featureTree-'.$featureTree->uuid] = array(
1068
                  '#type' => 'fieldset',
1069
                  '#title' => t('Show details'),
1070
                  '#collapsible' => TRUE,
1071
                  '#collapsed' => TRUE,
1072
              );
1073
              $form['featureTree-'.$featureTree->uuid]['details'] = array('#value'=>$treeDetails);
1074

    
1075
              $treeRepresentation .= drupal_render($form);
1076
            }
1077

    
1078
            $feature_trees[$featureTree->uuid] = $treeRepresentation;
1079
        }
1080

    
1081
    }
1082
    return $feature_trees;
1083
}
1084

    
1085
function cdm_get_taxontrees_as_options(){
1086
   $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1087
   $taxonomicTreeOptions = array();
1088
   if($taxonTrees){
1089
      foreach($taxonTrees as $tree){
1090
          $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
1091
      }
1092
   }
1093
   return $taxonomicTreeOptions;
1094
}
1095

    
1096

    
1097
function cdm_api_secref_cache_prefetch(&$secUuids){
1098
  global $secref_cache;
1099
  if(!is_array($secref_cache)){
1100
    $secref_cache = array();
1101
  }
1102
  $uniqueUuids = array_unique($secUuids);
1103
  $i = 0;
1104
  $param = '';
1105
  while($i++ < count($uniqueUuids)){
1106
    $param .= $secUuids[$i].',';
1107
    if(strlen($param) + 37 > 2000){
1108
      _cdm_api_secref_cache_add($param);
1109
      $param = '';
1110
    }
1111
  }
1112
  if($param){
1113
    _cdm_api_secref_cache_add($param);
1114
  }
1115
}
1116

    
1117
function cdm_api_secref_cache_get($secUuid){
1118
  global $secref_cache;
1119
  if(!is_array($secref_cache)){
1120
    $secref_cache = array();
1121
  }
1122
  if(!array_key_exists($secUuid, $secref_cache)){
1123
    _cdm_api_secref_cache_add($secUuid);
1124
  }
1125
  return $secref_cache[$secUuid];
1126
}
1127

    
1128
function cdm_api_secref_cache_clear(){
1129
  global $secref_cache;
1130
  $secref_cache = array();
1131
}
1132

    
1133
/**
1134
 * Validates if the given string is a uuid.
1135
 *
1136
 * @param unknown_type $str
1137
 */
1138
function is_uuid($str){
1139
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1140
}
1141

    
1142
/**
1143
 * Checks if the given $object is a valid cdm entity. An object is consirered
1144
 * cdm entity if it has a string field $object->class with at least 3 characters and
1145
 * if it has a valid uuid in $object->uuid.
1146
 *
1147
 * @author a.kohlbecker
1148
 * @param unknown_type $object
1149
 */
1150
function is_cdm_entity($object){
1151
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1152
}
1153

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

    
1168
/**
1169
 * Checks if the given $uri starts with the cdm webservice url stored in the
1170
 * Drupal variable 'cdm_webservice_url'. The 'cdm_webservice_url' can be set in the
1171
 * admins section of the portal.
1172
 *
1173
 * @param $uri the URI to test
1174
 */
1175
function _is_cdm_ws_uri($uri){
1176
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1177
}
1178

    
1179
function queryString($elements) {
1180
  $query = '';
1181
  foreach($elements as $key=>$value){
1182
    if(is_array($value)){
1183
      foreach($value as $v){
1184
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
1185
      }
1186
    } else{
1187
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
1188
    }
1189
  }
1190
  return $query;
1191
}
1192

    
1193
/**
1194
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
1195
 */
1196
function __clone(){
1197
  foreach($this as $name => $value){
1198
    if(gettype($value)=='object' || gettype($value)=='array'){
1199
      $this->$name= clone($this->$name);
1200
    }
1201
  }
1202
}
1203

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

    
1226
/**
1227
 * Implementation of theme_status_messages($display = NULL)
1228
 * @see includes/theme.inc
1229
 *
1230
 * @param $display
1231
 * @return unknown_type
1232
 */
1233
function _add_status_message_toggler() {
1234
  static $isAdded;
1235
  if(!$isAdded){
1236

    
1237
    drupal_add_js(
1238
          '$(document).ready(function(){
1239

    
1240
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
1241
            $(\'.messages_toggler\').click(function(){
1242
              $(this).next().slideToggle(\'fast\');
1243
                return false;
1244
            }).next().hide();
1245

    
1246
          });'
1247
          , 'inline');
1248
          $isAdded = TRUE;
1249
  }
1250
}
1251

    
1252
function _no_classfication_uuid_message(){
1253

    
1254
  if(!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)){
1255
    return t('This DataPortal is not configured properly or the CDM-Sever may be absent.')
1256
      . 'Please check the ' . l(t('CDM web service URL'), 'admin/settings/cdm_dataportal/general')
1257
      . t(', or contact the maintainer of this DataPortal.');
1258
  }
1259

    
1260
  return
1261
  t('This DataPortal is not configured properly.')
1262
      . l(t('Please choose a valid classification'), 'admin/settings/cdm_dataportal/general')
1263
      . t(', or contact the maintainer of this DataPortal.');
1264
}
(4-4/9)