Project

General

Profile

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

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

    
30

    
31
/**
32
 * 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 absolute CDM web service URI 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
 * Composes the the absolute REST service URI to the annotations pager
900
 * for the given CDM entity.
901
 *
902
 * NOTE: Not all CDM Base types are yet supported.
903
 *
904
 * @param $cdmBase
905
 *   The CDM entity to construct the annotations pager uri for
906
 */
907
function cdm_compose_annotations_uri($cdmBase) {
908
  if (!$cdmBase->uuid) {
909
    return;
910
  }
911

    
912
  $ws_base_uri = NULL;
913
  switch ($cdmBase->class) {
914
    case 'TaxonBase':
915
    case 'Taxon':
916
    case 'Synonym':
917
      $ws_base_uri = CDM_WS_TAXON;
918
      break;
919

    
920
    case 'TaxonNameBase':
921
    case 'NonViralName':
922
    case 'BacterialName':
923
    case 'BotanicalName':
924
    case 'CultivarPlantName':
925
    case 'ZoologicalName':
926
    case 'ViralName':
927
      $ws_base_uri = CDM_WS_NAME;
928
      break;
929

    
930
    case 'Media':
931
      $ws_base_uri = CDM_WS_MEDIA;
932
      break;
933

    
934
    case 'Reference':
935
      $ws_base_uri = CDM_WS_REFERENCE;
936
      break;
937

    
938
    case 'Distribution':
939
    case 'TextData':
940
    case 'TaxonInteraction':
941
    case 'QuantitativeData':
942
    case 'IndividualsAssociation':
943
    case 'Distribution':
944
    case 'CommonTaxonName':
945
    case 'CategoricalData':
946
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
947
      break;
948

    
949
    case 'PolytomousKey':
950
    case 'MediaKey':
951
    case 'MultiAccessKey':
952
      $ws_base_uri = $cdmBase->class;
953
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
954
      break;
955

    
956
    default:
957
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
958
      return;
959
  }
960
  return cdm_compose_url($ws_base_uri, array(
961
    $cdmBase->uuid,
962
    'annotations',
963
  ));
964
}
965

    
966
/**
967
 * Enter description here...
968
 *
969
 * @param string $resourceURI
970
 * @param int $pageSize
971
 *   The maximum number of entities returned per page.
972
 *   The default page size as configured in the cdm server
973
 *   will be used if set to NULL
974
 *   to return all entities in a single page).
975
 * @param int $pageNumber
976
 *   The number of the page to be returned, the first page has the
977
 *   pageNumber = 0
978
 * @param bool $absoluteURI
979
 *   TRUE when the URL should be treated as absolute URL.
980
 * @return the a CDM Pager object
981
 *
982
 */
983
function cdm_ws_page($resourceURI, $pageSize, $pageNumber,  $absoluteURI = FALSE) {
984
  return cdm_ws_get($resourceURI, NULL, queryString(array(
985
      "pageNumber" => $pageNumber,
986
      'pageSize' => $pageSize,
987
    )),
988
    'GET',
989
    $absoluteURI);
990
}
991

    
992
/**
993
 * Fetches all entities from the given REST endpoint using the pager mechanism.
994
 *
995
 * @param string $resourceURI
996
 * @param bool $absoluteURI
997
 *   TRUE when the URL should be treated as absolute URL.
998
 *
999
 * @return array
1000
 *     A list of CDM entitites
1001
 *
1002
 */
1003
function cdm_ws_fetch_all($resourceURI, $absoluteURI = FALSE) {
1004
  $page_index = 0;
1005
  // using a bigger page size to avoid to many multiple requests
1006
  $page_size = 500;
1007
  $entities = array();
1008

    
1009
  while ($page_index !== FALSE){
1010
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $absoluteURI);
1011
    if(isset($pager->records) && is_array($pager->records)) {
1012
      $entities = $pager->records;
1013
      if(!empty($pager->nextIndex)){
1014
        $page_index = $pager->nextIndex;
1015
      } else {
1016
        $page_index = FALSE;
1017
      }
1018
    } else {
1019
      $page_index = FALSE;
1020
    }
1021
  }
1022
  return $entities;
1023
}
1024

    
1025
/*
1026
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1027
  $viewrank = _cdm_taxonomy_compose_viewrank();
1028
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1029
  ? '/' . $path : '') ;
1030
}
1031
*/
1032

    
1033
/**
1034
 * @todo Enter description here...
1035
 *
1036
 * @param string $taxon_uuid
1037
 *  The UUID of a cdm taxon instance
1038
 * @param string $ignore_rank_limit
1039
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1040
 *
1041
 * @return A cdm REST service URL path to a Classification
1042
 */
1043
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1044

    
1045
  $view_uuid = get_taxonomictree_uuid_selected();
1046
  $rank_uuid = NULL;
1047
  if (!$ignore_rank_limit) {
1048
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1049
  }
1050

    
1051
  if (!empty($taxon_uuid)) {
1052
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1053
      $view_uuid,
1054
      $taxon_uuid,
1055
    ));
1056
  }
1057
  else {
1058
    if (!empty($rank_uuid)) {
1059
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1060
        $view_uuid,
1061
        $rank_uuid,
1062
      ));
1063
    }
1064
    else {
1065
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1066
        $view_uuid,
1067
      ));
1068
    }
1069
  }
1070
}
1071

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

    
1093
    $response = NULL;
1094

    
1095
    // 1st try
1096
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
1097

    
1098
    if ($response == NULL) {
1099
      // 2dn try by ignoring the rank limit
1100
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
1101
    }
1102

    
1103
    if ($response == NULL) {
1104
      // 3rd try, last fallback:
1105
      //    return the default classification
1106
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1107
        // Delete the session value and try again with the default.
1108
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1109
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1110
      }
1111
      else {
1112
        // Check if taxonomictree_uuid is valid.
1113
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1114
        if ($test == NULL) {
1115
          // The default set by the admin seems to be invalid or is not even set.
1116
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1117
        }
1118
      }
1119
    }
1120

    
1121
  return $response;
1122
}
1123

    
1124
/**
1125
 * @todo Enter description here...
1126
 *
1127
 * @param string $taxon_uuid
1128
 *
1129
 * @return unknown
1130
 */
1131
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1132
  $view_uuid = get_taxonomictree_uuid_selected();
1133
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1134

    
1135
  $response = NULL;
1136
  if ($rank_uuid) {
1137
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1138
      $view_uuid,
1139
      $taxon_uuid,
1140
      $rank_uuid,
1141
    ));
1142
  }
1143
  else {
1144
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1145
      $view_uuid,
1146
      $taxon_uuid,
1147
    ));
1148
  }
1149

    
1150
  if ($response == NULL) {
1151
    // Error handing.
1152
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1153
      // Delete the session value and try again with the default.
1154
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1155
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1156
    }
1157
    else {
1158
      // Check if taxonomictree_uuid is valid.
1159
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1160
      if ($test == NULL) {
1161
        // The default set by the admin seems to be invalid or is not even set.
1162
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1163
      }
1164
    }
1165
  }
1166

    
1167
  return $response;
1168
}
1169

    
1170
/**
1171
 * @todo Please document this function.
1172
 * @see http://drupal.org/node/1354
1173
 */
1174
function cdm_rankVocabulary_as_option() {
1175
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1176
  array_unshift ($options, "");
1177
  return $options;
1178
}
1179

    
1180
/**
1181
 *
1182
 * @param Object $definedTermBase
1183
 * 	  of cdm type DefinedTermBase
1184
 * @return string
1185
 * 	  the localized representation_L10n of the term,
1186
 *    otherwise the titleCache as fall back,
1187
 *    otherwise an empty string
1188
 */
1189
function cdm_term_representation($definedTermBase) {
1190
  if ( isset($definedTermBase->representation_L10n) ) {
1191
    return $definedTermBase->representation_L10n;
1192
  } elseif ( isset($definedTermBase->titleCache)) {
1193
    return $definedTermBase->titleCache;
1194
  }
1195
  return '';
1196
}
1197

    
1198
/**
1199
 * @todo Improve documentation of this function.
1200
 *
1201
 * eu.etaxonomy.cdm.model.description.
1202
 * CategoricalData
1203
 * CommonTaxonName
1204
 * Distribution
1205
 * IndividualsAssociation
1206
 * QuantitativeData
1207
 * TaxonInteraction
1208
 * TextData
1209
 */
1210
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1211
  static $types = array(
1212
    "CategoricalData",
1213
    "CommonTaxonName",
1214
    "Distribution",
1215
    "IndividualsAssociation",
1216
    "QuantitativeData",
1217
    "TaxonInteraction",
1218
    "TextData",
1219
  );
1220

    
1221
  static $options = NULL;
1222
  if ($options == NULL) {
1223
    $options = array();
1224
    if ($prependEmptyElement) {
1225
      $options[' '] = '';
1226
    }
1227
    foreach ($types as $type) {
1228
      // No internatianalization here since these are purely technical terms.
1229
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1230
    }
1231
  }
1232
  return $options;
1233
}
1234

    
1235
/**
1236
 * @todo Please document this function.
1237
 * @see http://drupal.org/node/1354
1238
 */
1239
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1240
  static $vocabularyOptions = array();
1241

    
1242
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1243
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1244
    $vocabularyOptions[$vocabularyUuid] = array();
1245

    
1246
    if ($vocab) {
1247
      foreach ($vocab->terms as $term) {
1248
        if ($term_label_callback && function_exists($term_label_callback)) {
1249
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1250
        }
1251
        else {
1252
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1253
        }
1254
      }
1255
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1256
    }
1257
  }
1258
  return $vocabularyOptions[$vocabularyUuid];
1259
}
1260

    
1261
/**
1262
 * @todo Please document this function.
1263
 * @see http://drupal.org/node/1354
1264
 */
1265
function _cdm_relationship_type_term_label_callback($term) {
1266
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1267
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1268
  }
1269
  else {
1270
    return t($term->representation_L10n);
1271
  }
1272
}
1273

    
1274
/**
1275
 * Fetches all TaxonDescription descriptions elements wich are accociated to the
1276
 * Taxon specified by the $taxon_uuid and megres the elements into the given
1277
 * feature tree.
1278
 * @param $feature_tree
1279
 *     The CDM FeatureTree to be used as template
1280
 * @param $taxon_uuid
1281
 *     The UUID of the taxon
1282
 * @return$feature_tree
1283
 *     The CDM FeatureTree wich was given as parameter merged tree wheras the
1284
 *     CDM FeatureNodes are extended by an additinal field 'descriptionElements'
1285
 *     witch will hold the accoding $descriptionElements.
1286
 */
1287
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid) {
1288

    
1289
  if (!$feature_tree) {
1290
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1291
      In order to see the species profiles of your taxa, please select a
1292
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1293
    return FALSE;
1294
  }
1295

    
1296
  $merged_trees = array();
1297

    
1298
  $description_elemens = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON . '?' . queryString(
1299
      array(
1300
      'taxon' => $taxon_uuid,
1301
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid')
1302
      )
1303
    )
1304
  );
1305

    
1306
  // Combine all descripions into one feature tree.
1307
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->children, $description_elemens);
1308
  $feature_tree->root->children = $merged_nodes;
1309

    
1310
  return $feature_tree;
1311
}
1312

    
1313
/**
1314
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1315
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1316
 * be requested for the annotations.
1317
 *
1318
 * @param string $cdmBase
1319
 *   An annotatable cdm entity.
1320
 * @param array $includeTypes
1321
 *   If an array of annotation type uuids is supplied by this parameter the
1322
 *   list of annotations is resticted to those which belong to this type.
1323
 *
1324
 * @return array
1325
 *   An array of Annotation objects or an empty array.
1326
 */
1327
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1328

    
1329
  if(!isset($cdmBase->annotations)){
1330
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1331
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, TRUE);
1332
  }
1333

    
1334
  $annotations = array();
1335
  foreach ($cdmBase->annotations as $annotation) {
1336
    if ($includeTypes) {
1337
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1338
        $annotations[] = $annotation;
1339
      }
1340
    }
1341
    else {
1342
      $annotations[] = $annotation;
1343
    }
1344
  }
1345
  return $annotations;
1346

    
1347
}
1348

    
1349
/**
1350
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1351
 *
1352
 * @param object $annotatable_entity
1353
 *   The CDM AnnotatableEntity to load annotations for
1354
 */
1355
function cdm_load_annotations(&$annotatable_entity) {
1356
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1357
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1358
    if (is_array($annotations)) {
1359
      $annotatable_entity->annotations = $annotations;
1360
    }
1361
  }
1362
}
1363

    
1364
/**
1365
 * Get a NomenclaturalReference string.
1366
 *
1367
 * Returns the NomenclaturalReference string with correctly placed
1368
 * microreference (= reference detail) e.g.
1369
 * in Phytotaxa 43: 1-48. 2012.
1370
 *
1371
 * @param string $referenceUuid
1372
 *   UUID of the reference.
1373
 * @param string $microreference
1374
 *   Reference detail.
1375
 *
1376
 * @return string
1377
 *   a NomenclaturalReference.
1378
 */
1379
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1380
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1381
    $referenceUuid,
1382
  ), "microReference=" . urlencode($microreference));
1383

    
1384
  if ($obj) {
1385
    return $obj->String;
1386
  }
1387
  else {
1388
    return NULL;
1389
  }
1390
}
1391

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

    
1416
  foreach ($featureNodes as &$node) {
1417
    // since the $featureNodes array is reused for each description
1418
    // it is nessecary to clear the custom node fields in advance
1419
    if(isset($node->descriptionElements)){
1420
      unset($node->descriptionElements);
1421
    }
1422

    
1423
    // Append corresponding elements to an additional node field:
1424
    // $node->descriptionElements.
1425
    foreach ($descriptionElements as $element) {
1426
      if ($element->feature->uuid == $node->feature->uuid) {
1427
        if (!isset($node->descriptionElements)) {
1428
          $node->descriptionElements = array();
1429
        }
1430
        $node->descriptionElements[] = $element;
1431
      }
1432
    }
1433

    
1434
    // Recurse into node children.
1435
    if (isset($node->children[0])) {
1436
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1437
      $node->children = $mergedChildNodes;
1438
    }
1439

    
1440
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1441
      unset($node);
1442
    }
1443

    
1444
  }
1445

    
1446
  return $featureNodes;
1447
}
1448

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

    
1485
  static $cacheL1 = array();
1486

    
1487
  // Transform the given uri path or pattern into a proper webservice uri.
1488
  if (!$absoluteURI) {
1489
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1490
  }
1491

    
1492
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1493
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1494

    
1495
  if (array_key_exists($uri, $cacheL1)) {
1496
    $cacheL1_obj = $cacheL1[$uri];
1497
  }
1498

    
1499
  $set_cacheL1 = FALSE;
1500
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1501
    $set_cacheL1 = TRUE;
1502
  }
1503

    
1504
  // Only cache cdm webservice URIs.
1505
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1506
  $cacheL2_entry = FALSE;
1507

    
1508
  if ($use_cacheL2) {
1509
    // Try to get object from cacheL2.
1510
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1511
  }
1512

    
1513
  if (isset($cacheL1_obj)) {
1514
    //
1515
    // The object has been found in the L1 cache.
1516
    //
1517
    $obj = $cacheL1_obj;
1518
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1519
      cdm_ws_debug_add($uri, 0, 0, NULL, 'cacheL1');
1520
    }
1521
  }
1522
  elseif ($cacheL2_entry) {
1523
    //
1524
    // The object has been found in the L2 cache.
1525
    //
1526
    $duration_parse_start = microtime(TRUE);
1527
    $obj = unserialize($cacheL2_entry->data);
1528
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1529

    
1530
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1531
      cdm_ws_debug_add($uri, 0, $duration_parse, NULL, 'cacheL2');
1532
    }
1533
  }
1534
  else {
1535
    //
1536
    // Get the object from the webservice and cache it.
1537
    //
1538
    $duration_fetch_start = microtime(TRUE);
1539
    // Request data from webservice JSON or XML.
1540
    $response = cdm_http_request($uri, $method);
1541
    $datastr = NULL;
1542
    if (isset($response->data)) {
1543
      $datastr = $response->data;
1544
    }
1545
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1546
    $duration_parse_start = microtime(TRUE);
1547

    
1548
    // Parse data and create object.
1549
    $obj = cdm_load_obj($datastr);
1550

    
1551
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1552
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1553
      if ($obj || $datastr == "[]") {
1554
        $status = 'valid';
1555
      }
1556
      else {
1557
        $status = 'invalid';
1558
      }
1559
      cdm_ws_debug_add($uri, $duration_fetch, $duration_parse, strlen($datastr), $status);
1560
    }
1561
    if ($set_cacheL2) {
1562
      // Store the object in cache L2.
1563
      // Comment @WA perhaps better if Drupal serializes here? Then the
1564
      // flag serialized is set properly in the cache table.
1565
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1566
    }
1567
  }
1568
  if ($obj) {
1569
    // Store the object in cache L1.
1570
    if ($set_cacheL1) {
1571
      $cacheL1[$uri] = $obj;
1572
    }
1573
  }
1574
  return $obj;
1575
}
1576

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

    
1597
  static $initial_time = NULL;
1598
  if(!$initial_time) {
1599
    $initial_time = microtime(TRUE);
1600
  }
1601
  $time = microtime(TRUE) - $initial_time;
1602

    
1603
  // Decompose uri into path and query element.
1604
  $uri_parts = explode("?", $uri);
1605
  $query = array();
1606
  if (count($uri_parts) == 2) {
1607
    $path = $uri_parts[0];
1608
  }
1609
  else {
1610
    $path = $uri;
1611
  }
1612

    
1613
  if(strpos($uri, '?') > 0){
1614
    $json_uri = str_replace('?', '.json?', $uri);
1615
    $xml_uri = str_replace('?', '.xml?', $uri);
1616
  } else {
1617
    $json_uri = $uri . '.json';
1618
    $xml_uri = $json_uri . '.xml';
1619
  }
1620

    
1621
  // data links to make data accecsible as json and xml
1622
  $data_links = '';
1623
  if (_is_cdm_ws_uri($path)) {
1624
    $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1625
    $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1626
    $data_links .= '<br/>';
1627
    $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1628
    $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1629
  }
1630
  else {
1631
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1632
  }
1633

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

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

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

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

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

    
1671
  return $obj;
1672
}
1673

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

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

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

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

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

    
1740
/**
1741
 * Concatenates recursively the fields of all features contained in the given
1742
 * CDM FeatureTree root node.
1743
 *
1744
 * @param $rootNode
1745
 *     A CDM FeatureTree node
1746
 * @param
1747
 *     The character to be used as glue for concatenation, default is ', '
1748
 * @param $field_name
1749
 *     The field name of the CDM Features
1750
 */
1751
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n') {
1752
  $out = '';
1753

    
1754
  $pre_child_separator = $separator;
1755
  $post_child_separator = '';
1756

    
1757
  foreach ($root_node->children as $feature_node) {
1758
    $out .= ($out ? $separator : '');
1759
    $out .= $feature_node->feature->$field_name;
1760
    if (is_array($feature_node->children)) {
1761
      $childlabels = '';
1762
      foreach ($feature_node->children as $child_node) {
1763
        $childlabels .= ($childlabels ? $separator : '');
1764
        $childlabels .= cdm_featureTree_elements_toString($child_node, $separator, $field_name);
1765
      }
1766
      if (strlen($childlabels)) {
1767
        $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1768
      }
1769
    }
1770
  }
1771
  return $out;
1772
}
1773

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

    
1808
/**
1809
 * Returns an array with all available FeatureTrees and the representations of the selected
1810
 * FeatureTree as a detail view.
1811
 *
1812
 * @param boolean $add_default_feature_free
1813
 * @return array
1814
 *  associative array with following keys:
1815
 *  -options: Returns an array with all available Feature Trees
1816
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1817
 *
1818
 */
1819
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1820

    
1821
  $options = array();
1822
  $tree_representations = array();
1823
  $feature_trees = array();
1824

    
1825
  // Set tree that contains all features.
1826
  if ($add_default_feature_free) {
1827
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1828
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1829
  }
1830

    
1831
  // Get feature trees from database.
1832
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1833
  if (is_array($persited_trees)) {
1834
    $feature_trees = array_merge($feature_trees, $persited_trees);
1835
  }
1836

    
1837
  foreach ($feature_trees as $featureTree) {
1838

    
1839
    // Do not add the DEFAULT_FEATURETREE again,
1840
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1841
      $options[$featureTree->uuid] = $featureTree->titleCache;
1842
    }
1843

    
1844
    // Render the hierarchic tree structure
1845
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1846

    
1847
      // Render the hierarchic tree structure.
1848
      $treeDetails = '<div class="featuretree_structure">'
1849
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1850
        . '</div>';
1851

    
1852
      $form = array();
1853
      $form['featureTree-' .  $featureTree->uuid] = array(
1854
        '#type' => 'fieldset',
1855
        '#title' => 'Show details',
1856
        '#attributes' => array('class' => array('collapsible collapsed')),
1857
        // '#collapsible' => TRUE,
1858
        // '#collapsed' => TRUE,
1859
      );
1860
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1861
        '#markup' => $treeDetails,
1862
      );
1863

    
1864
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1865
    }
1866

    
1867
  } // END loop over feature trees
1868

    
1869
  // return $options;
1870
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1871
}
1872

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

    
1891
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1892

    
1893
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1894
  $default_classification_label = '';
1895

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

    
1917
  // now set the labels
1918
  //   for none
1919
  if ($add_none_option) {
1920
    $taxonomic_tree_options['NONE'] = t('-- None --');
1921
  }
1922

    
1923
  //   for default_classification
1924
  if (is_uuid($default_classification_uuid)) {
1925
    $taxonomic_tree_options[$default_classification_uuid] =
1926
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1927
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1928
  }
1929

    
1930
  return $taxonomic_tree_options;
1931
}
1932

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

    
1959
/**
1960
 * @todo Please document this function.
1961
 * @see http://drupal.org/node/1354
1962
 */
1963
function cdm_api_secref_cache_get($secUuid) {
1964
  global $_cdm_api_secref_cache;
1965
  if (!is_array($_cdm_api_secref_cache)) {
1966
    $_cdm_api_secref_cache = array();
1967
  }
1968
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1969
    _cdm_api_secref_cache_add($secUuid);
1970
  }
1971
  return $_cdm_api_secref_cache[$secUuid];
1972
}
1973

    
1974
/**
1975
 * @todo Please document this function.
1976
 * @see http://drupal.org/node/1354
1977
 */
1978
function cdm_api_secref_cache_clear() {
1979
  global $_cdm_api_secref_cache;
1980
  $_cdm_api_secref_cache = array();
1981
}
1982

    
1983
/**
1984
 * Validates if the given string is a uuid.
1985
 *
1986
 * @param string $str
1987
 *   The string to validate.
1988
 *
1989
 * return bool
1990
 *   TRUE if the string is a UUID.
1991
 */
1992
function is_uuid($str) {
1993
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1994
}
1995

    
1996
/**
1997
 * Checks if the given $object is a valid cdm entity.
1998
 *
1999
 * An object is considered a cdm entity if it has a string field $object->class
2000
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2001
 *
2002
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2003
 *
2004
 * @param mixed $object
2005
 *   The object to validate
2006
 *
2007
 * @return bool
2008
 *   True if the object is a cdm entity.
2009
 */
2010
function is_cdm_entity($object) {
2011
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2012
}
2013

    
2014
/**
2015
 * @todo Please document this function.
2016
 * @see http://drupal.org/node/1354
2017
 */
2018
function _cdm_api_secref_cache_add($secUuidsStr) {
2019
  global $_cdm_api_secref_cache;
2020
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2021
  // Batch fetching not jet reimplemented thus:
2022
  /*
2023
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2024
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2025
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2026
  */
2027
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2028
}
2029

    
2030
/**
2031
 * Checks if the given uri starts with a cdm webservice url.
2032
 *
2033
 * Checks if the uri starts with the cdm webservice url stored in the
2034
 * Drupal variable 'cdm_webservice_url'.
2035
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2036
 *
2037
 * @param string $uri
2038
 *   The URI to test.
2039
 *
2040
 * @return bool
2041
 *   True if the uri starts with a cdm webservice url.
2042
 */
2043
function _is_cdm_ws_uri($uri) {
2044
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2045
}
2046

    
2047
/**
2048
 * @todo Please document this function.
2049
 * @see http://drupal.org/node/1354
2050
 */
2051
function queryString($elements) {
2052
  $query = '';
2053
  foreach ($elements as $key => $value) {
2054
    if (is_array($value)) {
2055
      foreach ($value as $v) {
2056
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2057
      }
2058
    }
2059
    else {
2060
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2061
    }
2062
  }
2063
  return $query;
2064
}
2065

    
2066
/**
2067
 * Implementation of the magic method __clone to allow deep cloning of objects
2068
 * and arrays.
2069
 */
2070
function __clone() {
2071
  foreach ($this as $name => $value) {
2072
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2073
      $this->$name = clone($this->$name);
2074
    }
2075
  }
2076
}
2077

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

    
2112
/**
2113
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2114
 *
2115
 */
2116
function _add_js_ws_debug() {
2117

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

    
2125
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/jquery.colorbox-min.js',
2126
    array(
2127
      'type' => 'file',
2128
      'weight' => JS_LIBRARY,
2129
      'cache' => TRUE)
2130
    );
2131
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2132
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2133

    
2134
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2135
    array(
2136
      'type' => 'file',
2137
      'weight' => JS_LIBRARY,
2138
      'cache' => TRUE)
2139
    );
2140

    
2141
}
2142

    
2143
/**
2144
 * @todo Please document this function.
2145
 * @see http://drupal.org/node/1354
2146
 */
2147
function _no_classfication_uuid_message() {
2148
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2149
    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.');
2150
  }
2151
  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.');
2152
}
2153

    
2154
/**
2155
 * Implementation of hook flush_caches
2156
 *
2157
 * Add custom cache tables to the list of cache tables that
2158
 * will be cleared by the Clear button on the Performance page or whenever
2159
 * drupal_flush_all_caches is invoked.
2160
 *
2161
 * @author W.Addink <waddink@eti.uva.nl>
2162
 *
2163
 * @return array
2164
 *   An array with custom cache tables to include.
2165
 */
2166
function cdm_api_flush_caches() {
2167
  return array('cache_cdm_ws');
2168
}
(4-4/9)