Project

General

Profile

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

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

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

    
26

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

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

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

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

    
46
  return $requirements;
47
}
48

    
49

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

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

    
72
  }
73

    
74
  return $items;
75
}
76

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

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

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

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

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

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

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

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

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

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

    
148
    $form['cdm_webservice']['cdm_webservice_debug'] =  array(
149
    '#type' => 'checkbox',
150
    '#title'         => t('Debug CDM Web Service'),
151
    '#default_value' => variable_get('cdm_webservice_debug', 1),
152
    '#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>!')
153
    );
154

    
155
    return $form;
156
}
157

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

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

    
173
// ----------------------------------------------------------- //
174

    
175

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

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

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

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

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

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

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

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

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

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

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

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

    
375
  $path = $ws_name.$uri_pattern;
376

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

    
381

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

    
384
  $args = func_get_args();
385

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

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

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

    
401
    $parameters = $_POST;
402

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

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

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

    
435
function setvalue_session(){
436

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

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

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

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

    
462
function cdm_compose_annotations_url($cdmBase){
463
	
464
    if(!$cdmBase->uuid){
465
        return;
466
    }
467
    
468
	$ws_base_uri = null;
469
    switch($cdmBase->class){
470
        case 'TaxonBase':
471
        case 'Taxon':
472
        case 'Synonym':
473
            $ws_base_uri = CDM_WS_TAXON;
474
            break;
475
        case 'TaxonNameBase':
476
        case 'NonViralName':
477
        case 'BacterialName':
478
        case 'BotanicalName':
479
        case 'CultivarPlantName':
480
        case 'ZoologicalName':
481
        case 'ViralName':
482
            $ws_base_uri = CDM_WS_NAME;
483
            break;
484
        case 'Media':
485
            $ws_base_uri = CDM_WS_MEDIA;
486
            break;
487
        default: 
488
            trigger_error('Unsupported CDM Class - no annotations available', E_USER_ERROR);
489
            return;
490
    }
491
    return  cdm_compose_url($ws_base_uri, array($cdmBase->uuid, 'annotation'));
492
}
493

    
494
/**
495
 * Enter description here...
496
 *
497
 * @param String $resourceURI
498
 * @param pageSize
499
 *            the maximum number of entities returned per page (can be null
500
 *            to return all entities in a single page)
501
 * @param pageNumber
502
 *            the number of the page to be returned, the first page has the
503
 *            pageNumber = 1
504
 * @return unknown
505
 */
506
function cdm_ws_page($resourceURI, $pageSize, $pageNumber){
507
  return cdm_ws_get($resourceURI, null, queryString(array("page" => $pageNumber, 'pageSize'=>$pageSize)));
508
}
509

    
510
function cdm_ws_taxonomy_find($uuid, $rank = null, $viewUuid = null){
511
  return cdm_ws_get(CDM_WS_PORTAL_TAXONOMY, null, queryString(array("uuid" => $uuid, 'rank'=>$rank)));
512
}
513

    
514
/**
515
 * Enter description here...
516
 *
517
 * @param unknown_type $secUuid
518
 * @param unknown_type $path
519
 * @return unknown
520
 */
521
function cdm_ws_taxonomy($path = null){
522
  return cdm_ws_get(cdm_ws_taxonomy_compose_resourcePath($path));
523
}
524

    
525
function cdm_ws_taxonomy_compose_resourcePath($path = null){
526
  $viewrank =  _cdm_taxonomy_compose_viewrank();
527
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path ? '/' . $path : '') ;
528
}
529

    
530
/**
531
 * Enter description here...
532
 *
533
 * @param UUID $secUuid
534
 * @param String $path
535
 * @return unknown
536
 */
537
function cdm_ws_taxonomy_pathFromRoot($path){
538
  $viewrank =  _cdm_taxonomy_compose_viewrank();
539
  return cdm_ws_get(CDM_WS_PORTAL_TAXONOMY .  ($viewrank ? '/' .$viewrank : '' )  . '/' . $path . '/path' );
540
}
541

    
542
/**
543
 * Enter description here...
544
 *
545
 * @param UUID $viewUuid
546
 * @param String $rank
547
 * @return unknown
548
 */
549
function _cdm_taxonomy_compose_viewrank(){
550
  $viewUuid = variable_get('cdm_taxonomictree_uuid', false);
551
  if(!$viewUuid){
552
    return;
553
  }
554
  $rank = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
555
  return $viewUuid . (empty($rank) ? '' : ','.$rank);
556
}
557

    
558

    
559
function cdm_rankVocabulary_as_option(){
560
  global $rankVocabularyOptions;
561
  if(!$rankVocabularyOptions){
562
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, UUID_RANK);
563
    $rankVocabularyOptions = array();
564
    foreach($vocab->terms as $term){
565
      $rankVocabularyOptions[$term->uuid] = t($term->representation_L10n);
566
    }
567
    array_reverse($rankVocabularyOptions);
568
  }
569
  return $rankVocabularyOptions;
570
}
571

    
572

    
573
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = false){
574

    
575
  if(!$featureTree){
576
    drupal_set_message('No \'FeatureTree\' has been set so far. '
577
    .'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');
578
    return false;
579
  }
580

    
581
  $mergedTrees = array();
582

    
583
  if($isDescriptionsSeparated){
584
    // merge any description into a sparate feature tree
585
    foreach($descriptions as $desc){
586
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
587

    
588
      $mergedTree = clone $featureTree;
589
      $mergedTree->root->children = $mergedNodes;
590
      $mergedTrees[] = $mergedTree;
591
    }
592
  } else {
593
    // combine all descripions into one feature tree
594
    foreach($descriptions as $desc){
595
      $mergedNodes = _mergeFeatureTreeDesciptions($featureTree->root->children, $desc->elements);
596
      $featureTree->root->children = $mergedNodes;
597
    }
598
    $mergedTrees[] = $featureTree;
599
  }
600

    
601
  return $mergedTrees;
602
}
603

    
604
function _mergeFeatureTreeDesciptions($featureNodes, $descriptionElements){
605

    
606
  foreach($featureNodes as &$node){
607

    
608
    // append corresponding elements to an additional node field: $node->descriptionElements
609
    foreach($descriptionElements as $element){
610
      if($element->feature->uuid == $node->feature->uuid){
611
        if(!isset($node->descriptionElements)){
612
          $node->descriptionElements = array();
613
        }
614
        $node->descriptionElements[] = $element;
615
      }
616
    }
617

    
618
    // recurse into node children
619
    if(is_array($node->children)){
620
      foreach($node->children as $nodes){
621
        $mergedChildNodes = _mergeFeatureTreeDesciptions($nodes, $descriptionElements);
622
        $node->children = $mergedChildNodes;
623
      }
624
    }
625

    
626
  }
627
  return $featureNodes;
628
}
629

    
630

    
631
/**
632
 * Send a HTTP GET request to the RESTService and deserializes
633
 * and returns the response as object.
634
 * The response objects coming from the webservice configured in the 'cdm_webservice_url' variable
635
 * are beeing cached in a level 1 (L1) and or in a level 2 (L2) cache.
636
 *
637
 * Since the L1 cache is implemented as static variable of the cdm_ws_get() function,
638
 * this cache persists only per each single page executiuon. Any object coming from the webservice is stored into it by default.
639
 * Incontrast to this default cacheich mechanism the L2 cache only is used if the 'cdm_webservice_cache' varialby is set to TRUE
640
 * which can be set using the modules administrative settings section. Object stored in this L2 cache are serialized and stored
641
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the objects are sored in a database will persist as
642
 * log as the drupal cache is not beeing cleared and are availabel across multiple sript executions.
643
 *
644
 * @param $uri
645
 * @param $pathParameters
646
 * @param $query  A query string to be appended to the URL.
647
 * @param $method the HTTP method to use, valuid values are "GET" or "POST";
648
 * @param $absoluteURI
649
 * @return unknown_type
650
 */
651
function cdm_ws_get($uri, $pathParameters = array(), $query = null, $method="GET", $absoluteURI = false){
652

    
653
  static $cacheL1;
654
  if(!isset($cacheL1)){
655
    $cacheL1 = array();
656
  }
657

    
658
  // transform the given uri path or patthern into a proper webservice uri
659
  if(!$absoluteURI){
660
    $uri = cdm_compose_url($uri, $pathParameters, $query);
661
  }
662

    
663
  $is_cdm_ws_uri = str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
664
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
665

    
666
  $cacheL1_obj = $cacheL1[$uri];
667
  //print $cacheL1_obj;
668
  $set_cacheL1 = false;
669
  if($is_cdm_ws_uri && !$cacheL1_obj){
670
    $set_cacheL1 = true;
671
  }
672

    
673
  // only cache cdm webservice URIs
674
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
675
  $cacheL2_entry = false;
676

    
677
  if($use_cacheL2){
678
    // try to get object from cacheL2
679
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
680
  }
681

    
682
  if($cacheL1_obj){
683
      //
684
      // The object has been found in the L1 cache
685
      //
686
      $obj = $cacheL1_obj;
687
      _add_debugMessageStr('Using cacheL1 for: '.$uri);
688
    } else if($cacheL2_entry) {
689
      //
690
      // The object has been found in the L2 cache
691
      //
692
      $obj = unserialize($cacheL2_entry->data);
693
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
694
        _add_status_message_toggler();
695
        _add_debugMessageStr('Using cacheL2 for: '.$uri);
696
      }
697
    } else {
698
      //
699
      // Get the object from the webservice and cache it
700
      //
701
      $time_get_start = microtime(true);
702
      // request data from webservice JSON or XML
703
      $datastr = cdm_http_request($uri, $method);
704
      $time_get = microtime(true) - $time_get_start;
705
  
706
      $time_parse_start = microtime(true);
707
      // parse data and create object
708
      $obj = cdm_load_obj($datastr);
709
  
710
      $time_parse = microtime(true) - $time_parse_start;
711
      if(variable_get('cdm_webservice_debug', 1) && user_access('administer')){
712
        $success_msg = $obj || $datastr == "[]" ? 'valid':'invalid';
713
        _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
714
      }
715
      if($set_cacheL2) {
716
        // store the object in cacheL2
717
        cache_set($uri, 'cache_cdm_ws', serialize($obj), CACHE_TEMPORARY);
718
      }
719
      
720
  }
721
  if($obj){
722
    // store the object in cacheL1
723
    if($set_cacheL1) {
724
      $cacheL1[$uri] = $obj;
725
    }
726
  }
727
  
728
  return $obj;
729
}
730
function _add_debugMessageStr($msg){
731
  _add_status_message_toggler();
732
  drupal_set_message($message, 'debug');
733
  
734
}
735
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg){
736

    
737
  static $cummulated_time_parse;
738
  static $cummulated_time_get;
739
  _add_status_message_toggler();
740

    
741
  $cummulated_time_get += $time_get;
742
  $cummulated_time_parse += $time_parse;
743
  
744
  // decompose uri into path and query element
745
  $uri_parts = explode("?", $uri);
746
  if(count($uri_parts) == 2){
747
    $path = $uri_parts[0];
748
    $query = $uri_parts[1];
749
  } else {
750
    $path = $uri;
751
  }
752

    
753
  $message = '<span class="uri">'.$uri.'</span><br />';
754
  $message .= '[fetched in: '.sprintf('%3.3f', $time_get).'s('.sprintf('%3.3f', $cummulated_time_get).'s); ';
755
  $message .= 'parsed in '.sprintf('%3.3f', $time_parse).' s('.sprintf('%3.3f', $cummulated_time_parse).'s); ';
756
  $message .= 'size:'.sprintf('%3.1f', ($datasize / 1024)).' kb of '.$success_msg.' data: ';
757
  $message .= '<a href="'.url($path.'.xml', $query).'" target="data" class="'.$success_msg.'">xml</a>,';
758
  $message .= '<a href="'.url($path.'.json', $query).'" target="data" class="'.$success_msg.'">json</a>';
759
  $message .= '] ';
760
  drupal_set_message($message, 'debug');
761

    
762
}
763

    
764

    
765
function cdm_load_obj($datastr){
766
   
767
  // NOTICE: the cdm dataportal currently does not support xml so the line below are commented out
768
  /*
769
   // if the web service delivers XML convert it into json
770
   if(variable_get('cdm_webservice_type', 'json') == 'xml'){
771
   $datastr = xml2json::transformXmlStringToJson($datastr);
772
   }
773
   */
774

    
775
  $obj = json_decode($datastr);
776

    
777
  if(!(is_object($obj) || is_array($obj)) ){
778
    ob_start();
779
    $obj_dump = ob_get_contents();
780
    ob_clean();
781
    return false;
782
  }
783

    
784
  return $obj;
785
}
786

    
787
/**
788
 *
789
 * @param $uri
790
 * @param $method the HTTP method to use, valuid values are "GET" or "POST"; efaults to "GET" even if null,
791
 *        false or any invalid value is supplied.
792
 * @param $parameters
793
 * @param $header
794
 * @return the response data 
795
 */
796
function cdm_http_request($uri, $method="GET", $parameters = array(), $header = false){
797
  global $locale;  // drupal variable containing the current locale i.e. language
798
  static $header;
799

    
800
  if($method != "GET" && $method != "POST"){
801
    $method  = "GET";
802
  }
803

    
804
  if(!$header){
805
    $header = array();
806
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
807
    $header['Accept-Language'] = $locale;
808
    $header['Accept-Charset'] = 'UTF-8';
809
  }
810

    
811
  if(function_exists('curl_init')){
812
    // use the CURL lib if installed it is supposed to be 20x faster
813
    return _http_request_using_curl($uri, $header, $method, $parameters);
814
  } else {
815
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
816
  }
817
}
818

    
819
function _http_request_using_fsockopen($uri, $header = array(), $method = "GET"){
820
 $response = drupal_http_request($uri, $header, $method);
821
 return $response->data;
822
}
823

    
824

    
825
/**
826
 * Return string content from a remote file
827
 *
828
 * @param string $uri
829
 * @return string
830
 *
831
 * @author Luiz Miguel Axcar (lmaxcar@yahoo.com.br)
832
 */
833
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array())
834
{
835
  $ch = curl_init();
836

    
837
  curl_setopt ($ch, CURLOPT_URL, $uri);
838
  // set proxy settings
839
  if(variable_get('cdm_webservice_proxy_url', false)){
840
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
841
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
842
    if(variable_get('cdm_webservice_proxy_usr', false)){
843
      curl_setopt ($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '').':'.variable_get('cdm_webservice_proxy_pwd', ''));
844
    }
845
  }
846
  // modify headers array to be used by curl
847
  foreach($headers as $header_key=>$header_val){
848
    $curl_headers[] = $header_key.': '.$header_val;
849
  }
850
  curl_setopt ($ch, CURLOPT_HTTPHEADER, $curl_headers);
851
  // set method if not default
852
  if($method != "GET"){
853
    if($method == "POST"){
854

    
855
      curl_setopt ($ch, CURLOPT_POST, 1);
856
      curl_setopt ($ch, CURLOPT_POSTFIELDS, $parameters);
857

    
858
    }else{
859
      // other obscure http methods get passed to curl directly
860
      // TODO generic parameter/body handling
861
      curl_setopt ($ch, CURLOPT_CUSTOMREQUEST, $method);
862
    }
863
  }
864

    
865
  ob_start();
866
  curl_exec ($ch);
867
  if(curl_errno($ch)){
868
    watchdog('CDM_API', '_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), WATCHDOG_ERROR);
869
    if(variable_get('cdm_webservice_debug', 1)  && user_access('administer') ){
870
      drupal_set_message('_http_request_curl() - '.curl_error($ch).'; REQUEST-METHOD:'.$method.' URL: '.substr($uri.' ', 0, 150), 'error');
871
    }
872
  }
873
  curl_close ($ch);
874
  $string = ob_get_contents();
875
  ob_end_clean();
876

    
877
  return $string;
878
}
879

    
880
function cdm_api_secref_cache_prefetch(&$secUuids){
881
  global $secref_cache;
882
  if(!is_array($secref_cache)){
883
    $secref_cache = array();
884
  }
885
  $uniqueUuids = array_unique($secUuids);
886
  $i = 0;
887
  $param = '';
888
  while($i++ < count($uniqueUuids)){
889
    $param .= $secUuids[$i].',';
890
    if(strlen($param) + 37 > 2000){
891
      _cdm_api_secref_cache_add($param);
892
      $param = '';
893
    }
894
  }
895
  if($param){
896
    _cdm_api_secref_cache_add($param);
897
  }
898
}
899

    
900
function cdm_api_secref_cache_get($secUuid){
901
  global $secref_cache;
902
  if(!is_array($secref_cache)){
903
    $secref_cache = array();
904
  }
905
  if(!array_key_exists($secUuid, $secref_cache)){
906
    _cdm_api_secref_cache_add($secUuid);
907
  }
908
  return $secref_cache[$secUuid];
909
}
910

    
911
function cdm_api_secref_cache_clear(){
912
  global $secref_cache;
913
  $secref_cache = array();
914
}
915

    
916
function _cdm_api_secref_cache_add($secUuidsStr){
917
  global $secref_cache;
918
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
919
  // batch fetching not jet reimplemented thus:
920
  /*$assocRefSTOs = array();
921
   if($refSTOs) {
922
   foreach($refSTOs as $ref){
923
   $assocRefSTOs[$ref->uuid] = $ref;
924
   }
925
   $secref_cache = array_merge($secref_cache, $assocRefSTOs);
926
   }*/
927
  $secref_cache[$ref->uuid] = $ref;
928
}
929

    
930
function queryString($elements) {
931
  $query = '';
932
  foreach($elements as $key=>$value){
933
    if(is_array($value)){
934
      foreach($value as $v){
935
        $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($v);
936
      }
937
    } else{
938
      $query .= (strlen($query) > 0 ? '&' : '').$key.'='.urlencode($value);
939
    }
940
  }
941
  return $query;
942
}
943

    
944
/**
945
 * implementation of the magic method __clone to allow deep cloning of objects and arrays
946
 */
947
function __clone(){
948
  foreach($this as $name => $value){
949
    if(gettype($value)=='object' || gettype($value)=='array'){
950
      $this->$name= clone($this->$name);
951
    }
952
  }
953
}
954

    
955
/**
956
 * Make a complete deep copy of an array replacing
957
 * references with deep copies until a certain depth is reached
958
 * ($maxdepth) whereupon references are copied as-is...
959
 * [From http://us3.php.net/manual/en/ref.array.php]
960
 * @param $array
961
 * @param $copy
962
 * @param $maxdepth
963
 * @param $depth
964
 * @return unknown_type
965
 */
966
function array_deep_copy (&$array, &$copy, $maxdepth=50, $depth=0) {
967
  if($depth > $maxdepth) { $copy = $array; return; }
968
  if(!is_array($copy)) $copy = array();
969
  foreach($array as $k => &$v) {
970
    if(is_array($v)) {        array_deep_copy($v,$copy[$k],$maxdepth,++$depth);
971
    } else {
972
      $copy[$k] = $v;
973
    }
974
  }
975
}
976

    
977
/**
978
 * Implementation of theme_status_messages($display = NULL)
979
 * @see includes/theme.inc
980
 *
981
 * @param $display
982
 * @return unknown_type
983
 */
984
function _add_status_message_toggler() {
985
  static $isAdded;
986
  if(!$isAdded){
987

    
988
    drupal_add_js(
989
          '$(document).ready(function(){
990
          
991
            $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (klick to toggle)</h6>\' );
992
            $(\'.messages_toggler\').click(function(){
993
              $(this).next().slideToggle(\'fast\');
994
                return false;
995
            }).next().hide();
996
            
997
          });'
998
          , 'inline');
999
          $isAdded = TRUE;
1000
  }
1001
}
(4-4/9)