Project

General

Profile

Download (35.6 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(user_access('administer')){
341
        drupal_set_message('cdm_compose_url(): missing pathParameters', 'debug');
342
      }
343
      break;
344
    }
345
    $uri_pattern = str_replace("$".$i, rawurlencode($pathParameters[$i]), $uri_pattern);
346
    ++$i;
347
  }
348

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

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

    
370
  $path = $ws_name.$uri_pattern;
371

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

    
376

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

    
379
  $args = func_get_args();
380

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

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

    
396

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

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

    
401
    $parameters = $_POST;
402

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

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

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

    
435
function setvalue_session(){
436

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

    
445
  // prevent from malicous tags
446
  $val = strip_tags($val);
447

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

    
461
function uri_uriByProxy($uri, $theme = false){
462
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
463
  return url('cdm_api/proxy/'.urlencode($uri).($theme?"/$theme":''));
464
}
465

    
466
function cdm_compose_annotations_url($cdmBase){
467

    
468
    if(!$cdmBase->uuid){
469
        return;
470
    }
471

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

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

    
532
//function cdm_ws_taxonomy_compose_resourcePath($path = null){
533
//  $viewrank =  _cdm_taxonomy_compose_viewrank();
534
//  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
535
//}
536

    
537

    
538
/**
539
 * Enter description here...
540
 *
541
 * @param unknown_type $secUuid
542
 * @param unknown_type $path
543
 * @return unknown
544
 */
545
function cdm_compose_taxonomy_path($taxonUuid = false){
546

    
547
  $viewUuid = get_taxonomictree_uuid_selected();
548
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
549

    
550
  if($taxonUuid){
551
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array($viewUuid, $taxonUuid));
552
  } else {
553
    if($rankUuid){
554
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array($viewUuid, $rankUuid));
555
    } else {
556
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY, array($viewUuid));
557
    }
558
  }
559
}
560

    
561
function cdm_ws_taxonomy($taxonUuid = null){
562

    
563
    $response = null;
564
    $response = cdm_ws_get(cdm_compose_taxonomy_path($taxonUuid), null, null, null, TRUE);
565

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

    
583
    return $response;
584
}
585

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

    
595
  $viewUuid = get_taxonomictree_uuid_selected();
596
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
597

    
598
  $response = null;
599
  if($rankUuid){
600
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array($viewUuid, $taxonUuid, $rankUuid));
601
  } else {
602
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array($viewUuid, $taxonUuid));
603
  }
604

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

    
623
  return $response;
624
}
625

    
626
function cdm_rankVocabulary_as_option(){
627
  global $rankVocabularyOptions;
628
  if(!$rankVocabularyOptions){
629
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, UUID_RANK);
630
    $rankVocabularyOptions = array();
631
    if($vocab){
632
      foreach($vocab->terms as $term){
633
        $rankVocabularyOptions[$term->uuid] = t($term->representation_L10n);
634
      }
635
      array_reverse($rankVocabularyOptions);
636
    }
637
  }
638
  return $rankVocabularyOptions;
639
}
640

    
641

    
642
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
643

    
644
  if(!$featureTree){
645
    drupal_set_message('No \'FeatureTree\' has been set so far. '
646
    .'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');
647
    return false;
648
  }
649

    
650
  $mergedTrees = array();
651

    
652
  if($isDescriptionsSeparated){
653
    // merge any description into a sparate feature tree
654
    foreach($descriptions as $desc){
655
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
656

    
657
      $mergedTree = clone $featureTree;
658
      $mergedTree->root->children = $mergedNodes;
659
      $mergedTrees[] = $mergedTree;
660
    }
661
  } else {
662
    // combine all descripions into one feature tree
663
    foreach($descriptions as $desc){
664
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
665
      $featureTree->root->children = $mergedNodes;
666
    }
667
    $mergedTrees[] = $featureTree;
668
  }
669

    
670
  return $mergedTrees;
671
}
672

    
673
/**
674
 * @param $cdmBase
675
 * @return an array or empty
676
 */
677
function cdm_ws_getAnnotationsFor($cdmBase){
678
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
679
    if($annotationUrl){
680
      $annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
681
      if(is_array($annotationPager->records)){
682
        return $annotationPager->records;
683
      }
684
    }
685
}
686

    
687
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements){
688

    
689
  foreach($featureNodes as &$node){
690

    
691
    // append corresponding elements to an additional node field: $node->descriptionElements
692
    foreach($descriptionElements as $element) {
693
      if($element->feature->uuid == $node->feature->uuid) {
694
        if(!isset($node->descriptionElements)) {
695
          $node->descriptionElements = array();
696
        }
697
        $node->descriptionElements[] = $element;
698
      }
699
    }
700

    
701
    // recurse into node children
702
    if(is_array($node->children)){
703
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
704
      $node->children = $mergedChildNodes;
705
    }
706

    
707
  }
708
  return $featureNodes;
709
}
710

    
711

    
712
/**
713
 * Send a HTTP GET request to the RESTService and deserializes
714
 * and returns the response as object.
715
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
716
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
717
 *
718
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
719
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
720
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
721
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
722
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
723
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
724
 *
725
 * @param $uri
726
 * @param $pathParameters an array of path parameters
727
 * @param $query  A query string to be appended to the URL.
728
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
729
 * @param $absoluteURI
730
 * @return unknown_type
731
 */
732
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
733

    
734
  static $cacheL1;
735
  if(!isset($cacheL1)){
736
    $cacheL1 = array();
737
  }
738

    
739
  // transform the given uri path or patthern into a proper webservice uri
740
  if(!$absoluteURI){
741
    $uri = cdm_compose_url($uri, $pathParameters, $query);
742
  }
743

    
744
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
745
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
746

    
747
  if(array_key_exists($uri, $cacheL1)){
748
    $cacheL1_obj = $cacheL1[$uri];
749
  }
750
  //print $cacheL1_obj;
751
  $set_cacheL1 = false;
752
  if($is_cdm_ws_uri && !$cacheL1_obj){
753
    $set_cacheL1 = true;
754
  }
755

    
756
  // only cache cdm webservice URIs
757
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
758
  $cacheL2_entry = false;
759

    
760
  if($use_cacheL2){
761
    // try to get object from cacheL2
762
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
763
  }
764

    
765
  if($cacheL1_obj){
766
      //
767
      // The object has been found in the L1 cache
768
      //
769
      $obj = $cacheL1_obj;
770
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
771
        _add_status_message_toggler();
772
        _add_debugMessageStr('Using cacheL1 for: '.$uri);
773
      }
774
    } else if($cacheL2_entry) {
775
      //
776
      // The object has been found in the L2 cache
777
      //
778
      $obj = unserialize($cacheL2_entry->data);
779
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
780
        _add_status_message_toggler();
781
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
782
      }
783
    } else {
784
      //
785
      // Get the object from the webservice and cache it
786
      //
787
      $time_get_start = microtime(true);
788
      // request data from webservice JSON or XML
789
      $datastr = cdm_http_request($uri, $method);
790
      $time_get = microtime(true) - $time_get_start;
791

    
792
      $time_parse_start = microtime(true);
793
      // parse data and create object
794
      $obj = cdm_load_obj($datastr);
795

    
796
      $time_parse = microtime(true) - $time_parse_start;
797
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
798
        $success_msg = $obj || $datastr == "[]" ? 'valid':'invalid';
799
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
800
      }
801
      if($set_cacheL2) {
802
        // store the object in cacheL2
803
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
804
      }
805

    
806
  }
807
  if($obj){
808
    // store the object in cacheL1
809
    if($set_cacheL1) {
810
      $cacheL1[$uri] = $obj;
811
    }
812
  }
813

    
814
  return $obj;
815
}
816
function _add_debugMessageStr($message){
817
  _add_status_message_toggler();
818
  drupal_set_message($message, 'debug');
819
}
820

    
821
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
822

    
823
  static $cummulated_time_parse;
824
  static $cummulated_time_get;
825
  _add_status_message_toggler();
826

    
827
  $cummulated_time_get += $time_get;
828
  $cummulated_time_parse += $time_parse;
829

    
830
  // decompose uri into path and query element
831
  $uri_parts = explode("?", $uri);
832
  if(count($uri_parts) == 2){
833
    $path = $uri_parts[0];
834
    $query = $uri_parts[1];
835
  } else {
836
    $path = $uri;
837
  }
838

    
839
  $message = '<span class="uri">'.$uri.'</span><br />';
840
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
841
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
842
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
843
  if(_is_cdm_ws_uri($path)){
844
    $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>,';
845
    $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>';
846
  } else {
847
      $message .= '<a href="'.url($path, $query).'" target="data" class="'.$success_msg.'">open</a>';
848
  }
849
  $message .= '] ';
850
  drupal_set_message($message, 'debug');
851

    
852
}
853

    
854

    
855
function cdm_load_obj($datastr){
856

    
857
  $obj = json_decode($datastr);
858

    
859
  if(!(is_object($obj) || is_array($obj)) ){
860
    ob_start();
861
    $obj_dump = ob_get_contents();
862
    ob_clean();
863
    return false;
864
  }
865

    
866
  return $obj;
867
}
868

    
869
/**
870
 *
871
 * @param $uri
872
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
873
 *        false or any invalid value is supplied.
874
 * @param $parameters
875
 * @param $header
876
 * @return the response data
877
 */
878
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
879

    
880
  static $acceptLanguage = null;
881

    
882
  if(!$acceptLanguage) {
883
    if(function_exists('apache_request_headers')){
884
      $headers = apache_request_headers();
885
      if($headers['Accept-Language']){
886
        $acceptLanguage = $headers['Accept-Language'];
887
      }
888
    }
889
    if( !$acceptLanguage ) {
890
      $acceptLanguage = "en"; // DEFAULT TODO make configurable
891
    }
892
  }
893

    
894
  if($method != "GET" && $method != "POST"){
895
    $method  = "GET";
896
  }
897

    
898
  $header = array();
899
  if(!$header && _is_cdm_ws_uri($uri)){
900
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
901
    $header['Accept-Language'] = $acceptLanguage;
902
    $header['Accept-Charset'] = 'UTF-8';
903
  }
904

    
905
  if(false && function_exists('curl_init')){
906
    // !!!!! CURL Disabled due to problems with forllowing redirects (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
907
    // use the CURL lib if installed it is supposed to be 20x faster
908
    return _http_request_using_curl($uri, $header, $method, $parameters);
909
  } else {
910
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
911
  }
912
}
913

    
914
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
915
 $response = drupal_http_request($uri, $header, $method);
916
 return $response->data;
917
}
918

    
919

    
920
/**
921
 * Return string content from a remote file
922
 *
923
 * @param string $uri
924
 * @return string
925
 *
926
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
927
 */
928
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
929
{
930
  $ch = curl_init();
931

    
932
  curl_setopt ($ch, CURLOPT_URL, $uri);
933
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
934
  curl_setopt ($ch, CURLOPT_MAXREDIRS, 5);
935

    
936
  // set proxy settings
937
  if(variable_get('cdm_webservice_proxy_url', false)){
938
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
939
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
940
    if(variable_get('cdm_webservice_proxy_usr', false)){
941
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
942
    }
943
  }
944

    
945
  // modify headers array to be used by curl
946
  foreach($headers as $header_key=>$header_val){
947
    $curl_headers[] = $header_key.': '.$header_val;
948
  }
949
  if(isset($curl_headers)){
950
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
951
  }
952

    
953
  // set method if not default
954
  if($method != "GET"){
955
    if($method == "POST"){
956

    
957
      curl_setopt ($ch, CURLOPT_POST, 1);
958
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
959

    
960
    }else{
961
      // other obscure http methods get passed to curl directly
962
      // TODO generic parameter/body handling
963
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
964
    }
965
  }
966

    
967
  ob_start();
968
  curl_exec($ch);
969
  $info = curl_getinfo($ch);
970
  if(curl_errno($ch)){
971
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
972
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
973
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
974
    }
975
  }
976
  curl_close ($ch);
977
  $string = ob_get_contents();
978
  ob_end_clean();
979

    
980
  return $string;
981
}
982

    
983
function _featureTree_elements_toString($rootNode, $separator = ', '){
984
  $out = '';
985
  $featureLabels = array();
986
  foreach ($rootNode->children as $featureNode){
987
    $out .= ($out ? $separator : '');
988
    $out .= $featureNode->feature->representation_L10n;
989
    if (is_array($featureNode->children)){
990
      $childlabels = '';
991
      foreach ($featureNode->children as $childNode)
992
      $childlabels .= ($childlabels ? $separator : '');
993
      $childlabels .= _featureTree_elements_toString($childNode);
994
    }
995
    if($childlabels){
996
      $out .= '['.$childlabels.' ]';
997
    }
998
  }
999
  return $out;
1000
}
1001

    
1002
function cdm_get_featureTrees_as_options($addDefaultFeatureTree = false){
1003
    $feature_trees = array();
1004

    
1005
    // set tree that contains all features
1006
    if($addDefaultFeatureTree){
1007
      $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1008
    }
1009

    
1010
    // get features from database
1011
    $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1012
    if(is_array($persisted_trees)){
1013

    
1014
        foreach($persisted_trees as $featureTree){
1015
            // do not add the DEFAULT_FEATURETREE again
1016
            if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1017
                continue;
1018
            }
1019

    
1020
            $treeRepresentation = $featureTree->titleCache;
1021

    
1022
            if(is_array($featureTree->root->children) && count($featureTree->root->children) > 0){
1023

    
1024
              // render the hierarchic tree structure
1025
              $treeDetails = '<div class="featuretree_structure">'
1026
                //._featureTree_elements_toString($featureTree->root)
1027
                .theme('featureTree_hierarchy', $featureTree->uuid)
1028
                .'</div>';
1029

    
1030
              $form = array();
1031
              $form['featureTree-'.$featureTree->uuid] = array(
1032
                  '#type' => 'fieldset',
1033
                  '#title' => t('Show details'),
1034
                  '#collapsible' => TRUE,
1035
                  '#collapsed' => TRUE,
1036
              );
1037
              $form['featureTree-'.$featureTree->uuid]['details'] = array('#value'=>$treeDetails);
1038

    
1039
              $treeRepresentation .= drupal_render($form);
1040
            }
1041

    
1042
            $feature_trees[$featureTree->uuid] = $treeRepresentation;
1043
        }
1044

    
1045
    }
1046
    return $feature_trees;
1047
}
1048

    
1049
function cdm_get_taxontrees_as_options(){
1050
   $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1051
   $taxonomicTreeOptions = array();
1052
   if($taxonTrees){
1053
      foreach($taxonTrees as $tree){
1054
          $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
1055
      }
1056
   }
1057
   return $taxonomicTreeOptions;
1058
}
1059

    
1060

    
1061
function cdm_api_secref_cache_prefetch(&$secUuids){
1062
  global $secref_cache;
1063
  if(!is_array($secref_cache)){
1064
    $secref_cache = array();
1065
  }
1066
  $uniqueUuids = array_unique($secUuids);
1067
  $i = 0;
1068
  $param = '';
1069
  while($i++ < count($uniqueUuids)){
1070
    $param .= $secUuids[$i].',';
1071
    if(strlen($param) + 37 > 2000){
1072
      _cdm_api_secref_cache_add($param);
1073
      $param = '';
1074
    }
1075
  }
1076
  if($param){
1077
    _cdm_api_secref_cache_add($param);
1078
  }
1079
}
1080

    
1081
function cdm_api_secref_cache_get($secUuid){
1082
  global $secref_cache;
1083
  if(!is_array($secref_cache)){
1084
    $secref_cache = array();
1085
  }
1086
  if(!array_key_exists($secUuid, $secref_cache)){
1087
    _cdm_api_secref_cache_add($secUuid);
1088
  }
1089
  return $secref_cache[$secUuid];
1090
}
1091

    
1092
function cdm_api_secref_cache_clear(){
1093
  global $secref_cache;
1094
  $secref_cache = array();
1095
}
1096

    
1097
function is_uuid($str){
1098
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1099
}
1100

    
1101
function _cdm_api_secref_cache_add($secUuidsStr){
1102
  global $secref_cache;
1103
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1104
  // batch fetching not jet reimplemented thus:
1105
  /*$assocRefSTOs = array();
1106
   if($refSTOs) {
1107
   foreach($refSTOs as $ref){
1108
   $assocRefSTOs[$ref->uuid] = $ref;
1109
   }
1110
   $secref_cache = array_merge($secref_cache, $assocRefSTOs);
1111
   }*/
1112
  $secref_cache[$ref->uuid] = $ref;
1113
}
1114

    
1115
function _is_cdm_ws_uri($uri){
1116
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1117
}
1118

    
1119
function queryString($elements) {
1120
  $query = '';
1121
  foreach($elements as $key=>$value){
1122
    if(is_array($value)){
1123
      foreach($value as $v){
1124
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
1125
      }
1126
    } else{
1127
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
1128
    }
1129
  }
1130
  return $query;
1131
}
1132

    
1133
/**
1134
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
1135
 */
1136
function __clone(){
1137
  foreach($this as $name => $value){
1138
    if(gettype($value)=='object' || gettype($value)=='array'){
1139
      $this->$name= clone($this->$name);
1140
    }
1141
  }
1142
}
1143

    
1144
/**
1145
 * Make a complete deep copy of an array replacing
1146
 * references with deep copies until a certain depth is reached
1147
 * ($maxdepth) whereupon references are copied as-is...
1148
 * [From http://us3.php.net/manual/en/ref.array.php]
1149
 * @param $array
1150
 * @param $copy
1151
 * @param $maxdepth
1152
 * @param $depth
1153
 * @return unknown_type
1154
 */
1155
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
1156
  if($depth > $maxdepth) { $copy = $array; return; }
1157
  if(!is_array($copy)) $copy = array();
1158
  foreach($array as $k => &$v) {
1159
    if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
1160
    } else {
1161
      $copy[$k] = $v;
1162
    }
1163
  }
1164
}
1165

    
1166
/**
1167
 * Implementation of theme_status_messages($display = NULL)
1168
 * @see includes/theme.inc
1169
 *
1170
 * @param $display
1171
 * @return unknown_type
1172
 */
1173
function _add_status_message_toggler() {
1174
  static $isAdded;
1175
  if(!$isAdded){
1176

    
1177
    drupal_add_js(
1178
          '$(document).ready(function(){
1179

    
1180
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
1181
            $(\'.messages_toggler\').click(function(){
1182
              $(this).next().slideToggle(\'fast\');
1183
                return false;
1184
            }).next().hide();
1185

    
1186
          });'
1187
          , 'inline');
1188
          $isAdded = TRUE;
1189
  }
1190
}
1191

    
1192
function _no_classfication_uuid_message(){
1193
  return
1194
  t('This DataPortal is not configured properly.')
1195
      . l(t('Please choose a valid classification'), 'admin/settings/cdm_dataportal/general')
1196
      . t(', or contact the maintainer of this DataPortal.');
1197
}
(4-4/9)