Project

General

Profile

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

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

    
30

    
31
/**
32
 * Tiemout used to override the default of 30 seconds
33
 * in @see drupal_http_request()
34
 *
35
 * @var CDM_HTTP_REQUEST_TIMEOUT: A float representing the maximum number of seconds the function
36
 *     call may take
37
 */
38
define('CDM_HTTP_REQUEST_TIMEOUT', 90.0);
39

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

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

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

    
63
  return $items;
64
}
65

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
330
      if ($representation->mimeType == $mimeType) {
331
        // Preferred mimetype found -> erase all remaining mimetypes
332
        // to end loop.
333
        $mimeTypes = array();
334
        $dwa = 0;
335
        $dw = 0;
336
        // Look for part with the best matching size.
337
        foreach ($representation->parts as $part) {
338
          if (isset($part->width) && isset($part->height)) {
339
            $dw = $part->width * $part->height - $height * $width;
340
          }
341
          if ($dw < 0) {
342
            $dw *= -1;
343
          }
344
          $dwa += $dw;
345
        }
346
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
347
        $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

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

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

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

    
718
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
719
      $theme_result = NULL;
720

    
721
      if (function_exists('compose_' . $hook)){
722
        // call compose hook
723

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

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

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

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

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

    
789
  // Prevent from malicous tags.
790
  $val = strip_tags($val);
791

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

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

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

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

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

    
843
    case 'Media':
844
      $ws_base_uri = CDM_WS_MEDIA;
845
      break;
846

    
847
    case 'Reference':
848
      $ws_base_uri = CDM_WS_REFERENCE;
849
      break;
850

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

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

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

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

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

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

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

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

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

    
968
    $response = NULL;
969

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

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

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

    
996
  return $response;
997
}
998

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

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

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

    
1042
  return $response;
1043
}
1044

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

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

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

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

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

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

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

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

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

    
1161
  $mergedTrees = array();
1162

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

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

    
1184
  return $mergedTrees;
1185
}
1186

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

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

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

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

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

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

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

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

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

    
1315
  }
1316

    
1317
  return $featureNodes;
1318
}
1319

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

    
1356
  static $cacheL1 = array();
1357

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

    
1363
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1364
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1365

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

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

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

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

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

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

    
1414
    $time_parse_start = microtime(TRUE);
1415

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

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

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

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

    
1463
  $cumulated_time_get += $time_get;
1464
  $cumulated_time_parse += $time_parse;
1465

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

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

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

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

    
1528
  return $obj;
1529
}
1530

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

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

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

    
1567
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1568
    $header['Accept'] = 'application/json';
1569
    $header['Accept-Language'] = $acceptLanguage;
1570
    $header['Accept-Charset'] = 'UTF-8';
1571
  }
1572

    
1573
  $response = drupal_http_request($uri, array('headers' => $header, 'method' => $method, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
1574
  if (isset($response->data)) {
1575
      return $response->data;
1576
  }
1577
}
1578

    
1579
/**
1580
 * @todo Please document this function.
1581
 * @see http://drupal.org/node/1354
1582
 */
1583
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1584
  $out = '';
1585

    
1586
  foreach ($rootNode->children as $featureNode) {
1587
    $out .= ($out ? $separator : '');
1588
    $out .= $featureNode->feature->representation_L10n;
1589
    if (is_array($featureNode->children)) {
1590
      $childlabels = '';
1591
      foreach ($featureNode->children as $childNode) {
1592
        $childlabels .= ($childlabels ? $separator : '');
1593
      }
1594
      $childlabels .= _featureTree_elements_toString($childNode);
1595
    }
1596
    if ($childlabels) {
1597
      $out .= '[' . $childlabels . ' ]';
1598
    }
1599
  }
1600
  return $out;
1601
}
1602

    
1603
/**
1604
 * Create a one-dimensional form options array.
1605
 *
1606
 * Creates an array of all features in the feature tree of feature nodes,
1607
 * the node labels are indented by $node_char and $childIndent depending on the
1608
 * hierachy level.
1609
 *
1610
 * @param - $rootNode
1611
 * @param - $node_char
1612
 * @param - $childIndentStr
1613
 * @param - $childIndent
1614
 *   ONLY USED INTERNALLY!
1615
 *
1616
 * @return array
1617
 *   A one dimensional Drupal form options array.
1618
 */
1619
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1620
  $options = array();
1621
  foreach ($rootNode->children as $featureNode) {
1622
    $indent_prefix = '';
1623
    if ($childIndent) {
1624
      $indent_prefix = $childIndent . $node_char . " ";
1625
    }
1626
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1627
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1628
      // Foreach ($featureNode->children as $childNode){
1629
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1630
      $options = array_merge_recursive($options, $childList);
1631
      // }
1632
    }
1633
  }
1634
  return $options;
1635
}
1636

    
1637
/**
1638
 * Returns an array with all available FeatureTrees and the representations of the selected
1639
 * FeatureTree as a detail view.
1640
 *
1641
 * @param boolean $add_default_feature_free
1642
 * @return array
1643
 *  associative array with following keys:
1644
 *  -options: Returns an array with all available Feature Trees
1645
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1646
 *
1647
 */
1648
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1649

    
1650
  $options = array();
1651
  $tree_representations = array();
1652
  $feature_trees = array();
1653

    
1654
  // Set tree that contains all features.
1655
  if ($add_default_feature_free) {
1656
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1657
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1658
  }
1659

    
1660
  // Get feature trees from database.
1661
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1662
  if (is_array($persited_trees)) {
1663
    $feature_trees = array_merge($feature_trees, $persited_trees);
1664
  }
1665

    
1666
  foreach ($feature_trees as $featureTree) {
1667

    
1668
    // Do not add the DEFAULT_FEATURETREE again,
1669
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1670
      $options[$featureTree->uuid] = $featureTree->titleCache;
1671
    }
1672

    
1673
    // Render the hierarchic tree structure
1674
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1675

    
1676
      // Render the hierarchic tree structure.
1677
      $treeDetails = '<div class="featuretree_structure">'
1678
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1679
        . '</div>';
1680

    
1681
      $form = array();
1682
      $form['featureTree-' .  $featureTree->uuid] = array(
1683
        '#type' => 'fieldset',
1684
        '#title' => 'Show details',
1685
        '#attributes' => array('class' => array('collapsible collapsed')),
1686
        // '#collapsible' => TRUE,
1687
        // '#collapsed' => TRUE,
1688
      );
1689
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1690
        '#markup' => $treeDetails,
1691
      );
1692

    
1693
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1694
    }
1695

    
1696
  } // END loop over feature trees
1697

    
1698
  // return $options;
1699
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1700
}
1701

    
1702
/**
1703
 * Provides the list of availbale classifications in form of an options array.
1704
 *
1705
 * The options array is suitable for drupal form API elements that allow multiple choices.
1706
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1707
 *
1708
 * The classifications are ordered alphabetically whereas the classification
1709
 * chosen as default will always appear on top of the array, followed by a
1710
 * blank line below.
1711
 *
1712
 * @param bool $add_none_option
1713
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1714
 *
1715
 * @return array
1716
 *   classifications in an array as options for a form element that allows multiple choices.
1717
 */
1718
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1719

    
1720
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1721

    
1722
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1723
  $default_classification_label = '';
1724

    
1725
  // add all classifications
1726
  $taxonomic_tree_options = array();
1727
  if ($add_none_option) {
1728
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1729
  }
1730
  if ($taxonTrees) {
1731
    foreach ($taxonTrees as $tree) {
1732
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1733
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1734
      } else {
1735
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1736
        if (count($taxonTrees) > 1) {
1737
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1738
        }
1739
        $default_classification_label = $tree->titleCache;
1740
      }
1741
    }
1742
  }
1743
  // oder alphabetically the space
1744
  asort($taxonomic_tree_options);
1745

    
1746
  // now set the labels
1747
  //   for none
1748
  if ($add_none_option) {
1749
    $taxonomic_tree_options['NONE'] = t('-- None --');
1750
  }
1751

    
1752
  //   for default_classification
1753
  if (is_uuid($default_classification_uuid)) {
1754
    $taxonomic_tree_options[$default_classification_uuid] =
1755
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1756
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1757
  }
1758

    
1759
  return $taxonomic_tree_options;
1760
}
1761

    
1762
/**
1763
 * @todo Please document this function.
1764
 * @see http://drupal.org/node/1354
1765
 */
1766
function cdm_api_secref_cache_prefetch(&$secUuids) {
1767
  // Comment @WA: global variables should start with a single underscore
1768
  // followed by the module and another underscore.
1769
  global $_cdm_api_secref_cache;
1770
  if (!is_array($_cdm_api_secref_cache)) {
1771
    $_cdm_api_secref_cache = array();
1772
  }
1773
  $uniqueUuids = array_unique($secUuids);
1774
  $i = 0;
1775
  $param = '';
1776
  while ($i++ < count($uniqueUuids)) {
1777
    $param .= $secUuids[$i] . ',';
1778
    if (strlen($param) + 37 > 2000) {
1779
      _cdm_api_secref_cache_add($param);
1780
      $param = '';
1781
    }
1782
  }
1783
  if ($param) {
1784
    _cdm_api_secref_cache_add($param);
1785
  }
1786
}
1787

    
1788
/**
1789
 * @todo Please document this function.
1790
 * @see http://drupal.org/node/1354
1791
 */
1792
function cdm_api_secref_cache_get($secUuid) {
1793
  global $_cdm_api_secref_cache;
1794
  if (!is_array($_cdm_api_secref_cache)) {
1795
    $_cdm_api_secref_cache = array();
1796
  }
1797
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1798
    _cdm_api_secref_cache_add($secUuid);
1799
  }
1800
  return $_cdm_api_secref_cache[$secUuid];
1801
}
1802

    
1803
/**
1804
 * @todo Please document this function.
1805
 * @see http://drupal.org/node/1354
1806
 */
1807
function cdm_api_secref_cache_clear() {
1808
  global $_cdm_api_secref_cache;
1809
  $_cdm_api_secref_cache = array();
1810
}
1811

    
1812
/**
1813
 * Validates if the given string is a uuid.
1814
 *
1815
 * @param string $str
1816
 *   The string to validate.
1817
 *
1818
 * return bool
1819
 *   TRUE if the string is a UUID.
1820
 */
1821
function is_uuid($str) {
1822
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1823
}
1824

    
1825
/**
1826
 * Checks if the given $object is a valid cdm entity.
1827
 *
1828
 * An object is considered a cdm entity if it has a string field $object->class
1829
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1830
 *
1831
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1832
 *
1833
 * @param mixed $object
1834
 *   The object to validate
1835
 *
1836
 * @return bool
1837
 *   True if the object is a cdm entity.
1838
 */
1839
function is_cdm_entity($object) {
1840
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
1841
}
1842

    
1843
/**
1844
 * @todo Please document this function.
1845
 * @see http://drupal.org/node/1354
1846
 */
1847
function _cdm_api_secref_cache_add($secUuidsStr) {
1848
  global $_cdm_api_secref_cache;
1849
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
1850
  // Batch fetching not jet reimplemented thus:
1851
  /*
1852
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
1853
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
1854
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
1855
  */
1856
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
1857
}
1858

    
1859
/**
1860
 * Checks if the given uri starts with a cdm webservice url.
1861
 *
1862
 * Checks if the uri starts with the cdm webservice url stored in the
1863
 * Drupal variable 'cdm_webservice_url'.
1864
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
1865
 *
1866
 * @param string $uri
1867
 *   The URI to test.
1868
 *
1869
 * @return bool
1870
 *   True if the uri starts with a cdm webservice url.
1871
 */
1872
function _is_cdm_ws_uri($uri) {
1873
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
1874
}
1875

    
1876
/**
1877
 * @todo Please document this function.
1878
 * @see http://drupal.org/node/1354
1879
 */
1880
function queryString($elements) {
1881
  $query = '';
1882
  foreach ($elements as $key => $value) {
1883
    if (is_array($value)) {
1884
      foreach ($value as $v) {
1885
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
1886
      }
1887
    }
1888
    else {
1889
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
1890
    }
1891
  }
1892
  return $query;
1893
}
1894

    
1895
/**
1896
 * Implementation of the magic method __clone to allow deep cloning of objects
1897
 * and arrays.
1898
 */
1899
function __clone() {
1900
  foreach ($this as $name => $value) {
1901
    if (gettype($value) == 'object' || gettype($value) == 'array') {
1902
      $this->$name = clone($this->$name);
1903
    }
1904
  }
1905
}
1906

    
1907
/**
1908
 * Make a 'deep copy' of an array.
1909
 *
1910
 * Make a complete deep copy of an array replacing
1911
 * references with deep copies until a certain depth is reached
1912
 * ($maxdepth) whereupon references are copied as-is...
1913
 *
1914
 * @see http://us3.php.net/manual/en/ref.array.php
1915
 *
1916
 * @param array $array
1917
 * @param array $copy
1918
 * @param int $maxdepth
1919
 * @param int $depth
1920
 *
1921
 * @return void
1922
 */
1923
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
1924
  if ($depth > $maxdepth) {
1925
    $copy = $array;
1926
    return;
1927
  }
1928
  if (!is_array($copy)) {
1929
    $copy = array();
1930
  }
1931
  foreach ($array as $k => &$v) {
1932
    if (is_array($v)) {
1933
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
1934
    }
1935
    else {
1936
      $copy[$k] = $v;
1937
    }
1938
  }
1939
}
1940

    
1941
/**
1942
 * Implementation of theme_status_messages($display = NULL).
1943
 *
1944
 * @see includes/theme.inc
1945
 *
1946
 * @return void
1947
 */
1948
function _add_status_message_toggler() {
1949
  static $isAdded = FALSE;
1950
  if (!$isAdded) {
1951
    drupal_add_js(
1952
    'jQuery(document).ready(function($){
1953
       $(\'.messages.debug\').before( \'<h6 class="messages_toggler debug">Debug Messages (click to toggle)</h6>\' );
1954
       $(\'.messages_toggler\').click(function(){
1955
         $(this).next().slideToggle(\'fast\');
1956
         return false;
1957
       }).next().hide();
1958
     });', array('type' => 'inline'));
1959

    
1960
    $isAdded = TRUE;
1961
  }
1962
}
1963

    
1964
/**
1965
 * @todo Please document this function.
1966
 * @see http://drupal.org/node/1354
1967
 */
1968
function _no_classfication_uuid_message() {
1969
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
1970
    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.');
1971
  }
1972
  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.');
1973
}
1974

    
1975
/**
1976
 * Implementation of hook flush_caches
1977
 *
1978
 * Add custom cache tables to the list of cache tables that
1979
 * will be cleared by the Clear button on the Performance page or whenever
1980
 * drupal_flush_all_caches is invoked.
1981
 *
1982
 * @author W.Addink <waddink@eti.uva.nl>
1983
 *
1984
 * @return array
1985
 *   An array with custom cache tables to include.
1986
 */
1987
function cdm_api_flush_caches() {
1988
  return array('cache_cdm_ws');
1989
}
(4-4/9)