Project

General

Profile

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

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

    
23
define(DEFAULT_TAXONTREE_RANKLIMIT, '');//TODO Genus UUID
24

    
25

    
26
/**
27
 * Implementation of hook_requirements()
28
 */
29
function cdm_api_requirements() {
30

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

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

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

    
45
  return $requirements;
46
}
47

    
48

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

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

    
71
  }
72

    
73
  return $items;
74
}
75

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

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

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

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

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

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

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

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

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

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

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

    
154
    return $form;
155
}
156

    
157
/**
158
 * Implementation of hook_cron().
159
 *
160
 * Expire outdated cache entries
161
 */
162
function cdm_api_cron() {
163
  cache_clear_all(NULL, 'cache_cdm_ws');
164
}
165

    
166
function cdm_api_perm() {
167
  return array(
168
      'administer cdm_api'
169
      );
170
}
171

    
172
// ----------------------------------------------------------- //
173

    
174

    
175
/**
176
 * Converts an array of TagedText items into a sequence of corresponding html tags whereas
177
 * each item will provided with a class attribute which set to the key of the TaggedText item.
178
 *
179
 * @param array $taggedtxt
180
 * @param String $tag
181
 * @param String $glue the string by which the chained text tokens are concatenated together.
182
 *       Default is a blank character
183
 * @return String of HTML
184
 */
185
function cdm_taggedtext2html(array &$taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()){
186
  $out = '';
187
  $i = 0;
188
  foreach($taggedtxt as $tt){
189
    if(!in_array($tt->type, $skiptags) && strlen($tt->text) > 0){
190
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt)? $glue : '').'<'.$tag.' class="'.$tt->type.'">'.t($tt->text).'</'.$tag.'>';
191
    }
192
  }
193
  return $out;
194
}
195

    
196
/**
197
 * Finds the text tagged with $$tag_type in an array of taggedText instances
198
 *
199
 * @param array $taggedtxt
200
 * @param string $tag_type
201
 * @return the text mapped by $tag_type or an empty string
202
 */
203
function cdm_taggedtext_value(array &$taggedtxt = array(), $tag_type){
204
  foreach($taggedtxt as $tagtxt){
205
    if($tagtxt->type == $tag_type)
206
    return $tagtxt->text;
207
  }
208
  return '';
209
}
210

    
211
/**
212
 * media Array [4]
213
 *   representations Array [3]
214
 *       mimeType  image/jpeg
215
 *       representationParts Array [1]
216
 *           duration  0
217
 *           heigth  0
218
 *           size  0
219
 *           uri http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
220
 *           uuid  15c687f1-f79d-4b79-992f-7ba0f55e610b
221
 *           width 0
222
 *       suffix  jpg
223
 *       uuid  930b7d51-e7b6-4350-b21e-8124b14fe29b
224
 *   title
225
 *   uuid  17e514f1-7a8e-4daa-87ea-8f13f8742cf9
226
 *
227
 * @param unknown_type $media
228
 * @param array $mimeTypes
229
 * @param unknown_type $width
230
 * @param unknown_type $height
231
 * @return unknown
232
 */
233
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300){
234
  /**
235

    
236
  *
237
  */
238
  $prefRepr = array();
239
  if(!isset($media->representations[0])){
240
    return $prefRepr;
241
  }
242

    
243
  while(count($mimeTypes) > 0){
244
    // getRepresentationByMimeType
245
    $mimeType = array_shift($mimeTypes);
246
    foreach($media->representations as $representation){
247
      if($representation->mimeType == $mimeType){
248
        // preffered mimetype found -> erase all remaining mimetypes to end loop
249
        $mimeTypes = array();
250
        $dwa = 0;
251
        // look for part with the best matching size
252
        foreach($representation->parts as $part){
253
          $dw = $part->width * $part->height - $height * $width;
254
          if($dw < 0){
255
            $dw *= -1;
256
          }
257
          $dwa+= $dw;
258
        }
259
        $dwa = (count($representation->parts)>0) ? $dwa / count($representation->parts) : 0;
260
        $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
261
      }
262
    }
263
  }
264
  // sort
265
  krsort($prefRepr);
266
  // return
267
  return $prefRepr;
268
}
269

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

    
322
/**
323
 *
324
 * @param $uri_pattern
325
 * @param $pathParameters an array of path elements, or a single element
326
 * @param $query  A query string to append to the URL.
327
 * @return unknown_type
328
 */
329
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL ){
330

    
331
  $request_params = '';
332
  $path_params = '';
333

    
334
  /* (1)
335
   * substitute all place holders ($0, $1, ..) in the
336
   * $uri_pattern by the according element of the $pathParameters array
337
   */
338
  static $helperArray = array();
339
  if($pathParameters && !is_array($pathParameters)){
340
    $helperArray[0] = $pathParameters;
341
    $pathParameters = $helperArray;
342
  }
343

    
344
  $i = 0;
345
  while(strpos($uri_pattern, "$".$i) !== FALSE){
346
    if(count($pathParameters) <= $i){
347
      drupal_set_message('cdm_compose_url(): missing pathParameters', 'debug');
348
    }
349
    $uri_pattern = str_replace("$".$i, rawurlencode($pathParameters[$i]), $uri_pattern);
350
    ++$i;
351
  }
352

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

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

    
374
  $path = $ws_name.$uri_pattern;
375

    
376
  $uri = variable_get('cdm_webservice_url', '').$path;
377
  return $uri;
378
}
379

    
380

    
381
function proxy_content($uri, $theme = null){
382

    
383
  $args = func_get_args();
384

    
385
  $uriEncoded = array_shift($args);
386
  $uri = urldecode($uriEncoded);
387
  $theme = array_shift($args);
388
  
389
  //find comma sepatated string in all args
390
  foreach($args as &$arg){
391
  	if(strpos($arg, ',')){
392
  		$arg = explode(',', $arg);
393
  	}
394
  }
395

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

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

    
400
    $parameters = $_POST;
401

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

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

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

    
434
function setvalue_session(){
435

    
436
  if(strlen(arg(3)) > 0){
437
    $keys = explode('|', arg(3));
438
  }
439
  $val = arg(4);
440

    
441
  // prevent from malicous tags
442
  $val = strip_tags($val);
443

    
444
  $var = &$_SESSION;
445
  $i = 0;
446
  foreach($keys as $key){
447
    $hasMoreKeys = ++$i < count($var);
448
    if($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))){
449
      $var[$key] = array();
450
    }
451
    $var = &$var[$key];
452
  }
453
  $var = $val;
454
}
455

    
456
function uri_uriByProxy($uri, $theme = false){
457
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
458
  return url('cdm_api/proxy/'.urlencode($uri).($theme?"/$theme":''));
459
}
460

    
461
/**
462
 * Enter description here...
463
 *
464
 * @param String $resourceURI
465
 * @param pageSize
466
 *            the maximum number of entities returned per page (can be null
467
 *            to return all entities in a single page)
468
 * @param pageNumber
469
 *            the number of the page to be returned, the first page has the
470
 *            pageNumber = 1
471
 * @return unknown
472
 */
473
function cdm_ws_page($resourceURI, $pageSize, $pageNumber){
474
  return cdm_ws_get($resourceURI, null, queryString(array("page" => $pageNumber, 'pageSize'=>$pageSize)));
475
}
476

    
477
function cdm_ws_taxonomy_find($uuid, $rank = null, $viewUuid = null){
478
  return cdm_ws_get(CDM_WS_TAXONOMY, null, queryString(array("uuid" => $uuid, 'rank'=>$rank)));
479
}
480

    
481
/**
482
 * Enter description here...
483
 *
484
 * @param unknown_type $secUuid
485
 * @param unknown_type $path
486
 * @return unknown
487
 */
488
function cdm_ws_taxonomy($path = null){
489
  return cdm_ws_get(cdm_ws_taxonomy_compose_resourcePath($path));
490
}
491

    
492
function cdm_ws_taxonomy_compose_resourcePath($path = null){
493
  $viewrank =  _cdm_taxonomy_compose_viewrank();
494
  return CDM_WS_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
495
}
496

    
497
/**
498
 * Enter description here...
499
 *
500
 * @param UUID $secUuid
501
 * @param String $path
502
 * @return unknown
503
 */
504
function cdm_ws_taxonomy_pathFromRoot($path){
505
  $viewrank =  _cdm_taxonomy_compose_viewrank();
506
  return cdm_ws_get(CDM_WS_TAXONOMY .  ($viewrank ? '/' .$viewrank : '' )  . '/' . $path . '/path' );
507
}
508

    
509
/**
510
 * Enter description here...
511
 *
512
 * @param UUID $viewUuid
513
 * @param String $rank
514
 * @return unknown
515
 */
516
function _cdm_taxonomy_compose_viewrank(){
517
  $viewUuid = variable_get('cdm_taxonomictree_uuid', false);
518
  if(!$viewUuid){
519
    return;
520
  }
521
  $rank = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
522
  return $viewUuid . (empty($rank) ? '' : ','.$rank);
523
}
524

    
525

    
526
function cdm_rankVocabulary_as_option(){
527
  global $rankVocabularyOptions;
528
  if(!$rankVocabularyOptions){
529
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, UUID_RANK);
530
    $rankVocabularyOptions = array();
531
    foreach($vocab->terms as $term){
532
      $rankVocabularyOptions[$term->uuid] = t($term->representation_L10n);
533
    }
534
    array_reverse($rankVocabularyOptions);
535
  }
536
  return $rankVocabularyOptions;
537
}
538

    
539

    
540
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
541

    
542
  if(!$featureTree){
543
    drupal_set_message('No \'FeatureTree\' has been set so far. '
544
    .'In order to display descriptive data of your taxa, please select a \'FeatureTree\' in the '.l('CDM Dataportal Ssettings', 'admin/settings/cdm_dataportal/general'), 'warning');
545
    return false;
546
  }
547

    
548
  $mergedTrees = array();
549

    
550
  if($isDescriptionsSeparated){
551
    // merge any description into a sparate feature tree
552
    foreach($descriptions as $desc){
553
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
554

    
555
      $mergedTree = clone $featureTree;
556
      $mergedTree->root->children = $mergedNodes;
557
      $mergedTrees[] = $mergedTree;
558
    }
559
  } else {
560
    // combine all descripions into one feature tree
561
    foreach($descriptions as $desc){
562
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
563
      $featureTree->root->children = $mergedNodes;
564
    }
565
    $mergedTrees[] = $featureTree;
566
  }
567

    
568
  return $mergedTrees;
569
}
570

    
571
function _mergeFeatureTreeDesciptions($featureNodes, $descriptionElements){
572

    
573
  foreach($featureNodes as &$node){
574

    
575
    // append corresponding elements to an additional node field: $node->descriptionElements
576
    foreach($descriptionElements as $element){
577
      if($element->feature->uuid == $node->feature->uuid){
578
        if(!isset($node->descriptionElements)){
579
          $node->descriptionElements = array();
580
        }
581
        $node->descriptionElements[] = $element;
582
      }
583
    }
584

    
585
    // recurse into node children
586
    if(is_array($node->children)){
587
      foreach($node->children as $nodes){
588
        $mergedChildNodes = _mergeFeatureTreeDesciptions($nodes, $descriptionElements);
589
        $node->children = $mergedChildNodes;
590
      }
591
    }
592

    
593
  }
594
  return $featureNodes;
595
}
596

    
597

    
598
/**
599
 * Send a HTTP GET request to the RESTService and deserializes
600
 * and returns the response as object.
601
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
602
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
603
 *
604
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
605
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
606
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
607
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
608
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
609
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
610
 *
611
 * @param $uri
612
 * @param $pathParameters
613
 * @param $query
614
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
615
 * @param $absoluteURI
616
 * @return unknown_type
617
 */
618
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
619

    
620
  static $cacheL1;
621
  if(!isset($cacheL1)){
622
    $cacheL1 = array();
623
  }
624

    
625
  // transform the given uri path or patthern into a proper webservice uri
626
  if(!$absoluteURI){
627
    $uri = cdm_compose_url($uri, $pathParameters, $query);
628
  }
629

    
630
  $is_cdm_ws_uri = str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
631
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
632

    
633
  $cacheL1_obj = $cacheL1[$uri];
634
  //print $cacheL1_obj;
635
  $set_cacheL1 = false;
636
  if($is_cdm_ws_uri && !$cacheL1_obj){
637
    $set_cacheL1 = true;
638
  }
639

    
640
  // only cache cdm webservice URIs
641
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
642
  $cacheL2_entry = false;
643

    
644
  if($use_cacheL2){
645
    // try to get object from cacheL2
646
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
647
  }
648

    
649
  if($cacheL1_obj){
650
      //
651
      // The object has been found in the L1 cache
652
      //
653
      $obj = $cacheL1_obj;
654
      _add_debugMessageStr('Using cacheL1 for: '.$uri);
655
    } else if($cacheL2_entry) {
656
      //
657
      // The object has been found in the L2 cache
658
      //
659
      $obj = unserialize($cacheL2_entry->data);
660
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
661
        _add_status_message_toggler();
662
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
663
      }
664
    } else {
665
      //
666
      // Get the object from the webservice and cache it
667
      //
668
      $time_get_start = microtime(true);
669
      // request data from webservice JSON or XML
670
      $datastr = cdm_http_request($uri, $method);
671
      $time_get = microtime(true) - $time_get_start;
672
  
673
      $time_parse_start = microtime(true);
674
      // parse data and create object
675
      $obj = cdm_load_obj($datastr);
676
  
677
      $time_parse = microtime(true) - $time_parse_start;
678
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
679
        $success_msg = $obj || $datastr == "[]" ? 'valid':'invalid';
680
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
681
      }
682
      if($set_cacheL2) {
683
        // store the object in cacheL2
684
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
685
      }
686
      
687
  }
688
  if($obj){
689
    // store the object in cacheL1
690
    if($set_cacheL1) {
691
      $cacheL1[$uri] = $obj;
692
    }
693
  }
694
  
695
  return $obj;
696
}
697
function _add_debugMessageStr($msg){
698
  _add_status_message_toggler();
699
  drupal_set_message($message, 'debug');
700
  
701
}
702
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
703

    
704
  static $cummulated_time_parse;
705
  static $cummulated_time_get;
706
  _add_status_message_toggler();
707

    
708
  $cummulated_time_get += $time_get;
709
  $cummulated_time_parse += $time_parse;
710
  
711
  // decompose uri into path and query element
712
  $uri_parts = explode("?", $uri);
713
  if(count($uri_parts) == 2){
714
    $path = $uri_parts[0];
715
    $query = $uri_parts[1];
716
  } else {
717
    $path = $uri;
718
  }
719

    
720
  $message = '<span class="uri">'.$uri.'</span><br />';
721
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
722
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
723
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
724
  $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>,';
725
  $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>';
726
  $message .= '] ';
727
  drupal_set_message($message, 'debug');
728

    
729
}
730

    
731

    
732
function cdm_load_obj($datastr){
733
   
734
  // NOTICE: the cdm dataportal currently does not support xml so the line below are commented out
735
  /*
736
   // if the web service delivers XML convert it into json
737
   if(variable_get('cdm_webservice_type', 'json') == 'xml'){
738
   $datastr = xml2json::transformXmlStringToJson($datastr);
739
   }
740
   */
741

    
742
  $obj = json_decode($datastr);
743

    
744
  if(!(is_object($obj) || is_array($obj)) ){
745
    ob_start();
746
    $obj_dump = ob_get_contents();
747
    ob_clean();
748
    return false;
749
  }
750

    
751
  return $obj;
752
}
753

    
754
/**
755
 *
756
 * @param $uri
757
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
758
 *        false or any invalid value is supplied.
759
 * @param $parameters
760
 * @param $header
761
 * @return the response data 
762
 */
763
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
764
  global $locale;  // drupal variable containing the current locale i.e. language
765
  static $header;
766

    
767
  if($method != "GET" && $method != "POST"){
768
    $method  = "GET";
769
  }
770

    
771
  if(!$header){
772
    $header = array();
773
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
774
    $header['Accept-Language'] = $locale;
775
    $header['Accept-Charset'] = 'UTF-8';
776
  }
777

    
778
  if(function_exists('curl_init')){
779
    // use the CURL lib if installed it is supposed to be 20x faster
780
    return _http_request_using_curl($uri, $header, $method, $parameters);
781
  } else {
782
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
783
  }
784
}
785

    
786
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
787
 $response = drupal_http_request($uri, $header, $method);
788
 return $response->data;
789
}
790

    
791

    
792
/**
793
 * Return string content from a remote file
794
 *
795
 * @param string $uri
796
 * @return string
797
 *
798
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
799
 */
800
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
801
{
802
  $ch = curl_init();
803

    
804
  curl_setopt ($ch, CURLOPT_URL, $uri);
805
  // set proxy settings
806
  if(variable_get('cdm_webservice_proxy_url', false)){
807
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
808
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
809
    if(variable_get('cdm_webservice_proxy_usr', false)){
810
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
811
    }
812
  }
813
  // modify headers array to be used by curl
814
  foreach($headers as $header_key=>$header_val){
815
    $curl_headers[] = $header_key.': '.$header_val;
816
  }
817
  curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
818
  // set method if not default
819
  if($method != "GET"){
820
    if($method == "POST"){
821

    
822
      curl_setopt ($ch, CURLOPT_POST, 1);
823
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
824

    
825
    }else{
826
      // other obscure http methods get passed to curl directly
827
      // TODO generic parameter/body handling
828
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
829
    }
830
  }
831

    
832
  ob_start();
833
  curl_exec ($ch);
834
  if(curl_errno($ch)){
835
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
836
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
837
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
838
    }
839
  }
840
  curl_close ($ch);
841
  $string = ob_get_contents();
842
  ob_end_clean();
843

    
844
  return $string;
845
}
846

    
847
function cdm_api_secref_cache_prefetch(&$secUuids){
848
  global $secref_cache;
849
  if(!is_array($secref_cache)){
850
    $secref_cache = array();
851
  }
852
  $uniqueUuids = array_unique($secUuids);
853
  $i = 0;
854
  $param = '';
855
  while($i++ < count($uniqueUuids)){
856
    $param .= $secUuids[$i].',';
857
    if(strlen($param) + 37 > 2000){
858
      _cdm_api_secref_cache_add($param);
859
      $param = '';
860
    }
861
  }
862
  if($param){
863
    _cdm_api_secref_cache_add($param);
864
  }
865
}
866

    
867
function cdm_api_secref_cache_get($secUuid){
868
  global $secref_cache;
869
  if(!is_array($secref_cache)){
870
    $secref_cache = array();
871
  }
872
  if(!array_key_exists($secUuid, $secref_cache)){
873
    _cdm_api_secref_cache_add($secUuid);
874
  }
875
  return $secref_cache[$secUuid];
876
}
877

    
878
function cdm_api_secref_cache_clear(){
879
  global $secref_cache;
880
  $secref_cache = array();
881
}
882

    
883
function _cdm_api_secref_cache_add($secUuidsStr){
884
  global $secref_cache;
885
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
886
  // batch fetching not jet reimplemented thus:
887
  /*$assocRefSTOs = array();
888
   if($refSTOs) {
889
   foreach($refSTOs as $ref){
890
   $assocRefSTOs[$ref->uuid] = $ref;
891
   }
892
   $secref_cache = array_merge($secref_cache, $assocRefSTOs);
893
   }*/
894
  $secref_cache[$ref->uuid] = $ref;
895
}
896

    
897
function queryString($elements) {
898
  $query = '';
899
  foreach($elements as $key=>$value){
900
    if(is_array($value)){
901
      foreach($value as $v){
902
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
903
      }
904
    } else{
905
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
906
    }
907
  }
908
  return $query;
909
}
910

    
911
/**
912
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
913
 */
914
function __clone(){
915
  foreach($this as $name => $value){
916
    if(gettype($value)=='object' || gettype($value)=='array'){
917
      $this->$name= clone($this->$name);
918
    }
919
  }
920
}
921

    
922
/**
923
 * Make a complete deep copy of an array replacing
924
 * references with deep copies until a certain depth is reached
925
 * ($maxdepth) whereupon references are copied as-is...
926
 * [From http://us3.php.net/manual/en/ref.array.php]
927
 * @param $array
928
 * @param $copy
929
 * @param $maxdepth
930
 * @param $depth
931
 * @return unknown_type
932
 */
933
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
934
  if($depth > $maxdepth) { $copy = $array; return; }
935
  if(!is_array($copy)) $copy = array();
936
  foreach($array as $k => &$v) {
937
    if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
938
    } else {
939
      $copy[$k] = $v;
940
    }
941
  }
942
}
943

    
944
/**
945
 * Implementation of theme_status_messages($display = NULL)
946
 * @see includes/theme.inc
947
 *
948
 * @param $display
949
 * @return unknown_type
950
 */
951
function _add_status_message_toggler() {
952
  static $isAdded;
953
  if(!$isAdded){
954

    
955
    drupal_add_js(
956
          '$(document).ready(function(){
957
          
958
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
959
            $(\'.messages_toggler\').click(function(){
960
              $(this).next().slideToggle(\'fast\');
961
                return false;
962
            }).next().hide();
963
            
964
          });'
965
          , 'inline');
966
          $isAdded = TRUE;
967
  }
968
}
969

    
970
define('CDM_WS_MEDIA', 'portal/media');
971

    
972
define('CDM_WS_MEDIA_METADATA', 'media/$0/metadata');
973

    
974
define('CDM_WS_NAME', 'name');
975

    
976
define('CDM_WS_NAME_TYPEDESIGNATIONS', 'name/$0/typeDesignations');
977

    
978
define('CDM_WS_TAXON_NAMETYPEDESIGNATIONS', 'portal/taxon/$0/nameTypeDesignations');
979

    
980
define('CDM_WS_TAXON_DESCRIPTIONS', 'portal/taxon/$0/descriptions');
981

    
982
define('CDM_WS_NAME_DESCRIPTIONS', 'portal/name/$0/descriptions');
983

    
984
define('CDM_WS_REFERENCE', 'reference');
985

    
986
define('CDM_WS_NOMENCLATURAL_REFERENCE_CITATION', 'reference/$0/nomenclaturalCitation/$1');
987

    
988
define('CDM_WS_FIND_TAXA', 'portal/taxon/find');
989

    
990
define('CDM_WS_TAXON', 'portal/taxon');
991

    
992
/**
993
 * @parameters $0 : the taxon uuid
994
 *
995
 * @returns
996
 */
997
define('CDM_WS_TAXON_SYNONYMY', 'portal/taxon/$0/synonymy');
998

    
999
define('CDM_WS_TAXON_RELATIONS', 'portal/taxon/$0/taxonRelationships');
1000

    
1001
define('CDM_WS_TAXON_NAMERELATIONS', 'portal/taxon/$0/nameRelationships');
1002

    
1003

    
1004
/**
1005
 * @parameters $0 : the taxon uuid
1006
 *
1007
 * @returns the taxon which is the accepted synonym for the taxon given as
1008
 * parameter taxonUuid. If the taxon specified by taxonUuid is itself the
1009
 * accepted taxon, this one will be returned.
1010
 */
1011
define('CDM_WS_TAXON_ACCEPTED', 'portal/taxon/$0/accepted');
1012

    
1013
define('CDM_WS_TAXON_MEDIA', 'portal/taxon/$0/media/$1/$2');
1014
define('CDM_WS_TAXON_SUBTREE_MEDIA', 'portal/taxon/$0/subtree/media/$1/$2');
1015

    
1016
/**
1017
 *
1018
 * Gets the root nodes of the taxonomic concept tree for the concept
1019
 * reference specified by the secUuid parameter.
1020
 *
1021
 * stub: treenode_root
1022
 */
1023
define('CDM_WS_TAXONOMY',  'portal/taxontree');
1024
define('CDM_WS_TAXONOMY_MEDIA', 'portal/taxontree/$0/$1');
1025

    
1026
define('CDM_WS_TERMVOCABULARY', 'term/$0');
1027

    
1028
define('CDM_WS_TERM_COMPARE', 'term/$0/compareTo/$1');
1029

    
1030
define('CDM_WS_TDWG_LEVEL', 'term/tdwg/$0');
1031

    
1032
/**
1033
 * returns FeatureTrees that are stored in this community store
1034
 *
1035
 */
1036
define('CDM_WS_FEATURETREE', 'featuretree/$0');
1037

    
1038
define('CDM_WS_FEATURETREES', 'featuretree');
1039

    
1040
define('CDM_WS_GEOSERVICE_DISTRIBUTIONMAP', 'geo/map/distribution/$0');
(4-4/9)