Project

General

Profile

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

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

    
30

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

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

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

    
54
  return $items;
55
}
56

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

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

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

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

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

    
144
/**
145
 * Lists the classifications a taxon belongs to
146
 *
147
 * @param CDM type Taxon $taxon
148
 *   the taxon
149
 *
150
 * @return array
151
 *   aray of CDM instances of Type Classification
152
 */
153
function get_classifications_for_taxon($taxon) {
154

    
155
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
156
}
157

    
158
/**
159
 * Returns the chosen FeatureTree for the taxon profile.
160
 *
161
 * The FeatureTree profile returned is the one that has been set in the
162
 * dataportal settings (layout->taxon:profile).
163
 * When the chosen FeatureTree is not found in the database,
164
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
165
 *
166
 * @return mixed
167
 *   A cdm FeatureTree object.
168
 */
169
function get_profile_featureTree() {
170
  static $profile_featureTree;
171

    
172
  if($profile_featureTree == NULL) {
173
    $profile_featureTree = cdm_ws_get(
174
      CDM_WS_FEATURETREE,
175
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
176
    );
177
    if (!$profile_featureTree) {
178
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
179
    }
180
  }
181
  return $profile_featureTree;
182
}
183

    
184
/**
185
 * Returns the chosen FeatureTree for SpecimenDescriptions.
186
 *
187
 * The FeatureTree returned is the one that has been set in the
188
 * dataportal settings (layout->taxon:specimen).
189
 * When the chosen FeatureTree is not found in the database,
190
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
191
 *
192
 * @return mixed
193
 *   A cdm FeatureTree object.
194
 */
195
function cdm_get_occurrence_featureTree() {
196
  static $occurrence_featureTree;
197

    
198
  if($occurrence_featureTree == NULL) {
199
    $occurrence_featureTree = cdm_ws_get(
200
      CDM_WS_FEATURETREE,
201
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
202
    );
203
    if (!$occurrence_featureTree) {
204
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
205
    }
206
  }
207
  return $occurrence_featureTree;
208
}
209

    
210
/**
211
 * Returns the FeatureTree for structured descriptions
212
 *
213
 * The FeatureTree returned is the one that has been set in the
214
 * dataportal settings (layout->taxon:profile).
215
 * When the chosen FeatureTree is not found in the database,
216
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
217
 *
218
 * @return mixed
219
 *   A cdm FeatureTree object.
220
 */
221
function get_structured_description_featureTree() {
222
  static $structured_description_featureTree;
223

    
224
  if($structured_description_featureTree == NULL) {
225
    $structured_description_featureTree = cdm_ws_get(
226
        CDM_WS_FEATURETREE,
227
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
228
    );
229
    if (!$structured_description_featureTree) {
230
      $structured_description_featureTree = cdm_ws_get(
231
          CDM_WS_FEATURETREE,
232
          UUID_DEFAULT_FEATURETREE
233
      );
234
    }
235
  }
236
  return $structured_description_featureTree;
237
}
238

    
239
/**
240
 * @todo Please document this function.
241
 * @see http://drupal.org/node/1354
242
 */
243
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
244
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
245
}
246

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

    
255
/**
256
 * @todo Please document this function.
257
 * @see http://drupal.org/node/1354
258
 */
259
function set_last_taxon_page_tab($taxonPageTab) {
260
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
261
}
262

    
263
/**
264
 * @todo Please document this function.
265
 * @see http://drupal.org/node/1354
266
 */
267
function get_last_taxon_page_tab() {
268
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
269
    return $_SESSION['cdm']['taxon_page_tab'];
270
  }
271
  else {
272
    return FALSE;
273
  }
274
}
275

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

    
309
  while (count($mimeTypes) > 0) {
310
    // getRepresentationByMimeType
311
    $mimeType = array_shift($mimeTypes);
312

    
313
    foreach ($media->representations as &$representation) {
314
      // If the mimetype is not known, try inferring it.
315
      if (!$representation->mimeType) {
316
        if (isset($representation->parts[0])) {
317
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
318
        }
319
      }
320

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

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

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

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

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

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

    
481
  $y = $y ? $y : '00';
482
  $m = $m ? $m : '00';
483
  $d = $d ? $d : '00';
484

    
485
  $date = '';
486

    
487
  if ($y == '00' && $stripZeros) {
488
    return;
489
  }
490
  else {
491
    $date = $y;
492
  }
493

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

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

    
510
/**
511
 * Converts a time period to a string.
512
 *
513
 * See also partialToDate($partial, $stripZeros).
514
 *
515
 * @param object $period
516
 *   An JodaTime org.joda.time.Period object.
517
 * @param bool $stripZeros
518
 *   If set to True, the zero (00) month and days will be hidden:
519
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
520
 *
521
 * @return string
522
 *   Returns a date in the form of a string.
523
 */
524
function timePeriodToString($period, $stripZeros = TRUE) {
525
  $dateString = '';
526
  if ($period->start) {
527
    $dateString = partialToDate($period->start, $stripZeros);
528
  }
529
  if ($period->end) {
530
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
531
  }
532
  return $dateString;
533
}
534

    
535
/**
536
 * Composes a CDM webservice URL with parameters and querystring.
537
 *
538
 * @param string $uri_pattern
539
 *   String with place holders ($0, $1, ..) that should be replaced by the
540
 *   according element of the $pathParameters array.
541
 * @param array $pathParameters
542
 *   An array of path elements, or a single element.
543
 * @param string $query
544
 *   A query string to append to the URL.
545
 *
546
 * @return string
547
 *   A complete URL with parameters to a CDM webservice.
548
 */
549
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
550
  if (empty($pathParameters)) {
551
    $pathParameters = array();
552
  }
553

    
554
  $request_params = '';
555
  $path_params = '';
556

    
557
  // (1)
558
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
559
  // according element of the $pathParameters array.
560
  static $helperArray = array();
561
  if (isset($pathParameters) && !is_array($pathParameters)) {
562
    $helperArray[0] = $pathParameters;
563
    $pathParameters = $helperArray;
564
  }
565

    
566
  $i = 0;
567
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
568
    if (count($pathParameters) <= $i) {
569
      if (module_exists("user") && user_access('administer')) {
570
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
571
      }
572
      break;
573
    }
574
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
575
    ++$i;
576
  }
577

    
578
  // (2)
579
  // Append all remaining element of the $pathParameters array as path
580
  // elements.
581
  if (count($pathParameters) > $i) {
582
    // Strip trailing slashes.
583
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
584
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
585
    }
586
    while (count($pathParameters) > $i) {
587
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
588
      ++$i;
589
    }
590
  }
591

    
592
  // (3)
593
  // Append the query string supplied by $query.
594
  if (isset($query)) {
595
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
596
  }
597

    
598
  // @WA: $ws_name seems unused
599
  // $path = $ws_name.$uri_pattern;
600
  $path = $uri_pattern;
601

    
602
  $uri = variable_get('cdm_webservice_url', '') . $path;
603
  return $uri;
604
}
605

    
606
/**
607
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
608
 *     together with a theme name to such a proxy function?
609
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
610
 *     Maybe we want to have two different proxy functions, one with theming and one without?
611
 *
612
 * @param string $uri
613
 *     A URI to a CDM Rest service from which to retrieve an object
614
 * @param string|null $hook
615
 *     (optional) The hook name to which the retrieved object should be passed.
616
 *     Hooks can either be a theme_hook() or compose_hook() implementation
617
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
618
 *     suitable for drupal_render()
619
 *
620
 * @todo Please document this function.
621
 * @see http://drupal.org/node/1354
622
 */
623
function proxy_content($uri, $hook = NULL) {
624
  $args = func_get_args();
625

    
626
  $uriEncoded = array_shift($args);
627
  $uri = urldecode($uriEncoded);
628
  $hook = array_shift($args);
629

    
630
  // Find and deserialize arrays.
631
  foreach ($args as &$arg) {
632
    // FIXME use regex to find serialized arrays.
633
    //       or should we accept json instead pf php serializations?
634
    if (strpos($arg, "a:") === 0) {
635
      $arg = unserialize($arg);
636
    }
637
  }
638

    
639
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
640
  if ($request_method == "POST") {
641
    // this is an experimental feature which will allow to
642
    // write data inot the cdm via the RESTfull web service
643
    $parameters = $_POST;
644
    $post_data = array();
645

    
646
    foreach ($parameters as $k => $v) {
647
      $post_data[] = "$k=" . utf8_encode($v);
648
    }
649
    $post_data = implode(',', $post_data);
650

    
651
    // For testing.
652
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data));
653
    print $data;
654
  } else {
655
    // Not a "POST" request
656
    // In all these cases perform a simple get request.
657
    // TODO reconsider caching logic in this function.
658

    
659
    if (empty($hook)) {
660
      // simply return the webservice response
661
      // Print out JSON, the cache cannot be used since it contains objects.
662
      $http_response = drupal_http_request($uri);
663
      if (isset($http_response->headers)) {
664
        foreach ($http_response->headers as $hname => $hvalue) {
665
          drupal_add_http_header($hname, $hvalue);
666
        }
667
      }
668
      if (isset($http_response->data)) {
669
        print $http_response->data;
670
      }
671
      exit();
672
    } else {
673
      // $hook has been supplied
674
      // handle $hook either as compose ot theme hook
675
      // pass through theme or comose hook
676

    
677
      // do a security check since the $uri will be passed
678
      // as absolute URI to cdm_ws_get()
679
      if( !_is_cdm_ws_uri($uri)) {
680
        drupal_set_message(
681
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
682
            'error'
683
        );
684
        return '';
685
      }
686

    
687
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
688
      $theme_result = NULL;
689

    
690
      if (function_exists('compose_' . $hook)){
691
        // call compose hook
692

    
693
        $elements =  call_user_func('compose_' . $hook, $obj);
694
        // pass the render array to drupal_render()
695
        $theme_result = drupal_render($elements);
696
      } else {
697
        // call theme hook
698

    
699
        // TODO use theme registry to get the registered hook info and
700
        //    use these defaults
701
        switch($hook) {
702
          case 'cdm_taxontree':
703
            $variables = array(
704
              'tree' => $obj,
705
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
706
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
707
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
708
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
709
            );
710
            $theme_result = theme($hook, $variables);
711
            break;
712

    
713
          case 'cdm_media_caption':
714
            $variables = array(
715
              'media' => $obj,
716
              // $args[0] is set in taxon_image_gallery_default in
717
              // cdm_dataportal.page.theme.
718
              'elements' => isset($args[0]) ? $args[0] : array(
719
                'title',
720
                'description',
721
                'artist',
722
                'location',
723
                'rights',
724
              ),
725
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
726
            );
727
            $theme_result = theme($hook, $variables);
728
            break;
729

    
730
          default:
731
            drupal_set_message(t(
732
            'Theme !theme is not supported yet by function !function.', array(
733
            '!theme' => $hook,
734
            '!function' => __FUNCTION__,
735
            )), 'error');
736
            break;
737
        } // END of theme hook switch
738
      } // END of tread as theme hook
739
      print $theme_result;
740
    } // END of handle $hook either as compose ot theme hook
741
  }
742
}
743

    
744
/**
745
 * @todo Please document this function.
746
 * @see http://drupal.org/node/1354
747
 */
748
function setvalue_session() {
749
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
750
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
751
    $keys = explode('][', $keys);
752
  }
753
  else {
754
    return;
755
  }
756
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
757

    
758
  // Prevent from malicous tags.
759
  $val = strip_tags($val);
760

    
761
  $var = &$_SESSION;
762
  $i = 0;
763
  foreach ($keys as $key) {
764
    $hasMoreKeys = ++$i < count($var);
765
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
766
      $var[$key] = array();
767
    }
768
    $var = &$var[$key];
769
  }
770
  $var = $val;
771
  if (isset($_REQUEST['destination'])) {
772
    drupal_goto($_REQUEST['destination']);
773
  }
774
}
775

    
776
/**
777
 * @todo Please document this function.
778
 * @see http://drupal.org/node/1354
779
 */
780
function uri_uriByProxy($uri, $theme = FALSE) {
781
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
782
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
783
}
784

    
785
/**
786
 * @todo Please document this function.
787
 * @see http://drupal.org/node/1354
788
 */
789
function cdm_compose_annotations_url($cdmBase) {
790
  if (!$cdmBase->uuid) {
791
    return;
792
  }
793

    
794
  $ws_base_uri = NULL;
795
  switch ($cdmBase->class) {
796
    case 'TaxonBase':
797
    case 'Taxon':
798
    case 'Synonym':
799
      $ws_base_uri = CDM_WS_TAXON;
800
      break;
801

    
802
    case 'TaxonNameBase':
803
    case 'NonViralName':
804
    case 'BacterialName':
805
    case 'BotanicalName':
806
    case 'CultivarPlantName':
807
    case 'ZoologicalName':
808
    case 'ViralName':
809
      $ws_base_uri = CDM_WS_NAME;
810
      break;
811

    
812
    case 'Media':
813
      $ws_base_uri = CDM_WS_MEDIA;
814
      break;
815

    
816
    case 'Reference':
817
      $ws_base_uri = CDM_WS_REFERENCE;
818
      break;
819

    
820
    case 'Distribution':
821
    case 'TextData':
822
    case 'TaxonInteraction':
823
    case 'QuantitativeData':
824
    case 'IndividualsAssociation':
825
    case 'Distribution':
826
    case 'CommonTaxonName':
827
    case 'CategoricalData':
828
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
829
      break;
830

    
831
    case 'PolytomousKey':
832
    case 'MediaKey':
833
    case 'MultiAccessKey':
834
      $ws_base_uri = $cdmBase->class;
835
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
836
      break;
837

    
838
    default:
839
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
840
      return;
841
  }
842
  return cdm_compose_url($ws_base_uri, array(
843
    $cdmBase->uuid,
844
    'annotations',
845
  ));
846
}
847

    
848
/**
849
 * Enter description here...
850
 *
851
 * @param string $resourceURI
852
 * @param mixed $pageSize
853
 *   The maximum number of entities returned per page (can be NULL
854
 *   to return all entities in a single page).
855
 * @param int $pageNumber
856
 *   The number of the page to be returned, the first page has the
857
 *   pageNumber = 1.
858
 *
859
 * @return unknown
860
 */
861
function cdm_ws_page($resourceURI, $pageSize, $pageNumber) {
862
  return cdm_ws_get($resourceURI, NULL, queryString(array(
863
    "page" => $pageNumber,
864
    'pageSize' => $pageSize,
865
  )));
866
}
867

    
868
/*
869
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
870
  $viewrank = _cdm_taxonomy_compose_viewrank();
871
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
872
  ? '/' . $path : '') ;
873
}
874
*/
875

    
876
/**
877
 * @todo Enter description here...
878
 *
879
 * @param string $taxon_uuid
880
 *  The UUID of a cdm taxon instance
881
 * @param string $ignore_rank_limit
882
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
883
 *
884
 * @return A cdm REST service URL path to a Classification
885
 */
886
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
887

    
888
  $view_uuid = get_taxonomictree_uuid_selected();
889
  $rank_uuid = NULL;
890
  if (!$ignore_rank_limit) {
891
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
892
  }
893

    
894
  if (!empty($taxon_uuid)) {
895
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
896
      $view_uuid,
897
      $taxon_uuid,
898
    ));
899
  }
900
  else {
901
    if (!empty($rank_uuid)) {
902
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
903
        $view_uuid,
904
        $rank_uuid,
905
      ));
906
    }
907
    else {
908
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
909
        $view_uuid,
910
      ));
911
    }
912
  }
913
}
914

    
915
/**
916
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
917
 *
918
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
919
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
920
 *
921
 * Operates in two modes depending on whether the parameter
922
 * $taxon_uuid is set or NULL.
923
 *
924
 * A) $taxon_uuid = NULL:
925
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
926
 *  2. otherwise return the default classification as defined by the admin via the settings
927
 *
928
 * b) $taxon_uuid is set:
929
 *   return the classification to whcih the taxon belongs to.
930
 *
931
 * @param UUID $taxon_uuid
932
 *   The UUID of a cdm taxon instance
933
 */
934
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
935

    
936
    $response = NULL;
937

    
938
    // 1st try
939
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
940

    
941
    if ($response == NULL) {
942
      // 2dn try by ignoring the rank limit
943
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
944
    }
945

    
946
    if ($response == NULL) {
947
      // 3rd try, last fallback:
948
      //    return the default classification
949
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
950
        // Delete the session value and try again with the default.
951
        unset($_SESSION['cdm']['taxonomictree_uuid']);
952
        return cdm_ws_taxonomy_root_level($taxon_uuid);
953
      }
954
      else {
955
        // Check if taxonomictree_uuid is valid.
956
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
957
        if ($test == NULL) {
958
          // The default set by the admin seems to be invalid or is not even set.
959
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
960
        }
961
      }
962
    }
963

    
964
  return $response;
965
}
966

    
967
/**
968
 * @todo Enter description here...
969
 *
970
 * @param string $taxon_uuid
971
 *
972
 * @return unknown
973
 */
974
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
975
  $view_uuid = get_taxonomictree_uuid_selected();
976
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
977

    
978
  $response = NULL;
979
  if ($rank_uuid) {
980
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
981
      $view_uuid,
982
      $taxon_uuid,
983
      $rank_uuid,
984
    ));
985
  }
986
  else {
987
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
988
      $view_uuid,
989
      $taxon_uuid,
990
    ));
991
  }
992

    
993
  if ($response == NULL) {
994
    // Error handing.
995
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
996
      // Delete the session value and try again with the default.
997
      unset($_SESSION['cdm']['taxonomictree_uuid']);
998
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
999
    }
1000
    else {
1001
      // Check if taxonomictree_uuid is valid.
1002
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1003
      if ($test == NULL) {
1004
        // The default set by the admin seems to be invalid or is not even set.
1005
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1006
      }
1007
    }
1008
  }
1009

    
1010
  return $response;
1011
}
1012

    
1013
/**
1014
 * @todo Please document this function.
1015
 * @see http://drupal.org/node/1354
1016
 */
1017
function cdm_rankVocabulary_as_option() {
1018
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1019
  array_unshift ($options, "");
1020
  return $options;
1021
}
1022

    
1023
/**
1024
 *
1025
 * @param Object $definedTermBase
1026
 * 	  of cdm type DefinedTermBase
1027
 * @return string
1028
 * 	  the localized representation_L10n of the term,
1029
 *    otherwise the titleCache as fall back,
1030
 *    otherwise an empty string
1031
 */
1032
function cdm_term_representation($definedTermBase) {
1033
  if ( isset($definedTermBase->representation_L10n) ) {
1034
    return $definedTermBase->representation_L10n;
1035
  } elseif ( isset($definedTermBase->titleCache)) {
1036
    return $definedTermBase->titleCache;
1037
  }
1038
  return '';
1039
}
1040

    
1041
/**
1042
 * @todo Improve documentation of this function.
1043
 *
1044
 * eu.etaxonomy.cdm.model.description.
1045
 * CategoricalData
1046
 * CommonTaxonName
1047
 * Distribution
1048
 * IndividualsAssociation
1049
 * QuantitativeData
1050
 * TaxonInteraction
1051
 * TextData
1052
 */
1053
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1054
  static $types = array(
1055
    "CategoricalData",
1056
    "CommonTaxonName",
1057
    "Distribution",
1058
    "IndividualsAssociation",
1059
    "QuantitativeData",
1060
    "TaxonInteraction",
1061
    "TextData",
1062
  );
1063

    
1064
  static $options = NULL;
1065
  if ($options == NULL) {
1066
    $options = array();
1067
    if ($prependEmptyElement) {
1068
      $options[' '] = '';
1069
    }
1070
    foreach ($types as $type) {
1071
      // No internatianalization here since these are purely technical terms.
1072
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1073
    }
1074
  }
1075
  return $options;
1076
}
1077

    
1078
/**
1079
 * @todo Please document this function.
1080
 * @see http://drupal.org/node/1354
1081
 */
1082
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1083
  static $vocabularyOptions = array();
1084

    
1085
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1086
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1087
    $vocabularyOptions[$vocabularyUuid] = array();
1088

    
1089
    if ($vocab) {
1090
      foreach ($vocab->terms as $term) {
1091
        if ($term_label_callback && function_exists($term_label_callback)) {
1092
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1093
        }
1094
        else {
1095
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1096
        }
1097
      }
1098
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1099
    }
1100
  }
1101
  return $vocabularyOptions[$vocabularyUuid];
1102
}
1103

    
1104
/**
1105
 * @todo Please document this function.
1106
 * @see http://drupal.org/node/1354
1107
 */
1108
function _cdm_relationship_type_term_label_callback($term) {
1109
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1110
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1111
  }
1112
  else {
1113
    return t($term->representation_L10n);
1114
  }
1115
}
1116

    
1117
/**
1118
 * @todo Please document this function.
1119
 * @see http://drupal.org/node/1354
1120
 */
1121
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1122
  if (!$featureTree) {
1123
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1124
      In order to see the species profiles of your taxa, please select a
1125
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1126
    return FALSE;
1127
  }
1128

    
1129
  $mergedTrees = array();
1130

    
1131
  if ($isDescriptionsSeparated) {
1132
    // Merge any description into a separate feature tree.
1133
    foreach ($descriptions as $desc) {
1134
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1135

    
1136
      $mergedTree = clone $featureTree;
1137
      $mergedTree->root->children = $mergedNodes;
1138
      $mergedTrees[] = $mergedTree;
1139
    }
1140
  }
1141
  else {
1142
    // Combine all descripions into one feature tree.
1143
    foreach ($descriptions as $desc) {
1144
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1145
      $featureTree->root->children = $mergedNodes;
1146
    }
1147
    $mergedTrees[] = $featureTree;
1148
  }
1149

    
1150
  return $mergedTrees;
1151
}
1152

    
1153
/**
1154
 * Get a list of annotations for a cdm entity.
1155
 *
1156
 * @param string $cdmBase
1157
 *   An annotatable cdm entity.
1158
 * @param array $includeTypes
1159
 *   If an array of annotation type uuids is supplied by this parameter the
1160
 *   list of annotations is resticted to those which belong to this type.
1161
 *
1162
 * @return array
1163
 *   An array of Annotation objects or an empty array.
1164
 */
1165
function cdm_ws_getAnnotationsFor($cdmBase, $includeTypes = FALSE) {
1166
  $annotationUrl = cdm_compose_annotations_url($cdmBase);
1167
  if ($annotationUrl) {
1168
    $annotationPager = cdm_ws_get($annotationUrl, NULL, NULL, NULL, TRUE);
1169
    if (isset($annotationPager->records) && is_array($annotationPager->records)) {
1170
      $annotations = array();
1171
      foreach ($annotationPager->records as $annotation) {
1172
        if ($includeTypes) {
1173
          if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1174
            $annotations[] = $annotation;
1175
          }
1176
        }
1177
        else {
1178
          $annotations[] = $annotation;
1179
        }
1180
      }
1181
      return $annotations;
1182
    }
1183
  }
1184
}
1185

    
1186
/**
1187
 * Get a NomenclaturalReference string.
1188
 *
1189
 * Returns the NomenclaturalReference string with correctly placed
1190
 * microreference (= reference detail) e.g.
1191
 * in Phytotaxa 43: 1-48. 2012.
1192
 *
1193
 * @param string $referenceUuid
1194
 *   UUID of the reference.
1195
 * @param string $microreference
1196
 *   Reference detail.
1197
 *
1198
 * @return string
1199
 *   a NomenclaturalReference.
1200
 */
1201
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1202
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1203
    $referenceUuid,
1204
  ), "microReference=" . urlencode($microreference));
1205

    
1206
  if ($obj) {
1207
    return $obj->String;
1208
  }
1209
  else {
1210
    return NULL;
1211
  }
1212
}
1213

    
1214
/**
1215
 * Merges the given featureNodes structure with the descriptionElements.
1216
 *
1217
 * This method is used in preparation for rendering the descriptionElements.
1218
 * The descriptionElements wich belong to a specific feature node are appended
1219
 * to a the feature node by creating a new field: FeatureNode->descriptionElements
1220
 * which originally is not existing in the cdm.
1221
 *
1222
 * @param array $featureNodes
1223
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1224
 *    may have children.
1225
 * @param array $descriptionElements
1226
 *    An flat array of cdm DescriptionElements
1227
 * @return array
1228
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1229
 */
1230
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1231
  foreach ($featureNodes as &$node) {
1232
    // Append corresponding elements to an additional node field:
1233
    // $node->descriptionElements.
1234
    foreach ($descriptionElements as $element) {
1235
      if ($element->feature->uuid == $node->feature->uuid) {
1236
        if (!isset($node->descriptionElements)) {
1237
          $node->descriptionElements = array();
1238
        }
1239
        $node->descriptionElements[] = $element;
1240
      }
1241
    }
1242

    
1243
    // Recurse into node children.
1244
    if (isset($node->children[0])) {
1245
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1246
      $node->children = $mergedChildNodes;
1247
    }
1248
  }
1249
  return $featureNodes;
1250
}
1251

    
1252
/**
1253
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1254
 *
1255
 * The response from the HTTP GET request is returned as object.
1256
 * The response objects coming from the webservice configured in the
1257
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1258
 *  in a level 2 (L2) cache.
1259
 *
1260
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1261
 * function, this cache persists only per each single page execution.
1262
 * Any object coming from the webservice is stored into it by default.
1263
 * In contrast to this default caching mechanism the L2 cache only is used if
1264
 * the 'cdm_webservice_cache' variable is set to TRUE,
1265
 * which can be set using the modules administrative settings section.
1266
 * Objects stored in this L2 cache are serialized and stored
1267
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1268
 * objects that are stored in the database will persist as
1269
 * long as the drupal cache is not beeing cleared and are available across
1270
 * multiple script executions.
1271
 *
1272
 * @param string $uri
1273
 *   URL to the webservice.
1274
 * @param array $pathParameters
1275
 *   An array of path parameters.
1276
 * @param string $query
1277
 *   A query string to be appended to the URL.
1278
 * @param string $method
1279
 *   The HTTP method to use, valid values are "GET" or "POST";
1280
 * @param bool $absoluteURI
1281
 *   TRUE when the URL should be treated as absolute URL.
1282
 *
1283
 * @return object
1284
 *   The deserialized webservice response object.
1285
 */
1286
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1287
  // static $cacheL1; if(!isset($cacheL1)){ $cacheL1 = array(); }
1288
  static $cacheL1 = array();
1289

    
1290
  // Transform the given uri path or pattern into a proper webservice uri.
1291
  if (!$absoluteURI) {
1292
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1293
  }
1294

    
1295
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1296
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1297

    
1298
  if (array_key_exists($uri, $cacheL1)) {
1299
    $cacheL1_obj = $cacheL1[$uri];
1300
  }
1301

    
1302
  $set_cacheL1 = FALSE;
1303
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1304
    $set_cacheL1 = TRUE;
1305
  }
1306

    
1307
  // Only cache cdm webservice URIs.
1308
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1309
  $cacheL2_entry = FALSE;
1310

    
1311
  if ($use_cacheL2) {
1312
    // Try to get object from cacheL2.
1313
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1314
  }
1315

    
1316
  if (isset($cacheL1_obj)) {
1317
    //
1318
    // The object has been found in the L1 cache.
1319
    //
1320
    $obj = $cacheL1_obj;
1321
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1322
      _add_status_message_toggler();
1323
      _add_debugMessageStr('Using cacheL1 for: ' . $uri);
1324
    }
1325
  }
1326
  elseif ($cacheL2_entry) {
1327
    //
1328
    // The object has been found in the L2 cache.
1329
    //
1330
    $obj = unserialize($cacheL2_entry->data);
1331

    
1332
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1333
      _add_status_message_toggler();
1334
      _add_debugMessageStr('Using cacheL2 for: ' . $uri);
1335
    }
1336
  }
1337
  else {
1338
    //
1339
    // Get the object from the webservice and cache it.
1340
    //
1341
    $time_get_start = microtime(TRUE);
1342
    // Request data from webservice JSON or XML.
1343
    $datastr = cdm_http_request($uri, $method);
1344
    $time_get = microtime(TRUE) - $time_get_start;
1345

    
1346
    $time_parse_start = microtime(TRUE);
1347

    
1348
    // Parse data and create object.
1349
    $obj = cdm_load_obj($datastr);
1350

    
1351
    $time_parse = microtime(TRUE) - $time_parse_start;
1352
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1353
      if ($obj || $datastr == "[]") {
1354
        $success_msg = 'valid';
1355
      }
1356
      else {
1357
        $success_msg = 'invalid';
1358
      }
1359
      _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
1360
    }
1361
    if ($set_cacheL2) {
1362
      // Store the object in cache L2.
1363
      // Comment @WA perhaps better if Drupal serializes here? Then the
1364
      // flag serialized is set properly in the cache table.
1365
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1366
    }
1367
  }
1368
  if ($obj) {
1369
    // Store the object in cache L1.
1370
    if ($set_cacheL1) {
1371
      $cacheL1[$uri] = $obj;
1372
    }
1373
  }
1374
  return $obj;
1375
}
1376

    
1377
/**
1378
 * @todo Please document this function.
1379
 * @see http://drupal.org/node/1354
1380
 */
1381
function _add_debugMessageStr($message) {
1382
  _add_status_message_toggler();
1383
  drupal_set_message(check_plain($message), 'debug');
1384
}
1385

    
1386
/**
1387
 * @todo Please document this function.
1388
 * @see http://drupal.org/node/1354
1389
 */
1390
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg) {
1391
  static $cumulated_time_parse = 0;
1392
  static $cumulated_time_get = 0;
1393
  _add_status_message_toggler();
1394

    
1395
  $cumulated_time_get += $time_get;
1396
  $cumulated_time_parse += $time_parse;
1397

    
1398
  // Decompose uri into path and query element.
1399
  // URI query elements are stored in an array
1400
  // suitable for drupal_http_build_query()
1401
  $uri_parts = explode("?", $uri);
1402
  $query = array();
1403
  if (count($uri_parts) == 2) {
1404
    $path = $uri_parts[0];
1405
    $queryparts = explode("&", $uri_parts[1]);
1406
    foreach ($queryparts as $querypart) {
1407
      $querypart = explode("=", $querypart);
1408
      if(count($querypart) == 2){
1409
        $query[$querypart[0]] = $querypart[1];
1410
      } else {
1411
        $query[$querypart[0]] = null;
1412
      }
1413
    }
1414
  }
1415
  else {
1416
    $path = $uri;
1417
  }
1418

    
1419
  $message = '<span class="uri">' . $uri . '</span><br />';
1420
  $message .= '[fetched in: ' . sprintf('%3.3f', $time_get) . 's(' . sprintf('%3.3f', $cumulated_time_get) . 's); ';
1421
  $message .= 'parsed in ' . sprintf('%3.3f', $time_parse) . ' s(' . sprintf('%3.3f', $cumulated_time_parse) . 's); ';
1422
  $message .= 'size:' . sprintf('%3.1f', ($datasize / 1024)) . ' kb of ' . $success_msg . ' data: ';
1423
  if (_is_cdm_ws_uri($path)) {
1424
    $message .= '<a href="' . url($path . '.xml', array(
1425
      'query' => $query,
1426
    )) . '" target="data" class="' . $success_msg . '">xml</a>-';
1427
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array(
1428
      'query' => $query,
1429
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>,';
1430
    $message .= '<a href="' . url($path . '.json', array(
1431
      'query' => $query,
1432
    )) . '" target="data" class="' . $success_msg . '">json</a>-';
1433
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.json', array(
1434
      'query' => $query,
1435
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>';
1436
  }
1437
  else {
1438
    $message .= '<a href="' . url($path, array(
1439
      'query' => $query,
1440
    )) . '" target="data" class="' . $success_msg . '">open</a>';
1441
  }
1442
  $message .= '] ';
1443
  drupal_set_message(($message), 'debug');
1444
}
1445

    
1446
/**
1447
 * @todo Please document this function.
1448
 * @see http://drupal.org/node/1354
1449
 */
1450
function cdm_load_obj($datastr) {
1451
  $obj = json_decode($datastr);
1452

    
1453
  if (!(is_object($obj) || is_array($obj))) {
1454
    ob_start();
1455
    $obj_dump = ob_get_contents();
1456
    ob_clean();
1457
    return FALSE;
1458
  }
1459

    
1460
  return $obj;
1461
}
1462

    
1463
/**
1464
 * Do a http request to a CDM webservice.
1465
 *
1466
 * @param string $uri
1467
 *   The webservice url.
1468
 * @param string $method
1469
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1470
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1471
 * @param array $parameters
1472
 *   Parameters to use in the request.
1473
 * @param array $header
1474
 *   The header to include in the request.
1475
 *
1476
 * @return
1477
 *   The response data from the request.
1478
 */
1479
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array()) {
1480
  static $acceptLanguage = NULL;
1481

    
1482
  if (!$acceptLanguage) {
1483
    if (function_exists('apache_request_headers')) {
1484
      $headers = apache_request_headers();
1485
      if (isset($headers['Accept-Language'])) {
1486
        $acceptLanguage = $headers['Accept-Language'];
1487
      }
1488
    }
1489
    if (!$acceptLanguage) {
1490
      // DEFAULT TODO make configurable.
1491
      $acceptLanguage = "en";
1492
    }
1493
  }
1494

    
1495
  if ($method != "GET" && $method != "POST") {
1496
    $method = "GET";
1497
  }
1498

    
1499
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1500
    $header['Accept'] = (variable_get('cdm_webservice_type', 'json') == 'json' ? 'application/json' : 'text/xml');
1501
    $header['Accept-Language'] = $acceptLanguage;
1502
    $header['Accept-Charset'] = 'UTF-8';
1503
  }
1504

    
1505
  if (FALSE && function_exists('curl_init')) {
1506
    // !!!!! CURL Disabled due to problems with following redirects
1507
    // (CURLOPT_FOLLOWLOCATION=1) and safe_mode = on
1508
    // Use the CURL lib if installed, it is supposed to be 20x faster.
1509
    return _http_request_using_curl($uri, $header, $method, $parameters);
1510
  }
1511
  else {
1512
    return _http_request_using_fsockopen($uri, $header, $method, $parameters);
1513
  }
1514
}
1515

    
1516
/**
1517
 * @todo Please document this function.
1518
 * @see http://drupal.org/node/1354
1519
 */
1520
function _http_request_using_fsockopen($uri, $header = array(), $method = 'GET') {
1521
  $response = drupal_http_request($uri, array('headers' => $header, 'method' => $method));
1522
  if (isset($response->data)) {
1523
      return $response->data;
1524
  }
1525
}
1526

    
1527
/**
1528
 * Return string content from a remote file.
1529
 *
1530
 * @author Luiz Miguel Axcar <lmaxcar@yahoo.com.br>
1531
 *
1532
 * @param string $uri
1533
 *   The url for which to return content.
1534
 *
1535
 * @return string
1536
 *   The returned content.
1537
 */
1538
function _http_request_using_curl($uri, $headers = array(), $method = "GET", $parameters = array()) {
1539
  $ch = curl_init();
1540

    
1541
  curl_setopt($ch, CURLOPT_URL, $uri);
1542
  curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
1543
  curl_setopt($ch, CURLOPT_MAXREDIRS, 5);
1544

    
1545
  // Set proxy settings.
1546
  if (variable_get('cdm_webservice_proxy_url', FALSE)) {
1547
    curl_setopt($ch, CURLOPT_PROXY, variable_get('cdm_webservice_proxy_url', ''));
1548
    curl_setopt($ch, CURLOPT_PROXYPORT, variable_get('cdm_webservice_proxy_port', '80'));
1549
    if (variable_get('cdm_webservice_proxy_usr', FALSE)) {
1550
      curl_setopt($ch, CURLOPT_PROXYUSERPWD, variable_get('cdm_webservice_proxy_usr', '') . ':' . variable_get('cdm_webservice_proxy_pwd', ''));
1551
    }
1552
  }
1553

    
1554
  // Modify headers array to be used by curl.
1555
  foreach ($headers as $header_key => $header_val) {
1556
    $curl_headers[] = $header_key . ': ' . $header_val;
1557
  }
1558
  if (isset($curl_headers)) {
1559
    curl_setopt($ch, CURLOPT_HTTPHEADER, $curl_headers);
1560
  }
1561

    
1562
  // Set method if not default.
1563
  if ($method != "GET") {
1564
    if ($method == "POST") {
1565

    
1566
      curl_setopt($ch, CURLOPT_POST, 1);
1567
      curl_setopt($ch, CURLOPT_POSTFIELDS, $parameters);
1568
    }
1569
    else {
1570
      // Other obscure http methods get passed to curl directly.
1571
      // TODO generic parameter/body handling
1572
      curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
1573
    }
1574
  }
1575

    
1576
  ob_start();
1577
  curl_exec($ch);
1578
  $info = curl_getinfo($ch);
1579
  if (curl_errno($ch)) {
1580
    watchdog('CDM_API', '_http_request_curl() - ' . curl_error($ch) . '; REQUEST-METHOD:' . $method . ' URL: ' . substr($uri . ' ', 0, 150), WATCHDOG_ERROR);
1581
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1582
      drupal_set_message(check_plain(t('_http_request_curl() - !curl_error; REQUEST-METHOD:!method URL: !url', array(
1583
      '!curl_error' => curl_error($ch),
1584
      '!method' => $method,
1585
      '!url' => substr($uri . ' ', 0, 150),
1586
       ))), 'error');
1587
    }
1588
  }
1589
  curl_close($ch);
1590
  $string = ob_get_contents();
1591
  ob_end_clean();
1592

    
1593
  return $string;
1594
}
1595

    
1596
/**
1597
 * @todo Please document this function.
1598
 * @see http://drupal.org/node/1354
1599
 */
1600
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1601
  $out = '';
1602

    
1603
  foreach ($rootNode->children as $featureNode) {
1604
    $out .= ($out ? $separator : '');
1605
    $out .= $featureNode->feature->representation_L10n;
1606
    if (is_array($featureNode->children)) {
1607
      $childlabels = '';
1608
      foreach ($featureNode->children as $childNode) {
1609
        $childlabels .= ($childlabels ? $separator : '');
1610
      }
1611
      $childlabels .= _featureTree_elements_toString($childNode);
1612
    }
1613
    if ($childlabels) {
1614
      $out .= '[' . $childlabels . ' ]';
1615
    }
1616
  }
1617
  return $out;
1618
}
1619

    
1620
/**
1621
 * Create a one-dimensional form options array.
1622
 *
1623
 * Creates an array of all features in the feature tree of feature nodes,
1624
 * the node labels are indented by $node_char and $childIndent depending on the
1625
 * hierachy level.
1626
 *
1627
 * @param - $rootNode
1628
 * @param - $node_char
1629
 * @param - $childIndentStr
1630
 * @param - $childIndent
1631
 *   ONLY USED INTERNALLY!
1632
 *
1633
 * @return array
1634
 *   A one dimensional Drupal form options array.
1635
 */
1636
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1637
  $options = array();
1638
  foreach ($rootNode->children as $featureNode) {
1639
    $indent_prefix = '';
1640
    if ($childIndent) {
1641
      $indent_prefix = $childIndent . $node_char . " ";
1642
    }
1643
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1644
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1645
      // Foreach ($featureNode->children as $childNode){
1646
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1647
      $options = array_merge_recursive($options, $childList);
1648
      // }
1649
    }
1650
  }
1651
  return $options;
1652
}
1653

    
1654
/**
1655
 * Returns an array with all available FeatureTrees and the representations of the selected
1656
 * FeatureTree as a detail view.
1657
 *
1658
 * @param boolean $add_default_feature_free
1659
 * @return array
1660
 *  associative array with following keys:
1661
 *  -options: Returns an array with all available Feature Trees
1662
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1663
 *
1664
 */
1665
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1666
  $feature_trees = array();
1667

    
1668
  // Set tree that contains all features.
1669
  if ($add_default_feature_free) {
1670
    $feature_trees[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1671
  }
1672

    
1673
  // Get features from database.
1674
  $persisted_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1675
  $tree_representation = NULL;
1676
  if (is_array($persisted_trees)) {
1677

    
1678
    foreach ($persisted_trees as $featureTree) {
1679
      // Do not add the DEFAULT_FEATURETREE again,
1680
      if ($featureTree->uuid == UUID_DEFAULT_FEATURETREE) {
1681
        continue;
1682
      }
1683
      $feature_trees[$featureTree->uuid] = $featureTree->titleCache;
1684
      // $feature_trees[$featureTree->uuid] = $tree_representation;
1685
    }
1686
  }
1687
  $selected_feature_tree = get_profile_featureTree();
1688
  // $tree_representation = $featureTree->titleCache;
1689
  $tree_representation = '';
1690
  if (is_array( $selected_feature_tree->root->children) && count( $selected_feature_tree->root->children) > 0) {
1691

    
1692
    // Render the hierarchic tree structure.
1693
    $treeDetails = '<div class="featuretree_structure">'
1694
      // ._featureTree_elements_toString($featureTree->root)
1695
      . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $selected_feature_tree->uuid))
1696
      . '</div>';
1697

    
1698
    $form = array();
1699
    $form['featureTree-' .  $selected_feature_tree->uuid] = array(
1700
      '#type' => 'fieldset',
1701
      '#title' => 'Show details',
1702
      '#attributes' => array('class' => array('collapsible collapsed')),
1703
      // '#collapsible' => TRUE,
1704
      // '#collapsed' => TRUE,
1705
    );
1706
    $form['featureTree-' .  $selected_feature_tree->uuid]['details'] = array(
1707
      '#markup' => $treeDetails,
1708
    );
1709
    // echo drupal_render($form);
1710
    $tree_representation .= drupal_render($form);
1711
  }
1712

    
1713

    
1714
  // return $feature_trees;
1715
  return array('options' => $feature_trees, 'treeRepresentations' => $tree_representation);
1716
}
1717

    
1718
/**
1719
 * Provides the list of availbale classifications in form of an options array.
1720
 *
1721
 * The options array is suitable for drupal form API elements that allow multiple choices.
1722
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1723
 *
1724
 * The classifications are ordered alphabetically whereas the classification
1725
 * chosen as default will always appear on top of the array, followed by a
1726
 * blank line below.
1727
 *
1728
 * @param bool $add_none_option
1729
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1730
 *
1731
 * @return array
1732
 *   classifications in an array as options for a form element that allows multiple choices.
1733
 */
1734
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1735

    
1736
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1737

    
1738
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1739
  $default_classification_label = '';
1740

    
1741
  // add all classifications
1742
  $taxonomic_tree_options = array();
1743
  if ($add_none_option) {
1744
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1745
  }
1746
  if ($taxonTrees) {
1747
    foreach ($taxonTrees as $tree) {
1748
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1749
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1750
      } else {
1751
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1752
        if (count($taxonTrees) > 1) {
1753
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1754
        }
1755
        $default_classification_label = $tree->titleCache;
1756
      }
1757
    }
1758
  }
1759
  // oder alphabetically the space
1760
  asort($taxonomic_tree_options);
1761

    
1762
  // now set the labels
1763
  //   for none
1764
  if ($add_none_option) {
1765
    $taxonomic_tree_options['NONE'] = t('-- None --');
1766
  }
1767

    
1768
  //   for default_classification
1769
  if (is_uuid($default_classification_uuid)) {
1770
    $taxonomic_tree_options[$default_classification_uuid] =
1771
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1772
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1773
  }
1774

    
1775
  return $taxonomic_tree_options;
1776
}
1777

    
1778
/**
1779
 * @todo Please document this function.
1780
 * @see http://drupal.org/node/1354
1781
 */
1782
function cdm_api_secref_cache_prefetch(&$secUuids) {
1783
  // Comment @WA: global variables should start with a single underscore
1784
  // followed by the module and another underscore.
1785
  global $_cdm_api_secref_cache;
1786
  if (!is_array($_cdm_api_secref_cache)) {
1787
    $_cdm_api_secref_cache = array();
1788
  }
1789
  $uniqueUuids = array_unique($secUuids);
1790
  $i = 0;
1791
  $param = '';
1792
  while ($i++ < count($uniqueUuids)) {
1793
    $param .= $secUuids[$i] . ',';
1794
    if (strlen($param) + 37 > 2000) {
1795
      _cdm_api_secref_cache_add($param);
1796
      $param = '';
1797
    }
1798
  }
1799
  if ($param) {
1800
    _cdm_api_secref_cache_add($param);
1801
  }
1802
}
1803

    
1804
/**
1805
 * @todo Please document this function.
1806
 * @see http://drupal.org/node/1354
1807
 */
1808
function cdm_api_secref_cache_get($secUuid) {
1809
  global $_cdm_api_secref_cache;
1810
  if (!is_array($_cdm_api_secref_cache)) {
1811
    $_cdm_api_secref_cache = array();
1812
  }
1813
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1814
    _cdm_api_secref_cache_add($secUuid);
1815
  }
1816
  return $_cdm_api_secref_cache[$secUuid];
1817
}
1818

    
1819
/**
1820
 * @todo Please document this function.
1821
 * @see http://drupal.org/node/1354
1822
 */
1823
function cdm_api_secref_cache_clear() {
1824
  global $_cdm_api_secref_cache;
1825
  $_cdm_api_secref_cache = array();
1826
}
1827

    
1828
/**
1829
 * Validates if the given string is a uuid.
1830
 *
1831
 * @param string $str
1832
 *   The string to validate.
1833
 *
1834
 * return bool
1835
 *   TRUE if the string is a UUID.
1836
 */
1837
function is_uuid($str) {
1838
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1839
}
1840

    
1841
/**
1842
 * Checks if the given $object is a valid cdm entity.
1843
 *
1844
 * An object is considered a cdm entity if it has a string field $object->class
1845
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1846
 *
1847
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1848
 *
1849
 * @param mixed $object
1850
 *   The object to validate
1851
 *
1852
 * @return bool
1853
 *   True if the object is a cdm entity.
1854
 */
1855
function is_cdm_entity($object) {
1856
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1857
}
1858

    
1859
/**
1860
 * @todo Please document this function.
1861
 * @see http://drupal.org/node/1354
1862
 */
1863
function _cdm_api_secref_cache_add($secUuidsStr) {
1864
  global $_cdm_api_secref_cache;
1865
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1866
  // Batch fetching not jet reimplemented thus:
1867
  /*
1868
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1869
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1870
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1871
  */
1872
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1873
}
1874

    
1875
/**
1876
 * Checks if the given uri starts with a cdm webservice url.
1877
 *
1878
 * Checks if the uri starts with the cdm webservice url stored in the
1879
 * Drupal variable 'cdm_webservice_url'.
1880
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1881
 *
1882
 * @param string $uri
1883
 *   The URI to test.
1884
 *
1885
 * @return bool
1886
 *   True if the uri starts with a cdm webservice url.
1887
 */
1888
function _is_cdm_ws_uri($uri) {
1889
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1890
}
1891

    
1892
/**
1893
 * @todo Please document this function.
1894
 * @see http://drupal.org/node/1354
1895
 */
1896
function queryString($elements) {
1897
  $query = '';
1898
  foreach ($elements as $key => $value) {
1899
    if (is_array($value)) {
1900
      foreach ($value as $v) {
1901
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1902
      }
1903
    }
1904
    else {
1905
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1906
    }
1907
  }
1908
  return $query;
1909
}
1910

    
1911
/**
1912
 * Implementation of the magic method __clone to allow deep cloning of objects
1913
 * and arrays.
1914
 */
1915
function __clone() {
1916
  foreach ($this as $name => $value) {
1917
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1918
      $this->$name = clone($this->$name);
1919
    }
1920
  }
1921
}
1922

    
1923
/**
1924
 * Make a 'deep copy' of an array.
1925
 *
1926
 * Make a complete deep copy of an array replacing
1927
 * references with deep copies until a certain depth is reached
1928
 * ($maxdepth) whereupon references are copied as-is...
1929
 *
1930
 * @see http://us3.php.net/manual/en/ref.array.php
1931
 *
1932
 * @param array $array
1933
 * @param array $copy
1934
 * @param int $maxdepth
1935
 * @param int $depth
1936
 *
1937
 * @return void
1938
 */
1939
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
1940
  if ($depth > $maxdepth) {
1941
    $copy = $array;
1942
    return;
1943
  }
1944
  if (!is_array($copy)) {
1945
    $copy = array();
1946
  }
1947
  foreach ($array as $k => &$v) {
1948
    if (is_array($v)) {
1949
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
1950
    }
1951
    else {
1952
      $copy[$k] = $v;
1953
    }
1954
  }
1955
}
1956

    
1957
/**
1958
 * Implementation of theme_status_messages($display = NULL).
1959
 *
1960
 * @see includes/theme.inc
1961
 *
1962
 * @return void
1963
 */
1964
function _add_status_message_toggler() {
1965
  static $isAdded = FALSE;
1966
  if (!$isAdded) {
1967
    drupal_add_js(
1968
    'jQuery(document).ready(function($){
1969
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
1970
       $(\'.messages_toggler\').click(function(){
1971
         $(this).next().slideToggle(\'fast\');
1972
         return false;
1973
       }).next().hide();
1974
     });', array('type' => 'inline'));
1975

    
1976
    $isAdded = TRUE;
1977
  }
1978
}
1979

    
1980
/**
1981
 * @todo Please document this function.
1982
 * @see http://drupal.org/node/1354
1983
 */
1984
function _no_classfication_uuid_message() {
1985
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
1986
    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.');
1987
  }
1988
  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.');
1989
}
1990

    
1991
/**
1992
 * Implementation of hook flush_caches
1993
 *
1994
 * Add custom cache tables to the list of cache tables that
1995
 * will be cleared by the Clear button on the Performance page or whenever
1996
 * drupal_flush_all_caches is invoked.
1997
 *
1998
 * @author W.Addink <waddink@eti.uva.nl>
1999
 *
2000
 * @return array
2001
 *   An array with custom cache tables to include.
2002
 */
2003
function cdm_api_flush_caches() {
2004
  return array('cache_cdm_ws');
2005
}
(4-4/9)