Project

General

Profile

Download (63 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_block_info().
68
 */
69
function cdm_api_block_info() {
70

    
71
  $block['cdm_ws_debug'] = array(
72
      "info" => t("CDM web service debug"),
73
      "cache" => DRUPAL_NO_CACHE
74
  );
75
  return $block;
76
}
77

    
78
/**
79
 * Implements hook_block_view().
80
 */
81
function cdm_api_block_view($delta) {
82
  switch ($delta) {
83
    case 'cdm_ws_debug':
84

    
85
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
86

    
87
    $field_map = array(
88
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
89
        'time' => t('Time'),
90
        'fetch_seconds' => t('Fetching [s]'),
91
        'parse_seconds' => t('Parsing [s]'),
92
        'size_kb' => t('Size [kb]'),
93
        'status' => t('Status'),
94
        'data_links' =>  t('Links'),
95
    );
96

    
97

    
98
    if (!isset($_SESSION['cdm']['ws_debug'])) {
99
      $_SESSION['cdm']['ws_debug'] = array();
100
    }
101

    
102
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
103
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
104
    $rows = array();
105

    
106
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
107

    
108
      $data = unserialize($data);
109

    
110
      // stip of webservice base url
111
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
112

    
113
      $cells = array();
114
      foreach ($field_map as $field => $label){
115
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
116
      }
117
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
118
    }
119
    // clear session again
120
    $_SESSION['cdm']['ws_debug'] = array();
121

    
122
    _add_js_ws_debug();
123

    
124
    $block['subject'] = ''; // no subject, title in content for having a defined element id
125
    // otherwise it would depend on the theme
126
    $block['content'] =
127
        '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
128
          // cannot use theme_table() since table footer is not jet supported in D7
129
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
130
        . $header
131
        . '<tbody>' . join('', $rows) . '</tbody>'
132
        . $footer
133
        . '</table></div>';
134

    
135
    return $block;
136
  }
137
}
138

    
139
/**
140
 * Implements hook_cron().
141
 *
142
 * Expire outdated cache entries.
143
 */
144
function cdm_api_cron() {
145
  cache_clear_all(NULL, 'cache_cdm_ws');
146
}
147

    
148
/**
149
 * @todo Please document this function.
150
 * @see http://drupal.org/node/1354
151
 */
152
function cdm_api_permission() {
153
  return array(
154
    'administer cdm_api' => array(
155
      'title' => t('administer cdm_api'),
156
      'description' => t("TODO Add a description for 'administer cdm_api'"),
157
    ),
158
  );
159
}
160

    
161
/**
162
 * Converts an array of TaggedText items into corresponding html tags.
163
 *
164
 * Each item is provided with a class attribute which is set to the key of the
165
 * TaggedText item.
166
 *
167
 * @param array $taggedtxt
168
 *   Array with text items to convert.
169
 * @param string $tag
170
 *   Html tag name to convert the items into, default is 'span'.
171
 * @param string $glue
172
 *   The string by which the chained text tokens are concatenated together.
173
 *   Default is a blank character.
174
 *
175
 * @return string
176
 *   A string with HTML.
177
 */
178
function cdm_taggedtext2html(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
179
  $out = '';
180
  $i = 0;
181
  foreach ($taggedtxt as $tt) {
182
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
183
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '') . '<' . $tag . ' class="' . $tt->type . '">' . t($tt->text) . '</' . $tag . '>';
184
    }
185
  }
186
  return $out;
187
}
188

    
189
/**
190
 * Finds the text tagged with $tag_type in an array of taggedText instances.
191
 *
192
 * Comment @WA: this function seems unused.
193
 *
194
 * @param array $taggedtxt
195
 *   Array with text items.
196
 * @param string $tag_type
197
 *   The type of tag for which to find text items in the $taggedtxt array.
198
 *
199
 * @return array
200
 *   An array with the texts mapped by $tag_type.
201
 */
202
function cdm_taggedtext_values(array $taggedtxt, $tag_type) {
203
  $tokens = array();
204
  if (!empty($taggedtxt)) {
205
    foreach ($taggedtxt as $tagtxt) {
206
      if ($tagtxt->type == $tag_type) {
207
        $tokens[] = $tagtxt->text;
208
      }
209
    }
210
  }
211
  return $tokens;
212
}
213

    
214
/**
215
 * Returns the currently classification tree in use.
216
 */
217
function get_taxonomictree_uuid_selected() {
218
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
219
    return $_SESSION['cdm']['taxonomictree_uuid'];
220
  }
221
  else {
222
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
223
  }
224
}
225

    
226
/**
227
 * Lists the classifications a taxon belongs to
228
 *
229
 * @param CDM type Taxon $taxon
230
 *   the taxon
231
 *
232
 * @return array
233
 *   aray of CDM instances of Type Classification
234
 */
235
function get_classifications_for_taxon($taxon) {
236

    
237
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
238
}
239

    
240
/**
241
 * Returns the chosen FeatureTree for the taxon profile.
242
 *
243
 * The FeatureTree profile returned is the one that has been set in the
244
 * dataportal settings (layout->taxon:profile).
245
 * When the chosen FeatureTree is not found in the database,
246
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
247
 *
248
 * @return mixed
249
 *   A cdm FeatureTree object.
250
 */
251
function get_profile_featureTree() {
252
  static $profile_featureTree;
253

    
254
  if($profile_featureTree == NULL) {
255
    $profile_featureTree = cdm_ws_get(
256
      CDM_WS_FEATURETREE,
257
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
258
    );
259
    if (!$profile_featureTree) {
260
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
261
    }
262
  }
263
  return $profile_featureTree;
264
}
265

    
266
/**
267
 * Returns the chosen FeatureTree for SpecimenDescriptions.
268
 *
269
 * The FeatureTree returned is the one that has been set in the
270
 * dataportal settings (layout->taxon:specimen).
271
 * When the chosen FeatureTree is not found in the database,
272
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
273
 *
274
 * @return mixed
275
 *   A cdm FeatureTree object.
276
 */
277
function cdm_get_occurrence_featureTree() {
278
  static $occurrence_featureTree;
279

    
280
  if($occurrence_featureTree == NULL) {
281
    $occurrence_featureTree = cdm_ws_get(
282
      CDM_WS_FEATURETREE,
283
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
284
    );
285
    if (!$occurrence_featureTree) {
286
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
287
    }
288
  }
289
  return $occurrence_featureTree;
290
}
291

    
292
/**
293
 * Returns the FeatureTree for structured descriptions
294
 *
295
 * The FeatureTree returned is the one that has been set in the
296
 * dataportal settings (layout->taxon:profile).
297
 * When the chosen FeatureTree is not found in the database,
298
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
299
 *
300
 * @return mixed
301
 *   A cdm FeatureTree object.
302
 */
303
function get_structured_description_featureTree() {
304
  static $structured_description_featureTree;
305

    
306
  if($structured_description_featureTree == NULL) {
307
    $structured_description_featureTree = cdm_ws_get(
308
        CDM_WS_FEATURETREE,
309
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
310
    );
311
    if (!$structured_description_featureTree) {
312
      $structured_description_featureTree = cdm_ws_get(
313
          CDM_WS_FEATURETREE,
314
          UUID_DEFAULT_FEATURETREE
315
      );
316
    }
317
  }
318
  return $structured_description_featureTree;
319
}
320

    
321
/**
322
 * @todo Please document this function.
323
 * @see http://drupal.org/node/1354
324
 */
325
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
326
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
327
}
328

    
329
/**
330
 * @todo Please document this function.
331
 * @see http://drupal.org/node/1354
332
 */
333
function reset_taxonomictree_uuid($taxonomictree_uuid) {
334
  unset($_SESSION['cdm']['taxonomictree_uuid']);
335
}
336

    
337
/**
338
 * @todo Please document this function.
339
 * @see http://drupal.org/node/1354
340
 */
341
function set_last_taxon_page_tab($taxonPageTab) {
342
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
343
}
344

    
345
/**
346
 * @todo Please document this function.
347
 * @see http://drupal.org/node/1354
348
 */
349
function get_last_taxon_page_tab() {
350
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
351
    return $_SESSION['cdm']['taxon_page_tab'];
352
  }
353
  else {
354
    return FALSE;
355
  }
356
}
357

    
358
/**
359
 * @todo Improve the documentation of this function.
360
 *
361
 * media Array [4]
362
 * representations Array [3]
363
 * mimeType image/jpeg
364
 * representationParts Array [1]
365
 * duration 0
366
 * heigth 0
367
 * size 0
368
 * uri
369
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
370
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
371
 * width 0
372
 * suffix jpg
373
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
374
 * title
375
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
376
 *
377
 * @param object $media
378
 * @param array $mimeTypes
379
 * @param int $width
380
 * @param int $height
381
 *
382
 * @return array
383
 *   An array with preferred media representations or else an empty array.
384
 */
385
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
386
  $prefRepr = array();
387
  if (!isset($media->representations[0])) {
388
    return $prefRepr;
389
  }
390

    
391
  while (count($mimeTypes) > 0) {
392
    // getRepresentationByMimeType
393
    $mimeType = array_shift($mimeTypes);
394

    
395
    foreach ($media->representations as &$representation) {
396
      // If the mimetype is not known, try inferring it.
397
      if (!$representation->mimeType) {
398
        if (isset($representation->parts[0])) {
399
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
400
        }
401
      }
402

    
403
      if ($representation->mimeType == $mimeType) {
404
        // Preferred mimetype found -> erase all remaining mimetypes
405
        // to end loop.
406
        $mimeTypes = array();
407
        $dwa = 0;
408
        $dw = 0;
409
        // Look for part with the best matching size.
410
        foreach ($representation->parts as $part) {
411
          if (isset($part->width) && isset($part->height)) {
412
            $dw = $part->width * $part->height - $height * $width;
413
          }
414
          if ($dw < 0) {
415
            $dw *= -1;
416
          }
417
          $dwa += $dw;
418
        }
419
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
420
        $prefRepr[$dwa . '_'] = $representation;
421
      }
422
    }
423
  }
424
  // Sort the array.
425
  krsort($prefRepr);
426
  return $prefRepr;
427
}
428

    
429
/**
430
 * Infers the mime type of a file using the filename extension.
431
 *
432
 * The filename extension is used to infer the mime type.
433
 *
434
 * @param string $filepath
435
 *   The path to the respective file.
436
 *
437
 * @return string
438
 *   The mimetype for the file or FALSE if the according mime type could
439
 *   not be found.
440
 */
441
function infer_mime_type($filepath) {
442
  static $mimemap = NULL;
443
  if (!$mimemap) {
444
    $mimemap = array(
445
      'jpg' => 'image/jpeg',
446
      'jpeg' => 'image/jpeg',
447
      'png' => 'image/png',
448
      'gif' => 'image/gif',
449
      'giff' => 'image/gif',
450
      'tif' => 'image/tif',
451
      'tiff' => 'image/tif',
452
      'pdf' => 'application/pdf',
453
      'html' => 'text/html',
454
      'htm' => 'text/html',
455
    );
456
  }
457
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
458
  if (isset($mimemap[$extension])) {
459
    return $mimemap[$extension];
460
  }
461
  else {
462
    // FIXME remove this hack just return FALSE;
463
    return 'text/html';
464
  }
465
}
466

    
467
/**
468
 * Converts an ISO 8601 org.joda.time.Partial to a year.
469
 *
470
 * The function expects an ISO 8601 time representation of a
471
 * org.joda.time.Partial of the form yyyy-MM-dd.
472
 *
473
 * @param string $partial
474
 *   ISO 8601 time representation of a org.joda.time.Partial.
475
 *
476
 * @return string
477
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
478
 */
479
function partialToYear($partial) {
480
  if (is_string($partial)) {
481
    $year = substr($partial, 0, 4);
482
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
483
      return $year;
484
    }
485
  }
486
  return;
487
}
488

    
489
/**
490
 * Converts an ISO 8601 org.joda.time.Partial to a month.
491
 *
492
 * This function expects an ISO 8601 time representation of a
493
 * org.joda.time.Partial of the form yyyy-MM-dd.
494
 * In case the month is unknown (= ???) NULL is returned.
495
 *
496
 * @param string $partial
497
 *   ISO 8601 time representation of a org.joda.time.Partial.
498
 *
499
 * @return string
500
 *   A month.
501
 */
502
function partialToMonth($partial) {
503
  if (is_string($partial)) {
504
    $month = substr($partial, 5, 2);
505
    if (preg_match("/[0-9][0-9]/", $month)) {
506
      return $month;
507
    }
508
  }
509
  return;
510
}
511

    
512
/**
513
 * Converts an ISO 8601 org.joda.time.Partial to a day.
514
 *
515
 * This function expects an ISO 8601 time representation of a
516
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
517
 * In case the day is unknown (= ???) NULL is returned.
518
 *
519
 * @param string $partial
520
 *   ISO 8601 time representation of a org.joda.time.Partial.
521
 *
522
 * @return string
523
 *   A day.
524
 */
525
function partialToDay($partial) {
526
  if (is_string($partial)) {
527
    $day = substr($partial, 8, 2);
528
    if (preg_match("/[0-9][0-9]/", $day)) {
529
      return $day;
530
    }
531
  }
532
  return;
533
}
534

    
535
/**
536
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
537
 *
538
 * This function expects an ISO 8601 time representations of a
539
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
540
 * four digit year, month and day with dashes:
541
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
542
 *
543
 * The partial may contain question marks eg: "1973-??-??",
544
 * these are turned in to '00' or are stripped depending of the $stripZeros
545
 * parameter.
546
 *
547
 * @param string $partial
548
 *   org.joda.time.Partial.
549
 * @param bool $stripZeros
550
 *   If set to TRUE the zero (00) month and days will be hidden:
551
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
552
 *
553
 * @return string
554
 *   YYYY-MM-DD formatted year, month, day.
555
 */
556
function partialToDate($partial, $stripZeros = TRUE) {
557
  $y = partialToYear($partial);
558
  $m = partialToMonth($partial);
559
  $d = partialToDay($partial);
560

    
561
  $y = $y ? $y : '00';
562
  $m = $m ? $m : '00';
563
  $d = $d ? $d : '00';
564

    
565
  $date = '';
566

    
567
  if ($y == '00' && $stripZeros) {
568
    return;
569
  }
570
  else {
571
    $date = $y;
572
  }
573

    
574
  if ($m == '00' && $stripZeros) {
575
    return $date;
576
  }
577
  else {
578
    $date .= "-" . $m;
579
  }
580

    
581
  if ($d == '00' && $stripZeros) {
582
    return $date;
583
  }
584
  else {
585
    $date .= "-" . $d;
586
  }
587
  return $date;
588
}
589

    
590
/**
591
 * Converts a time period to a string.
592
 *
593
 * See also partialToDate($partial, $stripZeros).
594
 *
595
 * @param object $period
596
 *   An JodaTime org.joda.time.Period object.
597
 * @param bool $stripZeros
598
 *   If set to True, the zero (00) month and days will be hidden:
599
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
600
 *
601
 * @return string
602
 *   Returns a date in the form of a string.
603
 */
604
function timePeriodToString($period, $stripZeros = TRUE) {
605
  $dateString = '';
606
  if ($period->start) {
607
    $dateString = partialToDate($period->start, $stripZeros);
608
  }
609
  if ($period->end) {
610
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
611
  }
612
  return $dateString;
613
}
614
/**
615
 * returns the earliest date available in the $period in a normalized
616
 * form suitable for sorting, e.g.:
617
 *
618
 *  - 1956-00-00
619
 *  - 0000-00-00
620
 *  - 1957-03-00
621
 *
622
 * that is either the start date is returned if set otherwise the
623
 * end date
624
 *
625
 * @param  $period
626
 *    An JodaTime org.joda.time.Period object.
627
 * @return string normalized form of the date
628
 *   suitable for sorting
629
 */
630
function timePeriodAsOrderKey($period) {
631
  $dateString = '';
632
  if ($period->start) {
633
    $dateString = partialToDate($period->start, false);
634
  }
635
  if ($period->end) {
636
    $dateString .= partialToDate($period->end, false);
637
  }
638
  return $dateString;
639
}
640

    
641
/**
642
 * Composes a CDM webservice URL with parameters and querystring.
643
 *
644
 * @param string $uri_pattern
645
 *   String with place holders ($0, $1, ..) that should be replaced by the
646
 *   according element of the $pathParameters array.
647
 * @param array $pathParameters
648
 *   An array of path elements, or a single element.
649
 * @param string $query
650
 *   A query string to append to the URL.
651
 *
652
 * @return string
653
 *   A complete URL with parameters to a CDM webservice.
654
 */
655
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
656
  if (empty($pathParameters)) {
657
    $pathParameters = array();
658
  }
659

    
660
  $request_params = '';
661
  $path_params = '';
662

    
663
  // (1)
664
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
665
  // according element of the $pathParameters array.
666
  static $helperArray = array();
667
  if (isset($pathParameters) && !is_array($pathParameters)) {
668
    $helperArray[0] = $pathParameters;
669
    $pathParameters = $helperArray;
670
  }
671

    
672
  $i = 0;
673
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
674
    if (count($pathParameters) <= $i) {
675
      if (module_exists("user") && user_access('administer')) {
676
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
677
      }
678
      break;
679
    }
680
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
681
    ++$i;
682
  }
683

    
684
  // (2)
685
  // Append all remaining element of the $pathParameters array as path
686
  // elements.
687
  if (count($pathParameters) > $i) {
688
    // Strip trailing slashes.
689
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
690
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
691
    }
692
    while (count($pathParameters) > $i) {
693
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
694
      ++$i;
695
    }
696
  }
697

    
698
  // (3)
699
  // Append the query string supplied by $query.
700
  if (isset($query)) {
701
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
702
  }
703

    
704
  $path = $uri_pattern;
705

    
706
  $uri = variable_get('cdm_webservice_url', '') . $path;
707
  return $uri;
708
}
709

    
710
/**
711
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
712
 *     together with a theme name to such a proxy function?
713
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
714
 *     Maybe we want to have two different proxy functions, one with theming and one without?
715
 *
716
 * @param string $uri
717
 *     A URI to a CDM Rest service from which to retrieve an object
718
 * @param string|null $hook
719
 *     (optional) The hook name to which the retrieved object should be passed.
720
 *     Hooks can either be a theme_hook() or compose_hook() implementation
721
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
722
 *     suitable for drupal_render()
723
 *
724
 * @todo Please document this function.
725
 * @see http://drupal.org/node/1354
726
 */
727
function proxy_content($uri, $hook = NULL) {
728
  $args = func_get_args();
729
  $do_gzip = function_exists('gzencode');
730
  $uriEncoded = array_shift($args);
731
  $uri = urldecode($uriEncoded);
732
  $hook = array_shift($args);
733

    
734
  // Find and deserialize arrays.
735
  foreach ($args as &$arg) {
736
    // FIXME use regex to find serialized arrays.
737
    //       or should we accept json instead pf php serializations?
738
    if (strpos($arg, "a:") === 0) {
739
      $arg = unserialize($arg);
740
    }
741
  }
742

    
743
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
744
  if ($request_method == "POST") {
745
    // this is an experimental feature which will allow to
746
    // write data inot the cdm via the RESTfull web service
747
    $parameters = $_POST;
748
    $post_data = array();
749

    
750
    foreach ($parameters as $k => $v) {
751
      $post_data[] = "$k=" . utf8_encode($v);
752
    }
753
    $post_data = implode(',', $post_data);
754

    
755
    // For testing.
756
    // TODO use cdm_http_request(..) instead; ( CDM_HTTP_REQUEST_TIMEOUT is already set in there )
757
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
758
    // print $data;
759
  } else {
760
    // Not a "POST" request
761
    // In all these cases perform a simple get request.
762
    // TODO reconsider caching logic in this function.
763

    
764
    if (empty($hook)) {
765
      // simply return the webservice response
766
      // Print out JSON, the cache cannot be used since it contains objects.
767
      $http_response = cdm_http_request($uri);
768
      if (isset($http_response->headers)) {
769
        foreach ($http_response->headers as $hname => $hvalue) {
770
          drupal_add_http_header($hname, $hvalue);
771
        }
772
      }
773
      if (isset($http_response->data)) {
774
        print $http_response->data;
775
        flush();
776
      }
777
      exit(); // leave drupal here
778
    } else {
779
      // $hook has been supplied
780
      // handle $hook either as compose ot theme hook
781
      // pass through theme or comose hook
782

    
783
      // do a security check since the $uri will be passed
784
      // as absolute URI to cdm_ws_get()
785
      if( !_is_cdm_ws_uri($uri)) {
786
        drupal_set_message(
787
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
788
            'error'
789
        );
790
        return '';
791
      }
792

    
793
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
794

    
795
      $reponse_data = NULL;
796

    
797
      if (function_exists('compose_' . $hook)){
798
        // call compose hook
799

    
800
        $elements =  call_user_func('compose_' . $hook, $obj);
801
        // pass the render array to drupal_render()
802
        $reponse_data = drupal_render($elements);
803
      } else {
804
        // call theme hook
805

    
806
        // TODO use theme registry to get the registered hook info and
807
        //    use these defaults
808
        switch($hook) {
809
          case 'cdm_taxontree':
810
            $variables = array(
811
              'tree' => $obj,
812
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
813
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
814
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
815
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
816
            );
817
            $reponse_data = theme($hook, $variables);
818
            break;
819

    
820
          case 'cdm_media_caption':
821
            $variables = array(
822
              'media' => $obj,
823
              // $args[0] is set in taxon_image_gallery_default in
824
              // cdm_dataportal.page.theme.
825
              'elements' => isset($args[0]) ? $args[0] : array(
826
                'title',
827
                'description',
828
                'artist',
829
                'location',
830
                'rights',
831
              ),
832
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
833
            );
834
            $reponse_data = theme($hook, $variables);
835
            break;
836

    
837
          default:
838
            drupal_set_message(t(
839
            'Theme !theme is not supported yet by function !function.', array(
840
            '!theme' => $hook,
841
            '!function' => __FUNCTION__,
842
            )), 'error');
843
            break;
844
        } // END of theme hook switch
845
      } // END of tread as theme hook
846
      if($do_gzip){
847
        $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
848
        drupal_add_http_header('Content-Encoding', 'gzip');
849
      }
850
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
851
      drupal_add_http_header('Content-Length', strlen($reponse_data));
852
      print $reponse_data;
853
    } // END of handle $hook either as compose ot theme hook
854
  }
855
}
856

    
857
/**
858
 * @todo Please document this function.
859
 * @see http://drupal.org/node/1354
860
 */
861
function setvalue_session() {
862
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
863
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
864
    $keys = explode('][', $keys);
865
  }
866
  else {
867
    return;
868
  }
869
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
870

    
871
  // Prevent from malicous tags.
872
  $val = strip_tags($val);
873

    
874
  $var = &$_SESSION;
875
  $i = 0;
876
  foreach ($keys as $key) {
877
    $hasMoreKeys = ++$i < count($var);
878
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
879
      $var[$key] = array();
880
    }
881
    $var = &$var[$key];
882
  }
883
  $var = $val;
884
  if (isset($_REQUEST['destination'])) {
885
    drupal_goto($_REQUEST['destination']);
886
  }
887
}
888

    
889
/**
890
 * @todo Please document this function.
891
 * @see http://drupal.org/node/1354
892
 */
893
function uri_uriByProxy($uri, $theme = FALSE) {
894
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
895
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
896
}
897

    
898
/**
899
 * @todo Please document this function.
900
 * @see http://drupal.org/node/1354
901
 */
902
function cdm_compose_annotations_url($cdmBase) {
903
  if (!$cdmBase->uuid) {
904
    return;
905
  }
906

    
907
  $ws_base_uri = NULL;
908
  switch ($cdmBase->class) {
909
    case 'TaxonBase':
910
    case 'Taxon':
911
    case 'Synonym':
912
      $ws_base_uri = CDM_WS_TAXON;
913
      break;
914

    
915
    case 'TaxonNameBase':
916
    case 'NonViralName':
917
    case 'BacterialName':
918
    case 'BotanicalName':
919
    case 'CultivarPlantName':
920
    case 'ZoologicalName':
921
    case 'ViralName':
922
      $ws_base_uri = CDM_WS_NAME;
923
      break;
924

    
925
    case 'Media':
926
      $ws_base_uri = CDM_WS_MEDIA;
927
      break;
928

    
929
    case 'Reference':
930
      $ws_base_uri = CDM_WS_REFERENCE;
931
      break;
932

    
933
    case 'Distribution':
934
    case 'TextData':
935
    case 'TaxonInteraction':
936
    case 'QuantitativeData':
937
    case 'IndividualsAssociation':
938
    case 'Distribution':
939
    case 'CommonTaxonName':
940
    case 'CategoricalData':
941
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
942
      break;
943

    
944
    case 'PolytomousKey':
945
    case 'MediaKey':
946
    case 'MultiAccessKey':
947
      $ws_base_uri = $cdmBase->class;
948
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
949
      break;
950

    
951
    default:
952
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
953
      return;
954
  }
955
  return cdm_compose_url($ws_base_uri, array(
956
    $cdmBase->uuid,
957
    'annotations',
958
  ));
959
}
960

    
961
/**
962
 * Enter description here...
963
 *
964
 * @param string $resourceURI
965
 * @param int $pageSize
966
 *   The maximum number of entities returned per page.
967
 *   The default page size as configured in the cdm server
968
 *   will be used if set to NULL
969
 *   to return all entities in a single page).
970
 * @param int $pageNumber
971
 *   The number of the page to be returned, the first page has the
972
 *   pageNumber = 0
973
 *
974
 * @return the a CDM Pager object
975
 *
976
 */
977
function cdm_ws_page($resourceURI, $pageSize, $pageNumber) {
978
  return cdm_ws_get($resourceURI, NULL, queryString(array(
979
    "pageNumber" => $pageNumber,
980
    'pageSize' => $pageSize,
981
  )));
982
}
983

    
984
/**
985
 * Fetches all entities from the given REST endpoint using the pager mechanism.
986
 *
987
 * @param string $resourceURI
988
 *
989
 * @return array
990
 *     A list of CDM entitites
991
 *
992
 */
993
function cdm_ws_fetch_all($resourceURI) {
994
  $page_index = 0;
995
  // using a bigger page size to avoid to many multiple requests
996
  $page_size = 200;
997
  $entities = array();
998

    
999
  while ($page_index !== FALSE){
1000
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index);
1001
    if(isset($pager->records) && is_array($pager->records)) {
1002
      $entities = $pager->records;
1003
      if(!empty($pager->nextIndex)){
1004
        $page_index = $pager->nextIndex;
1005
      } else {
1006
        $page_index = FALSE;
1007
      }
1008
    } else {
1009
      $page_index = FALSE;
1010
    }
1011
  }
1012
  return $entities;
1013
}
1014

    
1015
/*
1016
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1017
  $viewrank = _cdm_taxonomy_compose_viewrank();
1018
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1019
  ? '/' . $path : '') ;
1020
}
1021
*/
1022

    
1023
/**
1024
 * @todo Enter description here...
1025
 *
1026
 * @param string $taxon_uuid
1027
 *  The UUID of a cdm taxon instance
1028
 * @param string $ignore_rank_limit
1029
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1030
 *
1031
 * @return A cdm REST service URL path to a Classification
1032
 */
1033
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1034

    
1035
  $view_uuid = get_taxonomictree_uuid_selected();
1036
  $rank_uuid = NULL;
1037
  if (!$ignore_rank_limit) {
1038
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1039
  }
1040

    
1041
  if (!empty($taxon_uuid)) {
1042
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1043
      $view_uuid,
1044
      $taxon_uuid,
1045
    ));
1046
  }
1047
  else {
1048
    if (!empty($rank_uuid)) {
1049
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1050
        $view_uuid,
1051
        $rank_uuid,
1052
      ));
1053
    }
1054
    else {
1055
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1056
        $view_uuid,
1057
      ));
1058
    }
1059
  }
1060
}
1061

    
1062
/**
1063
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1064
 *
1065
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1066
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1067
 *
1068
 * Operates in two modes depending on whether the parameter
1069
 * $taxon_uuid is set or NULL.
1070
 *
1071
 * A) $taxon_uuid = NULL:
1072
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1073
 *  2. otherwise return the default classification as defined by the admin via the settings
1074
 *
1075
 * b) $taxon_uuid is set:
1076
 *   return the classification to whcih the taxon belongs to.
1077
 *
1078
 * @param UUID $taxon_uuid
1079
 *   The UUID of a cdm taxon instance
1080
 */
1081
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1082

    
1083
    $response = NULL;
1084

    
1085
    // 1st try
1086
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
1087

    
1088
    if ($response == NULL) {
1089
      // 2dn try by ignoring the rank limit
1090
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
1091
    }
1092

    
1093
    if ($response == NULL) {
1094
      // 3rd try, last fallback:
1095
      //    return the default classification
1096
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1097
        // Delete the session value and try again with the default.
1098
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1099
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1100
      }
1101
      else {
1102
        // Check if taxonomictree_uuid is valid.
1103
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1104
        if ($test == NULL) {
1105
          // The default set by the admin seems to be invalid or is not even set.
1106
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1107
        }
1108
      }
1109
    }
1110

    
1111
  return $response;
1112
}
1113

    
1114
/**
1115
 * @todo Enter description here...
1116
 *
1117
 * @param string $taxon_uuid
1118
 *
1119
 * @return unknown
1120
 */
1121
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1122
  $view_uuid = get_taxonomictree_uuid_selected();
1123
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1124

    
1125
  $response = NULL;
1126
  if ($rank_uuid) {
1127
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1128
      $view_uuid,
1129
      $taxon_uuid,
1130
      $rank_uuid,
1131
    ));
1132
  }
1133
  else {
1134
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1135
      $view_uuid,
1136
      $taxon_uuid,
1137
    ));
1138
  }
1139

    
1140
  if ($response == NULL) {
1141
    // Error handing.
1142
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1143
      // Delete the session value and try again with the default.
1144
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1145
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1146
    }
1147
    else {
1148
      // Check if taxonomictree_uuid is valid.
1149
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1150
      if ($test == NULL) {
1151
        // The default set by the admin seems to be invalid or is not even set.
1152
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1153
      }
1154
    }
1155
  }
1156

    
1157
  return $response;
1158
}
1159

    
1160
/**
1161
 * @todo Please document this function.
1162
 * @see http://drupal.org/node/1354
1163
 */
1164
function cdm_rankVocabulary_as_option() {
1165
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1166
  array_unshift ($options, "");
1167
  return $options;
1168
}
1169

    
1170
/**
1171
 *
1172
 * @param Object $definedTermBase
1173
 * 	  of cdm type DefinedTermBase
1174
 * @return string
1175
 * 	  the localized representation_L10n of the term,
1176
 *    otherwise the titleCache as fall back,
1177
 *    otherwise an empty string
1178
 */
1179
function cdm_term_representation($definedTermBase) {
1180
  if ( isset($definedTermBase->representation_L10n) ) {
1181
    return $definedTermBase->representation_L10n;
1182
  } elseif ( isset($definedTermBase->titleCache)) {
1183
    return $definedTermBase->titleCache;
1184
  }
1185
  return '';
1186
}
1187

    
1188
/**
1189
 * @todo Improve documentation of this function.
1190
 *
1191
 * eu.etaxonomy.cdm.model.description.
1192
 * CategoricalData
1193
 * CommonTaxonName
1194
 * Distribution
1195
 * IndividualsAssociation
1196
 * QuantitativeData
1197
 * TaxonInteraction
1198
 * TextData
1199
 */
1200
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1201
  static $types = array(
1202
    "CategoricalData",
1203
    "CommonTaxonName",
1204
    "Distribution",
1205
    "IndividualsAssociation",
1206
    "QuantitativeData",
1207
    "TaxonInteraction",
1208
    "TextData",
1209
  );
1210

    
1211
  static $options = NULL;
1212
  if ($options == NULL) {
1213
    $options = array();
1214
    if ($prependEmptyElement) {
1215
      $options[' '] = '';
1216
    }
1217
    foreach ($types as $type) {
1218
      // No internatianalization here since these are purely technical terms.
1219
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1220
    }
1221
  }
1222
  return $options;
1223
}
1224

    
1225
/**
1226
 * @todo Please document this function.
1227
 * @see http://drupal.org/node/1354
1228
 */
1229
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1230
  static $vocabularyOptions = array();
1231

    
1232
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1233
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1234
    $vocabularyOptions[$vocabularyUuid] = array();
1235

    
1236
    if ($vocab) {
1237
      foreach ($vocab->terms as $term) {
1238
        if ($term_label_callback && function_exists($term_label_callback)) {
1239
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1240
        }
1241
        else {
1242
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1243
        }
1244
      }
1245
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1246
    }
1247
  }
1248
  return $vocabularyOptions[$vocabularyUuid];
1249
}
1250

    
1251
/**
1252
 * @todo Please document this function.
1253
 * @see http://drupal.org/node/1354
1254
 */
1255
function _cdm_relationship_type_term_label_callback($term) {
1256
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1257
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1258
  }
1259
  else {
1260
    return t($term->representation_L10n);
1261
  }
1262
}
1263

    
1264
/**
1265
 * @todo Please document this function.
1266
 * @see http://drupal.org/node/1354
1267
 */
1268
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1269
  if (!$featureTree) {
1270
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1271
      In order to see the species profiles of your taxa, please select a
1272
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1273
    return FALSE;
1274
  }
1275

    
1276
  $mergedTrees = array();
1277

    
1278
  if ($isDescriptionsSeparated) {
1279
    // Merge any description into a separate feature tree.
1280
    foreach ($descriptions as $desc) {
1281
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1282

    
1283
      $mergedTree = clone $featureTree;
1284
      $mergedTree->root->children = $mergedNodes;
1285
      $mergedTrees[] = $mergedTree;
1286
    }
1287
  }
1288
  else {
1289
    // Combine all descripions into one feature tree.
1290
    $descriptionElemens = array();
1291
    foreach ($descriptions as $desc) {
1292
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1293
    }
1294
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1295
    $featureTree->root->children = $mergedNodes;
1296
    $mergedTrees[] = $featureTree;
1297
  }
1298

    
1299
  return $mergedTrees;
1300
}
1301

    
1302
/**
1303
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1304
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1305
 * be requested for the annotations.
1306
 *
1307
 * @param string $cdmBase
1308
 *   An annotatable cdm entity.
1309
 * @param array $includeTypes
1310
 *   If an array of annotation type uuids is supplied by this parameter the
1311
 *   list of annotations is resticted to those which belong to this type.
1312
 *
1313
 * @return array
1314
 *   An array of Annotation objects or an empty array.
1315
 */
1316
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1317

    
1318
  if(!isset($cdmBase->annotations)){
1319
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
1320
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl);
1321
  }
1322

    
1323
  $annotations = array();
1324
  foreach ($cdmBase->annotations as $annotation) {
1325
    if ($includeTypes) {
1326
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1327
        $annotations[] = $annotation;
1328
      }
1329
    }
1330
    else {
1331
      $annotations[] = $annotation;
1332
    }
1333
  }
1334
  return $annotations;
1335

    
1336
}
1337

    
1338
/**
1339
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1340
 *
1341
 * @param object $annotatable_entity
1342
 *   The CDM AnnotatableEntity to load annotations for
1343
 */
1344
function cdm_load_annotations(&$annotatable_entity) {
1345
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1346
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1347
    if (is_array($annotations)) {
1348
      $annotatable_entity->annotations = $annotations;
1349
    }
1350
  }
1351
}
1352

    
1353
/**
1354
 * Get a NomenclaturalReference string.
1355
 *
1356
 * Returns the NomenclaturalReference string with correctly placed
1357
 * microreference (= reference detail) e.g.
1358
 * in Phytotaxa 43: 1-48. 2012.
1359
 *
1360
 * @param string $referenceUuid
1361
 *   UUID of the reference.
1362
 * @param string $microreference
1363
 *   Reference detail.
1364
 *
1365
 * @return string
1366
 *   a NomenclaturalReference.
1367
 */
1368
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1369
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1370
    $referenceUuid,
1371
  ), "microReference=" . urlencode($microreference));
1372

    
1373
  if ($obj) {
1374
    return $obj->String;
1375
  }
1376
  else {
1377
    return NULL;
1378
  }
1379
}
1380

    
1381
/**
1382
 * Merges the given featureNodes structure with the descriptionElements.
1383
 *
1384
 * This method is used in preparation for rendering the descriptionElements.
1385
 * The descriptionElements wich belong to a specific feature node are appended
1386
 * to a the feature node by creating a new fields:
1387
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1388
 * The descriptionElements will be cleared in advance in order to allow reusing the
1389
 * same feature tree without the risk of mixing sets of descrition elemens.
1390
 *
1391
 * which originally is not existing in the cdm.
1392
 *
1393
 *
1394
 *
1395
 * @param array $featureNodes
1396
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1397
 *    may have children.
1398
 * @param array $descriptionElements
1399
 *    An flat array of cdm DescriptionElements
1400
 * @return array
1401
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1402
 */
1403
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1404

    
1405
  foreach ($featureNodes as &$node) {
1406
    // since the $featureNodes array is reused for each description
1407
    // it is nessecary to clear the custom node fields in advance
1408
    if(isset($node->descriptionElements)){
1409
      unset($node->descriptionElements);
1410
    }
1411

    
1412
    // Append corresponding elements to an additional node field:
1413
    // $node->descriptionElements.
1414
    foreach ($descriptionElements as $element) {
1415
      if ($element->feature->uuid == $node->feature->uuid) {
1416
        if (!isset($node->descriptionElements)) {
1417
          $node->descriptionElements = array();
1418
        }
1419
        $node->descriptionElements[] = $element;
1420
      }
1421
    }
1422

    
1423
    // Recurse into node children.
1424
    if (isset($node->children[0])) {
1425
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1426
      $node->children = $mergedChildNodes;
1427
    }
1428

    
1429
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1430
      unset($node);
1431
    }
1432

    
1433
  }
1434

    
1435
  return $featureNodes;
1436
}
1437

    
1438
/**
1439
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1440
 *
1441
 * The response from the HTTP GET request is returned as object.
1442
 * The response objects coming from the webservice configured in the
1443
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1444
 *  in a level 2 (L2) cache.
1445
 *
1446
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1447
 * function, this cache persists only per each single page execution.
1448
 * Any object coming from the webservice is stored into it by default.
1449
 * In contrast to this default caching mechanism the L2 cache only is used if
1450
 * the 'cdm_webservice_cache' variable is set to TRUE,
1451
 * which can be set using the modules administrative settings section.
1452
 * Objects stored in this L2 cache are serialized and stored
1453
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1454
 * objects that are stored in the database will persist as
1455
 * long as the drupal cache is not beeing cleared and are available across
1456
 * multiple script executions.
1457
 *
1458
 * @param string $uri
1459
 *   URL to the webservice.
1460
 * @param array $pathParameters
1461
 *   An array of path parameters.
1462
 * @param string $query
1463
 *   A query string to be appended to the URL.
1464
 * @param string $method
1465
 *   The HTTP method to use, valid values are "GET" or "POST";
1466
 * @param bool $absoluteURI
1467
 *   TRUE when the URL should be treated as absolute URL.
1468
 *
1469
 * @return object
1470
 *   The deserialized webservice response object.
1471
 */
1472
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1473

    
1474
  static $cacheL1 = array();
1475

    
1476
  // Transform the given uri path or pattern into a proper webservice uri.
1477
  if (!$absoluteURI) {
1478
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1479
  }
1480

    
1481
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1482
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1483

    
1484
  if (array_key_exists($uri, $cacheL1)) {
1485
    $cacheL1_obj = $cacheL1[$uri];
1486
  }
1487

    
1488
  $set_cacheL1 = FALSE;
1489
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1490
    $set_cacheL1 = TRUE;
1491
  }
1492

    
1493
  // Only cache cdm webservice URIs.
1494
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1495
  $cacheL2_entry = FALSE;
1496

    
1497
  if ($use_cacheL2) {
1498
    // Try to get object from cacheL2.
1499
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1500
  }
1501

    
1502
  if (isset($cacheL1_obj)) {
1503
    //
1504
    // The object has been found in the L1 cache.
1505
    //
1506
    $obj = $cacheL1_obj;
1507
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1508
      cdm_ws_debug_add($uri, 0, 0, NULL, 'cacheL1');
1509
    }
1510
  }
1511
  elseif ($cacheL2_entry) {
1512
    //
1513
    // The object has been found in the L2 cache.
1514
    //
1515
    $duration_parse_start = microtime(TRUE);
1516
    $obj = unserialize($cacheL2_entry->data);
1517
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1518

    
1519
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1520
      cdm_ws_debug_add($uri, 0, $duration_parse, NULL, 'cacheL2');
1521
    }
1522
  }
1523
  else {
1524
    //
1525
    // Get the object from the webservice and cache it.
1526
    //
1527
    $duration_fetch_start = microtime(TRUE);
1528
    // Request data from webservice JSON or XML.
1529
    $response = cdm_http_request($uri, $method);
1530
    $datastr = NULL;
1531
    if (isset($response->data)) {
1532
      $datastr = $response->data;
1533
    }
1534
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1535
    $duration_parse_start = microtime(TRUE);
1536

    
1537
    // Parse data and create object.
1538
    $obj = cdm_load_obj($datastr);
1539

    
1540
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1541
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1542
      if ($obj || $datastr == "[]") {
1543
        $status = 'valid';
1544
      }
1545
      else {
1546
        $status = 'invalid';
1547
      }
1548
      cdm_ws_debug_add($uri, $duration_fetch, $duration_parse, strlen($datastr), $status);
1549
    }
1550
    if ($set_cacheL2) {
1551
      // Store the object in cache L2.
1552
      // Comment @WA perhaps better if Drupal serializes here? Then the
1553
      // flag serialized is set properly in the cache table.
1554
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1555
    }
1556
  }
1557
  if ($obj) {
1558
    // Store the object in cache L1.
1559
    if ($set_cacheL1) {
1560
      $cacheL1[$uri] = $obj;
1561
    }
1562
  }
1563
  return $obj;
1564
}
1565

    
1566
/**
1567
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1568
 *
1569
 * The cdm_ws_debug block will display the debug information.
1570
 *
1571
 * @param $uri
1572
 *    The CDM REST URI to which the request has been send
1573
 * @param $duration_fetch
1574
 *    The time in seconds it took to fetch the data from the web service
1575
 * @param $duration_parse
1576
 *    Time in seconds which was needed to parse the json response
1577
 * @param $datasize
1578
 *    Size of the data received from the server
1579
 * @param $status
1580
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1581
 * @return bool
1582
 *    TRUE if adding the debug information was successful
1583
 */
1584
function cdm_ws_debug_add($uri, $duration_fetch, $duration_parse, $datasize, $status) {
1585

    
1586
  static $initial_time = NULL;
1587
  if(!$initial_time) {
1588
    $initial_time = microtime(TRUE);
1589
  }
1590
  $time = microtime(TRUE) - $initial_time;
1591

    
1592
  // Decompose uri into path and query element.
1593
  // URI query elements are stored in an array
1594
  // suitable for drupal_http_build_query()
1595
  $uri_parts = explode("?", $uri);
1596
  $query = array();
1597
  if (count($uri_parts) == 2) {
1598
    $path = $uri_parts[0];
1599
    $queryparts = explode("&", $uri_parts[1]);
1600
    foreach ($queryparts as $querypart) {
1601
      $querypart = explode("=", $querypart);
1602
      if(count($querypart) == 2){
1603
        $query[$querypart[0]] = $querypart[1];
1604
      } else {
1605
        $query[$querypart[0]] = null;
1606
      }
1607
    }
1608
  }
1609
  else {
1610
    $path = $uri;
1611
  }
1612

    
1613
  // data links to make data accecsible as json and xml
1614
  $data_links = '';
1615
  if (_is_cdm_ws_uri($path)) {
1616
    $data_links .= '<a href="'
1617
        . url($path . '.xml', array('query' => $query))
1618
        . '" target="data">xml</a>-';
1619
    $data_links .= '<a href="'
1620
        . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array('query' => $query))))
1621
        . '" target="data">proxied</a>';
1622
    $data_links .= '<br/>';
1623
    $data_links .= '<a href="'
1624
        . url($path . '.json', array('query' => $query))
1625
        . '" target="data">json</a>-';
1626
    $data_links .= '<a href="'
1627
        . url('cdm_api/proxy/' . urlencode(url($path . '.json', array('query' => $query))))
1628
        . '" target="data">proxied</a>';
1629
  }
1630
  else {
1631
    $data_links .= '<a href="' . url($path, array(
1632
        'query' => $query)) . '" target="data">open</a>';
1633
  }
1634

    
1635
  //
1636
  $data = array(
1637
      'ws_uri' => $uri,
1638
      'time' => sprintf('%3.3f', $time),
1639
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1640
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1641
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1642
      'status' => $status,
1643
      'data_links' => $data_links
1644
  );
1645
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1646
    $_SESSION['cdm']['ws_debug'] = array();
1647
  }
1648
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1649

    
1650
  // Mark this page as being uncacheable.
1651
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1652
  drupal_page_is_cacheable(FALSE);
1653

    
1654
  // Messages not set when DB connection fails.
1655
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1656
}
1657

    
1658
/**
1659
 * @todo Please document this function.
1660
 * @see http://drupal.org/node/1354
1661
 */
1662
function cdm_load_obj($datastr) {
1663
  $obj = json_decode($datastr);
1664

    
1665
  if (!(is_object($obj) || is_array($obj))) {
1666
    ob_start();
1667
    $obj_dump = ob_get_contents();
1668
    ob_clean();
1669
    return FALSE;
1670
  }
1671

    
1672
  return $obj;
1673
}
1674

    
1675
/**
1676
 * Do a http request to a CDM RESTful web service.
1677
 *
1678
 * @param string $uri
1679
 *   The webservice url.
1680
 * @param string $method
1681
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1682
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1683
 * @param array $parameters
1684
 *   Parameters to use in the request.
1685
 * @param array $header
1686
 *   The header to include in the request.
1687
 *
1688
 * @return object
1689
 *   The object as returned by drupal_http_request():
1690
 *   An object that can have one or more of the following components:
1691
 *   - request: A string containing the request body that was sent.
1692
 *   - code: An integer containing the response status code, or the error code
1693
 *     if an error occurred.
1694
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1695
 *   - status_message: The status message from the response, if a response was
1696
 *     received.
1697
 *   - redirect_code: If redirected, an integer containing the initial response
1698
 *     status code.
1699
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1700
 *     target.
1701
 *   - error: If an error occurred, the error message. Otherwise not set.
1702
 *   - headers: An array containing the response headers as name/value pairs.
1703
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1704
 *     easy access the array keys are returned in lower case.
1705
 *   - data: A string containing the response body that was received.
1706
 */
1707
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array(), $options = NULL) {
1708
  static $acceptLanguage = NULL;
1709

    
1710
  if (!$acceptLanguage) {
1711
    if (function_exists('apache_request_headers')) {
1712
      $headers = apache_request_headers();
1713
      if (isset($headers['Accept-Language'])) {
1714
        $acceptLanguage = $headers['Accept-Language'];
1715
      }
1716
    }
1717
    if (!$acceptLanguage) {
1718
      // DEFAULT TODO make configurable.
1719
      $acceptLanguage = "en";
1720
    }
1721
  }
1722

    
1723
  if ($method != "GET" && $method != "POST") {
1724
    $method = "GET";
1725
  }
1726

    
1727
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1728
    $header['Accept'] = 'application/json';
1729
    $header['Accept-Language'] = $acceptLanguage;
1730
    $header['Accept-Charset'] = 'UTF-8';
1731
  }
1732

    
1733
  return drupal_http_request($uri, array(
1734
      'headers' => $header,
1735
      'method' => $method,
1736
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1737
      )
1738
   );
1739
}
1740

    
1741
/**
1742
 * @todo Please document this function.
1743
 * @see http://drupal.org/node/1354
1744
 */
1745
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1746
  $out = '';
1747

    
1748
  foreach ($rootNode->children as $featureNode) {
1749
    $out .= ($out ? $separator : '');
1750
    $out .= $featureNode->feature->representation_L10n;
1751
    if (is_array($featureNode->children)) {
1752
      $childlabels = '';
1753
      foreach ($featureNode->children as $childNode) {
1754
        $childlabels .= ($childlabels ? $separator : '');
1755
      }
1756
      $childlabels .= _featureTree_elements_toString($childNode);
1757
    }
1758
    if ($childlabels) {
1759
      $out .= '[' . $childlabels . ' ]';
1760
    }
1761
  }
1762
  return $out;
1763
}
1764

    
1765
/**
1766
 * Create a one-dimensional form options array.
1767
 *
1768
 * Creates an array of all features in the feature tree of feature nodes,
1769
 * the node labels are indented by $node_char and $childIndent depending on the
1770
 * hierachy level.
1771
 *
1772
 * @param - $rootNode
1773
 * @param - $node_char
1774
 * @param - $childIndentStr
1775
 * @param - $childIndent
1776
 *   ONLY USED INTERNALLY!
1777
 *
1778
 * @return array
1779
 *   A one dimensional Drupal form options array.
1780
 */
1781
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1782
  $options = array();
1783
  foreach ($rootNode->children as $featureNode) {
1784
    $indent_prefix = '';
1785
    if ($childIndent) {
1786
      $indent_prefix = $childIndent . $node_char . " ";
1787
    }
1788
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1789
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1790
      // Foreach ($featureNode->children as $childNode){
1791
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1792
      $options = array_merge_recursive($options, $childList);
1793
      // }
1794
    }
1795
  }
1796
  return $options;
1797
}
1798

    
1799
/**
1800
 * Returns an array with all available FeatureTrees and the representations of the selected
1801
 * FeatureTree as a detail view.
1802
 *
1803
 * @param boolean $add_default_feature_free
1804
 * @return array
1805
 *  associative array with following keys:
1806
 *  -options: Returns an array with all available Feature Trees
1807
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1808
 *
1809
 */
1810
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1811

    
1812
  $options = array();
1813
  $tree_representations = array();
1814
  $feature_trees = array();
1815

    
1816
  // Set tree that contains all features.
1817
  if ($add_default_feature_free) {
1818
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1819
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1820
  }
1821

    
1822
  // Get feature trees from database.
1823
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1824
  if (is_array($persited_trees)) {
1825
    $feature_trees = array_merge($feature_trees, $persited_trees);
1826
  }
1827

    
1828
  foreach ($feature_trees as $featureTree) {
1829

    
1830
    // Do not add the DEFAULT_FEATURETREE again,
1831
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1832
      $options[$featureTree->uuid] = $featureTree->titleCache;
1833
    }
1834

    
1835
    // Render the hierarchic tree structure
1836
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1837

    
1838
      // Render the hierarchic tree structure.
1839
      $treeDetails = '<div class="featuretree_structure">'
1840
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1841
        . '</div>';
1842

    
1843
      $form = array();
1844
      $form['featureTree-' .  $featureTree->uuid] = array(
1845
        '#type' => 'fieldset',
1846
        '#title' => 'Show details',
1847
        '#attributes' => array('class' => array('collapsible collapsed')),
1848
        // '#collapsible' => TRUE,
1849
        // '#collapsed' => TRUE,
1850
      );
1851
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1852
        '#markup' => $treeDetails,
1853
      );
1854

    
1855
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1856
    }
1857

    
1858
  } // END loop over feature trees
1859

    
1860
  // return $options;
1861
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1862
}
1863

    
1864
/**
1865
 * Provides the list of availbale classifications in form of an options array.
1866
 *
1867
 * The options array is suitable for drupal form API elements that allow multiple choices.
1868
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1869
 *
1870
 * The classifications are ordered alphabetically whereas the classification
1871
 * chosen as default will always appear on top of the array, followed by a
1872
 * blank line below.
1873
 *
1874
 * @param bool $add_none_option
1875
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1876
 *
1877
 * @return array
1878
 *   classifications in an array as options for a form element that allows multiple choices.
1879
 */
1880
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1881

    
1882
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1883

    
1884
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1885
  $default_classification_label = '';
1886

    
1887
  // add all classifications
1888
  $taxonomic_tree_options = array();
1889
  if ($add_none_option) {
1890
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1891
  }
1892
  if ($taxonTrees) {
1893
    foreach ($taxonTrees as $tree) {
1894
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1895
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1896
      } else {
1897
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1898
        if (count($taxonTrees) > 1) {
1899
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1900
        }
1901
        $default_classification_label = $tree->titleCache;
1902
      }
1903
    }
1904
  }
1905
  // oder alphabetically the space
1906
  asort($taxonomic_tree_options);
1907

    
1908
  // now set the labels
1909
  //   for none
1910
  if ($add_none_option) {
1911
    $taxonomic_tree_options['NONE'] = t('-- None --');
1912
  }
1913

    
1914
  //   for default_classification
1915
  if (is_uuid($default_classification_uuid)) {
1916
    $taxonomic_tree_options[$default_classification_uuid] =
1917
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1918
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1919
  }
1920

    
1921
  return $taxonomic_tree_options;
1922
}
1923

    
1924
/**
1925
 * @todo Please document this function.
1926
 * @see http://drupal.org/node/1354
1927
 */
1928
function cdm_api_secref_cache_prefetch(&$secUuids) {
1929
  // Comment @WA: global variables should start with a single underscore
1930
  // followed by the module and another underscore.
1931
  global $_cdm_api_secref_cache;
1932
  if (!is_array($_cdm_api_secref_cache)) {
1933
    $_cdm_api_secref_cache = array();
1934
  }
1935
  $uniqueUuids = array_unique($secUuids);
1936
  $i = 0;
1937
  $param = '';
1938
  while ($i++ < count($uniqueUuids)) {
1939
    $param .= $secUuids[$i] . ',';
1940
    if (strlen($param) + 37 > 2000) {
1941
      _cdm_api_secref_cache_add($param);
1942
      $param = '';
1943
    }
1944
  }
1945
  if ($param) {
1946
    _cdm_api_secref_cache_add($param);
1947
  }
1948
}
1949

    
1950
/**
1951
 * @todo Please document this function.
1952
 * @see http://drupal.org/node/1354
1953
 */
1954
function cdm_api_secref_cache_get($secUuid) {
1955
  global $_cdm_api_secref_cache;
1956
  if (!is_array($_cdm_api_secref_cache)) {
1957
    $_cdm_api_secref_cache = array();
1958
  }
1959
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1960
    _cdm_api_secref_cache_add($secUuid);
1961
  }
1962
  return $_cdm_api_secref_cache[$secUuid];
1963
}
1964

    
1965
/**
1966
 * @todo Please document this function.
1967
 * @see http://drupal.org/node/1354
1968
 */
1969
function cdm_api_secref_cache_clear() {
1970
  global $_cdm_api_secref_cache;
1971
  $_cdm_api_secref_cache = array();
1972
}
1973

    
1974
/**
1975
 * Validates if the given string is a uuid.
1976
 *
1977
 * @param string $str
1978
 *   The string to validate.
1979
 *
1980
 * return bool
1981
 *   TRUE if the string is a UUID.
1982
 */
1983
function is_uuid($str) {
1984
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1985
}
1986

    
1987
/**
1988
 * Checks if the given $object is a valid cdm entity.
1989
 *
1990
 * An object is considered a cdm entity if it has a string field $object->class
1991
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
1992
 *
1993
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
1994
 *
1995
 * @param mixed $object
1996
 *   The object to validate
1997
 *
1998
 * @return bool
1999
 *   True if the object is a cdm entity.
2000
 */
2001
function is_cdm_entity($object) {
2002
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2003
}
2004

    
2005
/**
2006
 * @todo Please document this function.
2007
 * @see http://drupal.org/node/1354
2008
 */
2009
function _cdm_api_secref_cache_add($secUuidsStr) {
2010
  global $_cdm_api_secref_cache;
2011
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2012
  // Batch fetching not jet reimplemented thus:
2013
  /*
2014
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2015
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2016
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2017
  */
2018
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2019
}
2020

    
2021
/**
2022
 * Checks if the given uri starts with a cdm webservice url.
2023
 *
2024
 * Checks if the uri starts with the cdm webservice url stored in the
2025
 * Drupal variable 'cdm_webservice_url'.
2026
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2027
 *
2028
 * @param string $uri
2029
 *   The URI to test.
2030
 *
2031
 * @return bool
2032
 *   True if the uri starts with a cdm webservice url.
2033
 */
2034
function _is_cdm_ws_uri($uri) {
2035
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2036
}
2037

    
2038
/**
2039
 * @todo Please document this function.
2040
 * @see http://drupal.org/node/1354
2041
 */
2042
function queryString($elements) {
2043
  $query = '';
2044
  foreach ($elements as $key => $value) {
2045
    if (is_array($value)) {
2046
      foreach ($value as $v) {
2047
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2048
      }
2049
    }
2050
    else {
2051
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2052
    }
2053
  }
2054
  return $query;
2055
}
2056

    
2057
/**
2058
 * Implementation of the magic method __clone to allow deep cloning of objects
2059
 * and arrays.
2060
 */
2061
function __clone() {
2062
  foreach ($this as $name => $value) {
2063
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2064
      $this->$name = clone($this->$name);
2065
    }
2066
  }
2067
}
2068

    
2069
/**
2070
 * Make a 'deep copy' of an array.
2071
 *
2072
 * Make a complete deep copy of an array replacing
2073
 * references with deep copies until a certain depth is reached
2074
 * ($maxdepth) whereupon references are copied as-is...
2075
 *
2076
 * @see http://us3.php.net/manual/en/ref.array.php
2077
 *
2078
 * @param array $array
2079
 * @param array $copy
2080
 * @param int $maxdepth
2081
 * @param int $depth
2082
 *
2083
 * @return void
2084
 */
2085
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2086
  if ($depth > $maxdepth) {
2087
    $copy = $array;
2088
    return;
2089
  }
2090
  if (!is_array($copy)) {
2091
    $copy = array();
2092
  }
2093
  foreach ($array as $k => &$v) {
2094
    if (is_array($v)) {
2095
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2096
    }
2097
    else {
2098
      $copy[$k] = $v;
2099
    }
2100
  }
2101
}
2102

    
2103
/**
2104
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2105
 *
2106
 */
2107
function _add_js_ws_debug() {
2108

    
2109
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js',
2110
    array(
2111
      'type' => 'file',
2112
      'weight' => JS_LIBRARY,
2113
      'cache' => TRUE)
2114
    );
2115

    
2116
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/jquery.colorbox-min.js',
2117
    array(
2118
      'type' => 'file',
2119
      'weight' => JS_LIBRARY,
2120
      'cache' => TRUE)
2121
    );
2122
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2123
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2124

    
2125
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2126
    array(
2127
      'type' => 'file',
2128
      'weight' => JS_LIBRARY,
2129
      'cache' => TRUE)
2130
    );
2131

    
2132
}
2133

    
2134
/**
2135
 * @todo Please document this function.
2136
 * @see http://drupal.org/node/1354
2137
 */
2138
function _no_classfication_uuid_message() {
2139
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2140
    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.');
2141
  }
2142
  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.');
2143
}
2144

    
2145
/**
2146
 * Implementation of hook flush_caches
2147
 *
2148
 * Add custom cache tables to the list of cache tables that
2149
 * will be cleared by the Clear button on the Performance page or whenever
2150
 * drupal_flush_all_caches is invoked.
2151
 *
2152
 * @author W.Addink <waddink@eti.uva.nl>
2153
 *
2154
 * @return array
2155
 *   An array with custom cache tables to include.
2156
 */
2157
function cdm_api_flush_caches() {
2158
  return array('cache_cdm_ws');
2159
}
(4-4/9)