Project

General

Profile

Download (38.7 KB) Statistics
| Branch: | Tag: | Revision:
1 32a96ee6 Andreas Kohlbecker
<?php
2 1e687365 Andreas Kohlbecker
// $Id$
3 32a96ee6 Andreas Kohlbecker
4
/**
5
 * @file
6
 * Functions which are required or useful when accessing and processing CDM Data Store Webservices
7 94112bee n.hoffmann
 *
8 32a96ee6 Andreas Kohlbecker
 * Naming conventions:
9
 * ----------------------
10 94112bee n.hoffmann
 *
11 32a96ee6 Andreas Kohlbecker
 *  - all webservice access methods are prefixed with cdm_ws
12 94112bee n.hoffmann
 *
13 32a96ee6 Andreas Kohlbecker
 *
14
 * Copyright (C) 2007 EDIT
15 94112bee n.hoffmann
 * European Distributed Institute of Taxonomy
16 32a96ee6 Andreas Kohlbecker
 * http://www.e-taxonomy.eu
17
 */
18
require_once ('xml2json.php');
19 9d47d187 Andreas Kohlbecker
require_once ('commons.php');
20 6ee322a7 Andreas Kohlbecker
require_once ('uuids.php');
21 80e0aa8e Andreas Kohlbecker
require_once ('webservice_uris.php');
22 8ff851c6 Andreas Kohlbecker
require_once ('cdm_node.php');
23 ee780c57 Andreas Kohlbecker
24 32a96ee6 Andreas Kohlbecker
/**
25 d96a6e06 Andreas Kohlbecker
 * Implementation of hook_requirements()
26 32a96ee6 Andreas Kohlbecker
 */
27 d96a6e06 Andreas Kohlbecker
function cdm_api_requirements() {
28
29
  $requirements['cdm_api'] = array(
30
    'title' => t('CDM API')
31
  );
32
33
  if( function_exists('curl_init') ){
34 94112bee n.hoffmann
    $requirements['cdm_api']['description'] = ''; // description below title is not jet in use
35 8ff851c6 Andreas Kohlbecker
    $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 d96a6e06 Andreas Kohlbecker
  } else {
37 8ff851c6 Andreas Kohlbecker
    $requirements['cdm_api']['value'] =  'CURL php extension is missing. If CURL lib is installed HTTP requests will be up to 20x faster';
38 d96a6e06 Andreas Kohlbecker
  }
39 67168c2a Andreas Kohlbecker
40 d96a6e06 Andreas Kohlbecker
  //FIXME: once _get_content_fsockopen is implemented change  severity to  REQUIREMENT_WARNING,
41 8ff851c6 Andreas Kohlbecker
  $requirements['cdm_api']['severity'] =  (function_exists('curl_init') ? REQUIREMENT_OK : REQUIREMENT_INFO);
42 67168c2a Andreas Kohlbecker
43 d96a6e06 Andreas Kohlbecker
  return $requirements;
44 32a96ee6 Andreas Kohlbecker
}
45
46 d96a6e06 Andreas Kohlbecker
47 bd6b2769 Andreas Kohlbecker
/**
48 d96a6e06 Andreas Kohlbecker
 * Implementation of hook_menu()
49 bd6b2769 Andreas Kohlbecker
 */
50 d96a6e06 Andreas Kohlbecker
function cdm_api_menu($may_cache) {
51
  $items = array();
52
  if ($may_cache) {
53 5602a381 n.hoffmann
    $items[] = array(
54 67168c2a Andreas Kohlbecker
    // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
55 d96a6e06 Andreas Kohlbecker
      'path' => 'cdm_api/proxy',
56
      'callback' => 'proxy_content',
57
      'access' => true,
58
      'type' => MENU_CALLBACK,
59 5602a381 n.hoffmann
    );
60 67168c2a Andreas Kohlbecker
61 b09e63fd Andreas Kohlbecker
    $items[] = array(
62 67168c2a Andreas Kohlbecker
    // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
63 b09e63fd Andreas Kohlbecker
      'path' => 'cdm_api/setvalue/session',
64
      'callback' => 'setvalue_session',
65
      'access' => true,
66
      'type' => MENU_CALLBACK,
67
    );
68 67168c2a Andreas Kohlbecker
69 bd6b2769 Andreas Kohlbecker
  }
70 67168c2a Andreas Kohlbecker
71 d96a6e06 Andreas Kohlbecker
  return $items;
72 bd6b2769 Andreas Kohlbecker
}
73 d93dad11 n.hoffmann
74 2e748209 Andreas Kohlbecker
75 d96a6e06 Andreas Kohlbecker
/**
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 ba2bca28 Andreas Kohlbecker
function cdm_api_perm() {
85
  return array(
86
      'administer cdm_api'
87 67168c2a Andreas Kohlbecker
      );
88 ba2bca28 Andreas Kohlbecker
}
89
90 d96a6e06 Andreas Kohlbecker
// ----------------------------------------------------------- //
91
92
93
/**
94 94112bee n.hoffmann
 * Converts an array of TagedText items into a sequence of corresponding html tags whereas
95 d96a6e06 Andreas Kohlbecker
 * each item will provided with a class attribute which set to the key of the TaggedText item.
96 94112bee n.hoffmann
 *
97 d96a6e06 Andreas Kohlbecker
 * @param array $taggedtxt
98
 * @param String $tag
99 94112bee n.hoffmann
 * @param String $glue the string by which the chained text tokens are concatenated together.
100 d93dad11 n.hoffmann
 *       Default is a blank character
101 94112bee n.hoffmann
 * @return String of HTML
102 d96a6e06 Andreas Kohlbecker
 */
103 5a688ffe Andreas Kohlbecker
function cdm_taggedtext2html(array &$taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()){
104 67168c2a Andreas Kohlbecker
  $out = '';
105
  $i = 0;
106
  foreach($taggedtxt as $tt){
107
    if(!in_array($tt->type, $skiptags) && strlen($tt->text) > 0){
108 bd4696a1 n.hoffmann
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt)? $glue : '').'<'.$tag.' class="'.$tt->type.'">'.t($tt->text).'</'.$tag.'>';
109 67168c2a Andreas Kohlbecker
    }
110
  }
111
  return $out;
112 d96a6e06 Andreas Kohlbecker
}
113
114
/**
115 e0de338c Andreas Kohlbecker
 * Finds the text tagged with $tag_type in an array of taggedText instances
116 d96a6e06 Andreas Kohlbecker
 *
117
 * @param array $taggedtxt
118
 * @param string $tag_type
119 e0de338c Andreas Kohlbecker
 * @return an array with the texts mapped by $tag_type
120 d96a6e06 Andreas Kohlbecker
 */
121 e0de338c Andreas Kohlbecker
function cdm_taggedtext_values(array &$taggedtxt = array(), $tag_type){
122 f02a533d Andreas Kohlbecker
  $tokens = array();
123 d96a6e06 Andreas Kohlbecker
  foreach($taggedtxt as $tagtxt){
124
    if($tagtxt->type == $tag_type)
125 e0de338c Andreas Kohlbecker
    $tokens[] = $tagtxt->text;
126 d96a6e06 Andreas Kohlbecker
  }
127 e0de338c Andreas Kohlbecker
  return $tokens;
128 d96a6e06 Andreas Kohlbecker
}
129 90f6855c Andreas Kohlbecker
130 f9449d44 f.revilla
/**
131
 * Returns the currently classification tree in use
132
 */
133 90f6855c Andreas Kohlbecker
function get_taxonomictree_uuid_selected(){
134
  if(is_uuid($_SESSION['cdm']['taxonomictree_uuid']) ){
135
    return $_SESSION['cdm']['taxonomictree_uuid'];
136
  } else {
137 39b38137 Andreas Kohlbecker
    return variable_get(CDM_TAXONOMICTREE_UUID, false);
138 90f6855c Andreas Kohlbecker
  }
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 90713556 Andreas Kohlbecker
function set_last_taxon_page_tab($taxonPageTab){
150
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
151
}
152
153
function get_last_taxon_page_tab(){
154 f02a533d Andreas Kohlbecker
  if(isset($_SESSION['cdm']['taxon_page_tab'])){
155 90713556 Andreas Kohlbecker
    return $_SESSION['cdm']['taxon_page_tab'];
156 f02a533d Andreas Kohlbecker
  } else {
157
    return false;
158
  }
159 90713556 Andreas Kohlbecker
}
160
161 d93dad11 n.hoffmann
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 abd0ab13 Andreas Kohlbecker
 * @param unknown_type $media
179 d93dad11 n.hoffmann
 * @param array $mimeTypes
180
 * @param unknown_type $width
181
 * @param unknown_type $height
182
 * @return unknown
183
 */
184 abd0ab13 Andreas Kohlbecker
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300){
185 d93dad11 n.hoffmann
186 1712ae8f Andreas Kohlbecker
  $prefRepr = array();
187 abd0ab13 Andreas Kohlbecker
  if(!isset($media->representations[0])){
188 1712ae8f Andreas Kohlbecker
    return $prefRepr;
189
  }
190 67168c2a Andreas Kohlbecker
191 ac1c4d60 Andreas Kohlbecker
  while(count($mimeTypes) > 0){
192
    // getRepresentationByMimeType
193
    $mimeType = array_shift($mimeTypes);
194 90713556 Andreas Kohlbecker
195 d74aa4df Andreas Kohlbecker
    foreach($media->representations as &$representation){
196 90713556 Andreas Kohlbecker
197 f02a533d Andreas Kohlbecker
      //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 90713556 Andreas Kohlbecker
204 abd0ab13 Andreas Kohlbecker
      if($representation->mimeType == $mimeType){
205 ac1c4d60 Andreas Kohlbecker
        // 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 abd0ab13 Andreas Kohlbecker
        foreach($representation->parts as $part){
210 ac1c4d60 Andreas Kohlbecker
          $dw = $part->width * $part->height - $height * $width;
211
          if($dw < 0){
212
            $dw *= -1;
213
          }
214
          $dwa+= $dw;
215 1712ae8f Andreas Kohlbecker
        }
216 abd0ab13 Andreas Kohlbecker
        $dwa = (count($representation->parts)>0) ? $dwa / count($representation->parts) : 0;
217
        $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
218 1712ae8f Andreas Kohlbecker
      }
219 90713556 Andreas Kohlbecker
220 1712ae8f Andreas Kohlbecker
    }
221 90713556 Andreas Kohlbecker
222 1712ae8f Andreas Kohlbecker
  }
223
  // sort
224
  krsort($prefRepr);
225
  // return
226
  return $prefRepr;
227
}
228
229 94a6630e Andreas Kohlbecker
/**
230
 * Infers the mime type of a file using the filename extension.
231 90713556 Andreas Kohlbecker
 * @param $filepath the path to the respective file.
232 94a6630e Andreas Kohlbecker
 *        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 f02a533d Andreas Kohlbecker
  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 94a6630e Andreas Kohlbecker
      'tiff'=>'image/tif',
246 f02a533d Andreas Kohlbecker
      '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 94a6630e Andreas Kohlbecker
}
258
259 30c5a6bd Andreas Kohlbecker
/**
260 67168c2a Andreas Kohlbecker
 * 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 30c5a6bd Andreas Kohlbecker
 * In case the year is unknown (= ????) null is returned.
263
 *
264 67168c2a Andreas Kohlbecker
 * @param ISO 8601 time representations of a org.joda.time.Partial
265
 * @return String
266 30c5a6bd Andreas Kohlbecker
 */
267
function partialToYear($partial){
268 24b09d7c Andreas Kohlbecker
  if(is_string($partial)){
269 67168c2a Andreas Kohlbecker
    $year = substr($partial, 0, 4);
270 24b09d7c Andreas Kohlbecker
    if($year != '??'){
271
      return $year;
272 67168c2a Andreas Kohlbecker
    }
273 30c5a6bd Andreas Kohlbecker
  }
274 67168c2a Andreas Kohlbecker
  return;
275 30c5a6bd Andreas Kohlbecker
}
276
/**
277 67168c2a Andreas Kohlbecker
 * expects an ISO 8601 time representations of a org.joda.time.Partial
278 30c5a6bd Andreas Kohlbecker
 * of the form yyyy-MM-dd and returns the month as String.
279
 * In case the month is unknown (= ???) null is returned.
280
 *
281 67168c2a Andreas Kohlbecker
 * @param ISO 8601 time representations of a org.joda.time.Partial
282
 * @return String
283 30c5a6bd Andreas Kohlbecker
 */
284
function partialToMonth($partial){
285 24b09d7c Andreas Kohlbecker
  if(is_string($partial)){
286
    $month = substr($partial, 5, 2);
287
    if($month != '??'){
288
      return $month;
289
    }
290 30c5a6bd Andreas Kohlbecker
  }
291 67168c2a Andreas Kohlbecker
  return;
292 30c5a6bd Andreas Kohlbecker
}
293
/**
294 67168c2a Andreas Kohlbecker
 * expects an ISO 8601 time representations of a org.joda.time.Partial
295 30c5a6bd Andreas Kohlbecker
 * of the form yyyy-MM-dd and returns the day as String.
296
 * In case the day is unknown (= ???) null is returned.
297
 *
298 67168c2a Andreas Kohlbecker
 * @param ISO 8601 time representations of a org.joda.time.Partial
299
 * @return String
300 30c5a6bd Andreas Kohlbecker
 */
301
function partialToDay($partial){
302 24b09d7c Andreas Kohlbecker
  if(is_string($partial)){
303
    $day = substr($partial, 7, 2);
304
    if($day != '??'){
305
      return $day;
306
    }
307 30c5a6bd Andreas Kohlbecker
  }
308 24b09d7c Andreas Kohlbecker
  return;
309 30c5a6bd Andreas Kohlbecker
}
310 d96a6e06 Andreas Kohlbecker
311 fa97cd20 Andreas Kohlbecker
/**
312 67168c2a Andreas Kohlbecker
 *
313 24b09d7c Andreas Kohlbecker
 * @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 fa97cd20 Andreas Kohlbecker
 */
318 24b09d7c Andreas Kohlbecker
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL ){
319 67168c2a Andreas Kohlbecker
320 f02a533d Andreas Kohlbecker
  if(!isset($pathParameters)){
321
    $pathParameters = array();
322
  }
323 2264b60d Andreas Kohlbecker
324 cacc1bbf Andreas Kohlbecker
  $request_params = '';
325
  $path_params = '';
326 67168c2a Andreas Kohlbecker
327
  /* (1)
328
   * substitute all place holders ($0, $1, ..) in the
329 24b09d7c Andreas Kohlbecker
   * $uri_pattern by the according element of the $pathParameters array
330
   */
331
  static $helperArray = array();
332 784a4314 Andreas Kohlbecker
  if($pathParameters && !is_array($pathParameters)){
333 24b09d7c Andreas Kohlbecker
    $helperArray[0] = $pathParameters;
334
    $pathParameters = $helperArray;
335
  }
336 67168c2a Andreas Kohlbecker
337 24b09d7c Andreas Kohlbecker
  $i = 0;
338
  while(strpos($uri_pattern, "$".$i) !== FALSE){
339 2264b60d Andreas Kohlbecker
    if(count($pathParameters) <= $i){
340 5d49899e Andreas Kohlbecker
      if(module_exists("user") && user_access('administer')){
341 2264b60d Andreas Kohlbecker
        drupal_set_message('cdm_compose_url(): missing pathParameters', 'debug');
342 f02a533d Andreas Kohlbecker
      }
343 2264b60d Andreas Kohlbecker
      break;
344 24b09d7c Andreas Kohlbecker
    }
345 40184342 Andreas Kohlbecker
    $uri_pattern = str_replace("$".$i, rawurlencode($pathParameters[$i]), $uri_pattern);
346 67168c2a Andreas Kohlbecker
    ++$i;
347 24b09d7c Andreas Kohlbecker
  }
348 67168c2a Andreas Kohlbecker
349 24b09d7c Andreas Kohlbecker
  /* (2)
350
   * Append all remaining element of the $pathParameters array as path elements
351
   */
352
  if(count($pathParameters) > $i){
353
    // strip trailing slashes
354 67168c2a Andreas Kohlbecker
    if(strrchr($uri_pattern, '/') == strlen($uri_pattern)){
355
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
356 24b09d7c Andreas Kohlbecker
    }
357
    while(count($pathParameters) > $i){
358 40184342 Andreas Kohlbecker
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
359 24b09d7c Andreas Kohlbecker
      ++$i;
360 cacc1bbf Andreas Kohlbecker
    }
361 32a96ee6 Andreas Kohlbecker
  }
362 67168c2a Andreas Kohlbecker
363 24b09d7c Andreas Kohlbecker
  /* (3)
364
   * Append the query string supplied by $query
365
   */
366
  if (isset($query)) {
367
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
368 32a96ee6 Andreas Kohlbecker
  }
369 67168c2a Andreas Kohlbecker
370 24b09d7c Andreas Kohlbecker
  $path = $ws_name.$uri_pattern;
371 67168c2a Andreas Kohlbecker
372 24b09d7c Andreas Kohlbecker
  $uri = variable_get('cdm_webservice_url', '').$path;
373
  return $uri;
374 32a96ee6 Andreas Kohlbecker
}
375
376 6ee322a7 Andreas Kohlbecker
377 24b09d7c Andreas Kohlbecker
function proxy_content($uri, $theme = null){
378 67168c2a Andreas Kohlbecker
379 d96a6e06 Andreas Kohlbecker
  $args = func_get_args();
380 67168c2a Andreas Kohlbecker
381 24b09d7c Andreas Kohlbecker
  $uriEncoded = array_shift($args);
382
  $uri = urldecode($uriEncoded);
383 d96a6e06 Andreas Kohlbecker
  $theme = array_shift($args);
384 90713556 Andreas Kohlbecker
385 d74aa4df Andreas Kohlbecker
  // find and deserialize arrays
386
    foreach($args as &$arg){
387 f02a533d Andreas Kohlbecker
      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 d74aa4df Andreas Kohlbecker
//  	if(strpos($arg, ',')){
392
//  		$arg = explode(',', $arg);
393
//  	}
394 9049a2de Katja Luther
  }
395 d74aa4df Andreas Kohlbecker
396 67168c2a Andreas Kohlbecker
397 5602a381 n.hoffmann
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
398 67168c2a Andreas Kohlbecker
399 5602a381 n.hoffmann
  if($request_method == "POST"){
400 67168c2a Andreas Kohlbecker
401 5602a381 n.hoffmann
    $parameters = $_POST;
402 67168c2a Andreas Kohlbecker
403 5602a381 n.hoffmann
    $post_data = array();
404
    foreach ($parameters as $k=>$v)
405
    {
406 67168c2a Andreas Kohlbecker
      $post_data[] = "$k=".utf8_encode($v);
407 5602a381 n.hoffmann
    }
408
    $post_data = implode(',', $post_data);
409 67168c2a Andreas Kohlbecker
410 5602a381 n.hoffmann
    // testing
411 10811eb5 Andreas Kohlbecker
    $data = drupal_http_request($uri, "POST", $post_data);
412 5602a381 n.hoffmann
    print $data;
413 67168c2a Andreas Kohlbecker
414 8a60c8fc Andreas Kohlbecker
  }else if(strpos($theme, '/') > 0){ // must be a mimetype
415
    header('Content-Type: '.$theme);
416 784a4314 Andreas Kohlbecker
    $data = _http_request_binary($uri);
417 8a60c8fc Andreas Kohlbecker
    print $data;
418
    exit;
419
  } else {
420 5602a381 n.hoffmann
    // 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 10811eb5 Andreas Kohlbecker
      $http_response = drupal_http_request($uri);
425
      foreach($http_response->headers as $hname=>$hvalue) {
426
        drupal_set_header($hname . ":" . $hvalue);
427
      }
428
      print $http_response->data;
429 8a60c8fc Andreas Kohlbecker
      exit;
430 5602a381 n.hoffmann
    } else {
431 784a4314 Andreas Kohlbecker
      $obj = cdm_ws_get($uri, null, null, null, TRUE);
432 5602a381 n.hoffmann
      array_unshift($args, $theme, $obj);
433
      print call_user_func_array('theme', $args);
434
    }
435 8a60c8fc Andreas Kohlbecker
  }
436 32a96ee6 Andreas Kohlbecker
}
437
438 b09e63fd Andreas Kohlbecker
function setvalue_session(){
439 67168c2a Andreas Kohlbecker
440 1956d9b9 Andreas Kohlbecker
  if( $_REQUEST['var'] && strlen( $_REQUEST['var']) > 4){
441 f02a533d Andreas Kohlbecker
    $keys = substr( $_REQUEST['var'], 1, strlen( $_REQUEST['var']) - 2);
442 1956d9b9 Andreas Kohlbecker
    $keys = explode('][', $keys);
443
  } else {
444 f02a533d Andreas Kohlbecker
    return;
445 b09e63fd Andreas Kohlbecker
  }
446 1956d9b9 Andreas Kohlbecker
  $val =  $_REQUEST['val'] ?  $_REQUEST['val'] : null;
447 67168c2a Andreas Kohlbecker
448
  // prevent from malicous tags
449 b09e63fd Andreas Kohlbecker
  $val = strip_tags($val);
450 67168c2a Andreas Kohlbecker
451 b09e63fd Andreas Kohlbecker
  $var = &$_SESSION;
452
  $i = 0;
453
  foreach($keys as $key){
454
    $hasMoreKeys = ++$i < count($var);
455
    if($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))){
456
      $var[$key] = array();
457
    }
458
    $var = &$var[$key];
459
  }
460
  $var = $val;
461 1956d9b9 Andreas Kohlbecker
  drupal_goto($_REQUEST['destination']);
462 b09e63fd Andreas Kohlbecker
}
463
464 8a60c8fc Andreas Kohlbecker
function uri_uriByProxy($uri, $theme = false){
465
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
466
  return url('cdm_api/proxy/'.urlencode($uri).($theme?"/$theme":''));
467
}
468 32a96ee6 Andreas Kohlbecker
469 80e0aa8e Andreas Kohlbecker
function cdm_compose_annotations_url($cdmBase){
470 90713556 Andreas Kohlbecker
471 80e0aa8e Andreas Kohlbecker
    if(!$cdmBase->uuid){
472
        return;
473
    }
474 90713556 Andreas Kohlbecker
475 e96d2451 Andreas Kohlbecker
    $ws_base_uri = null;
476 80e0aa8e Andreas Kohlbecker
    switch($cdmBase->class){
477
        case 'TaxonBase':
478
        case 'Taxon':
479
        case 'Synonym':
480
            $ws_base_uri = CDM_WS_TAXON;
481
            break;
482
        case 'TaxonNameBase':
483
        case 'NonViralName':
484
        case 'BacterialName':
485
        case 'BotanicalName':
486
        case 'CultivarPlantName':
487
        case 'ZoologicalName':
488
        case 'ViralName':
489
            $ws_base_uri = CDM_WS_NAME;
490
            break;
491
        case 'Media':
492
            $ws_base_uri = CDM_WS_MEDIA;
493
            break;
494 48650990 Andreas Kohlbecker
        case 'ReferenceBase':
495
            $ws_base_uri = CDM_WS_REFERENCE;
496
            break;
497 b5e773ef Andreas Kohlbecker
        case 'Distribution':
498
        case 'TextData':
499
        case 'TaxonInteraction':
500
        case 'QuantitativeData':
501
        case 'IndividualsAssociation':
502
        case 'Distribution':
503
        case 'CommonTaxonName':
504 90713556 Andreas Kohlbecker
        case 'CategoricalData':
505 f02a533d Andreas Kohlbecker
          $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
506
          break;
507 2264b60d Andreas Kohlbecker
        case 'PolytomousKey':
508
        case 'MediaKey':
509
        case 'MultiAccessKey':
510 cafc7c3b Andreas Kohlbecker
          $ws_base_uri = $cdmBase->class;
511
          $ws_base_uri{0} = strtolower($ws_base_uri{0});
512 2264b60d Andreas Kohlbecker
          break;
513 48650990 Andreas Kohlbecker
        default:  trigger_error('Unsupported CDM Class - no annotations available for ' . $cdmBase->class, E_USER_ERROR);
514 80e0aa8e Andreas Kohlbecker
            return;
515
    }
516 cafc7c3b Andreas Kohlbecker
    return  cdm_compose_url($ws_base_uri, array($cdmBase->uuid, 'annotations'));
517 80e0aa8e Andreas Kohlbecker
}
518
519 30c5a6bd Andreas Kohlbecker
/**
520
 * Enter description here...
521
 *
522
 * @param String $resourceURI
523
 * @param pageSize
524
 *            the maximum number of entities returned per page (can be null
525
 *            to return all entities in a single page)
526
 * @param pageNumber
527
 *            the number of the page to be returned, the first page has the
528
 *            pageNumber = 1
529
 * @return unknown
530
 */
531
function cdm_ws_page($resourceURI, $pageSize, $pageNumber){
532 24b09d7c Andreas Kohlbecker
  return cdm_ws_get($resourceURI, null, queryString(array("page" => $pageNumber, 'pageSize'=>$pageSize)));
533 30c5a6bd Andreas Kohlbecker
}
534
535 424beeed Andreas Kohlbecker
//function cdm_ws_taxonomy_compose_resourcePath($path = null){
536
//  $viewrank =  _cdm_taxonomy_compose_viewrank();
537
//  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
538
//}
539
540 30c5a6bd Andreas Kohlbecker
541
/**
542
 * Enter description here...
543
 *
544
 * @param unknown_type $secUuid
545
 * @param unknown_type $path
546
 * @return unknown
547
 */
548 6b4212db Andreas Kohlbecker
function cdm_compose_taxonomy_path($taxonUuid = false){
549 424beeed Andreas Kohlbecker
550 f02a533d Andreas Kohlbecker
  $viewUuid = get_taxonomictree_uuid_selected();
551
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
552
553
  if($taxonUuid){
554
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array($viewUuid, $taxonUuid));
555
  } else {
556
    if($rankUuid){
557
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array($viewUuid, $rankUuid));
558
    } else {
559
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY, array($viewUuid));
560
    }
561
  }
562 30c5a6bd Andreas Kohlbecker
}
563
564 424beeed Andreas Kohlbecker
function cdm_ws_taxonomy($taxonUuid = null){
565 0538e428 Andreas Kohlbecker
566
    $response = null;
567
    $response = cdm_ws_get(cdm_compose_taxonomy_path($taxonUuid), null, null, null, TRUE);
568 90713556 Andreas Kohlbecker
569 f02a533d Andreas Kohlbecker
    if($response == null){
570
      // error handing
571
      if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
572
        // delete the session value and try again with the default
573
        unset($_SESSION['cdm']['taxonomictree_uuid']);
574
        return cdm_ws_taxonomy($taxonUuid);
575
      } else {
576
        // check if taxonomictree_uuid is valid
577
        $test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
578 6b4212db Andreas Kohlbecker
        if($test == null){
579 90713556 Andreas Kohlbecker
          // the default set by the admin seems to be invalid or is not even set
580 6b4212db Andreas Kohlbecker
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
581 f02a533d Andreas Kohlbecker
        }
582
      }
583
    }
584 90713556 Andreas Kohlbecker
585 0538e428 Andreas Kohlbecker
    return $response;
586 30c5a6bd Andreas Kohlbecker
}
587
588
/**
589
 * Enter description here...
590
 *
591
 * @param UUID $secUuid
592
 * @param String $path
593
 * @return unknown
594
 */
595 424beeed Andreas Kohlbecker
function cdm_ws_taxonomy_pathFromRoot($taxonUuid){
596 90713556 Andreas Kohlbecker
597 1956d9b9 Andreas Kohlbecker
  $viewUuid = get_taxonomictree_uuid_selected();
598 424beeed Andreas Kohlbecker
  $rankUuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
599
600 0538e428 Andreas Kohlbecker
  $response = null;
601 424beeed Andreas Kohlbecker
  if($rankUuid){
602 f02a533d Andreas Kohlbecker
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array($viewUuid, $taxonUuid, $rankUuid));
603 424beeed Andreas Kohlbecker
  } else {
604 0538e428 Andreas Kohlbecker
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array($viewUuid, $taxonUuid));
605
  }
606 90713556 Andreas Kohlbecker
607 0538e428 Andreas Kohlbecker
  if($response == null){
608 f02a533d Andreas Kohlbecker
    // error handing
609
    if(is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
610
      // delete the session value and try again with the default
611
      unset($_SESSION['cdm']['taxonomictree_uuid']);
612
      return cdm_ws_taxonomy_pathFromRoot($taxonUuid);
613
    } else {
614
        // check if taxonomictree_uuid is valid
615 6b4212db Andreas Kohlbecker
        $test = cdm_ws_get(cdm_compose_taxonomy_path(), null, null, null, TRUE);
616
        if($test == null){
617 90713556 Andreas Kohlbecker
          // the default set by the admin seems to be invalid or is not even set
618 6b4212db Andreas Kohlbecker
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
619
        }
620 f02a533d Andreas Kohlbecker
    }
621 424beeed Andreas Kohlbecker
  }
622 90713556 Andreas Kohlbecker
623 0538e428 Andreas Kohlbecker
  return $response;
624 30c5a6bd Andreas Kohlbecker
}
625
626 3fd1e1f2 Andreas Kohlbecker
function cdm_rankVocabulary_as_option() {
627
  return cdm_Vocabulary_as_option(UUID_RANK);
628
}
629
630 2b9108d4 Andreas Kohlbecker
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = null){
631 3fd1e1f2 Andreas Kohlbecker
  static $vocabularyOptions;
632
633 70fb5e15 Andreas Kohlbecker
  if(!$rankVocabularyOptions){
634 3fd1e1f2 Andreas Kohlbecker
    $vocabularyOptions = array();
635
    if(!isset($vocabularyOptions[$vocabularyUuid])){
636
      $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
637
      $vocabularyOptions[$vocabularyUuid] = array();
638
      if($vocab){
639
        foreach($vocab->terms as $term){
640 2b9108d4 Andreas Kohlbecker
          if($term_label_callback && function_exists($term_label_callback)){
641
            $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
642
          } else {
643
	        $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
644
          }
645 3fd1e1f2 Andreas Kohlbecker
        }
646
        array_reverse($vocabularyOptions[$vocabularyUuid]);
647 f02a533d Andreas Kohlbecker
      }
648 70fb5e15 Andreas Kohlbecker
    }
649
  }
650 3fd1e1f2 Andreas Kohlbecker
  return $vocabularyOptions[$vocabularyUuid];
651 70fb5e15 Andreas Kohlbecker
}
652
653 2b9108d4 Andreas Kohlbecker
function _cdm_relationship_type_term_label_callback($term){
654
  if(isset($term->representation_L10n_abbreviatedLabel)) {
655
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
656
  } else {
657
    return t($term->representation_L10n);
658
  }
659
}
660
661 70fb5e15 Andreas Kohlbecker
662 24b09d7c Andreas Kohlbecker
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
663 67168c2a Andreas Kohlbecker
664 24b09d7c Andreas Kohlbecker
  if(!$featureTree){
665 b5ea057c Andreas Kohlbecker
    drupal_set_message('No \'FeatureTree\' has been set so far. '
666 d74aa4df Andreas Kohlbecker
    .'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');
667 24b09d7c Andreas Kohlbecker
    return false;
668
  }
669 67168c2a Andreas Kohlbecker
670
  $mergedTrees = array();
671
672 24b09d7c Andreas Kohlbecker
  if($isDescriptionsSeparated){
673
    // merge any description into a sparate feature tree
674
    foreach($descriptions as $desc){
675 f02a533d Andreas Kohlbecker
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
676 67168c2a Andreas Kohlbecker
677 24b09d7c Andreas Kohlbecker
      $mergedTree = clone $featureTree;
678
      $mergedTree->root->children = $mergedNodes;
679
      $mergedTrees[] = $mergedTree;
680
    }
681
  } else {
682
    // combine all descripions into one feature tree
683
    foreach($descriptions as $desc){
684 f02a533d Andreas Kohlbecker
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
685 24b09d7c Andreas Kohlbecker
      $featureTree->root->children = $mergedNodes;
686
    }
687
    $mergedTrees[] = $featureTree;
688
  }
689 67168c2a Andreas Kohlbecker
690
  return $mergedTrees;
691 24b09d7c Andreas Kohlbecker
}
692
693 cafc7c3b Andreas Kohlbecker
/**
694
 * @param $cdmBase
695
 * @return an array or empty
696
 */
697 3fd1e1f2 Andreas Kohlbecker
function cdm_ws_getAnnotationsFor($cdmBase, $includeTypes = false){
698 cafc7c3b Andreas Kohlbecker
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
699
    if($annotationUrl){
700
      $annotationPager = cdm_ws_get($annotationUrl, null, null, null, true);
701
      if(is_array($annotationPager->records)){
702 3fd1e1f2 Andreas Kohlbecker
        $annotations = array();
703
        foreach($annotationPager->records as $annotation){
704 e353e8f5 Andreas Kohlbecker
          if($includeTypes) {
705
            if( (isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, true))
706
              || ($annotation->annotationType === null && in_array('NULL_VALUE', $includeTypes, true))){
707 5606901a Andreas Kohlbecker
              $annotations[] = $annotation;
708
            }
709 3fd1e1f2 Andreas Kohlbecker
          }
710
        }
711
        return $annotations;
712 cafc7c3b Andreas Kohlbecker
      }
713
    }
714
}
715
716 791e1c94 Andreas Kohlbecker
/**
717
 * returns the NomenclaturalReference string with correctly placed microreference (= reference detail) e.g. in Phytotaxa 43: 1-48. 2012
718
 * @param unknown_type $referenceUuid
719
 * @param unknown_type $microreference
720
 * @return string
721
 */
722
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference){
723
724
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array($referenceUuid), "microReference=".urlencode($microreference));
725
  if($obj){
726
    return $obj->String;
727
  } else {
728
    return null;
729
  }
730
}
731
732
733 f02a533d Andreas Kohlbecker
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements){
734 67168c2a Andreas Kohlbecker
735 24b09d7c Andreas Kohlbecker
  foreach($featureNodes as &$node){
736 67168c2a Andreas Kohlbecker
737
    // append corresponding elements to an additional node field: $node->descriptionElements
738 294bea51 Andreas Kohlbecker
    foreach($descriptionElements as $element) {
739
      if($element->feature->uuid == $node->feature->uuid) {
740
        if(!isset($node->descriptionElements)) {
741 24b09d7c Andreas Kohlbecker
          $node->descriptionElements = array();
742
        }
743
        $node->descriptionElements[] = $element;
744
      }
745
    }
746 67168c2a Andreas Kohlbecker
747 24b09d7c Andreas Kohlbecker
    // recurse into node children
748
    if(is_array($node->children)){
749 f02a533d Andreas Kohlbecker
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
750 ecc6714f f.revilla
      $node->children = $mergedChildNodes;
751 24b09d7c Andreas Kohlbecker
    }
752 67168c2a Andreas Kohlbecker
753 24b09d7c Andreas Kohlbecker
  }
754
  return $featureNodes;
755
}
756
757 30c5a6bd Andreas Kohlbecker
758 4f462b79 Andreas Kohlbecker
/**
759 67168c2a Andreas Kohlbecker
 * Send a HTTP GET request to the RESTService and deserializes
760
 * and returns the response as object.
761
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
762
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
763
 *
764
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
765
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
766
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
767
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
768
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
769
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
770 94112bee n.hoffmann
 *
771 2447830d Andreas Kohlbecker
 * @param $uri
772 424beeed Andreas Kohlbecker
 * @param $pathParameters an array of path parameters
773 80e0aa8e Andreas Kohlbecker
 * @param $query  A query string to be appended to the URL.
774 2447830d Andreas Kohlbecker
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
775
 * @param $absoluteURI
776
 * @return unknown_type
777 784a4314 Andreas Kohlbecker
 */
778
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
779 67168c2a Andreas Kohlbecker
780
  static $cacheL1;
781
  if(!isset($cacheL1)){
782
    $cacheL1 = array();
783
  }
784
785 784a4314 Andreas Kohlbecker
  // transform the given uri path or patthern into a proper webservice uri
786
  if(!$absoluteURI){
787
    $uri = cdm_compose_url($uri, $pathParameters, $query);
788
  }
789 67168c2a Andreas Kohlbecker
790 1a148a24 Andreas Kohlbecker
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
791 67168c2a Andreas Kohlbecker
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
792
793 2264b60d Andreas Kohlbecker
  if(array_key_exists($uri, $cacheL1)){
794
    $cacheL1_obj = $cacheL1[$uri];
795
  }
796 67168c2a Andreas Kohlbecker
  //print $cacheL1_obj;
797
  $set_cacheL1 = false;
798
  if($is_cdm_ws_uri && !$cacheL1_obj){
799
    $set_cacheL1 = true;
800
  }
801
802 9d47d187 Andreas Kohlbecker
  // only cache cdm webservice URIs
803 67168c2a Andreas Kohlbecker
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
804
  $cacheL2_entry = false;
805
806
  if($use_cacheL2){
807
    // try to get object from cacheL2
808
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
809 d96a6e06 Andreas Kohlbecker
  }
810 67168c2a Andreas Kohlbecker
811
  if($cacheL1_obj){
812
      //
813
      // The object has been found in the L1 cache
814
      //
815
      $obj = $cacheL1_obj;
816 d74aa4df Andreas Kohlbecker
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
817 f02a533d Andreas Kohlbecker
        _add_status_message_toggler();
818 d74aa4df Andreas Kohlbecker
        _add_debugMessageStr('Using cacheL1 for: '.$uri);
819
      }
820 67168c2a Andreas Kohlbecker
    } else if($cacheL2_entry) {
821
      //
822
      // The object has been found in the L2 cache
823
      //
824
      $obj = unserialize($cacheL2_entry->data);
825
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
826
        _add_status_message_toggler();
827 07a81b00 Andreas Kohlbecker
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
828 67168c2a Andreas Kohlbecker
      }
829
    } else {
830
      //
831
      // Get the object from the webservice and cache it
832
      //
833
      $time_get_start = microtime(true);
834
      // request data from webservice JSON or XML
835
      $datastr = cdm_http_request($uri, $method);
836
      $time_get = microtime(true) - $time_get_start;
837 90713556 Andreas Kohlbecker
838 67168c2a Andreas Kohlbecker
      $time_parse_start = microtime(true);
839
      // parse data and create object
840
      $obj = cdm_load_obj($datastr);
841 90713556 Andreas Kohlbecker
842 67168c2a Andreas Kohlbecker
      $time_parse = microtime(true) - $time_parse_start;
843
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
844 e96d2451 Andreas Kohlbecker
        if($obj || $datastr == "[]" ){
845
          $success_msg = 'valid';
846
        } else {
847
          $success_msg = 'invalid';
848
        }
849 67168c2a Andreas Kohlbecker
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
850
      }
851
      if($set_cacheL2) {
852
        // store the object in cacheL2
853
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
854
      }
855 90713556 Andreas Kohlbecker
856 67168c2a Andreas Kohlbecker
  }
857
  if($obj){
858
    // store the object in cacheL1
859
    if($set_cacheL1) {
860
      $cacheL1[$uri] = $obj;
861 e46927b4 Andreas Kohlbecker
    }
862 32a96ee6 Andreas Kohlbecker
  }
863 90713556 Andreas Kohlbecker
864 d96a6e06 Andreas Kohlbecker
  return $obj;
865 32a96ee6 Andreas Kohlbecker
}
866 d36d7e4e Andreas Kohlbecker
function _add_debugMessageStr($message){
867 07a81b00 Andreas Kohlbecker
  _add_status_message_toggler();
868
  drupal_set_message($message, 'debug');
869
}
870 d36d7e4e Andreas Kohlbecker
871 24b09d7c Andreas Kohlbecker
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
872 67168c2a Andreas Kohlbecker
873 2447830d Andreas Kohlbecker
  static $cummulated_time_parse;
874
  static $cummulated_time_get;
875 24b09d7c Andreas Kohlbecker
  _add_status_message_toggler();
876 67168c2a Andreas Kohlbecker
877 2447830d Andreas Kohlbecker
  $cummulated_time_get += $time_get;
878
  $cummulated_time_parse += $time_parse;
879 90713556 Andreas Kohlbecker
880 67168c2a Andreas Kohlbecker
  // decompose uri into path and query element
881
  $uri_parts = explode("?", $uri);
882
  if(count($uri_parts) == 2){
883
    $path = $uri_parts[0];
884
    $query = $uri_parts[1];
885
  } else {
886
    $path = $uri;
887
  }
888
889 2447830d Andreas Kohlbecker
  $message = '<span class="uri">'.$uri.'</span><br />';
890
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
891
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
892 24b09d7c Andreas Kohlbecker
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
893 1a148a24 Andreas Kohlbecker
  if(_is_cdm_ws_uri($path)){
894 10811eb5 Andreas Kohlbecker
    $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>-';
895
    $message .= '<a href="'.url('cdm_api/proxy/'.urlencode(url($path.'.xml', $query))).'" target="data" class="'.$success_msg.'">proxied</a>,';
896
    $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>-';
897
    $message .= '<a href="'.url('cdm_api/proxy/'.urlencode(url($path.'.json', $query))).'" target="data" class="'.$success_msg.'">proxied</a>';
898 1a148a24 Andreas Kohlbecker
  } else {
899 f02a533d Andreas Kohlbecker
      $message .= '<a href="'.url($path, $query).'" target="data" class="'.$success_msg.'">open</a>';
900 1a148a24 Andreas Kohlbecker
  }
901 24b09d7c Andreas Kohlbecker
  $message .= '] ';
902
  drupal_set_message($message, 'debug');
903
904
}
905
906 d96a6e06 Andreas Kohlbecker
907 32a96ee6 Andreas Kohlbecker
function cdm_load_obj($datastr){
908 90713556 Andreas Kohlbecker
909 24b09d7c Andreas Kohlbecker
  $obj = json_decode($datastr);
910 67168c2a Andreas Kohlbecker
911 24b09d7c Andreas Kohlbecker
  if(!(is_object($obj) || is_array($obj)) ){
912 6ee322a7 Andreas Kohlbecker
    ob_start();
913
    $obj_dump = ob_get_contents();
914
    ob_clean();
915
    return false;
916
  }
917
918 812a9c04 Andreas Kohlbecker
  return $obj;
919 32a96ee6 Andreas Kohlbecker
}
920 5602a381 n.hoffmann
921 2447830d Andreas Kohlbecker
/**
922 67168c2a Andreas Kohlbecker
 *
923 2447830d Andreas Kohlbecker
 * @param $uri
924 67168c2a Andreas Kohlbecker
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
925 2447830d Andreas Kohlbecker
 *        false or any invalid value is supplied.
926
 * @param $parameters
927
 * @param $header
928 90713556 Andreas Kohlbecker
 * @return the response data
929 2447830d Andreas Kohlbecker
 */
930 784a4314 Andreas Kohlbecker
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
931 90713556 Andreas Kohlbecker
932 3ba69f6b f.revilla
  static $acceptLanguage = null;
933 90713556 Andreas Kohlbecker
934 3ba69f6b f.revilla
  if(!$acceptLanguage) {
935 f02a533d Andreas Kohlbecker
    if(function_exists('apache_request_headers')){
936
      $headers = apache_request_headers();
937
      if($headers['Accept-Language']){
938
        $acceptLanguage = $headers['Accept-Language'];
939
      }
940
    }
941
    if( !$acceptLanguage ) {
942
      $acceptLanguage = "en"; // DEFAULT TODO make configurable
943
    }
944 3ba69f6b f.revilla
  }
945 67168c2a Andreas Kohlbecker
946 2447830d Andreas Kohlbecker
  if($method != "GET" && $method != "POST"){
947
    $method  = "GET";
948
  }
949 67168c2a Andreas Kohlbecker
950 1a148a24 Andreas Kohlbecker
  $header = array();
951
  if(!$header && _is_cdm_ws_uri($uri)){
952 8ff851c6 Andreas Kohlbecker
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
953 3ba69f6b f.revilla
    $header['Accept-Language'] = $acceptLanguage;
954 8ff851c6 Andreas Kohlbecker
    $header['Accept-Charset'] = 'UTF-8';
955 d96a6e06 Andreas Kohlbecker
  }
956 67168c2a Andreas Kohlbecker
957 90713556 Andreas Kohlbecker
  if(false && function_exists('curl_init')){
958 f02a533d Andreas Kohlbecker
    // !!!!! CURL Disabled due to problems with forllowing redirects (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
959 d96a6e06 Andreas Kohlbecker
    // use the CURL lib if installed it is supposed to be 20x faster
960 784a4314 Andreas Kohlbecker
    return _http_request_using_curl($uri, $header, $method, $parameters);
961 8a60c8fc Andreas Kohlbecker
  } else {
962 784a4314 Andreas Kohlbecker
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
963 8a60c8fc Andreas Kohlbecker
  }
964
}
965
966 784a4314 Andreas Kohlbecker
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
967 8ff851c6 Andreas Kohlbecker
 $response = drupal_http_request($uri, $header, $method);
968
 return $response->data;
969 32a96ee6 Andreas Kohlbecker
}
970
971
972 cacc1bbf Andreas Kohlbecker
/**
973 d96a6e06 Andreas Kohlbecker
 * Return string content from a remote file
974 94112bee n.hoffmann
 *
975 24b09d7c Andreas Kohlbecker
 * @param string $uri
976 d96a6e06 Andreas Kohlbecker
 * @return string
977 94112bee n.hoffmann
 *
978 d96a6e06 Andreas Kohlbecker
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
979 67168c2a Andreas Kohlbecker
 */
980 8ff851c6 Andreas Kohlbecker
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
981 d96a6e06 Andreas Kohlbecker
{
982 67168c2a Andreas Kohlbecker
  $ch = curl_init();
983
984
  curl_setopt ($ch, CURLOPT_URL, $uri);
985 1a148a24 Andreas Kohlbecker
  curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1);
986
  curl_setopt ($ch, CURLOPT_MAXREDIRS, 5);
987 90713556 Andreas Kohlbecker
988 67168c2a Andreas Kohlbecker
  // set proxy settings
989
  if(variable_get('cdm_webservice_proxy_url', false)){
990
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
991
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
992
    if(variable_get('cdm_webservice_proxy_usr', false)){
993
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
994 d96a6e06 Andreas Kohlbecker
    }
995 67168c2a Andreas Kohlbecker
  }
996 90713556 Andreas Kohlbecker
997 8ff851c6 Andreas Kohlbecker
  // modify headers array to be used by curl
998
  foreach($headers as $header_key=>$header_val){
999
    $curl_headers[] = $header_key.': '.$header_val;
1000
  }
1001 1a148a24 Andreas Kohlbecker
  if(isset($curl_headers)){
1002
    curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
1003
  }
1004 90713556 Andreas Kohlbecker
1005 67168c2a Andreas Kohlbecker
  // set method if not default
1006
  if($method != "GET"){
1007
    if($method == "POST"){
1008
1009
      curl_setopt ($ch, CURLOPT_POST, 1);
1010
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
1011
1012
    }else{
1013
      // other obscure http methods get passed to curl directly
1014
      // TODO generic parameter/body handling
1015
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
1016 5602a381 n.hoffmann
    }
1017 67168c2a Andreas Kohlbecker
  }
1018
1019
  ob_start();
1020 1a148a24 Andreas Kohlbecker
  curl_exec($ch);
1021
  $info = curl_getinfo($ch);
1022 67168c2a Andreas Kohlbecker
  if(curl_errno($ch)){
1023
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
1024
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
1025
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
1026 d96a6e06 Andreas Kohlbecker
    }
1027 67168c2a Andreas Kohlbecker
  }
1028
  curl_close ($ch);
1029
  $string = ob_get_contents();
1030
  ob_end_clean();
1031
1032
  return $string;
1033 32a96ee6 Andreas Kohlbecker
}
1034
1035 7f368773 Andreas Kohlbecker
function _featureTree_elements_toString($rootNode, $separator = ', '){
1036 f02a533d Andreas Kohlbecker
  $out = '';
1037
  $featureLabels = array();
1038 7f368773 Andreas Kohlbecker
  foreach ($rootNode->children as $featureNode){
1039 f02a533d Andreas Kohlbecker
    $out .= ($out ? $separator : '');
1040 7f368773 Andreas Kohlbecker
    $out .= $featureNode->feature->representation_L10n;
1041
    if (is_array($featureNode->children)){
1042 f02a533d Andreas Kohlbecker
      $childlabels = '';
1043
      foreach ($featureNode->children as $childNode)
1044
      $childlabels .= ($childlabels ? $separator : '');
1045
      $childlabels .= _featureTree_elements_toString($childNode);
1046 7f368773 Andreas Kohlbecker
    }
1047
    if($childlabels){
1048 f02a533d Andreas Kohlbecker
      $out .= '['.$childlabels.' ]';
1049 7f368773 Andreas Kohlbecker
    }
1050
  }
1051
  return $out;
1052
}
1053 1956d9b9 Andreas Kohlbecker
1054 7f368773 Andreas Kohlbecker
function cdm_get_featureTrees_as_options($addDefaultFeatureTree = false){
1055 1956d9b9 Andreas Kohlbecker
    $feature_trees = array();
1056
1057
    // set tree that contains all features
1058 7f368773 Andreas Kohlbecker
    if($addDefaultFeatureTree){
1059
      $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1060
    }
1061 90713556 Andreas Kohlbecker
1062 1956d9b9 Andreas Kohlbecker
    // get features from database
1063
    $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1064
    if(is_array($persisted_trees)){
1065 90713556 Andreas Kohlbecker
1066 1956d9b9 Andreas Kohlbecker
        foreach($persisted_trees as $featureTree){
1067
            // do not add the DEFAULT_FEATURETREE again
1068
            if($featureTree->uuid == UUID_DEFAULT_FEATURETREE){
1069
                continue;
1070
            }
1071 ff59ee31 Andreas Kohlbecker
1072 7f368773 Andreas Kohlbecker
            $treeRepresentation = $featureTree->titleCache;
1073 ff59ee31 Andreas Kohlbecker
1074
            if(is_array($featureTree->root->children) && count($featureTree->root->children) > 0){
1075 afc363df Andreas Kohlbecker
1076
              // render the hierarchic tree structure
1077 f02a533d Andreas Kohlbecker
              $treeDetails = '<div class="featuretree_structure">'
1078
                //._featureTree_elements_toString($featureTree->root)
1079
                .theme('featureTree_hierarchy', $featureTree->uuid)
1080
                .'</div>';
1081 afc363df Andreas Kohlbecker
1082 f02a533d Andreas Kohlbecker
              $form = array();
1083
              $form['featureTree-'.$featureTree->uuid] = array(
1084
                  '#type' => 'fieldset',
1085
                  '#title' => t('Show details'),
1086
                  '#collapsible' => TRUE,
1087
                  '#collapsed' => TRUE,
1088
              );
1089
              $form['featureTree-'.$featureTree->uuid]['details'] = array('#value'=>$treeDetails);
1090
1091
              $treeRepresentation .= drupal_render($form);
1092 ff59ee31 Andreas Kohlbecker
            }
1093
1094 7f368773 Andreas Kohlbecker
            $feature_trees[$featureTree->uuid] = $treeRepresentation;
1095 1956d9b9 Andreas Kohlbecker
        }
1096 90713556 Andreas Kohlbecker
1097 1956d9b9 Andreas Kohlbecker
    }
1098
    return $feature_trees;
1099
}
1100
1101
function cdm_get_taxontrees_as_options(){
1102
   $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1103 d74aa4df Andreas Kohlbecker
   $taxonomicTreeOptions = array();
1104
   if($taxonTrees){
1105 f02a533d Andreas Kohlbecker
      foreach($taxonTrees as $tree){
1106
          $taxonomicTreeOptions[$tree->uuid] = $tree->titleCache;
1107
      }
1108 d74aa4df Andreas Kohlbecker
   }
1109
   return $taxonomicTreeOptions;
1110 1956d9b9 Andreas Kohlbecker
}
1111
1112
1113 6e1ec3a4 Andreas Kohlbecker
function cdm_api_secref_cache_prefetch(&$secUuids){
1114
  global $secref_cache;
1115
  if(!is_array($secref_cache)){
1116
    $secref_cache = array();
1117
  }
1118
  $uniqueUuids = array_unique($secUuids);
1119
  $i = 0;
1120
  $param = '';
1121
  while($i++ < count($uniqueUuids)){
1122
    $param .= $secUuids[$i].',';
1123
    if(strlen($param) + 37 > 2000){
1124 67168c2a Andreas Kohlbecker
      _cdm_api_secref_cache_add($param);
1125 6e1ec3a4 Andreas Kohlbecker
      $param = '';
1126
    }
1127
  }
1128
  if($param){
1129 67168c2a Andreas Kohlbecker
    _cdm_api_secref_cache_add($param);
1130 6e1ec3a4 Andreas Kohlbecker
  }
1131
}
1132
1133
function cdm_api_secref_cache_get($secUuid){
1134
  global $secref_cache;
1135
  if(!is_array($secref_cache)){
1136
    $secref_cache = array();
1137
  }
1138
  if(!array_key_exists($secUuid, $secref_cache)){
1139
    _cdm_api_secref_cache_add($secUuid);
1140
  }
1141 94112bee n.hoffmann
  return $secref_cache[$secUuid];
1142 6e1ec3a4 Andreas Kohlbecker
}
1143
1144
function cdm_api_secref_cache_clear(){
1145
  global $secref_cache;
1146
  $secref_cache = array();
1147
}
1148
1149 54e498e3 Andreas Kohlbecker
/**
1150
 * Validates if the given string is a uuid.
1151
 *
1152
 * @param unknown_type $str
1153
 */
1154 1956d9b9 Andreas Kohlbecker
function is_uuid($str){
1155 f02a533d Andreas Kohlbecker
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1156 1956d9b9 Andreas Kohlbecker
}
1157
1158 54e498e3 Andreas Kohlbecker
/**
1159
 * Checks if the given $object is a valid cdm entity. An object is consirered
1160
 * cdm entity if it has a string field $object->class with at least 3 characters and
1161
 * if it has a valid uuid in $object->uuid.
1162
 *
1163
 * @author a.kohlbecker
1164
 * @param unknown_type $object
1165
 */
1166
function is_cdm_entity($object){
1167
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1168
}
1169
1170 6e1ec3a4 Andreas Kohlbecker
function _cdm_api_secref_cache_add($secUuidsStr){
1171
  global $secref_cache;
1172 24b09d7c Andreas Kohlbecker
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1173
  // batch fetching not jet reimplemented thus:
1174
  /*$assocRefSTOs = array();
1175 67168c2a Andreas Kohlbecker
   if($refSTOs) {
1176
   foreach($refSTOs as $ref){
1177
   $assocRefSTOs[$ref->uuid] = $ref;
1178
   }
1179
   $secref_cache = array_merge($secref_cache, $assocRefSTOs);
1180
   }*/
1181 24b09d7c Andreas Kohlbecker
  $secref_cache[$ref->uuid] = $ref;
1182
}
1183
1184 54e498e3 Andreas Kohlbecker
/**
1185
 * Checks if the given $uri starts with the cdm webservice url stored in the
1186
 * Drupal variable 'cdm_webservice_url'. The 'cdm_webservice_url' can be set in the
1187
 * admins section of the portal.
1188
 *
1189
 * @param $uri the URI to test
1190
 */
1191 1a148a24 Andreas Kohlbecker
function _is_cdm_ws_uri($uri){
1192 f02a533d Andreas Kohlbecker
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1193 1a148a24 Andreas Kohlbecker
}
1194
1195 24b09d7c Andreas Kohlbecker
function queryString($elements) {
1196
  $query = '';
1197
  foreach($elements as $key=>$value){
1198 8934f97c Andreas Kohlbecker
    if(is_array($value)){
1199
      foreach($value as $v){
1200
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
1201
      }
1202
    } else{
1203 67168c2a Andreas Kohlbecker
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
1204 8934f97c Andreas Kohlbecker
    }
1205 6e1ec3a4 Andreas Kohlbecker
  }
1206 24b09d7c Andreas Kohlbecker
  return $query;
1207 6e1ec3a4 Andreas Kohlbecker
}
1208 d96a6e06 Andreas Kohlbecker
1209 6ee322a7 Andreas Kohlbecker
/**
1210 fa650011 Andreas Kohlbecker
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
1211 32a96ee6 Andreas Kohlbecker
 */
1212 24b09d7c Andreas Kohlbecker
function __clone(){
1213 67168c2a Andreas Kohlbecker
  foreach($this as $name => $value){
1214
    if(gettype($value)=='object' || gettype($value)=='array'){
1215
      $this->$name= clone($this->$name);
1216 24b09d7c Andreas Kohlbecker
    }
1217 67168c2a Andreas Kohlbecker
  }
1218
}
1219 32a96ee6 Andreas Kohlbecker
1220 fa650011 Andreas Kohlbecker
/**
1221
 * Make a complete deep copy of an array replacing
1222
 * references with deep copies until a certain depth is reached
1223
 * ($maxdepth) whereupon references are copied as-is...
1224
 * [From http://us3.php.net/manual/en/ref.array.php]
1225
 * @param $array
1226
 * @param $copy
1227
 * @param $maxdepth
1228
 * @param $depth
1229
 * @return unknown_type
1230
 */
1231
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
1232 67168c2a Andreas Kohlbecker
  if($depth > $maxdepth) { $copy = $array; return; }
1233
  if(!is_array($copy)) $copy = array();
1234
  foreach($array as $k => &$v) {
1235
    if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
1236
    } else {
1237
      $copy[$k] = $v;
1238 fa650011 Andreas Kohlbecker
    }
1239 67168c2a Andreas Kohlbecker
  }
1240 fa650011 Andreas Kohlbecker
}
1241
1242 32a96ee6 Andreas Kohlbecker
/**
1243 67168c2a Andreas Kohlbecker
 * Implementation of theme_status_messages($display = NULL)
1244 24b09d7c Andreas Kohlbecker
 * @see includes/theme.inc
1245 67168c2a Andreas Kohlbecker
 *
1246 24b09d7c Andreas Kohlbecker
 * @param $display
1247
 * @return unknown_type
1248 32a96ee6 Andreas Kohlbecker
 */
1249 24b09d7c Andreas Kohlbecker
function _add_status_message_toggler() {
1250
  static $isAdded;
1251
  if(!$isAdded){
1252 67168c2a Andreas Kohlbecker
1253 24b09d7c Andreas Kohlbecker
    drupal_add_js(
1254
          '$(document).ready(function(){
1255 90713556 Andreas Kohlbecker
1256 784a4314 Andreas Kohlbecker
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
1257 24b09d7c Andreas Kohlbecker
            $(\'.messages_toggler\').click(function(){
1258
              $(this).next().slideToggle(\'fast\');
1259
                return false;
1260
            }).next().hide();
1261 90713556 Andreas Kohlbecker
1262 24b09d7c Andreas Kohlbecker
          });'
1263
          , 'inline');
1264 67168c2a Andreas Kohlbecker
          $isAdded = TRUE;
1265 24b09d7c Andreas Kohlbecker
  }
1266
}
1267 0538e428 Andreas Kohlbecker
1268
function _no_classfication_uuid_message(){
1269 c2259e80 Andreas Kohlbecker
1270
  if(!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)){
1271 89dfec92 Andreas Kohlbecker
    return t('This DataPortal is not configured properly or the CDM-Server may be absent.')
1272
      . ' Please check the ' . l(t('CDM web service URL'), 'admin/settings/cdm_dataportal/general')
1273 c2259e80 Andreas Kohlbecker
      . t(', or contact the maintainer of this DataPortal.');
1274
  }
1275
1276 f02a533d Andreas Kohlbecker
  return
1277
  t('This DataPortal is not configured properly.')
1278 0538e428 Andreas Kohlbecker
      . l(t('Please choose a valid classification'), 'admin/settings/cdm_dataportal/general')
1279
      . t(', or contact the maintainer of this DataPortal.');
1280
}