Project

General

Profile

Download (59.8 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-Encoding', 'gzip');
776
      }
777
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
778
      drupal_add_http_header('Content-Length', strlen($reponse_data));
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 int $pageSize
893
 *   The maximum number of entities returned per page.
894
 *   The default page size as configured in the cdm server
895
 *   will be used if set to NULL
896
 *   to return all entities in a single page).
897
 * @param int $pageNumber
898
 *   The number of the page to be returned, the first page has the
899
 *   pageNumber = 0
900
 *
901
 * @return the a CDM Pager object
902
 *
903
 */
904
function cdm_ws_page($resourceURI, $pageSize, $pageNumber) {
905
  return cdm_ws_get($resourceURI, NULL, queryString(array(
906
    "pageNumber" => $pageNumber,
907
    'pageSize' => $pageSize,
908
  )));
909
}
910

    
911
/**
912
 * Fetches all entities from the given REST endpoint using the pager mechanism.
913
 *
914
 * @param string $resourceURI
915
 *
916
 * @return array
917
 *     A list of CDM entitites
918
 *
919
 */
920
function cdm_ws_fetch_all($resourceURI) {
921
  $page_index = 0;
922
  // using a bigger page size to avoid to many multiple requests
923
  $page_size = 200;
924
  $entities = array();
925

    
926
  while ($page_index !== FALSE){
927
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index);
928
    if(isset($pager->records) && is_array($pager->records)) {
929
      $entities = $pager->records;
930
      if(!empty($pager->nextIndex)){
931
        $page_index = $pager->nextIndex;
932
      } else {
933
        $page_index = FALSE;
934
      }
935
    } else {
936
      $page_index = FALSE;
937
    }
938
  }
939
  return $entities;
940
}
941

    
942
/*
943
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
944
  $viewrank = _cdm_taxonomy_compose_viewrank();
945
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
946
  ? '/' . $path : '') ;
947
}
948
*/
949

    
950
/**
951
 * @todo Enter description here...
952
 *
953
 * @param string $taxon_uuid
954
 *  The UUID of a cdm taxon instance
955
 * @param string $ignore_rank_limit
956
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
957
 *
958
 * @return A cdm REST service URL path to a Classification
959
 */
960
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
961

    
962
  $view_uuid = get_taxonomictree_uuid_selected();
963
  $rank_uuid = NULL;
964
  if (!$ignore_rank_limit) {
965
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
966
  }
967

    
968
  if (!empty($taxon_uuid)) {
969
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
970
      $view_uuid,
971
      $taxon_uuid,
972
    ));
973
  }
974
  else {
975
    if (!empty($rank_uuid)) {
976
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
977
        $view_uuid,
978
        $rank_uuid,
979
      ));
980
    }
981
    else {
982
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
983
        $view_uuid,
984
      ));
985
    }
986
  }
987
}
988

    
989
/**
990
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
991
 *
992
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
993
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
994
 *
995
 * Operates in two modes depending on whether the parameter
996
 * $taxon_uuid is set or NULL.
997
 *
998
 * A) $taxon_uuid = NULL:
999
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1000
 *  2. otherwise return the default classification as defined by the admin via the settings
1001
 *
1002
 * b) $taxon_uuid is set:
1003
 *   return the classification to whcih the taxon belongs to.
1004
 *
1005
 * @param UUID $taxon_uuid
1006
 *   The UUID of a cdm taxon instance
1007
 */
1008
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1009

    
1010
    $response = NULL;
1011

    
1012
    // 1st try
1013
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
1014

    
1015
    if ($response == NULL) {
1016
      // 2dn try by ignoring the rank limit
1017
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
1018
    }
1019

    
1020
    if ($response == NULL) {
1021
      // 3rd try, last fallback:
1022
      //    return the default classification
1023
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1024
        // Delete the session value and try again with the default.
1025
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1026
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1027
      }
1028
      else {
1029
        // Check if taxonomictree_uuid is valid.
1030
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1031
        if ($test == NULL) {
1032
          // The default set by the admin seems to be invalid or is not even set.
1033
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1034
        }
1035
      }
1036
    }
1037

    
1038
  return $response;
1039
}
1040

    
1041
/**
1042
 * @todo Enter description here...
1043
 *
1044
 * @param string $taxon_uuid
1045
 *
1046
 * @return unknown
1047
 */
1048
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1049
  $view_uuid = get_taxonomictree_uuid_selected();
1050
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1051

    
1052
  $response = NULL;
1053
  if ($rank_uuid) {
1054
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1055
      $view_uuid,
1056
      $taxon_uuid,
1057
      $rank_uuid,
1058
    ));
1059
  }
1060
  else {
1061
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1062
      $view_uuid,
1063
      $taxon_uuid,
1064
    ));
1065
  }
1066

    
1067
  if ($response == NULL) {
1068
    // Error handing.
1069
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1070
      // Delete the session value and try again with the default.
1071
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1072
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1073
    }
1074
    else {
1075
      // Check if taxonomictree_uuid is valid.
1076
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1077
      if ($test == NULL) {
1078
        // The default set by the admin seems to be invalid or is not even set.
1079
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1080
      }
1081
    }
1082
  }
1083

    
1084
  return $response;
1085
}
1086

    
1087
/**
1088
 * @todo Please document this function.
1089
 * @see http://drupal.org/node/1354
1090
 */
1091
function cdm_rankVocabulary_as_option() {
1092
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1093
  array_unshift ($options, "");
1094
  return $options;
1095
}
1096

    
1097
/**
1098
 *
1099
 * @param Object $definedTermBase
1100
 * 	  of cdm type DefinedTermBase
1101
 * @return string
1102
 * 	  the localized representation_L10n of the term,
1103
 *    otherwise the titleCache as fall back,
1104
 *    otherwise an empty string
1105
 */
1106
function cdm_term_representation($definedTermBase) {
1107
  if ( isset($definedTermBase->representation_L10n) ) {
1108
    return $definedTermBase->representation_L10n;
1109
  } elseif ( isset($definedTermBase->titleCache)) {
1110
    return $definedTermBase->titleCache;
1111
  }
1112
  return '';
1113
}
1114

    
1115
/**
1116
 * @todo Improve documentation of this function.
1117
 *
1118
 * eu.etaxonomy.cdm.model.description.
1119
 * CategoricalData
1120
 * CommonTaxonName
1121
 * Distribution
1122
 * IndividualsAssociation
1123
 * QuantitativeData
1124
 * TaxonInteraction
1125
 * TextData
1126
 */
1127
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1128
  static $types = array(
1129
    "CategoricalData",
1130
    "CommonTaxonName",
1131
    "Distribution",
1132
    "IndividualsAssociation",
1133
    "QuantitativeData",
1134
    "TaxonInteraction",
1135
    "TextData",
1136
  );
1137

    
1138
  static $options = NULL;
1139
  if ($options == NULL) {
1140
    $options = array();
1141
    if ($prependEmptyElement) {
1142
      $options[' '] = '';
1143
    }
1144
    foreach ($types as $type) {
1145
      // No internatianalization here since these are purely technical terms.
1146
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1147
    }
1148
  }
1149
  return $options;
1150
}
1151

    
1152
/**
1153
 * @todo Please document this function.
1154
 * @see http://drupal.org/node/1354
1155
 */
1156
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1157
  static $vocabularyOptions = array();
1158

    
1159
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1160
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1161
    $vocabularyOptions[$vocabularyUuid] = array();
1162

    
1163
    if ($vocab) {
1164
      foreach ($vocab->terms as $term) {
1165
        if ($term_label_callback && function_exists($term_label_callback)) {
1166
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1167
        }
1168
        else {
1169
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1170
        }
1171
      }
1172
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1173
    }
1174
  }
1175
  return $vocabularyOptions[$vocabularyUuid];
1176
}
1177

    
1178
/**
1179
 * @todo Please document this function.
1180
 * @see http://drupal.org/node/1354
1181
 */
1182
function _cdm_relationship_type_term_label_callback($term) {
1183
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1184
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1185
  }
1186
  else {
1187
    return t($term->representation_L10n);
1188
  }
1189
}
1190

    
1191
/**
1192
 * @todo Please document this function.
1193
 * @see http://drupal.org/node/1354
1194
 */
1195
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1196
  if (!$featureTree) {
1197
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1198
      In order to see the species profiles of your taxa, please select a
1199
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1200
    return FALSE;
1201
  }
1202

    
1203
  $mergedTrees = array();
1204

    
1205
  if ($isDescriptionsSeparated) {
1206
    // Merge any description into a separate feature tree.
1207
    foreach ($descriptions as $desc) {
1208
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1209

    
1210
      $mergedTree = clone $featureTree;
1211
      $mergedTree->root->children = $mergedNodes;
1212
      $mergedTrees[] = $mergedTree;
1213
    }
1214
  }
1215
  else {
1216
    // Combine all descripions into one feature tree.
1217
    $descriptionElemens = array();
1218
    foreach ($descriptions as $desc) {
1219
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1220
    }
1221
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1222
    $featureTree->root->children = $mergedNodes;
1223
    $mergedTrees[] = $featureTree;
1224
  }
1225

    
1226
  return $mergedTrees;
1227
}
1228

    
1229
/**
1230
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1231
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1232
 * be requested for the annotations.
1233
 *
1234
 * @param string $cdmBase
1235
 *   An annotatable cdm entity.
1236
 * @param array $includeTypes
1237
 *   If an array of annotation type uuids is supplied by this parameter the
1238
 *   list of annotations is resticted to those which belong to this type.
1239
 *
1240
 * @return array
1241
 *   An array of Annotation objects or an empty array.
1242
 */
1243
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1244

    
1245
  if(!isset($cdmBase->annotations)){
1246
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
1247
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl);
1248
  }
1249

    
1250
  $annotations = array();
1251
  foreach ($cdmBase->annotations as $annotation) {
1252
    if ($includeTypes) {
1253
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1254
        $annotations[] = $annotation;
1255
      }
1256
    }
1257
    else {
1258
      $annotations[] = $annotation;
1259
    }
1260
  }
1261
  return $annotations;
1262

    
1263
}
1264

    
1265
/**
1266
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1267
 *
1268
 * @param object $annotatable_entity
1269
 *   The CDM AnnotatableEntity to load annotations for
1270
 */
1271
function cdm_load_annotations(&$annotatable_entity) {
1272
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1273
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1274
    if (is_array($annotations)) {
1275
      $annotatable_entity->annotations = $annotations;
1276
    }
1277
  }
1278
}
1279

    
1280
/**
1281
 * Get a NomenclaturalReference string.
1282
 *
1283
 * Returns the NomenclaturalReference string with correctly placed
1284
 * microreference (= reference detail) e.g.
1285
 * in Phytotaxa 43: 1-48. 2012.
1286
 *
1287
 * @param string $referenceUuid
1288
 *   UUID of the reference.
1289
 * @param string $microreference
1290
 *   Reference detail.
1291
 *
1292
 * @return string
1293
 *   a NomenclaturalReference.
1294
 */
1295
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1296
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1297
    $referenceUuid,
1298
  ), "microReference=" . urlencode($microreference));
1299

    
1300
  if ($obj) {
1301
    return $obj->String;
1302
  }
1303
  else {
1304
    return NULL;
1305
  }
1306
}
1307

    
1308
/**
1309
 * Merges the given featureNodes structure with the descriptionElements.
1310
 *
1311
 * This method is used in preparation for rendering the descriptionElements.
1312
 * The descriptionElements wich belong to a specific feature node are appended
1313
 * to a the feature node by creating a new fields:
1314
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1315
 * The descriptionElements will be cleared in advance in order to allow reusing the
1316
 * same feature tree without the risk of mixing sets of descrition elemens.
1317
 *
1318
 * which originally is not existing in the cdm.
1319
 *
1320
 *
1321
 *
1322
 * @param array $featureNodes
1323
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1324
 *    may have children.
1325
 * @param array $descriptionElements
1326
 *    An flat array of cdm DescriptionElements
1327
 * @return array
1328
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1329
 */
1330
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1331

    
1332
  foreach ($featureNodes as &$node) {
1333
    // since the $featureNodes array is reused for each description
1334
    // it is nessecary to clear the custom node fields in advance
1335
    if(isset($node->descriptionElements)){
1336
      unset($node->descriptionElements);
1337
    }
1338

    
1339
    // Append corresponding elements to an additional node field:
1340
    // $node->descriptionElements.
1341
    foreach ($descriptionElements as $element) {
1342
      if ($element->feature->uuid == $node->feature->uuid) {
1343
        if (!isset($node->descriptionElements)) {
1344
          $node->descriptionElements = array();
1345
        }
1346
        $node->descriptionElements[] = $element;
1347
      }
1348
    }
1349

    
1350
    // Recurse into node children.
1351
    if (isset($node->children[0])) {
1352
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1353
      $node->children = $mergedChildNodes;
1354
    }
1355

    
1356
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1357
      unset($node);
1358
    }
1359

    
1360
  }
1361

    
1362
  return $featureNodes;
1363
}
1364

    
1365
/**
1366
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1367
 *
1368
 * The response from the HTTP GET request is returned as object.
1369
 * The response objects coming from the webservice configured in the
1370
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1371
 *  in a level 2 (L2) cache.
1372
 *
1373
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1374
 * function, this cache persists only per each single page execution.
1375
 * Any object coming from the webservice is stored into it by default.
1376
 * In contrast to this default caching mechanism the L2 cache only is used if
1377
 * the 'cdm_webservice_cache' variable is set to TRUE,
1378
 * which can be set using the modules administrative settings section.
1379
 * Objects stored in this L2 cache are serialized and stored
1380
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1381
 * objects that are stored in the database will persist as
1382
 * long as the drupal cache is not beeing cleared and are available across
1383
 * multiple script executions.
1384
 *
1385
 * @param string $uri
1386
 *   URL to the webservice.
1387
 * @param array $pathParameters
1388
 *   An array of path parameters.
1389
 * @param string $query
1390
 *   A query string to be appended to the URL.
1391
 * @param string $method
1392
 *   The HTTP method to use, valid values are "GET" or "POST";
1393
 * @param bool $absoluteURI
1394
 *   TRUE when the URL should be treated as absolute URL.
1395
 *
1396
 * @return object
1397
 *   The deserialized webservice response object.
1398
 */
1399
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1400

    
1401
  static $cacheL1 = array();
1402

    
1403
  // Transform the given uri path or pattern into a proper webservice uri.
1404
  if (!$absoluteURI) {
1405
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1406
  }
1407

    
1408
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1409
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1410

    
1411
  if (array_key_exists($uri, $cacheL1)) {
1412
    $cacheL1_obj = $cacheL1[$uri];
1413
  }
1414

    
1415
  $set_cacheL1 = FALSE;
1416
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1417
    $set_cacheL1 = TRUE;
1418
  }
1419

    
1420
  // Only cache cdm webservice URIs.
1421
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1422
  $cacheL2_entry = FALSE;
1423

    
1424
  if ($use_cacheL2) {
1425
    // Try to get object from cacheL2.
1426
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1427
  }
1428

    
1429
  if (isset($cacheL1_obj)) {
1430
    //
1431
    // The object has been found in the L1 cache.
1432
    //
1433
    $obj = $cacheL1_obj;
1434
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1435
      _add_status_message_toggler();
1436
      _add_debugMessageStr('Using cacheL1 for: ' . $uri);
1437
    }
1438
  }
1439
  elseif ($cacheL2_entry) {
1440
    //
1441
    // The object has been found in the L2 cache.
1442
    //
1443
    $obj = unserialize($cacheL2_entry->data);
1444

    
1445
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1446
      _add_status_message_toggler();
1447
      _add_debugMessageStr('Using cacheL2 for: ' . $uri);
1448
    }
1449
  }
1450
  else {
1451
    //
1452
    // Get the object from the webservice and cache it.
1453
    //
1454
    $time_get_start = microtime(TRUE);
1455
    // Request data from webservice JSON or XML.
1456
    $response = cdm_http_request($uri, $method);
1457
    $datastr = NULL;
1458
    if (isset($response->data)) {
1459
      $datastr = $response->data;
1460
    }
1461
    $time_get = microtime(TRUE) - $time_get_start;
1462
    $time_parse_start = microtime(TRUE);
1463

    
1464
    // Parse data and create object.
1465
    $obj = cdm_load_obj($datastr);
1466

    
1467
    $time_parse = microtime(TRUE) - $time_parse_start;
1468
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1469
      if ($obj || $datastr == "[]") {
1470
        $success_msg = 'valid';
1471
      }
1472
      else {
1473
        $success_msg = 'invalid';
1474
      }
1475
      _add_debugMessage($uri, $time_get, $time_parse, strlen($datastr), $success_msg);
1476
    }
1477
    if ($set_cacheL2) {
1478
      // Store the object in cache L2.
1479
      // Comment @WA perhaps better if Drupal serializes here? Then the
1480
      // flag serialized is set properly in the cache table.
1481
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1482
    }
1483
  }
1484
  if ($obj) {
1485
    // Store the object in cache L1.
1486
    if ($set_cacheL1) {
1487
      $cacheL1[$uri] = $obj;
1488
    }
1489
  }
1490
  return $obj;
1491
}
1492

    
1493
/**
1494
 * @todo Please document this function.
1495
 * @see http://drupal.org/node/1354
1496
 */
1497
function _add_debugMessageStr($message) {
1498
  _add_status_message_toggler();
1499
  drupal_set_message(check_plain($message), 'debug');
1500
}
1501

    
1502
/**
1503
 * @todo Please document this function.
1504
 * @see http://drupal.org/node/1354
1505
 */
1506
function _add_debugMessage($uri, $time_get, $time_parse, $datasize, $success_msg) {
1507
  static $cumulated_time_parse = 0;
1508
  static $cumulated_time_get = 0;
1509
  _add_status_message_toggler();
1510

    
1511
  $cumulated_time_get += $time_get;
1512
  $cumulated_time_parse += $time_parse;
1513

    
1514
  // Decompose uri into path and query element.
1515
  // URI query elements are stored in an array
1516
  // suitable for drupal_http_build_query()
1517
  $uri_parts = explode("?", $uri);
1518
  $query = array();
1519
  if (count($uri_parts) == 2) {
1520
    $path = $uri_parts[0];
1521
    $queryparts = explode("&", $uri_parts[1]);
1522
    foreach ($queryparts as $querypart) {
1523
      $querypart = explode("=", $querypart);
1524
      if(count($querypart) == 2){
1525
        $query[$querypart[0]] = $querypart[1];
1526
      } else {
1527
        $query[$querypart[0]] = null;
1528
      }
1529
    }
1530
  }
1531
  else {
1532
    $path = $uri;
1533
  }
1534

    
1535
  $message = '<span class="uri">' . $uri . '</span><br />';
1536
  $message .= '[fetched in: ' . sprintf('%3.3f', $time_get) . 's(' . sprintf('%3.3f', $cumulated_time_get) . 's); ';
1537
  $message .= 'parsed in ' . sprintf('%3.3f', $time_parse) . ' s(' . sprintf('%3.3f', $cumulated_time_parse) . 's); ';
1538
  $message .= 'size:' . sprintf('%3.1f', ($datasize / 1024)) . ' kb of ' . $success_msg . ' data: ';
1539
  if (_is_cdm_ws_uri($path)) {
1540
    $message .= '<a href="' . url($path . '.xml', array(
1541
      'query' => $query,
1542
    )) . '" target="data" class="' . $success_msg . '">xml</a>-';
1543
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array(
1544
      'query' => $query,
1545
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>,';
1546
    $message .= '<a href="' . url($path . '.json', array(
1547
      'query' => $query,
1548
    )) . '" target="data" class="' . $success_msg . '">json</a>-';
1549
    $message .= '<a href="' . url('cdm_api/proxy/' . urlencode(url($path . '.json', array(
1550
      'query' => $query,
1551
    )))) . '" target="data" class="' . $success_msg . '">proxied</a>';
1552
  }
1553
  else {
1554
    $message .= '<a href="' . url($path, array(
1555
      'query' => $query,
1556
    )) . '" target="data" class="' . $success_msg . '">open</a>';
1557
  }
1558
  $message .= '] ';
1559
  drupal_set_message(($message), 'debug');
1560
}
1561

    
1562
/**
1563
 * @todo Please document this function.
1564
 * @see http://drupal.org/node/1354
1565
 */
1566
function cdm_load_obj($datastr) {
1567
  $obj = json_decode($datastr);
1568

    
1569
  if (!(is_object($obj) || is_array($obj))) {
1570
    ob_start();
1571
    $obj_dump = ob_get_contents();
1572
    ob_clean();
1573
    return FALSE;
1574
  }
1575

    
1576
  return $obj;
1577
}
1578

    
1579
/**
1580
 * Do a http request to a CDM RESTful web service.
1581
 *
1582
 * @param string $uri
1583
 *   The webservice url.
1584
 * @param string $method
1585
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1586
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1587
 * @param array $parameters
1588
 *   Parameters to use in the request.
1589
 * @param array $header
1590
 *   The header to include in the request.
1591
 *
1592
 * @return object
1593
 *   The object as returned by drupal_http_request():
1594
 *   An object that can have one or more of the following components:
1595
 *   - request: A string containing the request body that was sent.
1596
 *   - code: An integer containing the response status code, or the error code
1597
 *     if an error occurred.
1598
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1599
 *   - status_message: The status message from the response, if a response was
1600
 *     received.
1601
 *   - redirect_code: If redirected, an integer containing the initial response
1602
 *     status code.
1603
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1604
 *     target.
1605
 *   - error: If an error occurred, the error message. Otherwise not set.
1606
 *   - headers: An array containing the response headers as name/value pairs.
1607
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1608
 *     easy access the array keys are returned in lower case.
1609
 *   - data: A string containing the response body that was received.
1610
 */
1611
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array(), $options = NULL) {
1612
  static $acceptLanguage = NULL;
1613

    
1614
  if (!$acceptLanguage) {
1615
    if (function_exists('apache_request_headers')) {
1616
      $headers = apache_request_headers();
1617
      if (isset($headers['Accept-Language'])) {
1618
        $acceptLanguage = $headers['Accept-Language'];
1619
      }
1620
    }
1621
    if (!$acceptLanguage) {
1622
      // DEFAULT TODO make configurable.
1623
      $acceptLanguage = "en";
1624
    }
1625
  }
1626

    
1627
  if ($method != "GET" && $method != "POST") {
1628
    $method = "GET";
1629
  }
1630

    
1631
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1632
    $header['Accept'] = 'application/json';
1633
    $header['Accept-Language'] = $acceptLanguage;
1634
    $header['Accept-Charset'] = 'UTF-8';
1635
  }
1636

    
1637
  return drupal_http_request($uri, array(
1638
      'headers' => $header,
1639
      'method' => $method,
1640
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1641
      )
1642
   );
1643
}
1644

    
1645
/**
1646
 * @todo Please document this function.
1647
 * @see http://drupal.org/node/1354
1648
 */
1649
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1650
  $out = '';
1651

    
1652
  foreach ($rootNode->children as $featureNode) {
1653
    $out .= ($out ? $separator : '');
1654
    $out .= $featureNode->feature->representation_L10n;
1655
    if (is_array($featureNode->children)) {
1656
      $childlabels = '';
1657
      foreach ($featureNode->children as $childNode) {
1658
        $childlabels .= ($childlabels ? $separator : '');
1659
      }
1660
      $childlabels .= _featureTree_elements_toString($childNode);
1661
    }
1662
    if ($childlabels) {
1663
      $out .= '[' . $childlabels . ' ]';
1664
    }
1665
  }
1666
  return $out;
1667
}
1668

    
1669
/**
1670
 * Create a one-dimensional form options array.
1671
 *
1672
 * Creates an array of all features in the feature tree of feature nodes,
1673
 * the node labels are indented by $node_char and $childIndent depending on the
1674
 * hierachy level.
1675
 *
1676
 * @param - $rootNode
1677
 * @param - $node_char
1678
 * @param - $childIndentStr
1679
 * @param - $childIndent
1680
 *   ONLY USED INTERNALLY!
1681
 *
1682
 * @return array
1683
 *   A one dimensional Drupal form options array.
1684
 */
1685
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1686
  $options = array();
1687
  foreach ($rootNode->children as $featureNode) {
1688
    $indent_prefix = '';
1689
    if ($childIndent) {
1690
      $indent_prefix = $childIndent . $node_char . " ";
1691
    }
1692
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1693
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1694
      // Foreach ($featureNode->children as $childNode){
1695
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1696
      $options = array_merge_recursive($options, $childList);
1697
      // }
1698
    }
1699
  }
1700
  return $options;
1701
}
1702

    
1703
/**
1704
 * Returns an array with all available FeatureTrees and the representations of the selected
1705
 * FeatureTree as a detail view.
1706
 *
1707
 * @param boolean $add_default_feature_free
1708
 * @return array
1709
 *  associative array with following keys:
1710
 *  -options: Returns an array with all available Feature Trees
1711
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1712
 *
1713
 */
1714
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1715

    
1716
  $options = array();
1717
  $tree_representations = array();
1718
  $feature_trees = array();
1719

    
1720
  // Set tree that contains all features.
1721
  if ($add_default_feature_free) {
1722
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1723
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1724
  }
1725

    
1726
  // Get feature trees from database.
1727
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1728
  if (is_array($persited_trees)) {
1729
    $feature_trees = array_merge($feature_trees, $persited_trees);
1730
  }
1731

    
1732
  foreach ($feature_trees as $featureTree) {
1733

    
1734
    // Do not add the DEFAULT_FEATURETREE again,
1735
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1736
      $options[$featureTree->uuid] = $featureTree->titleCache;
1737
    }
1738

    
1739
    // Render the hierarchic tree structure
1740
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1741

    
1742
      // Render the hierarchic tree structure.
1743
      $treeDetails = '<div class="featuretree_structure">'
1744
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1745
        . '</div>';
1746

    
1747
      $form = array();
1748
      $form['featureTree-' .  $featureTree->uuid] = array(
1749
        '#type' => 'fieldset',
1750
        '#title' => 'Show details',
1751
        '#attributes' => array('class' => array('collapsible collapsed')),
1752
        // '#collapsible' => TRUE,
1753
        // '#collapsed' => TRUE,
1754
      );
1755
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1756
        '#markup' => $treeDetails,
1757
      );
1758

    
1759
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1760
    }
1761

    
1762
  } // END loop over feature trees
1763

    
1764
  // return $options;
1765
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1766
}
1767

    
1768
/**
1769
 * Provides the list of availbale classifications in form of an options array.
1770
 *
1771
 * The options array is suitable for drupal form API elements that allow multiple choices.
1772
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1773
 *
1774
 * The classifications are ordered alphabetically whereas the classification
1775
 * chosen as default will always appear on top of the array, followed by a
1776
 * blank line below.
1777
 *
1778
 * @param bool $add_none_option
1779
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1780
 *
1781
 * @return array
1782
 *   classifications in an array as options for a form element that allows multiple choices.
1783
 */
1784
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1785

    
1786
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1787

    
1788
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1789
  $default_classification_label = '';
1790

    
1791
  // add all classifications
1792
  $taxonomic_tree_options = array();
1793
  if ($add_none_option) {
1794
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1795
  }
1796
  if ($taxonTrees) {
1797
    foreach ($taxonTrees as $tree) {
1798
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1799
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1800
      } else {
1801
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1802
        if (count($taxonTrees) > 1) {
1803
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1804
        }
1805
        $default_classification_label = $tree->titleCache;
1806
      }
1807
    }
1808
  }
1809
  // oder alphabetically the space
1810
  asort($taxonomic_tree_options);
1811

    
1812
  // now set the labels
1813
  //   for none
1814
  if ($add_none_option) {
1815
    $taxonomic_tree_options['NONE'] = t('-- None --');
1816
  }
1817

    
1818
  //   for default_classification
1819
  if (is_uuid($default_classification_uuid)) {
1820
    $taxonomic_tree_options[$default_classification_uuid] =
1821
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1822
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1823
  }
1824

    
1825
  return $taxonomic_tree_options;
1826
}
1827

    
1828
/**
1829
 * @todo Please document this function.
1830
 * @see http://drupal.org/node/1354
1831
 */
1832
function cdm_api_secref_cache_prefetch(&$secUuids) {
1833
  // Comment @WA: global variables should start with a single underscore
1834
  // followed by the module and another underscore.
1835
  global $_cdm_api_secref_cache;
1836
  if (!is_array($_cdm_api_secref_cache)) {
1837
    $_cdm_api_secref_cache = array();
1838
  }
1839
  $uniqueUuids = array_unique($secUuids);
1840
  $i = 0;
1841
  $param = '';
1842
  while ($i++ < count($uniqueUuids)) {
1843
    $param .= $secUuids[$i] . ',';
1844
    if (strlen($param) + 37 > 2000) {
1845
      _cdm_api_secref_cache_add($param);
1846
      $param = '';
1847
    }
1848
  }
1849
  if ($param) {
1850
    _cdm_api_secref_cache_add($param);
1851
  }
1852
}
1853

    
1854
/**
1855
 * @todo Please document this function.
1856
 * @see http://drupal.org/node/1354
1857
 */
1858
function cdm_api_secref_cache_get($secUuid) {
1859
  global $_cdm_api_secref_cache;
1860
  if (!is_array($_cdm_api_secref_cache)) {
1861
    $_cdm_api_secref_cache = array();
1862
  }
1863
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1864
    _cdm_api_secref_cache_add($secUuid);
1865
  }
1866
  return $_cdm_api_secref_cache[$secUuid];
1867
}
1868

    
1869
/**
1870
 * @todo Please document this function.
1871
 * @see http://drupal.org/node/1354
1872
 */
1873
function cdm_api_secref_cache_clear() {
1874
  global $_cdm_api_secref_cache;
1875
  $_cdm_api_secref_cache = array();
1876
}
1877

    
1878
/**
1879
 * Validates if the given string is a uuid.
1880
 *
1881
 * @param string $str
1882
 *   The string to validate.
1883
 *
1884
 * return bool
1885
 *   TRUE if the string is a UUID.
1886
 */
1887
function is_uuid($str) {
1888
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1889
}
1890

    
1891
/**
1892
 * Checks if the given $object is a valid cdm entity.
1893
 *
1894
 * An object is considered a cdm entity if it has a string field $object->class
1895
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1896
 *
1897
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1898
 *
1899
 * @param mixed $object
1900
 *   The object to validate
1901
 *
1902
 * @return bool
1903
 *   True if the object is a cdm entity.
1904
 */
1905
function is_cdm_entity($object) {
1906
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1907
}
1908

    
1909
/**
1910
 * @todo Please document this function.
1911
 * @see http://drupal.org/node/1354
1912
 */
1913
function _cdm_api_secref_cache_add($secUuidsStr) {
1914
  global $_cdm_api_secref_cache;
1915
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1916
  // Batch fetching not jet reimplemented thus:
1917
  /*
1918
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1919
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1920
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1921
  */
1922
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1923
}
1924

    
1925
/**
1926
 * Checks if the given uri starts with a cdm webservice url.
1927
 *
1928
 * Checks if the uri starts with the cdm webservice url stored in the
1929
 * Drupal variable 'cdm_webservice_url'.
1930
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1931
 *
1932
 * @param string $uri
1933
 *   The URI to test.
1934
 *
1935
 * @return bool
1936
 *   True if the uri starts with a cdm webservice url.
1937
 */
1938
function _is_cdm_ws_uri($uri) {
1939
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1940
}
1941

    
1942
/**
1943
 * @todo Please document this function.
1944
 * @see http://drupal.org/node/1354
1945
 */
1946
function queryString($elements) {
1947
  $query = '';
1948
  foreach ($elements as $key => $value) {
1949
    if (is_array($value)) {
1950
      foreach ($value as $v) {
1951
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1952
      }
1953
    }
1954
    else {
1955
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1956
    }
1957
  }
1958
  return $query;
1959
}
1960

    
1961
/**
1962
 * Implementation of the magic method __clone to allow deep cloning of objects
1963
 * and arrays.
1964
 */
1965
function __clone() {
1966
  foreach ($this as $name => $value) {
1967
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1968
      $this->$name = clone($this->$name);
1969
    }
1970
  }
1971
}
1972

    
1973
/**
1974
 * Make a 'deep copy' of an array.
1975
 *
1976
 * Make a complete deep copy of an array replacing
1977
 * references with deep copies until a certain depth is reached
1978
 * ($maxdepth) whereupon references are copied as-is...
1979
 *
1980
 * @see http://us3.php.net/manual/en/ref.array.php
1981
 *
1982
 * @param array $array
1983
 * @param array $copy
1984
 * @param int $maxdepth
1985
 * @param int $depth
1986
 *
1987
 * @return void
1988
 */
1989
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
1990
  if ($depth > $maxdepth) {
1991
    $copy = $array;
1992
    return;
1993
  }
1994
  if (!is_array($copy)) {
1995
    $copy = array();
1996
  }
1997
  foreach ($array as $k => &$v) {
1998
    if (is_array($v)) {
1999
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2000
    }
2001
    else {
2002
      $copy[$k] = $v;
2003
    }
2004
  }
2005
}
2006

    
2007
/**
2008
 * Implementation of theme_status_messages($display = NULL).
2009
 *
2010
 * @see includes/theme.inc
2011
 *
2012
 * @return void
2013
 */
2014
function _add_status_message_toggler() {
2015
  static $isAdded = FALSE;
2016
  if (!$isAdded) {
2017
    drupal_add_js(
2018
    'jQuery(document).ready(function($){
2019
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
2020
       $(\'.messages_toggler\').click(function(){
2021
         $(this).next().slideToggle(\'fast\');
2022
         return false;
2023
       }).next().hide();
2024
     });', array('type' => 'inline'));
2025

    
2026
    $isAdded = TRUE;
2027
  }
2028
}
2029

    
2030
/**
2031
 * @todo Please document this function.
2032
 * @see http://drupal.org/node/1354
2033
 */
2034
function _no_classfication_uuid_message() {
2035
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2036
    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.');
2037
  }
2038
  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.');
2039
}
2040

    
2041
/**
2042
 * Implementation of hook flush_caches
2043
 *
2044
 * Add custom cache tables to the list of cache tables that
2045
 * will be cleared by the Clear button on the Performance page or whenever
2046
 * drupal_flush_all_caches is invoked.
2047
 *
2048
 * @author W.Addink <waddink@eti.uva.nl>
2049
 *
2050
 * @return array
2051
 *   An array with custom cache tables to include.
2052
 */
2053
function cdm_api_flush_caches() {
2054
  return array('cache_cdm_ws');
2055
}
(4-4/9)