Project

General

Profile

Download (53.7 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Required or useful functions for using CDM Data Store Webservices.
5
 *
6
 * Naming conventions:
7
 * ----------------------
8
 * - All webservice access methods are prefixed with cdm_ws.
9
 *
10
 * @copyright
11
 *   (C) 2007-2012 EDIT
12
 *   European Distributed Institute of Taxonomy
13
 *   http://www.e-taxonomy.eu
14
 *
15
 *   The contents of this module are subject to the Mozilla
16
 *   Public License Version 1.1.
17
 * @see http://www.mozilla.org/MPL/MPL-1.1.html
18
 *
19
 * @author
20
 *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
21
 *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
22
 */
23

    
24
module_load_include('php', 'cdm_api', 'xml2json');
25
module_load_include('php', 'cdm_api', 'commons');
26
module_load_include('php', 'cdm_api', 'uuids');
27
module_load_include('php', 'cdm_api', 'webservice_uris');
28
module_load_include('php', 'cdm_api', 'cdm_node');
29

    
30

    
31
/**
32
 * Implements hook_menu().
33
 */
34
function cdm_api_menu() {
35
  $items = array();
36

    
37
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
38
  $items['cdm_api/proxy'] = array(
39
    'page callback' => 'proxy_content',
40
    'access arguments' => array(
41
      'access content',
42
    ),
43
    'type' => MENU_CALLBACK,
44
  );
45

    
46
  $items['cdm_api/setvalue/session'] = array(
47
    'page callback' => 'setvalue_session',
48
    'access arguments' => array(
49
      'access content',
50
    ),
51
    'type' => MENU_CALLBACK,
52
  );
53

    
54
  return $items;
55
}
56

    
57
/**
58
 * Implements hook_cron().
59
 *
60
 * Expire outdated cache entries.
61
 */
62
function cdm_api_cron() {
63
  cache_clear_all(NULL, 'cache_cdm_ws');
64
}
65

    
66
/**
67
 * @todo Please document this function.
68
 * @see http://drupal.org/node/1354
69
 */
70
function cdm_api_permission() {
71
  return array(
72
    'administer cdm_api' => array(
73
      'title' => t('administer cdm_api'),
74
      'description' => t("TODO Add a description for 'administer cdm_api'"),
75
    ),
76
  );
77
}
78

    
79
/**
80
 * Converts an array of TaggedText items into corresponding html tags.
81
 *
82
 * Each item is provided with a class attribute which is set to the key of the
83
 * TaggedText item.
84
 *
85
 * @param array $taggedtxt
86
 *   Array with text items to convert.
87
 * @param string $tag
88
 *   Html tag name to convert the items into, default is 'span'.
89
 * @param string $glue
90
 *   The string by which the chained text tokens are concatenated together.
91
 *   Default is a blank character.
92
 *
93
 * @return string
94
 *   A string with HTML.
95
 */
96
function cdm_taggedtext2html(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
97
  $out = '';
98
  $i = 0;
99
  foreach ($taggedtxt as $tt) {
100
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
101
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '') . '<' . $tag . ' class="' . $tt->type . '">' . t($tt->text) . '</' . $tag . '>';
102
    }
103
  }
104
  return $out;
105
}
106

    
107
/**
108
 * Finds the text tagged with $tag_type in an array of taggedText instances.
109
 *
110
 * Comment @WA: this function seems unused.
111
 *
112
 * @param array $taggedtxt
113
 *   Array with text items.
114
 * @param string $tag_type
115
 *   The type of tag for which to find text items in the $taggedtxt array.
116
 *
117
 * @return array
118
 *   An array with the texts mapped by $tag_type.
119
 */
120
function cdm_taggedtext_values(array $taggedtxt, $tag_type) {
121
  $tokens = array();
122
  if (!empty($taggedtxt)) {
123
    foreach ($taggedtxt as $tagtxt) {
124
      if ($tagtxt->type == $tag_type) {
125
        $tokens[] = $tagtxt->text;
126
      }
127
    }
128
  }
129
  return $tokens;
130
}
131

    
132
/**
133
 * Returns the currently classification tree in use.
134
 */
135
function get_taxonomictree_uuid_selected() {
136
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
137
    return $_SESSION['cdm']['taxonomictree_uuid'];
138
  }
139
  else {
140
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
141
  }
142
}
143

    
144
/**
145
 * Returns the FeatureTree profile as selected.
146
 *
147
 * The FeatureTree profile returned is the one that has been set in the
148
 * dataportal settings (layout->taxon:profile).
149
 * When the chosen FeatureTree is not found in the database,
150
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
151
 *
152
 * @return mixed
153
 *   A feature profile tree object.
154
 */
155
function get_profile_featureTree() {
156
  $profile_featureTree = cdm_ws_get(
157
    CDM_WS_FEATURETREE,
158
    variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
159
  );
160
  if (!$profile_featureTree) {
161
    $profile_featureTree = cdm_ws_get(
162
      CDM_WS_FEATURETREE,
163
      UUID_DEFAULT_FEATURETREE
164
    );
165
  }
166
  return $profile_featureTree;
167
}
168

    
169
/**
170
 * @todo Please document this function.
171
 * @see http://drupal.org/node/1354
172
 */
173
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
174
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
175
}
176

    
177
/**
178
 * @todo Please document this function.
179
 * @see http://drupal.org/node/1354
180
 */
181
function reset_taxonomictree_uuid($taxonomictree_uuid) {
182
  unset($_SESSION['cdm']['taxonomictree_uuid']);
183
}
184

    
185
/**
186
 * @todo Please document this function.
187
 * @see http://drupal.org/node/1354
188
 */
189
function set_last_taxon_page_tab($taxonPageTab) {
190
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
191
}
192

    
193
/**
194
 * @todo Please document this function.
195
 * @see http://drupal.org/node/1354
196
 */
197
function get_last_taxon_page_tab() {
198
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
199
    return $_SESSION['cdm']['taxon_page_tab'];
200
  }
201
  else {
202
    return FALSE;
203
  }
204
}
205

    
206
/**
207
 * @todo Improve the documentation of this function.
208
 *
209
 * media Array [4]
210
 * representations Array [3]
211
 * mimeType image/jpeg
212
 * representationParts Array [1]
213
 * duration 0
214
 * heigth 0
215
 * size 0
216
 * uri
217
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
218
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
219
 * width 0
220
 * suffix jpg
221
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
222
 * title
223
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
224
 *
225
 * @param object $media
226
 * @param array $mimeTypes
227
 * @param int $width
228
 * @param int $height
229
 *
230
 * @return array
231
 *   An array with preferred media representations or else an empty array.
232
 */
233
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
234
  $prefRepr = array();
235
  if (!isset($media->representations[0])) {
236
    return $prefRepr;
237
  }
238

    
239
  while (count($mimeTypes) > 0) {
240
    // getRepresentationByMimeType
241
    $mimeType = array_shift($mimeTypes);
242

    
243
    foreach ($media->representations as &$representation) {
244
      // If the mimetype is not known, try inferring it.
245
      if (!$representation->mimeType) {
246
        if (isset($representation->parts[0])) {
247
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
248
        }
249
      }
250

    
251
      if ($representation->mimeType == $mimeType) {
252
        // Preferred mimetype found -> erase all remaining mimetypes
253
        // to end loop.
254
        $mimeTypes = array();
255
        $dwa = 0;
256
        $dw = 0;
257
        // Look for part with the best matching size.
258
        foreach ($representation->parts as $part) {
259
          if (isset($part->width) && isset($part->height)) {
260
            $dw = $part->width * $part->height - $height * $width;
261
          }
262
          if ($dw < 0) {
263
            $dw *= -1;
264
          }
265
          $dwa += $dw;
266
        }
267
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
268
        // @WA: $mimeTypeKey is not defined.
269
        // $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
270
        $prefRepr[$dwa . '_'] = $representation;
271
      }
272
    }
273
  }
274
  // Sort the array.
275
  krsort($prefRepr);
276
  return $prefRepr;
277
}
278

    
279
/**
280
 * Infers the mime type of a file using the filename extension.
281
 *
282
 * The filename extension is used to infer the mime type.
283
 *
284
 * @param string $filepath
285
 *   The path to the respective file.
286
 *
287
 * @return string
288
 *   The mimetype for the file or FALSE if the according mime type could
289
 *   not be found.
290
 */
291
function infer_mime_type($filepath) {
292
  static $mimemap = NULL;
293
  if (!$mimemap) {
294
    $mimemap = array(
295
      'jpg' => 'image/jpeg',
296
      'jpeg' => 'image/jpeg',
297
      'png' => 'image/png',
298
      'gif' => 'image/gif',
299
      'giff' => 'image/gif',
300
      'tif' => 'image/tif',
301
      'tiff' => 'image/tif',
302
      'pdf' => 'application/pdf',
303
      'html' => 'text/html',
304
      'htm' => 'text/html',
305
    );
306
  }
307
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
308
  if (isset($mimemap[$extension])) {
309
    return $mimemap[$extension];
310
  }
311
  else {
312
    // FIXME remove this hack just return FALSE;
313
    return 'text/html';
314
  }
315
}
316

    
317
/**
318
 * Converts an ISO 8601 org.joda.time.Partial to a year.
319
 *
320
 * The function expects an ISO 8601 time representation of a
321
 * org.joda.time.Partial of the form yyyy-MM-dd.
322
 *
323
 * @param string $partial
324
 *   ISO 8601 time representation of a org.joda.time.Partial.
325
 *
326
 * @return string
327
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
328
 */
329
function partialToYear($partial) {
330
  if (is_string($partial)) {
331
    $year = substr($partial, 0, 4);
332
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
333
      return $year;
334
    }
335
  }
336
  return;
337
}
338

    
339
/**
340
 * Converts an ISO 8601 org.joda.time.Partial to a month.
341
 *
342
 * This function expects an ISO 8601 time representation of a
343
 * org.joda.time.Partial of the form yyyy-MM-dd.
344
 * In case the month is unknown (= ???) NULL is returned.
345
 *
346
 * @param string $partial
347
 *   ISO 8601 time representation of a org.joda.time.Partial.
348
 *
349
 * @return string
350
 *   A month.
351
 */
352
function partialToMonth($partial) {
353
  if (is_string($partial)) {
354
    $month = substr($partial, 5, 2);
355
    if (preg_match("/[0-9][0-9]/", $month)) {
356
      return $month;
357
    }
358
  }
359
  return;
360
}
361

    
362
/**
363
 * Converts an ISO 8601 org.joda.time.Partial to a day.
364
 *
365
 * This function expects an ISO 8601 time representation of a
366
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
367
 * In case the day is unknown (= ???) NULL is returned.
368
 *
369
 * @param string $partial
370
 *   ISO 8601 time representation of a org.joda.time.Partial.
371
 *
372
 * @return string
373
 *   A day.
374
 */
375
function partialToDay($partial) {
376
  if (is_string($partial)) {
377
    $day = substr($partial, 7, 2);
378
    if (preg_match("/[0-9][0-9]/", $day)) {
379
      return $day;
380
    }
381
  }
382
  return;
383
}
384

    
385
/**
386
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
387
 *
388
 * This function expects an ISO 8601 time representations of a
389
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
390
 * four digit year, month and day with dashes:
391
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
392
 *
393
 * The partial may contain question marks eg: "1973-??-??",
394
 * these are turned in to '00' or are stripped depending of the $stripZeros
395
 * parameter.
396
 *
397
 * @param string $partial
398
 *   org.joda.time.Partial.
399
 * @param bool $stripZeros
400
 *   If set to TRUE the zero (00) month and days will be hidden:
401
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
402
 *
403
 * @return string
404
 *   YYYY-MM-DD formatted year, month, day.
405
 */
406
function partialToDate($partial, $stripZeros = TRUE) {
407
  $y = partialToYear($partial);
408
  $m = partialToMonth($partial);
409
  $d = partialToDay($partial);
410

    
411
  $y = $y ? $y : '00';
412
  $m = $m ? $m : '00';
413
  $d = $d ? $d : '00';
414

    
415
  $date = '';
416

    
417
  if ($y == '00' && $stripZeros) {
418
    return;
419
  }
420
  else {
421
    $date = $y;
422
  }
423

    
424
  if ($m == '00' && $stripZeros) {
425
    return $date;
426
  }
427
  else {
428
    $date .= "-" . $m;
429
  }
430

    
431
  if ($d == '00' && $stripZeros) {
432
    return $date;
433
  }
434
  else {
435
    $date .= "-" . $d;
436
  }
437
  return $date;
438
}
439

    
440
/**
441
 * Converts a time period to a string.
442
 *
443
 * See also partialToDate($partial, $stripZeros).
444
 *
445
 * @param object $period
446
 *   An JodaTime org.joda.time.Period object.
447
 * @param bool $stripZeros
448
 *   If set to True, the zero (00) month and days will be hidden:
449
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
450
 *
451
 * @return string
452
 *   Returns a date in the form of a string.
453
 */
454
function timePeriodToString($period, $stripZeros = TRUE) {
455
  $dateString = '';
456
  if ($period->start) {
457
    $dateString = partialToDate($period->start, $stripZeros);
458
  }
459
  if ($period->end) {
460
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
461
  }
462
  return $dateString;
463
}
464

    
465
/**
466
 * Composes a CDM webservice URL with parameters and querystring.
467
 *
468
 * @param string $uri_pattern
469
 *   String with place holders ($0, $1, ..) that should be replaced by the
470
 *   according element of the $pathParameters array.
471
 * @param array $pathParameters
472
 *   An array of path elements, or a single element.
473
 * @param string $query
474
 *   A query string to append to the URL.
475
 *
476
 * @return string
477
 *   A complete URL with parameters to a CDM webservice.
478
 */
479
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
480
  if (empty($pathParameters)) {
481
    $pathParameters = array();
482
  }
483

    
484
  $request_params = '';
485
  $path_params = '';
486

    
487
  // (1)
488
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
489
  // according element of the $pathParameters array.
490
  static $helperArray = array();
491
  if (isset($pathParameters) && !is_array($pathParameters)) {
492
    $helperArray[0] = $pathParameters;
493
    $pathParameters = $helperArray;
494
  }
495

    
496
  $i = 0;
497
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
498
    if (count($pathParameters) <= $i) {
499
      if (module_exists("user") && user_access('administer')) {
500
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
501
      }
502
      break;
503
    }
504
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
505
    ++$i;
506
  }
507

    
508
  // (2)
509
  // Append all remaining element of the $pathParameters array as path
510
  // elements.
511
  if (count($pathParameters) > $i) {
512
    // Strip trailing slashes.
513
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
514
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
515
    }
516
    while (count($pathParameters) > $i) {
517
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
518
      ++$i;
519
    }
520
  }
521

    
522
  // (3)
523
  // Append the query string supplied by $query.
524
  if (isset($query)) {
525
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
526
  }
527

    
528
  // @WA: $ws_name seems unused
529
  // $path = $ws_name.$uri_pattern;
530
  $path = $uri_pattern;
531

    
532
  $uri = variable_get('cdm_webservice_url', '') . $path;
533
  return $uri;
534
}
535

    
536
/**
537
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
538
 *     together with a theme name to such a proxy function?
539
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
540
 *     Maybe we want to have two different proxy functions, one with theming and one without?
541
 *
542
 * @param string $uri
543
 *     A URI to a CDM Rest service from which to retrieve an object
544
 * @param string|null $hook
545
 *     (optional) The hook name to which the retrieved object should be passed.
546
 *     Hooks can either be a theme_hook() or compose_hook() implementation
547
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
548
 *     suitable for drupal_render()
549
 *
550
 * @todo Please document this function.
551
 * @see http://drupal.org/node/1354
552
 */
553
function proxy_content($uri, $hook = NULL) {
554
  $args = func_get_args();
555

    
556
  $uriEncoded = array_shift($args);
557
  $uri = urldecode($uriEncoded);
558
  $hook = array_shift($args);
559

    
560
  // Find and deserialize arrays.
561
  foreach ($args as &$arg) {
562
    // FIXME use regex to find serialized arrays.
563
    //       or should we accept json instead pf php serializations?
564
    if (strpos($arg, "a:") === 0) {
565
      $arg = unserialize($arg);
566
    }
567
  }
568

    
569
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
570
  if ($request_method == "POST") {
571
    // this is an experimental feature which will allow to
572
    // write data inot the cdm via the RESTfull web service
573
    $parameters = $_POST;
574
    $post_data = array();
575

    
576
    foreach ($parameters as $k => $v) {
577
      $post_data[] = "$k=" . utf8_encode($v);
578
    }
579
    $post_data = implode(',', $post_data);
580

    
581
    // For testing.
582
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data));
583
    print $data;
584
  } else {
585
    // Not a "POST" request
586
    // In all these cases perform a simple get request.
587
    // TODO reconsider caching logic in this function.
588

    
589
    if (empty($hook)) {
590
      // simply return the webservice response
591
      // Print out JSON, the cache cannot be used since it contains objects.
592
      $http_response = drupal_http_request($uri);
593
      if (isset($http_response->headers)) {
594
        foreach ($http_response->headers as $hname => $hvalue) {
595
          drupal_add_http_header($hname, $hvalue);
596
        }
597
      }
598
      if (isset($http_response->data)) {
599
        print $http_response->data;
600
      }
601
      exit();
602
    } else {
603
      // $hook has been supplied
604
      // handle $hook either as compose ot theme hook
605
      // pass through theme or comose hook
606

    
607
      // do a security check since the $uri will be passed
608
      // as absolute URI to cdm_ws_get()
609
      if( !_is_cdm_ws_uri($uri)) {
610
        drupal_set_message(
611
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
612
            'error'
613
        );
614
        return '';
615
      }
616

    
617
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
618
      $theme_result = NULL;
619

    
620
      if (function_exists('compose_' . $hook)){
621
        // call compose hook
622

    
623
        $elements =  call_user_func('compose_' . $hook, $obj);
624
        // pass the render array to drupal_render()
625
        $theme_result = drupal_render($elements);
626
      } else {
627
        // call theme hook
628

    
629
        // TODO use theme registry to get the registered hook info and
630
        //    use these defaults
631
        switch($hook) {
632
          case 'cdm_taxontree':
633
            $variables = array(
634
              'tree' => $obj,
635
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
636
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
637
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
638
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
639
            );
640
            $theme_result = theme($hook, $variables);
641
            break;
642

    
643
          case 'cdm_media_caption':
644
            $variables = array(
645
              'media' => $obj,
646
              // $args[0] is set in taxon_image_gallery_default in
647
              // cdm_dataportal.page.theme.
648
              'elements' => isset($args[0]) ? $args[0] : array(
649
                'title',
650
                'description',
651
                'artist',
652
                'location',
653
                'rights',
654
              ),
655
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
656
            );
657
            $theme_result = theme($hook, $variables);
658
            break;
659

    
660
          default:
661
            drupal_set_message(t(
662
            'Theme !theme is not supported yet by function !function.', array(
663
            '!theme' => $hook,
664
            '!function' => __FUNCTION__,
665
            )), 'error');
666
            break;
667
        } // END of theme hook switch
668
      } // END of tread as theme hook
669
      print $theme_result;
670
    } // END of handle $hook either as compose ot theme hook
671
  }
672
}
673

    
674
/**
675
 * @todo Please document this function.
676
 * @see http://drupal.org/node/1354
677
 */
678
function setvalue_session() {
679
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
680
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
681
    $keys = explode('][', $keys);
682
  }
683
  else {
684
    return;
685
  }
686
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
687

    
688
  // Prevent from malicous tags.
689
  $val = strip_tags($val);
690

    
691
  $var = &$_SESSION;
692
  $i = 0;
693
  foreach ($keys as $key) {
694
    $hasMoreKeys = ++$i < count($var);
695
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
696
      $var[$key] = array();
697
    }
698
    $var = &$var[$key];
699
  }
700
  $var = $val;
701
  if (isset($_REQUEST['destination'])) {
702
    drupal_goto($_REQUEST['destination']);
703
  }
704
}
705

    
706
/**
707
 * @todo Please document this function.
708
 * @see http://drupal.org/node/1354
709
 */
710
function uri_uriByProxy($uri, $theme = FALSE) {
711
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
712
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
713
}
714

    
715
/**
716
 * @todo Please document this function.
717
 * @see http://drupal.org/node/1354
718
 */
719
function cdm_compose_annotations_url($cdmBase) {
720
  if (!$cdmBase->uuid) {
721
    return;
722
  }
723

    
724
  $ws_base_uri = NULL;
725
  switch ($cdmBase->class) {
726
    case 'TaxonBase':
727
    case 'Taxon':
728
    case 'Synonym':
729
      $ws_base_uri = CDM_WS_TAXON;
730
      break;
731

    
732
    case 'TaxonNameBase':
733
    case 'NonViralName':
734
    case 'BacterialName':
735
    case 'BotanicalName':
736
    case 'CultivarPlantName':
737
    case 'ZoologicalName':
738
    case 'ViralName':
739
      $ws_base_uri = CDM_WS_NAME;
740
      break;
741

    
742
    case 'Media':
743
      $ws_base_uri = CDM_WS_MEDIA;
744
      break;
745

    
746
    case 'Reference':
747
      $ws_base_uri = CDM_WS_REFERENCE;
748
      break;
749

    
750
    case 'Distribution':
751
    case 'TextData':
752
    case 'TaxonInteraction':
753
    case 'QuantitativeData':
754
    case 'IndividualsAssociation':
755
    case 'Distribution':
756
    case 'CommonTaxonName':
757
    case 'CategoricalData':
758
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
759
      break;
760

    
761
    case 'PolytomousKey':
762
    case 'MediaKey':
763
    case 'MultiAccessKey':
764
      $ws_base_uri = $cdmBase->class;
765
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
766
      break;
767

    
768
    default:
769
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
770
      return;
771
  }
772
  return cdm_compose_url($ws_base_uri, array(
773
    $cdmBase->uuid,
774
    'annotations',
775
  ));
776
}
777

    
778
/**
779
 * Enter description here...
780
 *
781
 * @param string $resourceURI
782
 * @param mixed $pageSize
783
 *   The maximum number of entities returned per page (can be NULL
784
 *   to return all entities in a single page).
785
 * @param int $pageNumber
786
 *   The number of the page to be returned, the first page has the
787
 *   pageNumber = 1.
788
 *
789
 * @return unknown
790
 */
791
function cdm_ws_page($resourceURI, $pageSize, $pageNumber) {
792
  return cdm_ws_get($resourceURI, NULL, queryString(array(
793
    "page" => $pageNumber,
794
    'pageSize' => $pageSize,
795
  )));
796
}
797

    
798
/*
799
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
800
  $viewrank = _cdm_taxonomy_compose_viewrank();
801
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
802
  ? '/' . $path : '') ;
803
}
804
*/
805

    
806
/**
807
 * @todo Enter description here...
808
 *
809
 * @param string $taxon_uuid
810
 *  The UUID of a cdm taxon instance
811
 * @param string $ignore_rank_limit
812
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
813
 *
814
 * @return A cdm REST service URL path to a Classification
815
 */
816
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
817

    
818
  $view_uuid = get_taxonomictree_uuid_selected();
819
  $rank_uuid = NULL;
820
  if (!$ignore_rank_limit) {
821
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
822
  }
823

    
824
  if (!empty($taxon_uuid)) {
825
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
826
      $view_uuid,
827
      $taxon_uuid,
828
    ));
829
  }
830
  else {
831
    if (!empty($rank_uuid)) {
832
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
833
        $view_uuid,
834
        $rank_uuid,
835
      ));
836
    }
837
    else {
838
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
839
        $view_uuid,
840
      ));
841
    }
842
  }
843
}
844

    
845
/**
846
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
847
 *
848
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
849
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
850
 *
851
 * Operates in two modes depending on whether the parameter
852
 * $taxon_uuid is set or NULL.
853
 *
854
 * A) $taxon_uuid = NULL:
855
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
856
 *  2. otherwise return the default classification as defined by the admin via the settings
857
 *
858
 * b) $taxon_uuid is set:
859
 *   return the classification to whcih the taxon belongs to.
860
 *
861
 * @param UUID $taxon_uuid
862
 *   The UUID of a cdm taxon instance
863
 */
864
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
865

    
866
    $response = NULL;
867

    
868
    // 1st try
869
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
870

    
871
    if ($response == NULL) {
872
      // 2dn try by ignoring the rank limit
873
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
874
    }
875

    
876
    if ($response == NULL) {
877
      // 3rd try, last fallback:
878
      //    return the default classification
879
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
880
        // Delete the session value and try again with the default.
881
        unset($_SESSION['cdm']['taxonomictree_uuid']);
882
        return cdm_ws_taxonomy_root_level($taxon_uuid);
883
      }
884
      else {
885
        // Check if taxonomictree_uuid is valid.
886
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
887
        if ($test == NULL) {
888
          // The default set by the admin seems to be invalid or is not even set.
889
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
890
        }
891
      }
892
    }
893

    
894
  return $response;
895
}
896

    
897
/**
898
 * @todo Enter description here...
899
 *
900
 * @param string $taxon_uuid
901
 *
902
 * @return unknown
903
 */
904
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
905
  $view_uuid = get_taxonomictree_uuid_selected();
906
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
907

    
908
  $response = NULL;
909
  if ($rank_uuid) {
910
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
911
      $view_uuid,
912
      $taxon_uuid,
913
      $rank_uuid,
914
    ));
915
  }
916
  else {
917
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
918
      $view_uuid,
919
      $taxon_uuid,
920
    ));
921
  }
922

    
923
  if ($response == NULL) {
924
    // Error handing.
925
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
926
      // Delete the session value and try again with the default.
927
      unset($_SESSION['cdm']['taxonomictree_uuid']);
928
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
929
    }
930
    else {
931
      // Check if taxonomictree_uuid is valid.
932
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
933
      if ($test == NULL) {
934
        // The default set by the admin seems to be invalid or is not even set.
935
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
936
      }
937
    }
938
  }
939

    
940
  return $response;
941
}
942

    
943
/**
944
 * @todo Please document this function.
945
 * @see http://drupal.org/node/1354
946
 */
947
function cdm_rankVocabulary_as_option() {
948
  $options = cdm_Vocabulary_as_option(UUID_RANK);
949
  array_unshift ($options, "");
950
  return $options;
951
}
952

    
953
/**
954
 *
955
 * @param Object $definedTermBase
956
 * 	  of cdm type DefinedTermBase
957
 * @return string
958
 * 	  the localized representation_L10n of the term,
959
 *    otherwise the titleCache as fall back,
960
 *    otherwise an empty string
961
 */
962
function cdm_term_representation($definedTermBase) {
963
  if ( isset($definedTermBase->representation_L10n) ) {
964
    return $definedTermBase->representation_L10n;
965
  } elseif ( isset($definedTermBase->titleCache)) {
966
    return $definedTermBase->titleCache;
967
  }
968
  return '';
969
}
970

    
971
/**
972
 * @todo Improve documentation of this function.
973
 *
974
 * eu.etaxonomy.cdm.model.description.
975
 * CategoricalData
976
 * CommonTaxonName
977
 * Distribution
978
 * IndividualsAssociation
979
 * QuantitativeData
980
 * TaxonInteraction
981
 * TextData
982
 */
983
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
984
  static $types = array(
985
    "CategoricalData",
986
    "CommonTaxonName",
987
    "Distribution",
988
    "IndividualsAssociation",
989
    "QuantitativeData",
990
    "TaxonInteraction",
991
    "TextData",
992
  );
993

    
994
  static $options = NULL;
995
  if ($options == NULL) {
996
    $options = array();
997
    if ($prependEmptyElement) {
998
      $options[' '] = '';
999
    }
1000
    foreach ($types as $type) {
1001
      // No internatianalization here since these are purely technical terms.
1002
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1003
    }
1004
  }
1005
  return $options;
1006
}
1007

    
1008
/**
1009
 * @todo Please document this function.
1010
 * @see http://drupal.org/node/1354
1011
 */
1012
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1013
  static $vocabularyOptions = array();
1014

    
1015
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1016
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1017
    $vocabularyOptions[$vocabularyUuid] = array();
1018

    
1019
    if ($vocab) {
1020
      foreach ($vocab->terms as $term) {
1021
        if ($term_label_callback && function_exists($term_label_callback)) {
1022
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1023
        }
1024
        else {
1025
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1026
        }
1027
      }
1028
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1029
    }
1030
  }
1031
  return $vocabularyOptions[$vocabularyUuid];
1032
}
1033

    
1034
/**
1035
 * @todo Please document this function.
1036
 * @see http://drupal.org/node/1354
1037
 */
1038
function _cdm_relationship_type_term_label_callback($term) {
1039
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1040
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1041
  }
1042
  else {
1043
    return t($term->representation_L10n);
1044
  }
1045
}
1046

    
1047
/**
1048
 * @todo Please document this function.
1049
 * @see http://drupal.org/node/1354
1050
 */
1051
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1052
  if (!$featureTree) {
1053
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1054
      In order to see the species profiles of your taxa, please select a
1055
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1056
    return FALSE;
1057
  }
1058

    
1059
  $mergedTrees = array();
1060

    
1061
  if ($isDescriptionsSeparated) {
1062
    // Merge any description into a separate feature tree.
1063
    foreach ($descriptions as $desc) {
1064
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1065

    
1066
      $mergedTree = clone $featureTree;
1067
      $mergedTree->root->children = $mergedNodes;
1068
      $mergedTrees[] = $mergedTree;
1069
    }
1070
  }
1071
  else {
1072
    // Combine all descripions into one feature tree.
1073
    foreach ($descriptions as $desc) {
1074
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1075
      $featureTree->root->children = $mergedNodes;
1076
    }
1077
    $mergedTrees[] = $featureTree;
1078
  }
1079

    
1080
  return $mergedTrees;
1081
}
1082

    
1083
/**
1084
 * Get a list of annotations for a cdm entity.
1085
 *
1086
 * @param string $cdmBase
1087
 *   An annotatable cdm entity.
1088
 * @param array $includeTypes
1089
 *   If an array of annotation type uuids is supplied by this parameter the
1090
 *   list of annotations is resticted to those which belong to this type.
1091
 *
1092
 * @return array
1093
 *   An array of Annotation objects or an empty array.
1094
 */
1095
function cdm_ws_getAnnotationsFor($cdmBase, $includeTypes = FALSE) {
1096
  $annotationUrl = cdm_compose_annotations_url($cdmBase);
1097
  if ($annotationUrl) {
1098
    $annotationPager = cdm_ws_get($annotationUrl, NULL, NULL, NULL, TRUE);
1099
    if (isset($annotationPager->records) && is_array($annotationPager->records)) {
1100
      $annotations = array();
1101
      foreach ($annotationPager->records as $annotation) {
1102
        if ($includeTypes) {
1103
          if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1104
            $annotations[] = $annotation;
1105
          }
1106
        }
1107
        else {
1108
          $annotations[] = $annotation;
1109
        }
1110
      }
1111
      return $annotations;
1112
    }
1113
  }
1114
}
1115

    
1116
/**
1117
 * Get a NomenclaturalReference string.
1118
 *
1119
 * Returns the NomenclaturalReference string with correctly placed
1120
 * microreference (= reference detail) e.g.
1121
 * in Phytotaxa 43: 1-48. 2012.
1122
 *
1123
 * @param string $referenceUuid
1124
 *   UUID of the reference.
1125
 * @param string $microreference
1126
 *   Reference detail.
1127
 *
1128
 * @return string
1129
 *   a NomenclaturalReference.
1130
 */
1131
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1132
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1133
    $referenceUuid,
1134
  ), "microReference=" . urlencode($microreference));
1135

    
1136
  if ($obj) {
1137
    return $obj->String;
1138
  }
1139
  else {
1140
    return NULL;
1141
  }
1142
}
1143

    
1144
/**
1145
 * @todo Please document this function.
1146
 * @see http://drupal.org/node/1354
1147
 */
1148
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1149
  foreach ($featureNodes as &$node) {
1150
    // Append corresponding elements to an additional node field:
1151
    // $node->descriptionElements.
1152
    foreach ($descriptionElements as $element) {
1153
      if ($element->feature->uuid == $node->feature->uuid) {
1154
        if (!isset($node->descriptionElements)) {
1155
          $node->descriptionElements = array();
1156
        }
1157
        $node->descriptionElements[] = $element;
1158
      }
1159
    }
1160

    
1161
    // Recurse into node children.
1162
    if (isset($node->children) && is_array($node->children)) {
1163
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1164
      $node->children = $mergedChildNodes;
1165
    }
1166
  }
1167
  return $featureNodes;
1168
}
1169

    
1170
/**
1171
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1172
 *
1173
 * The response from the HTTP GET request is returned as object.
1174
 * The response objects coming from the webservice configured in the
1175
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1176
 *  in a level 2 (L2) cache.
1177
 *
1178
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1179
 * function, this cache persists only per each single page execution.
1180
 * Any object coming from the webservice is stored into it by default.
1181
 * In contrast to this default caching mechanism the L2 cache only is used if
1182
 * the 'cdm_webservice_cache' variable is set to TRUE,
1183
 * which can be set using the modules administrative settings section.
1184
 * Objects stored in this L2 cache are serialized and stored
1185
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1186
 * objects that are stored in the database will persist as
1187
 * long as the drupal cache is not beeing cleared and are available across
1188
 * multiple script executions.
1189
 *
1190
 * @param string $uri
1191
 *   URL to the webservice.
1192
 * @param array $pathParameters
1193
 *   An array of path parameters.
1194
 * @param string $query
1195
 *   A query string to be appended to the URL.
1196
 * @param string $method
1197
 *   The HTTP method to use, valid values are "GET" or "POST";
1198
 * @param bool $absoluteURI
1199
 *   TRUE when the URL should be treated as absolute URL.
1200
 *
1201
 * @return object
1202
 *   The deserialized webservice response object.
1203
 */
1204
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1205
  // static $cacheL1; if(!isset($cacheL1)){ $cacheL1 = array(); }
1206
  static $cacheL1 = array();
1207

    
1208
  // Transform the given uri path or pattern into a proper webservice uri.
1209
  if (!$absoluteURI) {
1210
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1211
  }
1212

    
1213
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1214
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1215

    
1216
  if (array_key_exists($uri, $cacheL1)) {
1217
    $cacheL1_obj = $cacheL1[$uri];
1218
  }
1219

    
1220
  $set_cacheL1 = FALSE;
1221
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1222
    $set_cacheL1 = TRUE;
1223
  }
1224

    
1225
  // Only cache cdm webservice URIs.
1226
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1227
  $cacheL2_entry = FALSE;
1228

    
1229
  if ($use_cacheL2) {
1230
    // Try to get object from cacheL2.
1231
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1232
  }
1233

    
1234
  if (isset($cacheL1_obj)) {
1235
    //
1236
    // The object has been found in the L1 cache.
1237
    //
1238
    $obj = $cacheL1_obj;
1239
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1240
      _add_status_message_toggler();
1241
      _add_debugMessageStr('Using cacheL1 for: ' . $uri);
1242
    }
1243
  }
1244
  elseif ($cacheL2_entry) {
1245
    //
1246
    // The object has been found in the L2 cache.
1247
    //
1248
    $obj = unserialize($cacheL2_entry->data);
1249

    
1250
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1251
      _add_status_message_toggler();
1252
      _add_debugMessageStr('Using cacheL2 for: ' . $uri);
1253
    }
1254
  }
1255
  else {
1256
    //
1257
    // Get the object from the webservice and cache it.
1258
    //
1259
    $time_get_start = microtime(TRUE);
1260
    // Request data from webservice JSON or XML.
1261
    $datastr = cdm_http_request($uri, $method);
1262
    $time_get = microtime(TRUE) - $time_get_start;
1263

    
1264
    $time_parse_start = microtime(TRUE);
1265

    
1266
    // Parse data and create object.
1267
    $obj = cdm_load_obj($datastr);
1268

    
1269
    $time_parse = microtime(TRUE) - $time_parse_start;
1270
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1271
      if ($obj || $datastr == "[]") {
1272
        $success_msg = 'valid';
1273
      }
1274
      else {
1275
        $success_msg = 'invalid';
1276
      }
1277
      _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
1278
    }
1279
    if ($set_cacheL2) {
1280
      // Store the object in cache L2.
1281
      // Comment @WA perhaps better if Drupal serializes here? Then the
1282
      // flag serialized is set properly in the cache table.
1283
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1284
    }
1285
  }
1286
  if ($obj) {
1287
    // Store the object in cache L1.
1288
    if ($set_cacheL1) {
1289
      $cacheL1[$uri] = $obj;
1290
    }
1291
  }
1292
  return $obj;
1293
}
1294

    
1295
/**
1296
 * @todo Please document this function.
1297
 * @see http://drupal.org/node/1354
1298
 */
1299
function _add_debugMessageStr($message) {
1300
  _add_status_message_toggler();
1301
  drupal_set_message(check_plain($message), 'debug');
1302
}
1303

    
1304
/**
1305
 * @todo Please document this function.
1306
 * @see http://drupal.org/node/1354
1307
 */
1308
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg) {
1309
  static $cumulated_time_parse = 0;
1310
  static $cumulated_time_get = 0;
1311
  _add_status_message_toggler();
1312

    
1313
  $cumulated_time_get += $time_get;
1314
  $cumulated_time_parse += $time_parse;
1315

    
1316
  // Decompose uri into path and query element.
1317
  // URI query elements are stored in an array
1318
  // suitable for drupal_http_build_query()
1319
  $uri_parts = explode("?", $uri);
1320
  $query = array();
1321
  if (count($uri_parts) == 2) {
1322
    $path = $uri_parts[0];
1323
    $queryparts = explode("&", $uri_parts[1]);
1324
    foreach ($queryparts as $querypart) {
1325
      $querypart = explode("=", $querypart);
1326
      if(count($querypart) == 2){
1327
        $query[$querypart[0]] = $querypart[1];
1328
      } else {
1329
        $query[$querypart[0]] = null;
1330
      }
1331
    }
1332
  }
1333
  else {
1334
    $path = $uri;
1335
  }
1336

    
1337
  $message = '<span class="uri">' . $uri . '</span><br />';
1338
  $message .= '[fetched in: ' . sprintf('%3.3f', $time_get) . 's(' . sprintf('%3.3f', $cumulated_time_get) . 's); ';
1339
  $message .= 'parsed in ' . sprintf('%3.3f', $time_parse) . ' s(' . sprintf('%3.3f', $cumulated_time_parse) . 's); ';
1340
  $message .= 'size:' . sprintf('%3.1f', ($datasize / 1024)) . ' kb of ' . $success_msg . ' data: ';
1341
  if (_is_cdm_ws_uri($path)) {
1342
    $message .= '<a href="' . url($path . '.xml', array(
1343
      'query' => $query,
1344
    )) . '" target="data" class="' . $success_msg . '">xml</a>-';
1345
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array(
1346
      'query' => $query,
1347
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>,';
1348
    $message .= '<a href="' . url($path . '.json', array(
1349
      'query' => $query,
1350
    )) . '" target="data" class="' . $success_msg . '">json</a>-';
1351
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.json', array(
1352
      'query' => $query,
1353
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>';
1354
  }
1355
  else {
1356
    $message .= '<a href="' . url($path, array(
1357
      'query' => $query,
1358
    )) . '" target="data" class="' . $success_msg . '">open</a>';
1359
  }
1360
  $message .= '] ';
1361
  drupal_set_message(($message), 'debug');
1362
}
1363

    
1364
/**
1365
 * @todo Please document this function.
1366
 * @see http://drupal.org/node/1354
1367
 */
1368
function cdm_load_obj($datastr) {
1369
  $obj = json_decode($datastr);
1370

    
1371
  if (!(is_object($obj) || is_array($obj))) {
1372
    ob_start();
1373
    $obj_dump = ob_get_contents();
1374
    ob_clean();
1375
    return FALSE;
1376
  }
1377

    
1378
  return $obj;
1379
}
1380

    
1381
/**
1382
 * Do a http request to a CDM webservice.
1383
 *
1384
 * @param string $uri
1385
 *   The webservice url.
1386
 * @param string $method
1387
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1388
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1389
 * @param array $parameters
1390
 *   Parameters to use in the request.
1391
 * @param array $header
1392
 *   The header to include in the request.
1393
 *
1394
 * @return
1395
 *   The response data from the request.
1396
 */
1397
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array()) {
1398
  static $acceptLanguage = NULL;
1399

    
1400
  if (!$acceptLanguage) {
1401
    if (function_exists('apache_request_headers')) {
1402
      $headers = apache_request_headers();
1403
      if (isset($headers['Accept-Language'])) {
1404
        $acceptLanguage = $headers['Accept-Language'];
1405
      }
1406
    }
1407
    if (!$acceptLanguage) {
1408
      // DEFAULT TODO make configurable.
1409
      $acceptLanguage = "en";
1410
    }
1411
  }
1412

    
1413
  if ($method != "GET" && $method != "POST") {
1414
    $method = "GET";
1415
  }
1416

    
1417
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1418
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
1419
    $header['Accept-Language'] = $acceptLanguage;
1420
    $header['Accept-Charset'] = 'UTF-8';
1421
  }
1422

    
1423
  if (FALSE && function_exists('curl_init')) {
1424
    // !!!!! CURL Disabled due to problems with following redirects
1425
    // (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
1426
    // Use the CURL lib if installed, it is supposed to be 20x faster.
1427
    return _http_request_using_curl($uri, $header, $method, $parameters);
1428
  }
1429
  else {
1430
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
1431
  }
1432
}
1433

    
1434
/**
1435
 * @todo Please document this function.
1436
 * @see http://drupal.org/node/1354
1437
 */
1438
function _http_request_using_fsockopen($uri, $header = array(), $method = 'GET') {
1439
  $response = drupal_http_request($uri, array('headers' => $header, 'method' => $method));
1440
  if (isset($response->data)) {
1441
      return $response->data;
1442
  }
1443
}
1444

    
1445
/**
1446
 * Return string content from a remote file.
1447
 *
1448
 * @author Luiz Miguel Axcar <lmaxcar@yahoo.com.br>
1449
 *
1450
 * @param string $uri
1451
 *   The url for which to return content.
1452
 *
1453
 * @return string
1454
 *   The returned content.
1455
 */
1456
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array()) {
1457
  $ch = curl_init();
1458

    
1459
  curl_setopt($ch, CURLOPT_URL, $uri);
1460
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1461
  curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1462

    
1463
  // Set proxy settings.
1464
  if (variable_get('cdm_webservice_proxy_url', FALSE)) {
1465
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
1466
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
1467
    if (variable_get('cdm_webservice_proxy_usr', FALSE)) {
1468
      curl_setopt($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '') . ':' . variable_get('cdm_webservice_proxy_pwd', ''));
1469
    }
1470
  }
1471

    
1472
  // Modify headers array to be used by curl.
1473
  foreach ($headers as $header_key => $header_val) {
1474
    $curl_headers[] = $header_key . ': ' . $header_val;
1475
  }
1476
  if (isset($curl_headers)) {
1477
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
1478
  }
1479

    
1480
  // Set method if not default.
1481
  if ($method != "GET") {
1482
    if ($method == "POST") {
1483

    
1484
      curl_setopt($ch, CURLOPT_POST, 1);
1485
      curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
1486
    }
1487
    else {
1488
      // Other obscure http methods get passed to curl directly.
1489
      // TODO generic parameter/body handling
1490
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
1491
    }
1492
  }
1493

    
1494
  ob_start();
1495
  curl_exec($ch);
1496
  $info = curl_getinfo($ch);
1497
  if (curl_errno($ch)) {
1498
    watchdog('CDM_API', '_http_request_curl() - ' . curl_error($ch) . '; REQUEST-METHOD:' . $method . ' URL: ' . substr($uri . ' ', 0, 150), WATCHDOG_ERROR);
1499
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1500
      drupal_set_message(check_plain(t('_http_request_curl() - !curl_error; REQUEST-METHOD:!method URL: !url', array(
1501
      '!curl_error' => curl_error($ch),
1502
      '!method' => $method,
1503
      '!url' => substr($uri . ' ', 0, 150),
1504
       ))), 'error');
1505
    }
1506
  }
1507
  curl_close($ch);
1508
  $string = ob_get_contents();
1509
  ob_end_clean();
1510

    
1511
  return $string;
1512
}
1513

    
1514
/**
1515
 * @todo Please document this function.
1516
 * @see http://drupal.org/node/1354
1517
 */
1518
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1519
  $out = '';
1520

    
1521
  foreach ($rootNode->children as $featureNode) {
1522
    $out .= ($out ? $separator : '');
1523
    $out .= $featureNode->feature->representation_L10n;
1524
    if (is_array($featureNode->children)) {
1525
      $childlabels = '';
1526
      foreach ($featureNode->children as $childNode) {
1527
        $childlabels .= ($childlabels ? $separator : '');
1528
      }
1529
      $childlabels .= _featureTree_elements_toString($childNode);
1530
    }
1531
    if ($childlabels) {
1532
      $out .= '[' . $childlabels . ' ]';
1533
    }
1534
  }
1535
  return $out;
1536
}
1537

    
1538
/**
1539
 * Create a one-dimensional form options array.
1540
 *
1541
 * Creates an array of all features in the feature tree of feature nodes,
1542
 * the node labels are indented by $node_char and $childIndent depending on the
1543
 * hierachy level.
1544
 *
1545
 * @param - $rootNode
1546
 * @param - $node_char
1547
 * @param - $childIndentStr
1548
 * @param - $childIndent
1549
 *   ONLY USED INTERNALLY!
1550
 *
1551
 * @return array
1552
 *   A one dimensional Drupal form options array.
1553
 */
1554
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1555
  $options = array();
1556
  foreach ($rootNode->children as $featureNode) {
1557
    $indent_prefix = '';
1558
    if ($childIndent) {
1559
      $indent_prefix = $childIndent . $node_char . " ";
1560
    }
1561
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1562
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1563
      // Foreach ($featureNode->children as $childNode){
1564
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1565
      $options = array_merge_recursive($options, $childList);
1566
      // }
1567
    }
1568
  }
1569
  return $options;
1570
}
1571

    
1572
/**
1573
 * @todo Please document this function.
1574
 * @see http://drupal.org/node/1354
1575
 */
1576
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1577
  $feature_trees = array();
1578

    
1579
  // Set tree that contains all features.
1580
  if ($add_default_feature_free) {
1581
    $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1582
  }
1583

    
1584
  // Get features from database.
1585
  $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1586
  $tree_representation = NULL;
1587
  if (is_array($persisted_trees)) {
1588

    
1589
    foreach ($persisted_trees as $featureTree) {
1590
      // Do not add the DEFAULT_FEATURETREE again,
1591
      if ($featureTree->uuid == UUID_DEFAULT_FEATURETREE) {
1592
        continue;
1593
      }
1594

    
1595
      // $tree_representation = $featureTree->titleCache;
1596
      $tree_representation = '';
1597
      if (is_array($featureTree->root->children) && count($featureTree->root->children) > 0) {
1598

    
1599
        // Render the hierarchic tree structure.
1600
        $treeDetails = '<div class="featuretree_structure">'
1601
          // ._featureTree_elements_toString($featureTree->root)
1602
          . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' => $featureTree->uuid))
1603
          . '</div>';
1604

    
1605
        $form = array();
1606
        $form['featureTree-' . $featureTree->uuid] = array(
1607
          '#type' => 'fieldset',
1608
          '#title' => 'Show details',
1609
          '#attributes' => array('class' => array('collapsible collapsed')),
1610
          // '#collapsible' => TRUE,
1611
          // '#collapsed' => TRUE,
1612
        );
1613
        $form['featureTree-' . $featureTree->uuid]['details'] = array(
1614
          '#markup' => $treeDetails,
1615
        );
1616
        // echo drupal_render($form);
1617
        $tree_representation .= drupal_render($form);
1618
      }
1619
      $feature_trees[$featureTree->uuid] = $featureTree->titleCache;
1620
      // $feature_trees[$featureTree->uuid] = $tree_representation;
1621
    }
1622
  }
1623

    
1624
  // return $feature_trees;
1625
  return array('options' => $feature_trees, 'treeRepresentations' => $tree_representation);
1626
}
1627

    
1628
/**
1629
 * @todo Please document this function.
1630
 * @see http://drupal.org/node/1354
1631
 */
1632
function cdm_get_taxontrees_as_options() {
1633
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1634
  $taxonomic_tree_options = array();
1635
  if ($taxonTrees) {
1636
    foreach ($taxonTrees as $tree) {
1637
      $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1638
    }
1639
  }
1640
  return $taxonomic_tree_options;
1641
}
1642

    
1643
/**
1644
 * @todo Please document this function.
1645
 * @see http://drupal.org/node/1354
1646
 */
1647
function cdm_api_secref_cache_prefetch(&$secUuids) {
1648
  // Comment @WA: global variables should start with a single underscore
1649
  // followed by the module and another underscore.
1650
  global $_cdm_api_secref_cache;
1651
  if (!is_array($_cdm_api_secref_cache)) {
1652
    $_cdm_api_secref_cache = array();
1653
  }
1654
  $uniqueUuids = array_unique($secUuids);
1655
  $i = 0;
1656
  $param = '';
1657
  while ($i++ < count($uniqueUuids)) {
1658
    $param .= $secUuids[$i] . ',';
1659
    if (strlen($param) + 37 > 2000) {
1660
      _cdm_api_secref_cache_add($param);
1661
      $param = '';
1662
    }
1663
  }
1664
  if ($param) {
1665
    _cdm_api_secref_cache_add($param);
1666
  }
1667
}
1668

    
1669
/**
1670
 * @todo Please document this function.
1671
 * @see http://drupal.org/node/1354
1672
 */
1673
function cdm_api_secref_cache_get($secUuid) {
1674
  global $_cdm_api_secref_cache;
1675
  if (!is_array($_cdm_api_secref_cache)) {
1676
    $_cdm_api_secref_cache = array();
1677
  }
1678
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1679
    _cdm_api_secref_cache_add($secUuid);
1680
  }
1681
  return $_cdm_api_secref_cache[$secUuid];
1682
}
1683

    
1684
/**
1685
 * @todo Please document this function.
1686
 * @see http://drupal.org/node/1354
1687
 */
1688
function cdm_api_secref_cache_clear() {
1689
  global $_cdm_api_secref_cache;
1690
  $_cdm_api_secref_cache = array();
1691
}
1692

    
1693
/**
1694
 * Validates if the given string is a uuid.
1695
 *
1696
 * @param string $str
1697
 *   The string to validate.
1698
 *
1699
 * return bool
1700
 *   TRUE if the string is a UUID.
1701
 */
1702
function is_uuid($str) {
1703
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1704
}
1705

    
1706
/**
1707
 * Checks if the given $object is a valid cdm entity.
1708
 *
1709
 * An object is considered a cdm entity if it has a string field $object->class
1710
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1711
 *
1712
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1713
 *
1714
 * @param mixed $object
1715
 *   The object to validate
1716
 *
1717
 * @return bool
1718
 *   True if the object is a cdm entity.
1719
 */
1720
function is_cdm_entity($object) {
1721
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1722
}
1723

    
1724
/**
1725
 * @todo Please document this function.
1726
 * @see http://drupal.org/node/1354
1727
 */
1728
function _cdm_api_secref_cache_add($secUuidsStr) {
1729
  global $_cdm_api_secref_cache;
1730
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1731
  // Batch fetching not jet reimplemented thus:
1732
  /*
1733
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1734
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1735
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1736
  */
1737
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1738
}
1739

    
1740
/**
1741
 * Checks if the given uri starts with a cdm webservice url.
1742
 *
1743
 * Checks if the uri starts with the cdm webservice url stored in the
1744
 * Drupal variable 'cdm_webservice_url'.
1745
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1746
 *
1747
 * @param string $uri
1748
 *   The URI to test.
1749
 *
1750
 * @return bool
1751
 *   True if the uri starts with a cdm webservice url.
1752
 */
1753
function _is_cdm_ws_uri($uri) {
1754
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1755
}
1756

    
1757
/**
1758
 * @todo Please document this function.
1759
 * @see http://drupal.org/node/1354
1760
 */
1761
function queryString($elements) {
1762
  $query = '';
1763
  foreach ($elements as $key => $value) {
1764
    if (is_array($value)) {
1765
      foreach ($value as $v) {
1766
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1767
      }
1768
    }
1769
    else {
1770
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1771
    }
1772
  }
1773
  return $query;
1774
}
1775

    
1776
/**
1777
 * Implementation of the magic method __clone to allow deep cloning of objects
1778
 * and arrays.
1779
 */
1780
function __clone() {
1781
  foreach ($this as $name => $value) {
1782
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1783
      $this->$name = clone($this->$name);
1784
    }
1785
  }
1786
}
1787

    
1788
/**
1789
 * Make a 'deep copy' of an array.
1790
 *
1791
 * Make a complete deep copy of an array replacing
1792
 * references with deep copies until a certain depth is reached
1793
 * ($maxdepth) whereupon references are copied as-is...
1794
 *
1795
 * @see http://us3.php.net/manual/en/ref.array.php
1796
 *
1797
 * @param array $array
1798
 * @param array $copy
1799
 * @param int $maxdepth
1800
 * @param int $depth
1801
 *
1802
 * @return void
1803
 */
1804
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
1805
  if ($depth > $maxdepth) {
1806
    $copy = $array;
1807
    return;
1808
  }
1809
  if (!is_array($copy)) {
1810
    $copy = array();
1811
  }
1812
  foreach ($array as $k => &$v) {
1813
    if (is_array($v)) {
1814
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
1815
    }
1816
    else {
1817
      $copy[$k] = $v;
1818
    }
1819
  }
1820
}
1821

    
1822
/**
1823
 * Implementation of theme_status_messages($display = NULL).
1824
 *
1825
 * @see includes/theme.inc
1826
 *
1827
 * @return void
1828
 */
1829
function _add_status_message_toggler() {
1830
  static $isAdded = FALSE;
1831
  if (!$isAdded) {
1832
    drupal_add_js(
1833
    'jQuery(document).ready(function($){
1834
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
1835
       $(\'.messages_toggler\').click(function(){
1836
         $(this).next().slideToggle(\'fast\');
1837
         return false;
1838
       }).next().hide();
1839
     });', array('type' => 'inline'));
1840

    
1841
    $isAdded = TRUE;
1842
  }
1843
}
1844

    
1845
/**
1846
 * @todo Please document this function.
1847
 * @see http://drupal.org/node/1354
1848
 */
1849
function _no_classfication_uuid_message() {
1850
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
1851
    return t('This DataPortal is not configured properly or the CDM-Server may be absent.') . ' Please check the ' . l(t('CDM web service URL'), 'admin/config/cdm_dataportal/settings/general') . t(', or contact the maintainer of this DataPortal.');
1852
  }
1853
  return t('This DataPortal is not configured properly.') . l(t('Please choose a valid classification'), 'admin/config/cdm_dataportal/settings/general') . t(', or contact the maintainer of this DataPortal.');
1854
}
1855

    
1856
/**
1857
 * Implementation of hook flush_caches
1858
 *
1859
 * Add custom cache tables to the list of cache tables that
1860
 * will be cleared by the Clear button on the Performance page or whenever
1861
 * drupal_flush_all_caches is invoked.
1862
 *
1863
 * @author W.Addink <waddink@eti.uva.nl>
1864
 *
1865
 * @return array
1866
 *   An array with custom cache tables to include.
1867
 */
1868
function cdm_api_flush_caches() {
1869
  return array('cache_cdm_ws');
1870
}
(4-4/9)