Project

General

Profile

Download (60.6 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
 * Tiemout used to override the default of 30 seconds
33
 * in @see drupal_http_request()
34
 *
35
 * @var CDM_HTTP_REQUEST_TIMEOUT: A float representing the maximum number of seconds the function
36
 *     call may take
37
 */
38
define('CDM_HTTP_REQUEST_TIMEOUT', 90.0);
39

    
40
/**
41
 * Implements hook_menu().
42
 */
43
function cdm_api_menu() {
44
  $items = array();
45

    
46
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
47
  $items['cdm_api/proxy'] = array(
48
    'page callback' => 'proxy_content',
49
    'access arguments' => array(
50
      'access content',
51
    ),
52
    'type' => MENU_CALLBACK,
53
  );
54

    
55
  $items['cdm_api/setvalue/session'] = array(
56
    'page callback' => 'setvalue_session',
57
    'access arguments' => array(
58
      'access content',
59
    ),
60
    'type' => MENU_CALLBACK,
61
  );
62

    
63
  return $items;
64
}
65

    
66
/**
67
 * Implements hook_cron().
68
 *
69
 * Expire outdated cache entries.
70
 */
71
function cdm_api_cron() {
72
  cache_clear_all(NULL, 'cache_cdm_ws');
73
}
74

    
75
/**
76
 * @todo Please document this function.
77
 * @see http://drupal.org/node/1354
78
 */
79
function cdm_api_permission() {
80
  return array(
81
    'administer cdm_api' => array(
82
      'title' => t('administer cdm_api'),
83
      'description' => t("TODO Add a description for 'administer cdm_api'"),
84
    ),
85
  );
86
}
87

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

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

    
141
/**
142
 * Returns the currently classification tree in use.
143
 */
144
function get_taxonomictree_uuid_selected() {
145
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
146
    return $_SESSION['cdm']['taxonomictree_uuid'];
147
  }
148
  else {
149
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
150
  }
151
}
152

    
153
/**
154
 * Lists the classifications a taxon belongs to
155
 *
156
 * @param CDM type Taxon $taxon
157
 *   the taxon
158
 *
159
 * @return array
160
 *   aray of CDM instances of Type Classification
161
 */
162
function get_classifications_for_taxon($taxon) {
163

    
164
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
165
}
166

    
167
/**
168
 * Returns the chosen FeatureTree for the taxon profile.
169
 *
170
 * The FeatureTree profile returned is the one that has been set in the
171
 * dataportal settings (layout->taxon:profile).
172
 * When the chosen FeatureTree is not found in the database,
173
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
174
 *
175
 * @return mixed
176
 *   A cdm FeatureTree object.
177
 */
178
function get_profile_featureTree() {
179
  static $profile_featureTree;
180

    
181
  if($profile_featureTree == NULL) {
182
    $profile_featureTree = cdm_ws_get(
183
      CDM_WS_FEATURETREE,
184
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
185
    );
186
    if (!$profile_featureTree) {
187
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
188
    }
189
  }
190
  return $profile_featureTree;
191
}
192

    
193
/**
194
 * Returns the chosen FeatureTree for SpecimenDescriptions.
195
 *
196
 * The FeatureTree returned is the one that has been set in the
197
 * dataportal settings (layout->taxon:specimen).
198
 * When the chosen FeatureTree is not found in the database,
199
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
200
 *
201
 * @return mixed
202
 *   A cdm FeatureTree object.
203
 */
204
function cdm_get_occurrence_featureTree() {
205
  static $occurrence_featureTree;
206

    
207
  if($occurrence_featureTree == NULL) {
208
    $occurrence_featureTree = cdm_ws_get(
209
      CDM_WS_FEATURETREE,
210
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
211
    );
212
    if (!$occurrence_featureTree) {
213
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
214
    }
215
  }
216
  return $occurrence_featureTree;
217
}
218

    
219
/**
220
 * Returns the FeatureTree for structured descriptions
221
 *
222
 * The FeatureTree returned is the one that has been set in the
223
 * dataportal settings (layout->taxon:profile).
224
 * When the chosen FeatureTree is not found in the database,
225
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
226
 *
227
 * @return mixed
228
 *   A cdm FeatureTree object.
229
 */
230
function get_structured_description_featureTree() {
231
  static $structured_description_featureTree;
232

    
233
  if($structured_description_featureTree == NULL) {
234
    $structured_description_featureTree = cdm_ws_get(
235
        CDM_WS_FEATURETREE,
236
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
237
    );
238
    if (!$structured_description_featureTree) {
239
      $structured_description_featureTree = cdm_ws_get(
240
          CDM_WS_FEATURETREE,
241
          UUID_DEFAULT_FEATURETREE
242
      );
243
    }
244
  }
245
  return $structured_description_featureTree;
246
}
247

    
248
/**
249
 * @todo Please document this function.
250
 * @see http://drupal.org/node/1354
251
 */
252
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
253
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
254
}
255

    
256
/**
257
 * @todo Please document this function.
258
 * @see http://drupal.org/node/1354
259
 */
260
function reset_taxonomictree_uuid($taxonomictree_uuid) {
261
  unset($_SESSION['cdm']['taxonomictree_uuid']);
262
}
263

    
264
/**
265
 * @todo Please document this function.
266
 * @see http://drupal.org/node/1354
267
 */
268
function set_last_taxon_page_tab($taxonPageTab) {
269
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
270
}
271

    
272
/**
273
 * @todo Please document this function.
274
 * @see http://drupal.org/node/1354
275
 */
276
function get_last_taxon_page_tab() {
277
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
278
    return $_SESSION['cdm']['taxon_page_tab'];
279
  }
280
  else {
281
    return FALSE;
282
  }
283
}
284

    
285
/**
286
 * @todo Improve the documentation of this function.
287
 *
288
 * media Array [4]
289
 * representations Array [3]
290
 * mimeType image/jpeg
291
 * representationParts Array [1]
292
 * duration 0
293
 * heigth 0
294
 * size 0
295
 * uri
296
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
297
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
298
 * width 0
299
 * suffix jpg
300
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
301
 * title
302
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
303
 *
304
 * @param object $media
305
 * @param array $mimeTypes
306
 * @param int $width
307
 * @param int $height
308
 *
309
 * @return array
310
 *   An array with preferred media representations or else an empty array.
311
 */
312
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
313
  $prefRepr = array();
314
  if (!isset($media->representations[0])) {
315
    return $prefRepr;
316
  }
317

    
318
  while (count($mimeTypes) > 0) {
319
    // getRepresentationByMimeType
320
    $mimeType = array_shift($mimeTypes);
321

    
322
    foreach ($media->representations as &$representation) {
323
      // If the mimetype is not known, try inferring it.
324
      if (!$representation->mimeType) {
325
        if (isset($representation->parts[0])) {
326
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
327
        }
328
      }
329

    
330
      if ($representation->mimeType == $mimeType) {
331
        // Preferred mimetype found -> erase all remaining mimetypes
332
        // to end loop.
333
        $mimeTypes = array();
334
        $dwa = 0;
335
        $dw = 0;
336
        // Look for part with the best matching size.
337
        foreach ($representation->parts as $part) {
338
          if (isset($part->width) && isset($part->height)) {
339
            $dw = $part->width * $part->height - $height * $width;
340
          }
341
          if ($dw < 0) {
342
            $dw *= -1;
343
          }
344
          $dwa += $dw;
345
        }
346
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
347
        // @WA: $mimeTypeKey is not defined.
348
        // $prefRepr[$dwa.'_'.$mimeTypeKey] = $representation;
349
        $prefRepr[$dwa . '_'] = $representation;
350
      }
351
    }
352
  }
353
  // Sort the array.
354
  krsort($prefRepr);
355
  return $prefRepr;
356
}
357

    
358
/**
359
 * Infers the mime type of a file using the filename extension.
360
 *
361
 * The filename extension is used to infer the mime type.
362
 *
363
 * @param string $filepath
364
 *   The path to the respective file.
365
 *
366
 * @return string
367
 *   The mimetype for the file or FALSE if the according mime type could
368
 *   not be found.
369
 */
370
function infer_mime_type($filepath) {
371
  static $mimemap = NULL;
372
  if (!$mimemap) {
373
    $mimemap = array(
374
      'jpg' => 'image/jpeg',
375
      'jpeg' => 'image/jpeg',
376
      'png' => 'image/png',
377
      'gif' => 'image/gif',
378
      'giff' => 'image/gif',
379
      'tif' => 'image/tif',
380
      'tiff' => 'image/tif',
381
      'pdf' => 'application/pdf',
382
      'html' => 'text/html',
383
      'htm' => 'text/html',
384
    );
385
  }
386
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
387
  if (isset($mimemap[$extension])) {
388
    return $mimemap[$extension];
389
  }
390
  else {
391
    // FIXME remove this hack just return FALSE;
392
    return 'text/html';
393
  }
394
}
395

    
396
/**
397
 * Converts an ISO 8601 org.joda.time.Partial to a year.
398
 *
399
 * The function expects an ISO 8601 time representation of a
400
 * org.joda.time.Partial of the form yyyy-MM-dd.
401
 *
402
 * @param string $partial
403
 *   ISO 8601 time representation of a org.joda.time.Partial.
404
 *
405
 * @return string
406
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
407
 */
408
function partialToYear($partial) {
409
  if (is_string($partial)) {
410
    $year = substr($partial, 0, 4);
411
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
412
      return $year;
413
    }
414
  }
415
  return;
416
}
417

    
418
/**
419
 * Converts an ISO 8601 org.joda.time.Partial to a month.
420
 *
421
 * This function expects an ISO 8601 time representation of a
422
 * org.joda.time.Partial of the form yyyy-MM-dd.
423
 * In case the month is unknown (= ???) NULL is returned.
424
 *
425
 * @param string $partial
426
 *   ISO 8601 time representation of a org.joda.time.Partial.
427
 *
428
 * @return string
429
 *   A month.
430
 */
431
function partialToMonth($partial) {
432
  if (is_string($partial)) {
433
    $month = substr($partial, 5, 2);
434
    if (preg_match("/[0-9][0-9]/", $month)) {
435
      return $month;
436
    }
437
  }
438
  return;
439
}
440

    
441
/**
442
 * Converts an ISO 8601 org.joda.time.Partial to a day.
443
 *
444
 * This function expects an ISO 8601 time representation of a
445
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
446
 * In case the day is unknown (= ???) NULL is returned.
447
 *
448
 * @param string $partial
449
 *   ISO 8601 time representation of a org.joda.time.Partial.
450
 *
451
 * @return string
452
 *   A day.
453
 */
454
function partialToDay($partial) {
455
  if (is_string($partial)) {
456
    $day = substr($partial, 8, 2);
457
    if (preg_match("/[0-9][0-9]/", $day)) {
458
      return $day;
459
    }
460
  }
461
  return;
462
}
463

    
464
/**
465
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
466
 *
467
 * This function expects an ISO 8601 time representations of a
468
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
469
 * four digit year, month and day with dashes:
470
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
471
 *
472
 * The partial may contain question marks eg: "1973-??-??",
473
 * these are turned in to '00' or are stripped depending of the $stripZeros
474
 * parameter.
475
 *
476
 * @param string $partial
477
 *   org.joda.time.Partial.
478
 * @param bool $stripZeros
479
 *   If set to TRUE the zero (00) month and days will be hidden:
480
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
481
 *
482
 * @return string
483
 *   YYYY-MM-DD formatted year, month, day.
484
 */
485
function partialToDate($partial, $stripZeros = TRUE) {
486
  $y = partialToYear($partial);
487
  $m = partialToMonth($partial);
488
  $d = partialToDay($partial);
489

    
490
  $y = $y ? $y : '00';
491
  $m = $m ? $m : '00';
492
  $d = $d ? $d : '00';
493

    
494
  $date = '';
495

    
496
  if ($y == '00' && $stripZeros) {
497
    return;
498
  }
499
  else {
500
    $date = $y;
501
  }
502

    
503
  if ($m == '00' && $stripZeros) {
504
    return $date;
505
  }
506
  else {
507
    $date .= "-" . $m;
508
  }
509

    
510
  if ($d == '00' && $stripZeros) {
511
    return $date;
512
  }
513
  else {
514
    $date .= "-" . $d;
515
  }
516
  return $date;
517
}
518

    
519
/**
520
 * Converts a time period to a string.
521
 *
522
 * See also partialToDate($partial, $stripZeros).
523
 *
524
 * @param object $period
525
 *   An JodaTime org.joda.time.Period object.
526
 * @param bool $stripZeros
527
 *   If set to True, the zero (00) month and days will be hidden:
528
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
529
 *
530
 * @return string
531
 *   Returns a date in the form of a string.
532
 */
533
function timePeriodToString($period, $stripZeros = TRUE) {
534
  $dateString = '';
535
  if ($period->start) {
536
    $dateString = partialToDate($period->start, $stripZeros);
537
  }
538
  if ($period->end) {
539
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
540
  }
541
  return $dateString;
542
}
543
/**
544
 * returns the earliest date available in the $period in a normalized
545
 * form suitable for sorting, e.g.:
546
 *
547
 *  - 1956-00-00
548
 *  - 0000-00-00
549
 *  - 1957-03-00
550
 *
551
 * that is either the start date is returned if set otherwise the
552
 * end date
553
 *
554
 * @param  $period
555
 *    An JodaTime org.joda.time.Period object.
556
 * @return string normalized form of the date
557
 *   suitable for sorting
558
 */
559
function timePeriodAsOrderKey($period) {
560
  $dateString = '';
561
  if ($period->start) {
562
    $dateString = partialToDate($period->start, false);
563
  }
564
  if ($period->end) {
565
    $dateString .= partialToDate($period->end, false);
566
  }
567
  return $dateString;
568
}
569

    
570
/**
571
 * Composes a CDM webservice URL with parameters and querystring.
572
 *
573
 * @param string $uri_pattern
574
 *   String with place holders ($0, $1, ..) that should be replaced by the
575
 *   according element of the $pathParameters array.
576
 * @param array $pathParameters
577
 *   An array of path elements, or a single element.
578
 * @param string $query
579
 *   A query string to append to the URL.
580
 *
581
 * @return string
582
 *   A complete URL with parameters to a CDM webservice.
583
 */
584
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
585
  if (empty($pathParameters)) {
586
    $pathParameters = array();
587
  }
588

    
589
  $request_params = '';
590
  $path_params = '';
591

    
592
  // (1)
593
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
594
  // according element of the $pathParameters array.
595
  static $helperArray = array();
596
  if (isset($pathParameters) && !is_array($pathParameters)) {
597
    $helperArray[0] = $pathParameters;
598
    $pathParameters = $helperArray;
599
  }
600

    
601
  $i = 0;
602
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
603
    if (count($pathParameters) <= $i) {
604
      if (module_exists("user") && user_access('administer')) {
605
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
606
      }
607
      break;
608
    }
609
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
610
    ++$i;
611
  }
612

    
613
  // (2)
614
  // Append all remaining element of the $pathParameters array as path
615
  // elements.
616
  if (count($pathParameters) > $i) {
617
    // Strip trailing slashes.
618
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
619
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
620
    }
621
    while (count($pathParameters) > $i) {
622
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
623
      ++$i;
624
    }
625
  }
626

    
627
  // (3)
628
  // Append the query string supplied by $query.
629
  if (isset($query)) {
630
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
631
  }
632

    
633
  $path = $uri_pattern;
634

    
635
  $uri = variable_get('cdm_webservice_url', '') . $path;
636
  return $uri;
637
}
638

    
639
/**
640
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
641
 *     together with a theme name to such a proxy function?
642
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
643
 *     Maybe we want to have two different proxy functions, one with theming and one without?
644
 *
645
 * @param string $uri
646
 *     A URI to a CDM Rest service from which to retrieve an object
647
 * @param string|null $hook
648
 *     (optional) The hook name to which the retrieved object should be passed.
649
 *     Hooks can either be a theme_hook() or compose_hook() implementation
650
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
651
 *     suitable for drupal_render()
652
 *
653
 * @todo Please document this function.
654
 * @see http://drupal.org/node/1354
655
 */
656
function proxy_content($uri, $hook = NULL) {
657
  $args = func_get_args();
658

    
659
  $uriEncoded = array_shift($args);
660
  $uri = urldecode($uriEncoded);
661
  $hook = array_shift($args);
662

    
663
  // Find and deserialize arrays.
664
  foreach ($args as &$arg) {
665
    // FIXME use regex to find serialized arrays.
666
    //       or should we accept json instead pf php serializations?
667
    if (strpos($arg, "a:") === 0) {
668
      $arg = unserialize($arg);
669
    }
670
  }
671

    
672
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
673
  if ($request_method == "POST") {
674
    // this is an experimental feature which will allow to
675
    // write data inot the cdm via the RESTfull web service
676
    $parameters = $_POST;
677
    $post_data = array();
678

    
679
    foreach ($parameters as $k => $v) {
680
      $post_data[] = "$k=" . utf8_encode($v);
681
    }
682
    $post_data = implode(',', $post_data);
683

    
684
    // For testing.
685
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
686
    // print $data;
687
  } else {
688
    // Not a "POST" request
689
    // In all these cases perform a simple get request.
690
    // TODO reconsider caching logic in this function.
691

    
692
    if (empty($hook)) {
693
      // simply return the webservice response
694
      // Print out JSON, the cache cannot be used since it contains objects.
695
      $http_response = drupal_http_request($uri, array('timeout' => CDM_HTTP_REQUEST_TIMEOUT));
696
      if (isset($http_response->headers)) {
697
        foreach ($http_response->headers as $hname => $hvalue) {
698
          drupal_add_http_header($hname, $hvalue);
699
        }
700
      }
701
      if (isset($http_response->data)) {
702
        print $http_response->data;
703
      }
704
      exit();
705
    } else {
706
      // $hook has been supplied
707
      // handle $hook either as compose ot theme hook
708
      // pass through theme or comose hook
709

    
710
      // do a security check since the $uri will be passed
711
      // as absolute URI to cdm_ws_get()
712
      if( !_is_cdm_ws_uri($uri)) {
713
        drupal_set_message(
714
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
715
            'error'
716
        );
717
        return '';
718
      }
719

    
720
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
721
      $theme_result = NULL;
722

    
723
      if (function_exists('compose_' . $hook)){
724
        // call compose hook
725

    
726
        $elements =  call_user_func('compose_' . $hook, $obj);
727
        // pass the render array to drupal_render()
728
        $theme_result = drupal_render($elements);
729
      } else {
730
        // call theme hook
731

    
732
        // TODO use theme registry to get the registered hook info and
733
        //    use these defaults
734
        switch($hook) {
735
          case 'cdm_taxontree':
736
            $variables = array(
737
              'tree' => $obj,
738
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
739
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
740
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
741
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
742
            );
743
            $theme_result = theme($hook, $variables);
744
            break;
745

    
746
          case 'cdm_media_caption':
747
            $variables = array(
748
              'media' => $obj,
749
              // $args[0] is set in taxon_image_gallery_default in
750
              // cdm_dataportal.page.theme.
751
              'elements' => isset($args[0]) ? $args[0] : array(
752
                'title',
753
                'description',
754
                'artist',
755
                'location',
756
                'rights',
757
              ),
758
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
759
            );
760
            $theme_result = theme($hook, $variables);
761
            break;
762

    
763
          default:
764
            drupal_set_message(t(
765
            'Theme !theme is not supported yet by function !function.', array(
766
            '!theme' => $hook,
767
            '!function' => __FUNCTION__,
768
            )), 'error');
769
            break;
770
        } // END of theme hook switch
771
      } // END of tread as theme hook
772
      print $theme_result;
773
    } // END of handle $hook either as compose ot theme hook
774
  }
775
}
776

    
777
/**
778
 * @todo Please document this function.
779
 * @see http://drupal.org/node/1354
780
 */
781
function setvalue_session() {
782
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
783
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
784
    $keys = explode('][', $keys);
785
  }
786
  else {
787
    return;
788
  }
789
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
790

    
791
  // Prevent from malicous tags.
792
  $val = strip_tags($val);
793

    
794
  $var = &$_SESSION;
795
  $i = 0;
796
  foreach ($keys as $key) {
797
    $hasMoreKeys = ++$i < count($var);
798
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
799
      $var[$key] = array();
800
    }
801
    $var = &$var[$key];
802
  }
803
  $var = $val;
804
  if (isset($_REQUEST['destination'])) {
805
    drupal_goto($_REQUEST['destination']);
806
  }
807
}
808

    
809
/**
810
 * @todo Please document this function.
811
 * @see http://drupal.org/node/1354
812
 */
813
function uri_uriByProxy($uri, $theme = FALSE) {
814
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
815
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
816
}
817

    
818
/**
819
 * @todo Please document this function.
820
 * @see http://drupal.org/node/1354
821
 */
822
function cdm_compose_annotations_url($cdmBase) {
823
  if (!$cdmBase->uuid) {
824
    return;
825
  }
826

    
827
  $ws_base_uri = NULL;
828
  switch ($cdmBase->class) {
829
    case 'TaxonBase':
830
    case 'Taxon':
831
    case 'Synonym':
832
      $ws_base_uri = CDM_WS_TAXON;
833
      break;
834

    
835
    case 'TaxonNameBase':
836
    case 'NonViralName':
837
    case 'BacterialName':
838
    case 'BotanicalName':
839
    case 'CultivarPlantName':
840
    case 'ZoologicalName':
841
    case 'ViralName':
842
      $ws_base_uri = CDM_WS_NAME;
843
      break;
844

    
845
    case 'Media':
846
      $ws_base_uri = CDM_WS_MEDIA;
847
      break;
848

    
849
    case 'Reference':
850
      $ws_base_uri = CDM_WS_REFERENCE;
851
      break;
852

    
853
    case 'Distribution':
854
    case 'TextData':
855
    case 'TaxonInteraction':
856
    case 'QuantitativeData':
857
    case 'IndividualsAssociation':
858
    case 'Distribution':
859
    case 'CommonTaxonName':
860
    case 'CategoricalData':
861
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
862
      break;
863

    
864
    case 'PolytomousKey':
865
    case 'MediaKey':
866
    case 'MultiAccessKey':
867
      $ws_base_uri = $cdmBase->class;
868
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
869
      break;
870

    
871
    default:
872
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
873
      return;
874
  }
875
  return cdm_compose_url($ws_base_uri, array(
876
    $cdmBase->uuid,
877
    'annotations',
878
  ));
879
}
880

    
881
/**
882
 * Enter description here...
883
 *
884
 * @param string $resourceURI
885
 * @param mixed $pageSize
886
 *   The maximum number of entities returned per page (can be NULL
887
 *   to return all entities in a single page).
888
 * @param int $pageNumber
889
 *   The number of the page to be returned, the first page has the
890
 *   pageNumber = 1.
891
 *
892
 * @return unknown
893
 * FIXME seems to be out of date, maybe uused? webservices are using pageNumber parameter?
894
 */
895
function cdm_ws_page($resourceURI, $pageSize, $pageNumber) {
896
  return cdm_ws_get($resourceURI, NULL, queryString(array(
897
    "page" => $pageNumber,
898
    'pageSize' => $pageSize,
899
  )));
900
}
901

    
902
/*
903
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
904
  $viewrank = _cdm_taxonomy_compose_viewrank();
905
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
906
  ? '/' . $path : '') ;
907
}
908
*/
909

    
910
/**
911
 * @todo Enter description here...
912
 *
913
 * @param string $taxon_uuid
914
 *  The UUID of a cdm taxon instance
915
 * @param string $ignore_rank_limit
916
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
917
 *
918
 * @return A cdm REST service URL path to a Classification
919
 */
920
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
921

    
922
  $view_uuid = get_taxonomictree_uuid_selected();
923
  $rank_uuid = NULL;
924
  if (!$ignore_rank_limit) {
925
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
926
  }
927

    
928
  if (!empty($taxon_uuid)) {
929
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
930
      $view_uuid,
931
      $taxon_uuid,
932
    ));
933
  }
934
  else {
935
    if (!empty($rank_uuid)) {
936
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
937
        $view_uuid,
938
        $rank_uuid,
939
      ));
940
    }
941
    else {
942
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
943
        $view_uuid,
944
      ));
945
    }
946
  }
947
}
948

    
949
/**
950
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
951
 *
952
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
953
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
954
 *
955
 * Operates in two modes depending on whether the parameter
956
 * $taxon_uuid is set or NULL.
957
 *
958
 * A) $taxon_uuid = NULL:
959
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
960
 *  2. otherwise return the default classification as defined by the admin via the settings
961
 *
962
 * b) $taxon_uuid is set:
963
 *   return the classification to whcih the taxon belongs to.
964
 *
965
 * @param UUID $taxon_uuid
966
 *   The UUID of a cdm taxon instance
967
 */
968
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
969

    
970
    $response = NULL;
971

    
972
    // 1st try
973
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
974

    
975
    if ($response == NULL) {
976
      // 2dn try by ignoring the rank limit
977
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
978
    }
979

    
980
    if ($response == NULL) {
981
      // 3rd try, last fallback:
982
      //    return the default classification
983
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
984
        // Delete the session value and try again with the default.
985
        unset($_SESSION['cdm']['taxonomictree_uuid']);
986
        return cdm_ws_taxonomy_root_level($taxon_uuid);
987
      }
988
      else {
989
        // Check if taxonomictree_uuid is valid.
990
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
991
        if ($test == NULL) {
992
          // The default set by the admin seems to be invalid or is not even set.
993
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
994
        }
995
      }
996
    }
997

    
998
  return $response;
999
}
1000

    
1001
/**
1002
 * @todo Enter description here...
1003
 *
1004
 * @param string $taxon_uuid
1005
 *
1006
 * @return unknown
1007
 */
1008
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1009
  $view_uuid = get_taxonomictree_uuid_selected();
1010
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1011

    
1012
  $response = NULL;
1013
  if ($rank_uuid) {
1014
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1015
      $view_uuid,
1016
      $taxon_uuid,
1017
      $rank_uuid,
1018
    ));
1019
  }
1020
  else {
1021
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1022
      $view_uuid,
1023
      $taxon_uuid,
1024
    ));
1025
  }
1026

    
1027
  if ($response == NULL) {
1028
    // Error handing.
1029
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1030
      // Delete the session value and try again with the default.
1031
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1032
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1033
    }
1034
    else {
1035
      // Check if taxonomictree_uuid is valid.
1036
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1037
      if ($test == NULL) {
1038
        // The default set by the admin seems to be invalid or is not even set.
1039
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1040
      }
1041
    }
1042
  }
1043

    
1044
  return $response;
1045
}
1046

    
1047
/**
1048
 * @todo Please document this function.
1049
 * @see http://drupal.org/node/1354
1050
 */
1051
function cdm_rankVocabulary_as_option() {
1052
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1053
  array_unshift ($options, "");
1054
  return $options;
1055
}
1056

    
1057
/**
1058
 *
1059
 * @param Object $definedTermBase
1060
 * 	  of cdm type DefinedTermBase
1061
 * @return string
1062
 * 	  the localized representation_L10n of the term,
1063
 *    otherwise the titleCache as fall back,
1064
 *    otherwise an empty string
1065
 */
1066
function cdm_term_representation($definedTermBase) {
1067
  if ( isset($definedTermBase->representation_L10n) ) {
1068
    return $definedTermBase->representation_L10n;
1069
  } elseif ( isset($definedTermBase->titleCache)) {
1070
    return $definedTermBase->titleCache;
1071
  }
1072
  return '';
1073
}
1074

    
1075
/**
1076
 * @todo Improve documentation of this function.
1077
 *
1078
 * eu.etaxonomy.cdm.model.description.
1079
 * CategoricalData
1080
 * CommonTaxonName
1081
 * Distribution
1082
 * IndividualsAssociation
1083
 * QuantitativeData
1084
 * TaxonInteraction
1085
 * TextData
1086
 */
1087
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1088
  static $types = array(
1089
    "CategoricalData",
1090
    "CommonTaxonName",
1091
    "Distribution",
1092
    "IndividualsAssociation",
1093
    "QuantitativeData",
1094
    "TaxonInteraction",
1095
    "TextData",
1096
  );
1097

    
1098
  static $options = NULL;
1099
  if ($options == NULL) {
1100
    $options = array();
1101
    if ($prependEmptyElement) {
1102
      $options[' '] = '';
1103
    }
1104
    foreach ($types as $type) {
1105
      // No internatianalization here since these are purely technical terms.
1106
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1107
    }
1108
  }
1109
  return $options;
1110
}
1111

    
1112
/**
1113
 * @todo Please document this function.
1114
 * @see http://drupal.org/node/1354
1115
 */
1116
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1117
  static $vocabularyOptions = array();
1118

    
1119
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1120
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1121
    $vocabularyOptions[$vocabularyUuid] = array();
1122

    
1123
    if ($vocab) {
1124
      foreach ($vocab->terms as $term) {
1125
        if ($term_label_callback && function_exists($term_label_callback)) {
1126
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1127
        }
1128
        else {
1129
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1130
        }
1131
      }
1132
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1133
    }
1134
  }
1135
  return $vocabularyOptions[$vocabularyUuid];
1136
}
1137

    
1138
/**
1139
 * @todo Please document this function.
1140
 * @see http://drupal.org/node/1354
1141
 */
1142
function _cdm_relationship_type_term_label_callback($term) {
1143
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1144
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1145
  }
1146
  else {
1147
    return t($term->representation_L10n);
1148
  }
1149
}
1150

    
1151
/**
1152
 * @todo Please document this function.
1153
 * @see http://drupal.org/node/1354
1154
 */
1155
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1156
  if (!$featureTree) {
1157
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1158
      In order to see the species profiles of your taxa, please select a
1159
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1160
    return FALSE;
1161
  }
1162

    
1163
  $mergedTrees = array();
1164

    
1165
  if ($isDescriptionsSeparated) {
1166
    // Merge any description into a separate feature tree.
1167
    foreach ($descriptions as $desc) {
1168
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1169

    
1170
      $mergedTree = clone $featureTree;
1171
      $mergedTree->root->children = $mergedNodes;
1172
      $mergedTrees[] = $mergedTree;
1173
    }
1174
  }
1175
  else {
1176
    // Combine all descripions into one feature tree.
1177
    $descriptionElemens = array();
1178
    foreach ($descriptions as $desc) {
1179
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1180
    }
1181
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1182
    $featureTree->root->children = $mergedNodes;
1183
    $mergedTrees[] = $featureTree;
1184
  }
1185

    
1186
  return $mergedTrees;
1187
}
1188

    
1189
/**
1190
 * Get a list of annotations for a cdm entity.
1191
 *
1192
 * @param string $cdmBase
1193
 *   An annotatable cdm entity.
1194
 * @param array $includeTypes
1195
 *   If an array of annotation type uuids is supplied by this parameter the
1196
 *   list of annotations is resticted to those which belong to this type.
1197
 *
1198
 * @return array
1199
 *   An array of Annotation objects or an empty array.
1200
 */
1201
function cdm_ws_getAnnotationsFor($cdmBase, $includeTypes = FALSE) {
1202
  $annotationUrl = cdm_compose_annotations_url($cdmBase);
1203
  if ($annotationUrl) {
1204
    $annotationPager = cdm_ws_get($annotationUrl, NULL, NULL, NULL, TRUE);
1205
    if (isset($annotationPager->records) && is_array($annotationPager->records)) {
1206
      $annotations = array();
1207
      foreach ($annotationPager->records as $annotation) {
1208
        if ($includeTypes) {
1209
          if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1210
            $annotations[] = $annotation;
1211
          }
1212
        }
1213
        else {
1214
          $annotations[] = $annotation;
1215
        }
1216
      }
1217
      return $annotations;
1218
    }
1219
  }
1220
}
1221

    
1222
/**
1223
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1224
 *
1225
 * @param object $annotatable_entity
1226
 *   The CDM AnnotatableEntity to load annotations for
1227
 */
1228
function cdm_load_annotations(&$annotatable_entity) {
1229
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1230
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1231
    if (is_array($annotations)) {
1232
      $annotatable_entity->annotations = $annotations;
1233
    }
1234
  }
1235
}
1236

    
1237
/**
1238
 * Get a NomenclaturalReference string.
1239
 *
1240
 * Returns the NomenclaturalReference string with correctly placed
1241
 * microreference (= reference detail) e.g.
1242
 * in Phytotaxa 43: 1-48. 2012.
1243
 *
1244
 * @param string $referenceUuid
1245
 *   UUID of the reference.
1246
 * @param string $microreference
1247
 *   Reference detail.
1248
 *
1249
 * @return string
1250
 *   a NomenclaturalReference.
1251
 */
1252
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1253
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1254
    $referenceUuid,
1255
  ), "microReference=" . urlencode($microreference));
1256

    
1257
  if ($obj) {
1258
    return $obj->String;
1259
  }
1260
  else {
1261
    return NULL;
1262
  }
1263
}
1264

    
1265
/**
1266
 * Merges the given featureNodes structure with the descriptionElements.
1267
 *
1268
 * This method is used in preparation for rendering the descriptionElements.
1269
 * The descriptionElements wich belong to a specific feature node are appended
1270
 * to a the feature node by creating a new fields:
1271
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1272
 * The descriptionElements will be cleared in advance in order to allow reusing the
1273
 * same feature tree without the risk of mixing sets of descrition elemens.
1274
 *
1275
 * which originally is not existing in the cdm.
1276
 *
1277
 *
1278
 *
1279
 * @param array $featureNodes
1280
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1281
 *    may have children.
1282
 * @param array $descriptionElements
1283
 *    An flat array of cdm DescriptionElements
1284
 * @return array
1285
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1286
 */
1287
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1288

    
1289
  foreach ($featureNodes as &$node) {
1290
    // since the $featureNodes array is reused for each description
1291
    // it is nessecary to clear the custom node fields in advance
1292
    if(isset($node->descriptionElements)){
1293
      unset($node->descriptionElements);
1294
    }
1295

    
1296
    // Append corresponding elements to an additional node field:
1297
    // $node->descriptionElements.
1298
    foreach ($descriptionElements as $element) {
1299
      if ($element->feature->uuid == $node->feature->uuid) {
1300
        if (!isset($node->descriptionElements)) {
1301
          $node->descriptionElements = array();
1302
        }
1303
        $node->descriptionElements[] = $element;
1304
      }
1305
    }
1306

    
1307
    // Recurse into node children.
1308
    if (isset($node->children[0])) {
1309
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1310
      $node->children = $mergedChildNodes;
1311
    }
1312

    
1313
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1314
      unset($node);
1315
    }
1316

    
1317
  }
1318

    
1319
  return $featureNodes;
1320
}
1321

    
1322
/**
1323
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1324
 *
1325
 * The response from the HTTP GET request is returned as object.
1326
 * The response objects coming from the webservice configured in the
1327
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1328
 *  in a level 2 (L2) cache.
1329
 *
1330
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1331
 * function, this cache persists only per each single page execution.
1332
 * Any object coming from the webservice is stored into it by default.
1333
 * In contrast to this default caching mechanism the L2 cache only is used if
1334
 * the 'cdm_webservice_cache' variable is set to TRUE,
1335
 * which can be set using the modules administrative settings section.
1336
 * Objects stored in this L2 cache are serialized and stored
1337
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1338
 * objects that are stored in the database will persist as
1339
 * long as the drupal cache is not beeing cleared and are available across
1340
 * multiple script executions.
1341
 *
1342
 * @param string $uri
1343
 *   URL to the webservice.
1344
 * @param array $pathParameters
1345
 *   An array of path parameters.
1346
 * @param string $query
1347
 *   A query string to be appended to the URL.
1348
 * @param string $method
1349
 *   The HTTP method to use, valid values are "GET" or "POST";
1350
 * @param bool $absoluteURI
1351
 *   TRUE when the URL should be treated as absolute URL.
1352
 *
1353
 * @return object
1354
 *   The deserialized webservice response object.
1355
 */
1356
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1357
  // static $cacheL1; if(!isset($cacheL1)){ $cacheL1 = array(); }
1358
  static $cacheL1 = array();
1359

    
1360
  // Transform the given uri path or pattern into a proper webservice uri.
1361
  if (!$absoluteURI) {
1362
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1363
  }
1364

    
1365
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1366
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1367

    
1368
  if (array_key_exists($uri, $cacheL1)) {
1369
    $cacheL1_obj = $cacheL1[$uri];
1370
  }
1371

    
1372
  $set_cacheL1 = FALSE;
1373
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1374
    $set_cacheL1 = TRUE;
1375
  }
1376

    
1377
  // Only cache cdm webservice URIs.
1378
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1379
  $cacheL2_entry = FALSE;
1380

    
1381
  if ($use_cacheL2) {
1382
    // Try to get object from cacheL2.
1383
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1384
  }
1385

    
1386
  if (isset($cacheL1_obj)) {
1387
    //
1388
    // The object has been found in the L1 cache.
1389
    //
1390
    $obj = $cacheL1_obj;
1391
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1392
      _add_status_message_toggler();
1393
      _add_debugMessageStr('Using cacheL1 for: ' . $uri);
1394
    }
1395
  }
1396
  elseif ($cacheL2_entry) {
1397
    //
1398
    // The object has been found in the L2 cache.
1399
    //
1400
    $obj = unserialize($cacheL2_entry->data);
1401

    
1402
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1403
      _add_status_message_toggler();
1404
      _add_debugMessageStr('Using cacheL2 for: ' . $uri);
1405
    }
1406
  }
1407
  else {
1408
    //
1409
    // Get the object from the webservice and cache it.
1410
    //
1411
    $time_get_start = microtime(TRUE);
1412
    // Request data from webservice JSON or XML.
1413
    $datastr = cdm_http_request($uri, $method);
1414
    $time_get = microtime(TRUE) - $time_get_start;
1415

    
1416
    $time_parse_start = microtime(TRUE);
1417

    
1418
    // Parse data and create object.
1419
    $obj = cdm_load_obj($datastr);
1420

    
1421
    $time_parse = microtime(TRUE) - $time_parse_start;
1422
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1423
      if ($obj || $datastr == "[]") {
1424
        $success_msg = 'valid';
1425
      }
1426
      else {
1427
        $success_msg = 'invalid';
1428
      }
1429
      _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
1430
    }
1431
    if ($set_cacheL2) {
1432
      // Store the object in cache L2.
1433
      // Comment @WA perhaps better if Drupal serializes here? Then the
1434
      // flag serialized is set properly in the cache table.
1435
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1436
    }
1437
  }
1438
  if ($obj) {
1439
    // Store the object in cache L1.
1440
    if ($set_cacheL1) {
1441
      $cacheL1[$uri] = $obj;
1442
    }
1443
  }
1444
  return $obj;
1445
}
1446

    
1447
/**
1448
 * @todo Please document this function.
1449
 * @see http://drupal.org/node/1354
1450
 */
1451
function _add_debugMessageStr($message) {
1452
  _add_status_message_toggler();
1453
  drupal_set_message(check_plain($message), 'debug');
1454
}
1455

    
1456
/**
1457
 * @todo Please document this function.
1458
 * @see http://drupal.org/node/1354
1459
 */
1460
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg) {
1461
  static $cumulated_time_parse = 0;
1462
  static $cumulated_time_get = 0;
1463
  _add_status_message_toggler();
1464

    
1465
  $cumulated_time_get += $time_get;
1466
  $cumulated_time_parse += $time_parse;
1467

    
1468
  // Decompose uri into path and query element.
1469
  // URI query elements are stored in an array
1470
  // suitable for drupal_http_build_query()
1471
  $uri_parts = explode("?", $uri);
1472
  $query = array();
1473
  if (count($uri_parts) == 2) {
1474
    $path = $uri_parts[0];
1475
    $queryparts = explode("&", $uri_parts[1]);
1476
    foreach ($queryparts as $querypart) {
1477
      $querypart = explode("=", $querypart);
1478
      if(count($querypart) == 2){
1479
        $query[$querypart[0]] = $querypart[1];
1480
      } else {
1481
        $query[$querypart[0]] = null;
1482
      }
1483
    }
1484
  }
1485
  else {
1486
    $path = $uri;
1487
  }
1488

    
1489
  $message = '<span class="uri">' . $uri . '</span><br />';
1490
  $message .= '[fetched in: ' . sprintf('%3.3f', $time_get) . 's(' . sprintf('%3.3f', $cumulated_time_get) . 's); ';
1491
  $message .= 'parsed in ' . sprintf('%3.3f', $time_parse) . ' s(' . sprintf('%3.3f', $cumulated_time_parse) . 's); ';
1492
  $message .= 'size:' . sprintf('%3.1f', ($datasize / 1024)) . ' kb of ' . $success_msg . ' data: ';
1493
  if (_is_cdm_ws_uri($path)) {
1494
    $message .= '<a href="' . url($path . '.xml', array(
1495
      'query' => $query,
1496
    )) . '" target="data" class="' . $success_msg . '">xml</a>-';
1497
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array(
1498
      'query' => $query,
1499
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>,';
1500
    $message .= '<a href="' . url($path . '.json', array(
1501
      'query' => $query,
1502
    )) . '" target="data" class="' . $success_msg . '">json</a>-';
1503
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.json', array(
1504
      'query' => $query,
1505
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>';
1506
  }
1507
  else {
1508
    $message .= '<a href="' . url($path, array(
1509
      'query' => $query,
1510
    )) . '" target="data" class="' . $success_msg . '">open</a>';
1511
  }
1512
  $message .= '] ';
1513
  drupal_set_message(($message), 'debug');
1514
}
1515

    
1516
/**
1517
 * @todo Please document this function.
1518
 * @see http://drupal.org/node/1354
1519
 */
1520
function cdm_load_obj($datastr) {
1521
  $obj = json_decode($datastr);
1522

    
1523
  if (!(is_object($obj) || is_array($obj))) {
1524
    ob_start();
1525
    $obj_dump = ob_get_contents();
1526
    ob_clean();
1527
    return FALSE;
1528
  }
1529

    
1530
  return $obj;
1531
}
1532

    
1533
/**
1534
 * Do a http request to a CDM webservice.
1535
 *
1536
 * @param string $uri
1537
 *   The webservice url.
1538
 * @param string $method
1539
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1540
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1541
 * @param array $parameters
1542
 *   Parameters to use in the request.
1543
 * @param array $header
1544
 *   The header to include in the request.
1545
 *
1546
 * @return
1547
 *   The response data from the request.
1548
 */
1549
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array()) {
1550
  static $acceptLanguage = NULL;
1551

    
1552
  if (!$acceptLanguage) {
1553
    if (function_exists('apache_request_headers')) {
1554
      $headers = apache_request_headers();
1555
      if (isset($headers['Accept-Language'])) {
1556
        $acceptLanguage = $headers['Accept-Language'];
1557
      }
1558
    }
1559
    if (!$acceptLanguage) {
1560
      // DEFAULT TODO make configurable.
1561
      $acceptLanguage = "en";
1562
    }
1563
  }
1564

    
1565
  if ($method != "GET" && $method != "POST") {
1566
    $method = "GET";
1567
  }
1568

    
1569
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1570
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
1571
    $header['Accept-Language'] = $acceptLanguage;
1572
    $header['Accept-Charset'] = 'UTF-8';
1573
  }
1574

    
1575
  if (FALSE && function_exists('curl_init')) {
1576
    // !!!!! CURL Disabled due to problems with following redirects
1577
    // (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
1578
    // Use the CURL lib if installed, it is supposed to be 20x faster.
1579
    return _http_request_using_curl($uri, $header, $method, $parameters);
1580
  }
1581
  else {
1582
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
1583
  }
1584
}
1585

    
1586
/**
1587
 * @todo Please document this function.
1588
 * @see http://drupal.org/node/1354
1589
 */
1590
function _http_request_using_fsockopen($uri, $header = array(), $method = 'GET') {
1591
  $response = drupal_http_request($uri, array('headers' => $header, 'method' => $method, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
1592
  if (isset($response->data)) {
1593
      return $response->data;
1594
  }
1595
}
1596

    
1597
/**
1598
 * Return string content from a remote file.
1599
 *
1600
 * @author Luiz Miguel Axcar <lmaxcar@yahoo.com.br>
1601
 *
1602
 * @param string $uri
1603
 *   The url for which to return content.
1604
 *
1605
 * @return string
1606
 *   The returned content.
1607
 */
1608
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array()) {
1609
  $ch = curl_init();
1610

    
1611
  curl_setopt($ch, CURLOPT_URL, $uri);
1612
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1613
  curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1614

    
1615
  // Set proxy settings.
1616
  if (variable_get('cdm_webservice_proxy_url', FALSE)) {
1617
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
1618
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
1619
    if (variable_get('cdm_webservice_proxy_usr', FALSE)) {
1620
      curl_setopt($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '') . ':' . variable_get('cdm_webservice_proxy_pwd', ''));
1621
    }
1622
  }
1623

    
1624
  // Modify headers array to be used by curl.
1625
  foreach ($headers as $header_key => $header_val) {
1626
    $curl_headers[] = $header_key . ': ' . $header_val;
1627
  }
1628
  if (isset($curl_headers)) {
1629
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
1630
  }
1631

    
1632
  // Set method if not default.
1633
  if ($method != "GET") {
1634
    if ($method == "POST") {
1635

    
1636
      curl_setopt($ch, CURLOPT_POST, 1);
1637
      curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
1638
    }
1639
    else {
1640
      // Other obscure http methods get passed to curl directly.
1641
      // TODO generic parameter/body handling
1642
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
1643
    }
1644
  }
1645

    
1646
  ob_start();
1647
  curl_exec($ch);
1648
  $info = curl_getinfo($ch);
1649
  if (curl_errno($ch)) {
1650
    watchdog('CDM_API', '_http_request_curl() - ' . curl_error($ch) . '; REQUEST-METHOD:' . $method . ' URL: ' . substr($uri . ' ', 0, 150), WATCHDOG_ERROR);
1651
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1652
      drupal_set_message(check_plain(t('_http_request_curl() - !curl_error; REQUEST-METHOD:!method URL: !url', array(
1653
      '!curl_error' => curl_error($ch),
1654
      '!method' => $method,
1655
      '!url' => substr($uri . ' ', 0, 150),
1656
       ))), 'error');
1657
    }
1658
  }
1659
  curl_close($ch);
1660
  $string = ob_get_contents();
1661
  ob_end_clean();
1662

    
1663
  return $string;
1664
}
1665

    
1666
/**
1667
 * @todo Please document this function.
1668
 * @see http://drupal.org/node/1354
1669
 */
1670
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1671
  $out = '';
1672

    
1673
  foreach ($rootNode->children as $featureNode) {
1674
    $out .= ($out ? $separator : '');
1675
    $out .= $featureNode->feature->representation_L10n;
1676
    if (is_array($featureNode->children)) {
1677
      $childlabels = '';
1678
      foreach ($featureNode->children as $childNode) {
1679
        $childlabels .= ($childlabels ? $separator : '');
1680
      }
1681
      $childlabels .= _featureTree_elements_toString($childNode);
1682
    }
1683
    if ($childlabels) {
1684
      $out .= '[' . $childlabels . ' ]';
1685
    }
1686
  }
1687
  return $out;
1688
}
1689

    
1690
/**
1691
 * Create a one-dimensional form options array.
1692
 *
1693
 * Creates an array of all features in the feature tree of feature nodes,
1694
 * the node labels are indented by $node_char and $childIndent depending on the
1695
 * hierachy level.
1696
 *
1697
 * @param - $rootNode
1698
 * @param - $node_char
1699
 * @param - $childIndentStr
1700
 * @param - $childIndent
1701
 *   ONLY USED INTERNALLY!
1702
 *
1703
 * @return array
1704
 *   A one dimensional Drupal form options array.
1705
 */
1706
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1707
  $options = array();
1708
  foreach ($rootNode->children as $featureNode) {
1709
    $indent_prefix = '';
1710
    if ($childIndent) {
1711
      $indent_prefix = $childIndent . $node_char . " ";
1712
    }
1713
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1714
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1715
      // Foreach ($featureNode->children as $childNode){
1716
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1717
      $options = array_merge_recursive($options, $childList);
1718
      // }
1719
    }
1720
  }
1721
  return $options;
1722
}
1723

    
1724
/**
1725
 * Returns an array with all available FeatureTrees and the representations of the selected
1726
 * FeatureTree as a detail view.
1727
 *
1728
 * @param boolean $add_default_feature_free
1729
 * @return array
1730
 *  associative array with following keys:
1731
 *  -options: Returns an array with all available Feature Trees
1732
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1733
 *
1734
 */
1735
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1736

    
1737
  $options = array();
1738
  $tree_representations = array();
1739
  $feature_trees = array();
1740

    
1741
  // Set tree that contains all features.
1742
  if ($add_default_feature_free) {
1743
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1744
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1745
  }
1746

    
1747
  // Get feature trees from database.
1748
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1749
  if (is_array($persited_trees)) {
1750
    $feature_trees = array_merge($feature_trees, $persited_trees);
1751
  }
1752

    
1753
  foreach ($feature_trees as $featureTree) {
1754

    
1755
    // Do not add the DEFAULT_FEATURETREE again,
1756
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1757
      $options[$featureTree->uuid] = $featureTree->titleCache;
1758
    }
1759

    
1760
    // Render the hierarchic tree structure
1761
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1762

    
1763
      // Render the hierarchic tree structure.
1764
      $treeDetails = '<div class="featuretree_structure">'
1765
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1766
        . '</div>';
1767

    
1768
      $form = array();
1769
      $form['featureTree-' .  $featureTree->uuid] = array(
1770
        '#type' => 'fieldset',
1771
        '#title' => 'Show details',
1772
        '#attributes' => array('class' => array('collapsible collapsed')),
1773
        // '#collapsible' => TRUE,
1774
        // '#collapsed' => TRUE,
1775
      );
1776
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1777
        '#markup' => $treeDetails,
1778
      );
1779

    
1780
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1781
    }
1782

    
1783
  } // END loop over feature trees
1784

    
1785
  // return $options;
1786
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1787
}
1788

    
1789
/**
1790
 * Provides the list of availbale classifications in form of an options array.
1791
 *
1792
 * The options array is suitable for drupal form API elements that allow multiple choices.
1793
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1794
 *
1795
 * The classifications are ordered alphabetically whereas the classification
1796
 * chosen as default will always appear on top of the array, followed by a
1797
 * blank line below.
1798
 *
1799
 * @param bool $add_none_option
1800
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1801
 *
1802
 * @return array
1803
 *   classifications in an array as options for a form element that allows multiple choices.
1804
 */
1805
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1806

    
1807
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1808

    
1809
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1810
  $default_classification_label = '';
1811

    
1812
  // add all classifications
1813
  $taxonomic_tree_options = array();
1814
  if ($add_none_option) {
1815
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1816
  }
1817
  if ($taxonTrees) {
1818
    foreach ($taxonTrees as $tree) {
1819
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1820
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1821
      } else {
1822
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1823
        if (count($taxonTrees) > 1) {
1824
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1825
        }
1826
        $default_classification_label = $tree->titleCache;
1827
      }
1828
    }
1829
  }
1830
  // oder alphabetically the space
1831
  asort($taxonomic_tree_options);
1832

    
1833
  // now set the labels
1834
  //   for none
1835
  if ($add_none_option) {
1836
    $taxonomic_tree_options['NONE'] = t('-- None --');
1837
  }
1838

    
1839
  //   for default_classification
1840
  if (is_uuid($default_classification_uuid)) {
1841
    $taxonomic_tree_options[$default_classification_uuid] =
1842
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1843
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1844
  }
1845

    
1846
  return $taxonomic_tree_options;
1847
}
1848

    
1849
/**
1850
 * @todo Please document this function.
1851
 * @see http://drupal.org/node/1354
1852
 */
1853
function cdm_api_secref_cache_prefetch(&$secUuids) {
1854
  // Comment @WA: global variables should start with a single underscore
1855
  // followed by the module and another underscore.
1856
  global $_cdm_api_secref_cache;
1857
  if (!is_array($_cdm_api_secref_cache)) {
1858
    $_cdm_api_secref_cache = array();
1859
  }
1860
  $uniqueUuids = array_unique($secUuids);
1861
  $i = 0;
1862
  $param = '';
1863
  while ($i++ < count($uniqueUuids)) {
1864
    $param .= $secUuids[$i] . ',';
1865
    if (strlen($param) + 37 > 2000) {
1866
      _cdm_api_secref_cache_add($param);
1867
      $param = '';
1868
    }
1869
  }
1870
  if ($param) {
1871
    _cdm_api_secref_cache_add($param);
1872
  }
1873
}
1874

    
1875
/**
1876
 * @todo Please document this function.
1877
 * @see http://drupal.org/node/1354
1878
 */
1879
function cdm_api_secref_cache_get($secUuid) {
1880
  global $_cdm_api_secref_cache;
1881
  if (!is_array($_cdm_api_secref_cache)) {
1882
    $_cdm_api_secref_cache = array();
1883
  }
1884
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1885
    _cdm_api_secref_cache_add($secUuid);
1886
  }
1887
  return $_cdm_api_secref_cache[$secUuid];
1888
}
1889

    
1890
/**
1891
 * @todo Please document this function.
1892
 * @see http://drupal.org/node/1354
1893
 */
1894
function cdm_api_secref_cache_clear() {
1895
  global $_cdm_api_secref_cache;
1896
  $_cdm_api_secref_cache = array();
1897
}
1898

    
1899
/**
1900
 * Validates if the given string is a uuid.
1901
 *
1902
 * @param string $str
1903
 *   The string to validate.
1904
 *
1905
 * return bool
1906
 *   TRUE if the string is a UUID.
1907
 */
1908
function is_uuid($str) {
1909
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1910
}
1911

    
1912
/**
1913
 * Checks if the given $object is a valid cdm entity.
1914
 *
1915
 * An object is considered a cdm entity if it has a string field $object->class
1916
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1917
 *
1918
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1919
 *
1920
 * @param mixed $object
1921
 *   The object to validate
1922
 *
1923
 * @return bool
1924
 *   True if the object is a cdm entity.
1925
 */
1926
function is_cdm_entity($object) {
1927
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1928
}
1929

    
1930
/**
1931
 * @todo Please document this function.
1932
 * @see http://drupal.org/node/1354
1933
 */
1934
function _cdm_api_secref_cache_add($secUuidsStr) {
1935
  global $_cdm_api_secref_cache;
1936
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1937
  // Batch fetching not jet reimplemented thus:
1938
  /*
1939
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1940
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1941
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1942
  */
1943
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1944
}
1945

    
1946
/**
1947
 * Checks if the given uri starts with a cdm webservice url.
1948
 *
1949
 * Checks if the uri starts with the cdm webservice url stored in the
1950
 * Drupal variable 'cdm_webservice_url'.
1951
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1952
 *
1953
 * @param string $uri
1954
 *   The URI to test.
1955
 *
1956
 * @return bool
1957
 *   True if the uri starts with a cdm webservice url.
1958
 */
1959
function _is_cdm_ws_uri($uri) {
1960
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1961
}
1962

    
1963
/**
1964
 * @todo Please document this function.
1965
 * @see http://drupal.org/node/1354
1966
 */
1967
function queryString($elements) {
1968
  $query = '';
1969
  foreach ($elements as $key => $value) {
1970
    if (is_array($value)) {
1971
      foreach ($value as $v) {
1972
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1973
      }
1974
    }
1975
    else {
1976
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1977
    }
1978
  }
1979
  return $query;
1980
}
1981

    
1982
/**
1983
 * Implementation of the magic method __clone to allow deep cloning of objects
1984
 * and arrays.
1985
 */
1986
function __clone() {
1987
  foreach ($this as $name => $value) {
1988
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1989
      $this->$name = clone($this->$name);
1990
    }
1991
  }
1992
}
1993

    
1994
/**
1995
 * Make a 'deep copy' of an array.
1996
 *
1997
 * Make a complete deep copy of an array replacing
1998
 * references with deep copies until a certain depth is reached
1999
 * ($maxdepth) whereupon references are copied as-is...
2000
 *
2001
 * @see http://us3.php.net/manual/en/ref.array.php
2002
 *
2003
 * @param array $array
2004
 * @param array $copy
2005
 * @param int $maxdepth
2006
 * @param int $depth
2007
 *
2008
 * @return void
2009
 */
2010
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2011
  if ($depth > $maxdepth) {
2012
    $copy = $array;
2013
    return;
2014
  }
2015
  if (!is_array($copy)) {
2016
    $copy = array();
2017
  }
2018
  foreach ($array as $k => &$v) {
2019
    if (is_array($v)) {
2020
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2021
    }
2022
    else {
2023
      $copy[$k] = $v;
2024
    }
2025
  }
2026
}
2027

    
2028
/**
2029
 * Implementation of theme_status_messages($display = NULL).
2030
 *
2031
 * @see includes/theme.inc
2032
 *
2033
 * @return void
2034
 */
2035
function _add_status_message_toggler() {
2036
  static $isAdded = FALSE;
2037
  if (!$isAdded) {
2038
    drupal_add_js(
2039
    'jQuery(document).ready(function($){
2040
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
2041
       $(\'.messages_toggler\').click(function(){
2042
         $(this).next().slideToggle(\'fast\');
2043
         return false;
2044
       }).next().hide();
2045
     });', array('type' => 'inline'));
2046

    
2047
    $isAdded = TRUE;
2048
  }
2049
}
2050

    
2051
/**
2052
 * @todo Please document this function.
2053
 * @see http://drupal.org/node/1354
2054
 */
2055
function _no_classfication_uuid_message() {
2056
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2057
    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.');
2058
  }
2059
  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.');
2060
}
2061

    
2062
/**
2063
 * Implementation of hook flush_caches
2064
 *
2065
 * Add custom cache tables to the list of cache tables that
2066
 * will be cleared by the Clear button on the Performance page or whenever
2067
 * drupal_flush_all_caches is invoked.
2068
 *
2069
 * @author W.Addink <waddink@eti.uva.nl>
2070
 *
2071
 * @return array
2072
 *   An array with custom cache tables to include.
2073
 */
2074
function cdm_api_flush_caches() {
2075
  return array('cache_cdm_ws');
2076
}
(4-4/9)