Project

General

Profile

Download (59.1 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
        $prefRepr[$dwa . '_'] = $representation;
348
      }
349
    }
350
  }
351
  // Sort the array.
352
  krsort($prefRepr);
353
  return $prefRepr;
354
}
355

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

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

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

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

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

    
488
  $y = $y ? $y : '00';
489
  $m = $m ? $m : '00';
490
  $d = $d ? $d : '00';
491

    
492
  $date = '';
493

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

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

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

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

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

    
587
  $request_params = '';
588
  $path_params = '';
589

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

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

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

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

    
631
  $path = $uri_pattern;
632

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

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

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

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

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

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

    
691
    if (empty($hook)) {
692
      // simply return the webservice response
693
      // Print out JSON, the cache cannot be used since it contains objects.
694
      $http_response = cdm_http_request($uri);
695
      if (isset($http_response->headers)) {
696
        foreach ($http_response->headers as $hname => $hvalue) {
697
          drupal_add_http_header($hname, $hvalue);
698
        }
699
      }
700
      if (isset($http_response->data)) {
701
        print $http_response->data;
702
        flush();
703
      }
704
      exit(); // leave drupal here
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

    
722
      $reponse_data = NULL;
723

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

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

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

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

    
764
          default:
765
            drupal_set_message(t(
766
            'Theme !theme is not supported yet by function !function.', array(
767
            '!theme' => $hook,
768
            '!function' => __FUNCTION__,
769
            )), 'error');
770
            break;
771
        } // END of theme hook switch
772
      } // END of tread as theme hook
773
      if($do_gzip){
774
        $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
775
        drupal_add_http_header('Content-Length', strlen($reponse_data));
776
      }
777
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
778
      drupal_add_http_header('Content-Encoding', 'gzip');
779
      print $reponse_data;
780
    } // END of handle $hook either as compose ot theme hook
781
  }
782
}
783

    
784
/**
785
 * @todo Please document this function.
786
 * @see http://drupal.org/node/1354
787
 */
788
function setvalue_session() {
789
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
790
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
791
    $keys = explode('][', $keys);
792
  }
793
  else {
794
    return;
795
  }
796
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
797

    
798
  // Prevent from malicous tags.
799
  $val = strip_tags($val);
800

    
801
  $var = &$_SESSION;
802
  $i = 0;
803
  foreach ($keys as $key) {
804
    $hasMoreKeys = ++$i < count($var);
805
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
806
      $var[$key] = array();
807
    }
808
    $var = &$var[$key];
809
  }
810
  $var = $val;
811
  if (isset($_REQUEST['destination'])) {
812
    drupal_goto($_REQUEST['destination']);
813
  }
814
}
815

    
816
/**
817
 * @todo Please document this function.
818
 * @see http://drupal.org/node/1354
819
 */
820
function uri_uriByProxy($uri, $theme = FALSE) {
821
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
822
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
823
}
824

    
825
/**
826
 * @todo Please document this function.
827
 * @see http://drupal.org/node/1354
828
 */
829
function cdm_compose_annotations_url($cdmBase) {
830
  if (!$cdmBase->uuid) {
831
    return;
832
  }
833

    
834
  $ws_base_uri = NULL;
835
  switch ($cdmBase->class) {
836
    case 'TaxonBase':
837
    case 'Taxon':
838
    case 'Synonym':
839
      $ws_base_uri = CDM_WS_TAXON;
840
      break;
841

    
842
    case 'TaxonNameBase':
843
    case 'NonViralName':
844
    case 'BacterialName':
845
    case 'BotanicalName':
846
    case 'CultivarPlantName':
847
    case 'ZoologicalName':
848
    case 'ViralName':
849
      $ws_base_uri = CDM_WS_NAME;
850
      break;
851

    
852
    case 'Media':
853
      $ws_base_uri = CDM_WS_MEDIA;
854
      break;
855

    
856
    case 'Reference':
857
      $ws_base_uri = CDM_WS_REFERENCE;
858
      break;
859

    
860
    case 'Distribution':
861
    case 'TextData':
862
    case 'TaxonInteraction':
863
    case 'QuantitativeData':
864
    case 'IndividualsAssociation':
865
    case 'Distribution':
866
    case 'CommonTaxonName':
867
    case 'CategoricalData':
868
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
869
      break;
870

    
871
    case 'PolytomousKey':
872
    case 'MediaKey':
873
    case 'MultiAccessKey':
874
      $ws_base_uri = $cdmBase->class;
875
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
876
      break;
877

    
878
    default:
879
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
880
      return;
881
  }
882
  return cdm_compose_url($ws_base_uri, array(
883
    $cdmBase->uuid,
884
    'annotations',
885
  ));
886
}
887

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

    
909
/*
910
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
911
  $viewrank = _cdm_taxonomy_compose_viewrank();
912
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
913
  ? '/' . $path : '') ;
914
}
915
*/
916

    
917
/**
918
 * @todo Enter description here...
919
 *
920
 * @param string $taxon_uuid
921
 *  The UUID of a cdm taxon instance
922
 * @param string $ignore_rank_limit
923
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
924
 *
925
 * @return A cdm REST service URL path to a Classification
926
 */
927
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
928

    
929
  $view_uuid = get_taxonomictree_uuid_selected();
930
  $rank_uuid = NULL;
931
  if (!$ignore_rank_limit) {
932
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
933
  }
934

    
935
  if (!empty($taxon_uuid)) {
936
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
937
      $view_uuid,
938
      $taxon_uuid,
939
    ));
940
  }
941
  else {
942
    if (!empty($rank_uuid)) {
943
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
944
        $view_uuid,
945
        $rank_uuid,
946
      ));
947
    }
948
    else {
949
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
950
        $view_uuid,
951
      ));
952
    }
953
  }
954
}
955

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

    
977
    $response = NULL;
978

    
979
    // 1st try
980
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
981

    
982
    if ($response == NULL) {
983
      // 2dn try by ignoring the rank limit
984
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
985
    }
986

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

    
1005
  return $response;
1006
}
1007

    
1008
/**
1009
 * @todo Enter description here...
1010
 *
1011
 * @param string $taxon_uuid
1012
 *
1013
 * @return unknown
1014
 */
1015
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1016
  $view_uuid = get_taxonomictree_uuid_selected();
1017
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1018

    
1019
  $response = NULL;
1020
  if ($rank_uuid) {
1021
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1022
      $view_uuid,
1023
      $taxon_uuid,
1024
      $rank_uuid,
1025
    ));
1026
  }
1027
  else {
1028
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1029
      $view_uuid,
1030
      $taxon_uuid,
1031
    ));
1032
  }
1033

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

    
1051
  return $response;
1052
}
1053

    
1054
/**
1055
 * @todo Please document this function.
1056
 * @see http://drupal.org/node/1354
1057
 */
1058
function cdm_rankVocabulary_as_option() {
1059
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1060
  array_unshift ($options, "");
1061
  return $options;
1062
}
1063

    
1064
/**
1065
 *
1066
 * @param Object $definedTermBase
1067
 * 	  of cdm type DefinedTermBase
1068
 * @return string
1069
 * 	  the localized representation_L10n of the term,
1070
 *    otherwise the titleCache as fall back,
1071
 *    otherwise an empty string
1072
 */
1073
function cdm_term_representation($definedTermBase) {
1074
  if ( isset($definedTermBase->representation_L10n) ) {
1075
    return $definedTermBase->representation_L10n;
1076
  } elseif ( isset($definedTermBase->titleCache)) {
1077
    return $definedTermBase->titleCache;
1078
  }
1079
  return '';
1080
}
1081

    
1082
/**
1083
 * @todo Improve documentation of this function.
1084
 *
1085
 * eu.etaxonomy.cdm.model.description.
1086
 * CategoricalData
1087
 * CommonTaxonName
1088
 * Distribution
1089
 * IndividualsAssociation
1090
 * QuantitativeData
1091
 * TaxonInteraction
1092
 * TextData
1093
 */
1094
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1095
  static $types = array(
1096
    "CategoricalData",
1097
    "CommonTaxonName",
1098
    "Distribution",
1099
    "IndividualsAssociation",
1100
    "QuantitativeData",
1101
    "TaxonInteraction",
1102
    "TextData",
1103
  );
1104

    
1105
  static $options = NULL;
1106
  if ($options == NULL) {
1107
    $options = array();
1108
    if ($prependEmptyElement) {
1109
      $options[' '] = '';
1110
    }
1111
    foreach ($types as $type) {
1112
      // No internatianalization here since these are purely technical terms.
1113
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1114
    }
1115
  }
1116
  return $options;
1117
}
1118

    
1119
/**
1120
 * @todo Please document this function.
1121
 * @see http://drupal.org/node/1354
1122
 */
1123
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1124
  static $vocabularyOptions = array();
1125

    
1126
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1127
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1128
    $vocabularyOptions[$vocabularyUuid] = array();
1129

    
1130
    if ($vocab) {
1131
      foreach ($vocab->terms as $term) {
1132
        if ($term_label_callback && function_exists($term_label_callback)) {
1133
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1134
        }
1135
        else {
1136
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1137
        }
1138
      }
1139
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1140
    }
1141
  }
1142
  return $vocabularyOptions[$vocabularyUuid];
1143
}
1144

    
1145
/**
1146
 * @todo Please document this function.
1147
 * @see http://drupal.org/node/1354
1148
 */
1149
function _cdm_relationship_type_term_label_callback($term) {
1150
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1151
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1152
  }
1153
  else {
1154
    return t($term->representation_L10n);
1155
  }
1156
}
1157

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

    
1170
  $mergedTrees = array();
1171

    
1172
  if ($isDescriptionsSeparated) {
1173
    // Merge any description into a separate feature tree.
1174
    foreach ($descriptions as $desc) {
1175
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1176

    
1177
      $mergedTree = clone $featureTree;
1178
      $mergedTree->root->children = $mergedNodes;
1179
      $mergedTrees[] = $mergedTree;
1180
    }
1181
  }
1182
  else {
1183
    // Combine all descripions into one feature tree.
1184
    $descriptionElemens = array();
1185
    foreach ($descriptions as $desc) {
1186
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1187
    }
1188
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1189
    $featureTree->root->children = $mergedNodes;
1190
    $mergedTrees[] = $featureTree;
1191
  }
1192

    
1193
  return $mergedTrees;
1194
}
1195

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

    
1229
/**
1230
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1231
 *
1232
 * @param object $annotatable_entity
1233
 *   The CDM AnnotatableEntity to load annotations for
1234
 */
1235
function cdm_load_annotations(&$annotatable_entity) {
1236
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1237
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1238
    if (is_array($annotations)) {
1239
      $annotatable_entity->annotations = $annotations;
1240
    }
1241
  }
1242
}
1243

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

    
1264
  if ($obj) {
1265
    return $obj->String;
1266
  }
1267
  else {
1268
    return NULL;
1269
  }
1270
}
1271

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

    
1296
  foreach ($featureNodes as &$node) {
1297
    // since the $featureNodes array is reused for each description
1298
    // it is nessecary to clear the custom node fields in advance
1299
    if(isset($node->descriptionElements)){
1300
      unset($node->descriptionElements);
1301
    }
1302

    
1303
    // Append corresponding elements to an additional node field:
1304
    // $node->descriptionElements.
1305
    foreach ($descriptionElements as $element) {
1306
      if ($element->feature->uuid == $node->feature->uuid) {
1307
        if (!isset($node->descriptionElements)) {
1308
          $node->descriptionElements = array();
1309
        }
1310
        $node->descriptionElements[] = $element;
1311
      }
1312
    }
1313

    
1314
    // Recurse into node children.
1315
    if (isset($node->children[0])) {
1316
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1317
      $node->children = $mergedChildNodes;
1318
    }
1319

    
1320
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1321
      unset($node);
1322
    }
1323

    
1324
  }
1325

    
1326
  return $featureNodes;
1327
}
1328

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

    
1365
  static $cacheL1 = array();
1366

    
1367
  // Transform the given uri path or pattern into a proper webservice uri.
1368
  if (!$absoluteURI) {
1369
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1370
  }
1371

    
1372
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1373
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1374

    
1375
  if (array_key_exists($uri, $cacheL1)) {
1376
    $cacheL1_obj = $cacheL1[$uri];
1377
  }
1378

    
1379
  $set_cacheL1 = FALSE;
1380
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1381
    $set_cacheL1 = TRUE;
1382
  }
1383

    
1384
  // Only cache cdm webservice URIs.
1385
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1386
  $cacheL2_entry = FALSE;
1387

    
1388
  if ($use_cacheL2) {
1389
    // Try to get object from cacheL2.
1390
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1391
  }
1392

    
1393
  if (isset($cacheL1_obj)) {
1394
    //
1395
    // The object has been found in the L1 cache.
1396
    //
1397
    $obj = $cacheL1_obj;
1398
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1399
      _add_status_message_toggler();
1400
      _add_debugMessageStr('Using cacheL1 for: ' . $uri);
1401
    }
1402
  }
1403
  elseif ($cacheL2_entry) {
1404
    //
1405
    // The object has been found in the L2 cache.
1406
    //
1407
    $obj = unserialize($cacheL2_entry->data);
1408

    
1409
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1410
      _add_status_message_toggler();
1411
      _add_debugMessageStr('Using cacheL2 for: ' . $uri);
1412
    }
1413
  }
1414
  else {
1415
    //
1416
    // Get the object from the webservice and cache it.
1417
    //
1418
    $time_get_start = microtime(TRUE);
1419
    // Request data from webservice JSON or XML.
1420
    $response = cdm_http_request($uri, $method);
1421
    $datastr = NULL;
1422
    if (isset($response->data)) {
1423
      $datastr = $response->data;
1424
    }
1425
    $time_get = microtime(TRUE) - $time_get_start;
1426
    $time_parse_start = microtime(TRUE);
1427

    
1428
    // Parse data and create object.
1429
    $obj = cdm_load_obj($datastr);
1430

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

    
1457
/**
1458
 * @todo Please document this function.
1459
 * @see http://drupal.org/node/1354
1460
 */
1461
function _add_debugMessageStr($message) {
1462
  _add_status_message_toggler();
1463
  drupal_set_message(check_plain($message), 'debug');
1464
}
1465

    
1466
/**
1467
 * @todo Please document this function.
1468
 * @see http://drupal.org/node/1354
1469
 */
1470
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg) {
1471
  static $cumulated_time_parse = 0;
1472
  static $cumulated_time_get = 0;
1473
  _add_status_message_toggler();
1474

    
1475
  $cumulated_time_get += $time_get;
1476
  $cumulated_time_parse += $time_parse;
1477

    
1478
  // Decompose uri into path and query element.
1479
  // URI query elements are stored in an array
1480
  // suitable for drupal_http_build_query()
1481
  $uri_parts = explode("?", $uri);
1482
  $query = array();
1483
  if (count($uri_parts) == 2) {
1484
    $path = $uri_parts[0];
1485
    $queryparts = explode("&", $uri_parts[1]);
1486
    foreach ($queryparts as $querypart) {
1487
      $querypart = explode("=", $querypart);
1488
      if(count($querypart) == 2){
1489
        $query[$querypart[0]] = $querypart[1];
1490
      } else {
1491
        $query[$querypart[0]] = null;
1492
      }
1493
    }
1494
  }
1495
  else {
1496
    $path = $uri;
1497
  }
1498

    
1499
  $message = '<span class="uri">' . $uri . '</span><br />';
1500
  $message .= '[fetched in: ' . sprintf('%3.3f', $time_get) . 's(' . sprintf('%3.3f', $cumulated_time_get) . 's); ';
1501
  $message .= 'parsed in ' . sprintf('%3.3f', $time_parse) . ' s(' . sprintf('%3.3f', $cumulated_time_parse) . 's); ';
1502
  $message .= 'size:' . sprintf('%3.1f', ($datasize / 1024)) . ' kb of ' . $success_msg . ' data: ';
1503
  if (_is_cdm_ws_uri($path)) {
1504
    $message .= '<a href="' . url($path . '.xml', array(
1505
      'query' => $query,
1506
    )) . '" target="data" class="' . $success_msg . '">xml</a>-';
1507
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array(
1508
      'query' => $query,
1509
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>,';
1510
    $message .= '<a href="' . url($path . '.json', array(
1511
      'query' => $query,
1512
    )) . '" target="data" class="' . $success_msg . '">json</a>-';
1513
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.json', array(
1514
      'query' => $query,
1515
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>';
1516
  }
1517
  else {
1518
    $message .= '<a href="' . url($path, array(
1519
      'query' => $query,
1520
    )) . '" target="data" class="' . $success_msg . '">open</a>';
1521
  }
1522
  $message .= '] ';
1523
  drupal_set_message(($message), 'debug');
1524
}
1525

    
1526
/**
1527
 * @todo Please document this function.
1528
 * @see http://drupal.org/node/1354
1529
 */
1530
function cdm_load_obj($datastr) {
1531
  $obj = json_decode($datastr);
1532

    
1533
  if (!(is_object($obj) || is_array($obj))) {
1534
    ob_start();
1535
    $obj_dump = ob_get_contents();
1536
    ob_clean();
1537
    return FALSE;
1538
  }
1539

    
1540
  return $obj;
1541
}
1542

    
1543
/**
1544
 * Do a http request to a CDM RESTful web service.
1545
 *
1546
 * @param string $uri
1547
 *   The webservice url.
1548
 * @param string $method
1549
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1550
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1551
 * @param array $parameters
1552
 *   Parameters to use in the request.
1553
 * @param array $header
1554
 *   The header to include in the request.
1555
 *
1556
 * @return object
1557
 *   The object as returned by drupal_http_request():
1558
 *   An object that can have one or more of the following components:
1559
 *   - request: A string containing the request body that was sent.
1560
 *   - code: An integer containing the response status code, or the error code
1561
 *     if an error occurred.
1562
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1563
 *   - status_message: The status message from the response, if a response was
1564
 *     received.
1565
 *   - redirect_code: If redirected, an integer containing the initial response
1566
 *     status code.
1567
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1568
 *     target.
1569
 *   - error: If an error occurred, the error message. Otherwise not set.
1570
 *   - headers: An array containing the response headers as name/value pairs.
1571
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1572
 *     easy access the array keys are returned in lower case.
1573
 *   - data: A string containing the response body that was received.
1574
 */
1575
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array(), $options = NULL) {
1576
  static $acceptLanguage = NULL;
1577

    
1578
  if (!$acceptLanguage) {
1579
    if (function_exists('apache_request_headers')) {
1580
      $headers = apache_request_headers();
1581
      if (isset($headers['Accept-Language'])) {
1582
        $acceptLanguage = $headers['Accept-Language'];
1583
      }
1584
    }
1585
    if (!$acceptLanguage) {
1586
      // DEFAULT TODO make configurable.
1587
      $acceptLanguage = "en";
1588
    }
1589
  }
1590

    
1591
  if ($method != "GET" && $method != "POST") {
1592
    $method = "GET";
1593
  }
1594

    
1595
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1596
    $header['Accept'] = 'application/json';
1597
    $header['Accept-Language'] = $acceptLanguage;
1598
    $header['Accept-Charset'] = 'UTF-8';
1599
  }
1600

    
1601
  return drupal_http_request($uri, array(
1602
      'headers' => $header,
1603
      'method' => $method,
1604
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1605
      )
1606
   );
1607
}
1608

    
1609
/**
1610
 * @todo Please document this function.
1611
 * @see http://drupal.org/node/1354
1612
 */
1613
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1614
  $out = '';
1615

    
1616
  foreach ($rootNode->children as $featureNode) {
1617
    $out .= ($out ? $separator : '');
1618
    $out .= $featureNode->feature->representation_L10n;
1619
    if (is_array($featureNode->children)) {
1620
      $childlabels = '';
1621
      foreach ($featureNode->children as $childNode) {
1622
        $childlabels .= ($childlabels ? $separator : '');
1623
      }
1624
      $childlabels .= _featureTree_elements_toString($childNode);
1625
    }
1626
    if ($childlabels) {
1627
      $out .= '[' . $childlabels . ' ]';
1628
    }
1629
  }
1630
  return $out;
1631
}
1632

    
1633
/**
1634
 * Create a one-dimensional form options array.
1635
 *
1636
 * Creates an array of all features in the feature tree of feature nodes,
1637
 * the node labels are indented by $node_char and $childIndent depending on the
1638
 * hierachy level.
1639
 *
1640
 * @param - $rootNode
1641
 * @param - $node_char
1642
 * @param - $childIndentStr
1643
 * @param - $childIndent
1644
 *   ONLY USED INTERNALLY!
1645
 *
1646
 * @return array
1647
 *   A one dimensional Drupal form options array.
1648
 */
1649
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1650
  $options = array();
1651
  foreach ($rootNode->children as $featureNode) {
1652
    $indent_prefix = '';
1653
    if ($childIndent) {
1654
      $indent_prefix = $childIndent . $node_char . " ";
1655
    }
1656
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1657
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1658
      // Foreach ($featureNode->children as $childNode){
1659
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1660
      $options = array_merge_recursive($options, $childList);
1661
      // }
1662
    }
1663
  }
1664
  return $options;
1665
}
1666

    
1667
/**
1668
 * Returns an array with all available FeatureTrees and the representations of the selected
1669
 * FeatureTree as a detail view.
1670
 *
1671
 * @param boolean $add_default_feature_free
1672
 * @return array
1673
 *  associative array with following keys:
1674
 *  -options: Returns an array with all available Feature Trees
1675
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1676
 *
1677
 */
1678
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1679

    
1680
  $options = array();
1681
  $tree_representations = array();
1682
  $feature_trees = array();
1683

    
1684
  // Set tree that contains all features.
1685
  if ($add_default_feature_free) {
1686
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1687
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1688
  }
1689

    
1690
  // Get feature trees from database.
1691
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1692
  if (is_array($persited_trees)) {
1693
    $feature_trees = array_merge($feature_trees, $persited_trees);
1694
  }
1695

    
1696
  foreach ($feature_trees as $featureTree) {
1697

    
1698
    // Do not add the DEFAULT_FEATURETREE again,
1699
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1700
      $options[$featureTree->uuid] = $featureTree->titleCache;
1701
    }
1702

    
1703
    // Render the hierarchic tree structure
1704
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1705

    
1706
      // Render the hierarchic tree structure.
1707
      $treeDetails = '<div class="featuretree_structure">'
1708
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1709
        . '</div>';
1710

    
1711
      $form = array();
1712
      $form['featureTree-' .  $featureTree->uuid] = array(
1713
        '#type' => 'fieldset',
1714
        '#title' => 'Show details',
1715
        '#attributes' => array('class' => array('collapsible collapsed')),
1716
        // '#collapsible' => TRUE,
1717
        // '#collapsed' => TRUE,
1718
      );
1719
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1720
        '#markup' => $treeDetails,
1721
      );
1722

    
1723
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1724
    }
1725

    
1726
  } // END loop over feature trees
1727

    
1728
  // return $options;
1729
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1730
}
1731

    
1732
/**
1733
 * Provides the list of availbale classifications in form of an options array.
1734
 *
1735
 * The options array is suitable for drupal form API elements that allow multiple choices.
1736
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1737
 *
1738
 * The classifications are ordered alphabetically whereas the classification
1739
 * chosen as default will always appear on top of the array, followed by a
1740
 * blank line below.
1741
 *
1742
 * @param bool $add_none_option
1743
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1744
 *
1745
 * @return array
1746
 *   classifications in an array as options for a form element that allows multiple choices.
1747
 */
1748
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1749

    
1750
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1751

    
1752
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1753
  $default_classification_label = '';
1754

    
1755
  // add all classifications
1756
  $taxonomic_tree_options = array();
1757
  if ($add_none_option) {
1758
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1759
  }
1760
  if ($taxonTrees) {
1761
    foreach ($taxonTrees as $tree) {
1762
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1763
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1764
      } else {
1765
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1766
        if (count($taxonTrees) > 1) {
1767
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1768
        }
1769
        $default_classification_label = $tree->titleCache;
1770
      }
1771
    }
1772
  }
1773
  // oder alphabetically the space
1774
  asort($taxonomic_tree_options);
1775

    
1776
  // now set the labels
1777
  //   for none
1778
  if ($add_none_option) {
1779
    $taxonomic_tree_options['NONE'] = t('-- None --');
1780
  }
1781

    
1782
  //   for default_classification
1783
  if (is_uuid($default_classification_uuid)) {
1784
    $taxonomic_tree_options[$default_classification_uuid] =
1785
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1786
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1787
  }
1788

    
1789
  return $taxonomic_tree_options;
1790
}
1791

    
1792
/**
1793
 * @todo Please document this function.
1794
 * @see http://drupal.org/node/1354
1795
 */
1796
function cdm_api_secref_cache_prefetch(&$secUuids) {
1797
  // Comment @WA: global variables should start with a single underscore
1798
  // followed by the module and another underscore.
1799
  global $_cdm_api_secref_cache;
1800
  if (!is_array($_cdm_api_secref_cache)) {
1801
    $_cdm_api_secref_cache = array();
1802
  }
1803
  $uniqueUuids = array_unique($secUuids);
1804
  $i = 0;
1805
  $param = '';
1806
  while ($i++ < count($uniqueUuids)) {
1807
    $param .= $secUuids[$i] . ',';
1808
    if (strlen($param) + 37 > 2000) {
1809
      _cdm_api_secref_cache_add($param);
1810
      $param = '';
1811
    }
1812
  }
1813
  if ($param) {
1814
    _cdm_api_secref_cache_add($param);
1815
  }
1816
}
1817

    
1818
/**
1819
 * @todo Please document this function.
1820
 * @see http://drupal.org/node/1354
1821
 */
1822
function cdm_api_secref_cache_get($secUuid) {
1823
  global $_cdm_api_secref_cache;
1824
  if (!is_array($_cdm_api_secref_cache)) {
1825
    $_cdm_api_secref_cache = array();
1826
  }
1827
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1828
    _cdm_api_secref_cache_add($secUuid);
1829
  }
1830
  return $_cdm_api_secref_cache[$secUuid];
1831
}
1832

    
1833
/**
1834
 * @todo Please document this function.
1835
 * @see http://drupal.org/node/1354
1836
 */
1837
function cdm_api_secref_cache_clear() {
1838
  global $_cdm_api_secref_cache;
1839
  $_cdm_api_secref_cache = array();
1840
}
1841

    
1842
/**
1843
 * Validates if the given string is a uuid.
1844
 *
1845
 * @param string $str
1846
 *   The string to validate.
1847
 *
1848
 * return bool
1849
 *   TRUE if the string is a UUID.
1850
 */
1851
function is_uuid($str) {
1852
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1853
}
1854

    
1855
/**
1856
 * Checks if the given $object is a valid cdm entity.
1857
 *
1858
 * An object is considered a cdm entity if it has a string field $object->class
1859
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1860
 *
1861
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1862
 *
1863
 * @param mixed $object
1864
 *   The object to validate
1865
 *
1866
 * @return bool
1867
 *   True if the object is a cdm entity.
1868
 */
1869
function is_cdm_entity($object) {
1870
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1871
}
1872

    
1873
/**
1874
 * @todo Please document this function.
1875
 * @see http://drupal.org/node/1354
1876
 */
1877
function _cdm_api_secref_cache_add($secUuidsStr) {
1878
  global $_cdm_api_secref_cache;
1879
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1880
  // Batch fetching not jet reimplemented thus:
1881
  /*
1882
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1883
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1884
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1885
  */
1886
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1887
}
1888

    
1889
/**
1890
 * Checks if the given uri starts with a cdm webservice url.
1891
 *
1892
 * Checks if the uri starts with the cdm webservice url stored in the
1893
 * Drupal variable 'cdm_webservice_url'.
1894
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1895
 *
1896
 * @param string $uri
1897
 *   The URI to test.
1898
 *
1899
 * @return bool
1900
 *   True if the uri starts with a cdm webservice url.
1901
 */
1902
function _is_cdm_ws_uri($uri) {
1903
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1904
}
1905

    
1906
/**
1907
 * @todo Please document this function.
1908
 * @see http://drupal.org/node/1354
1909
 */
1910
function queryString($elements) {
1911
  $query = '';
1912
  foreach ($elements as $key => $value) {
1913
    if (is_array($value)) {
1914
      foreach ($value as $v) {
1915
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1916
      }
1917
    }
1918
    else {
1919
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1920
    }
1921
  }
1922
  return $query;
1923
}
1924

    
1925
/**
1926
 * Implementation of the magic method __clone to allow deep cloning of objects
1927
 * and arrays.
1928
 */
1929
function __clone() {
1930
  foreach ($this as $name => $value) {
1931
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1932
      $this->$name = clone($this->$name);
1933
    }
1934
  }
1935
}
1936

    
1937
/**
1938
 * Make a 'deep copy' of an array.
1939
 *
1940
 * Make a complete deep copy of an array replacing
1941
 * references with deep copies until a certain depth is reached
1942
 * ($maxdepth) whereupon references are copied as-is...
1943
 *
1944
 * @see http://us3.php.net/manual/en/ref.array.php
1945
 *
1946
 * @param array $array
1947
 * @param array $copy
1948
 * @param int $maxdepth
1949
 * @param int $depth
1950
 *
1951
 * @return void
1952
 */
1953
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
1954
  if ($depth > $maxdepth) {
1955
    $copy = $array;
1956
    return;
1957
  }
1958
  if (!is_array($copy)) {
1959
    $copy = array();
1960
  }
1961
  foreach ($array as $k => &$v) {
1962
    if (is_array($v)) {
1963
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
1964
    }
1965
    else {
1966
      $copy[$k] = $v;
1967
    }
1968
  }
1969
}
1970

    
1971
/**
1972
 * Implementation of theme_status_messages($display = NULL).
1973
 *
1974
 * @see includes/theme.inc
1975
 *
1976
 * @return void
1977
 */
1978
function _add_status_message_toggler() {
1979
  static $isAdded = FALSE;
1980
  if (!$isAdded) {
1981
    drupal_add_js(
1982
    'jQuery(document).ready(function($){
1983
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
1984
       $(\'.messages_toggler\').click(function(){
1985
         $(this).next().slideToggle(\'fast\');
1986
         return false;
1987
       }).next().hide();
1988
     });', array('type' => 'inline'));
1989

    
1990
    $isAdded = TRUE;
1991
  }
1992
}
1993

    
1994
/**
1995
 * @todo Please document this function.
1996
 * @see http://drupal.org/node/1354
1997
 */
1998
function _no_classfication_uuid_message() {
1999
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2000
    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.');
2001
  }
2002
  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.');
2003
}
2004

    
2005
/**
2006
 * Implementation of hook flush_caches
2007
 *
2008
 * Add custom cache tables to the list of cache tables that
2009
 * will be cleared by the Clear button on the Performance page or whenever
2010
 * drupal_flush_all_caches is invoked.
2011
 *
2012
 * @author W.Addink <waddink@eti.uva.nl>
2013
 *
2014
 * @return array
2015
 *   An array with custom cache tables to include.
2016
 */
2017
function cdm_api_flush_caches() {
2018
  return array('cache_cdm_ws');
2019
}
(4-4/9)