Project

General

Profile

Download (62.7 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
    $field_map = array(
86
        'ws_uri' => t('URI'),
87
        'time' => t('Time'),
88
        'fetch_seconds' => t('Fetching [s]'),
89
        'parse_seconds' => t('Parsing [s]'),
90
        'size_kb' => t('Size [kb]'),
91
        'status' => t('Status'),
92
        'data_links' =>  t('Links'),
93
    );
94

    
95

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

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

    
104
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
105
      $cells = array();
106
      $data = unserialize($data);
107
      foreach ($field_map as $field => $label){
108
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
109
      }
110
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
111
    }
112
    // clear session again
113
    $_SESSION['cdm']['ws_debug'] = array();
114

    
115
    _add_js_ws_debug();
116

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

    
128
    return $block;
129
  }
130
}
131

    
132
/**
133
 * Implements hook_cron().
134
 *
135
 * Expire outdated cache entries.
136
 */
137
function cdm_api_cron() {
138
  cache_clear_all(NULL, 'cache_cdm_ws');
139
}
140

    
141
/**
142
 * @todo Please document this function.
143
 * @see http://drupal.org/node/1354
144
 */
145
function cdm_api_permission() {
146
  return array(
147
    'administer cdm_api' => array(
148
      'title' => t('administer cdm_api'),
149
      'description' => t("TODO Add a description for 'administer cdm_api'"),
150
    ),
151
  );
152
}
153

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

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

    
207
/**
208
 * Returns the currently classification tree in use.
209
 */
210
function get_taxonomictree_uuid_selected() {
211
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
212
    return $_SESSION['cdm']['taxonomictree_uuid'];
213
  }
214
  else {
215
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
216
  }
217
}
218

    
219
/**
220
 * Lists the classifications a taxon belongs to
221
 *
222
 * @param CDM type Taxon $taxon
223
 *   the taxon
224
 *
225
 * @return array
226
 *   aray of CDM instances of Type Classification
227
 */
228
function get_classifications_for_taxon($taxon) {
229

    
230
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
231
}
232

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

    
247
  if($profile_featureTree == NULL) {
248
    $profile_featureTree = cdm_ws_get(
249
      CDM_WS_FEATURETREE,
250
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
251
    );
252
    if (!$profile_featureTree) {
253
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
254
    }
255
  }
256
  return $profile_featureTree;
257
}
258

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

    
273
  if($occurrence_featureTree == NULL) {
274
    $occurrence_featureTree = cdm_ws_get(
275
      CDM_WS_FEATURETREE,
276
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
277
    );
278
    if (!$occurrence_featureTree) {
279
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
280
    }
281
  }
282
  return $occurrence_featureTree;
283
}
284

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

    
299
  if($structured_description_featureTree == NULL) {
300
    $structured_description_featureTree = cdm_ws_get(
301
        CDM_WS_FEATURETREE,
302
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
303
    );
304
    if (!$structured_description_featureTree) {
305
      $structured_description_featureTree = cdm_ws_get(
306
          CDM_WS_FEATURETREE,
307
          UUID_DEFAULT_FEATURETREE
308
      );
309
    }
310
  }
311
  return $structured_description_featureTree;
312
}
313

    
314
/**
315
 * @todo Please document this function.
316
 * @see http://drupal.org/node/1354
317
 */
318
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
319
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
320
}
321

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

    
330
/**
331
 * @todo Please document this function.
332
 * @see http://drupal.org/node/1354
333
 */
334
function set_last_taxon_page_tab($taxonPageTab) {
335
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
336
}
337

    
338
/**
339
 * @todo Please document this function.
340
 * @see http://drupal.org/node/1354
341
 */
342
function get_last_taxon_page_tab() {
343
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
344
    return $_SESSION['cdm']['taxon_page_tab'];
345
  }
346
  else {
347
    return FALSE;
348
  }
349
}
350

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

    
384
  while (count($mimeTypes) > 0) {
385
    // getRepresentationByMimeType
386
    $mimeType = array_shift($mimeTypes);
387

    
388
    foreach ($media->representations as &$representation) {
389
      // If the mimetype is not known, try inferring it.
390
      if (!$representation->mimeType) {
391
        if (isset($representation->parts[0])) {
392
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
393
        }
394
      }
395

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

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

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

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

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

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

    
554
  $y = $y ? $y : '00';
555
  $m = $m ? $m : '00';
556
  $d = $d ? $d : '00';
557

    
558
  $date = '';
559

    
560
  if ($y == '00' && $stripZeros) {
561
    return;
562
  }
563
  else {
564
    $date = $y;
565
  }
566

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

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

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

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

    
653
  $request_params = '';
654
  $path_params = '';
655

    
656
  // (1)
657
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
658
  // according element of the $pathParameters array.
659
  static $helperArray = array();
660
  if (isset($pathParameters) && !is_array($pathParameters)) {
661
    $helperArray[0] = $pathParameters;
662
    $pathParameters = $helperArray;
663
  }
664

    
665
  $i = 0;
666
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
667
    if (count($pathParameters) <= $i) {
668
      if (module_exists("user") && user_access('administer')) {
669
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
670
      }
671
      break;
672
    }
673
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
674
    ++$i;
675
  }
676

    
677
  // (2)
678
  // Append all remaining element of the $pathParameters array as path
679
  // elements.
680
  if (count($pathParameters) > $i) {
681
    // Strip trailing slashes.
682
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
683
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
684
    }
685
    while (count($pathParameters) > $i) {
686
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
687
      ++$i;
688
    }
689
  }
690

    
691
  // (3)
692
  // Append the query string supplied by $query.
693
  if (isset($query)) {
694
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
695
  }
696

    
697
  $path = $uri_pattern;
698

    
699
  $uri = variable_get('cdm_webservice_url', '') . $path;
700
  return $uri;
701
}
702

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

    
727
  // Find and deserialize arrays.
728
  foreach ($args as &$arg) {
729
    // FIXME use regex to find serialized arrays.
730
    //       or should we accept json instead pf php serializations?
731
    if (strpos($arg, "a:") === 0) {
732
      $arg = unserialize($arg);
733
    }
734
  }
735

    
736
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
737
  if ($request_method == "POST") {
738
    // this is an experimental feature which will allow to
739
    // write data inot the cdm via the RESTfull web service
740
    $parameters = $_POST;
741
    $post_data = array();
742

    
743
    foreach ($parameters as $k => $v) {
744
      $post_data[] = "$k=" . utf8_encode($v);
745
    }
746
    $post_data = implode(',', $post_data);
747

    
748
    // For testing.
749
    // TODO use cdm_http_request(..) instead; ( CDM_HTTP_REQUEST_TIMEOUT is already set in there )
750
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
751
    // print $data;
752
  } else {
753
    // Not a "POST" request
754
    // In all these cases perform a simple get request.
755
    // TODO reconsider caching logic in this function.
756

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

    
776
      // do a security check since the $uri will be passed
777
      // as absolute URI to cdm_ws_get()
778
      if( !_is_cdm_ws_uri($uri)) {
779
        drupal_set_message(
780
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
781
            'error'
782
        );
783
        return '';
784
      }
785

    
786
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
787

    
788
      $reponse_data = NULL;
789

    
790
      if (function_exists('compose_' . $hook)){
791
        // call compose hook
792

    
793
        $elements =  call_user_func('compose_' . $hook, $obj);
794
        // pass the render array to drupal_render()
795
        $reponse_data = drupal_render($elements);
796
      } else {
797
        // call theme hook
798

    
799
        // TODO use theme registry to get the registered hook info and
800
        //    use these defaults
801
        switch($hook) {
802
          case 'cdm_taxontree':
803
            $variables = array(
804
              'tree' => $obj,
805
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
806
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
807
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
808
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
809
            );
810
            $reponse_data = theme($hook, $variables);
811
            break;
812

    
813
          case 'cdm_media_caption':
814
            $variables = array(
815
              'media' => $obj,
816
              // $args[0] is set in taxon_image_gallery_default in
817
              // cdm_dataportal.page.theme.
818
              'elements' => isset($args[0]) ? $args[0] : array(
819
                'title',
820
                'description',
821
                'artist',
822
                'location',
823
                'rights',
824
              ),
825
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
826
            );
827
            $reponse_data = theme($hook, $variables);
828
            break;
829

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

    
850
/**
851
 * @todo Please document this function.
852
 * @see http://drupal.org/node/1354
853
 */
854
function setvalue_session() {
855
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
856
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
857
    $keys = explode('][', $keys);
858
  }
859
  else {
860
    return;
861
  }
862
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
863

    
864
  // Prevent from malicous tags.
865
  $val = strip_tags($val);
866

    
867
  $var = &$_SESSION;
868
  $i = 0;
869
  foreach ($keys as $key) {
870
    $hasMoreKeys = ++$i < count($var);
871
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
872
      $var[$key] = array();
873
    }
874
    $var = &$var[$key];
875
  }
876
  $var = $val;
877
  if (isset($_REQUEST['destination'])) {
878
    drupal_goto($_REQUEST['destination']);
879
  }
880
}
881

    
882
/**
883
 * @todo Please document this function.
884
 * @see http://drupal.org/node/1354
885
 */
886
function uri_uriByProxy($uri, $theme = FALSE) {
887
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
888
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
889
}
890

    
891
/**
892
 * @todo Please document this function.
893
 * @see http://drupal.org/node/1354
894
 */
895
function cdm_compose_annotations_url($cdmBase) {
896
  if (!$cdmBase->uuid) {
897
    return;
898
  }
899

    
900
  $ws_base_uri = NULL;
901
  switch ($cdmBase->class) {
902
    case 'TaxonBase':
903
    case 'Taxon':
904
    case 'Synonym':
905
      $ws_base_uri = CDM_WS_TAXON;
906
      break;
907

    
908
    case 'TaxonNameBase':
909
    case 'NonViralName':
910
    case 'BacterialName':
911
    case 'BotanicalName':
912
    case 'CultivarPlantName':
913
    case 'ZoologicalName':
914
    case 'ViralName':
915
      $ws_base_uri = CDM_WS_NAME;
916
      break;
917

    
918
    case 'Media':
919
      $ws_base_uri = CDM_WS_MEDIA;
920
      break;
921

    
922
    case 'Reference':
923
      $ws_base_uri = CDM_WS_REFERENCE;
924
      break;
925

    
926
    case 'Distribution':
927
    case 'TextData':
928
    case 'TaxonInteraction':
929
    case 'QuantitativeData':
930
    case 'IndividualsAssociation':
931
    case 'Distribution':
932
    case 'CommonTaxonName':
933
    case 'CategoricalData':
934
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
935
      break;
936

    
937
    case 'PolytomousKey':
938
    case 'MediaKey':
939
    case 'MultiAccessKey':
940
      $ws_base_uri = $cdmBase->class;
941
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
942
      break;
943

    
944
    default:
945
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
946
      return;
947
  }
948
  return cdm_compose_url($ws_base_uri, array(
949
    $cdmBase->uuid,
950
    'annotations',
951
  ));
952
}
953

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

    
977
/**
978
 * Fetches all entities from the given REST endpoint using the pager mechanism.
979
 *
980
 * @param string $resourceURI
981
 *
982
 * @return array
983
 *     A list of CDM entitites
984
 *
985
 */
986
function cdm_ws_fetch_all($resourceURI) {
987
  $page_index = 0;
988
  // using a bigger page size to avoid to many multiple requests
989
  $page_size = 200;
990
  $entities = array();
991

    
992
  while ($page_index !== FALSE){
993
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index);
994
    if(isset($pager->records) && is_array($pager->records)) {
995
      $entities = $pager->records;
996
      if(!empty($pager->nextIndex)){
997
        $page_index = $pager->nextIndex;
998
      } else {
999
        $page_index = FALSE;
1000
      }
1001
    } else {
1002
      $page_index = FALSE;
1003
    }
1004
  }
1005
  return $entities;
1006
}
1007

    
1008
/*
1009
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1010
  $viewrank = _cdm_taxonomy_compose_viewrank();
1011
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1012
  ? '/' . $path : '') ;
1013
}
1014
*/
1015

    
1016
/**
1017
 * @todo Enter description here...
1018
 *
1019
 * @param string $taxon_uuid
1020
 *  The UUID of a cdm taxon instance
1021
 * @param string $ignore_rank_limit
1022
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1023
 *
1024
 * @return A cdm REST service URL path to a Classification
1025
 */
1026
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1027

    
1028
  $view_uuid = get_taxonomictree_uuid_selected();
1029
  $rank_uuid = NULL;
1030
  if (!$ignore_rank_limit) {
1031
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1032
  }
1033

    
1034
  if (!empty($taxon_uuid)) {
1035
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1036
      $view_uuid,
1037
      $taxon_uuid,
1038
    ));
1039
  }
1040
  else {
1041
    if (!empty($rank_uuid)) {
1042
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1043
        $view_uuid,
1044
        $rank_uuid,
1045
      ));
1046
    }
1047
    else {
1048
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1049
        $view_uuid,
1050
      ));
1051
    }
1052
  }
1053
}
1054

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

    
1076
    $response = NULL;
1077

    
1078
    // 1st try
1079
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
1080

    
1081
    if ($response == NULL) {
1082
      // 2dn try by ignoring the rank limit
1083
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
1084
    }
1085

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

    
1104
  return $response;
1105
}
1106

    
1107
/**
1108
 * @todo Enter description here...
1109
 *
1110
 * @param string $taxon_uuid
1111
 *
1112
 * @return unknown
1113
 */
1114
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1115
  $view_uuid = get_taxonomictree_uuid_selected();
1116
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1117

    
1118
  $response = NULL;
1119
  if ($rank_uuid) {
1120
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1121
      $view_uuid,
1122
      $taxon_uuid,
1123
      $rank_uuid,
1124
    ));
1125
  }
1126
  else {
1127
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1128
      $view_uuid,
1129
      $taxon_uuid,
1130
    ));
1131
  }
1132

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

    
1150
  return $response;
1151
}
1152

    
1153
/**
1154
 * @todo Please document this function.
1155
 * @see http://drupal.org/node/1354
1156
 */
1157
function cdm_rankVocabulary_as_option() {
1158
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1159
  array_unshift ($options, "");
1160
  return $options;
1161
}
1162

    
1163
/**
1164
 *
1165
 * @param Object $definedTermBase
1166
 * 	  of cdm type DefinedTermBase
1167
 * @return string
1168
 * 	  the localized representation_L10n of the term,
1169
 *    otherwise the titleCache as fall back,
1170
 *    otherwise an empty string
1171
 */
1172
function cdm_term_representation($definedTermBase) {
1173
  if ( isset($definedTermBase->representation_L10n) ) {
1174
    return $definedTermBase->representation_L10n;
1175
  } elseif ( isset($definedTermBase->titleCache)) {
1176
    return $definedTermBase->titleCache;
1177
  }
1178
  return '';
1179
}
1180

    
1181
/**
1182
 * @todo Improve documentation of this function.
1183
 *
1184
 * eu.etaxonomy.cdm.model.description.
1185
 * CategoricalData
1186
 * CommonTaxonName
1187
 * Distribution
1188
 * IndividualsAssociation
1189
 * QuantitativeData
1190
 * TaxonInteraction
1191
 * TextData
1192
 */
1193
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1194
  static $types = array(
1195
    "CategoricalData",
1196
    "CommonTaxonName",
1197
    "Distribution",
1198
    "IndividualsAssociation",
1199
    "QuantitativeData",
1200
    "TaxonInteraction",
1201
    "TextData",
1202
  );
1203

    
1204
  static $options = NULL;
1205
  if ($options == NULL) {
1206
    $options = array();
1207
    if ($prependEmptyElement) {
1208
      $options[' '] = '';
1209
    }
1210
    foreach ($types as $type) {
1211
      // No internatianalization here since these are purely technical terms.
1212
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1213
    }
1214
  }
1215
  return $options;
1216
}
1217

    
1218
/**
1219
 * @todo Please document this function.
1220
 * @see http://drupal.org/node/1354
1221
 */
1222
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1223
  static $vocabularyOptions = array();
1224

    
1225
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1226
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1227
    $vocabularyOptions[$vocabularyUuid] = array();
1228

    
1229
    if ($vocab) {
1230
      foreach ($vocab->terms as $term) {
1231
        if ($term_label_callback && function_exists($term_label_callback)) {
1232
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1233
        }
1234
        else {
1235
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1236
        }
1237
      }
1238
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1239
    }
1240
  }
1241
  return $vocabularyOptions[$vocabularyUuid];
1242
}
1243

    
1244
/**
1245
 * @todo Please document this function.
1246
 * @see http://drupal.org/node/1354
1247
 */
1248
function _cdm_relationship_type_term_label_callback($term) {
1249
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1250
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1251
  }
1252
  else {
1253
    return t($term->representation_L10n);
1254
  }
1255
}
1256

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

    
1269
  $mergedTrees = array();
1270

    
1271
  if ($isDescriptionsSeparated) {
1272
    // Merge any description into a separate feature tree.
1273
    foreach ($descriptions as $desc) {
1274
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1275

    
1276
      $mergedTree = clone $featureTree;
1277
      $mergedTree->root->children = $mergedNodes;
1278
      $mergedTrees[] = $mergedTree;
1279
    }
1280
  }
1281
  else {
1282
    // Combine all descripions into one feature tree.
1283
    $descriptionElemens = array();
1284
    foreach ($descriptions as $desc) {
1285
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1286
    }
1287
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1288
    $featureTree->root->children = $mergedNodes;
1289
    $mergedTrees[] = $featureTree;
1290
  }
1291

    
1292
  return $mergedTrees;
1293
}
1294

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

    
1311
  if(!isset($cdmBase->annotations)){
1312
    $annotationUrl = cdm_compose_annotations_url($cdmBase);
1313
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl);
1314
  }
1315

    
1316
  $annotations = array();
1317
  foreach ($cdmBase->annotations as $annotation) {
1318
    if ($includeTypes) {
1319
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1320
        $annotations[] = $annotation;
1321
      }
1322
    }
1323
    else {
1324
      $annotations[] = $annotation;
1325
    }
1326
  }
1327
  return $annotations;
1328

    
1329
}
1330

    
1331
/**
1332
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1333
 *
1334
 * @param object $annotatable_entity
1335
 *   The CDM AnnotatableEntity to load annotations for
1336
 */
1337
function cdm_load_annotations(&$annotatable_entity) {
1338
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1339
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1340
    if (is_array($annotations)) {
1341
      $annotatable_entity->annotations = $annotations;
1342
    }
1343
  }
1344
}
1345

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

    
1366
  if ($obj) {
1367
    return $obj->String;
1368
  }
1369
  else {
1370
    return NULL;
1371
  }
1372
}
1373

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

    
1398
  foreach ($featureNodes as &$node) {
1399
    // since the $featureNodes array is reused for each description
1400
    // it is nessecary to clear the custom node fields in advance
1401
    if(isset($node->descriptionElements)){
1402
      unset($node->descriptionElements);
1403
    }
1404

    
1405
    // Append corresponding elements to an additional node field:
1406
    // $node->descriptionElements.
1407
    foreach ($descriptionElements as $element) {
1408
      if ($element->feature->uuid == $node->feature->uuid) {
1409
        if (!isset($node->descriptionElements)) {
1410
          $node->descriptionElements = array();
1411
        }
1412
        $node->descriptionElements[] = $element;
1413
      }
1414
    }
1415

    
1416
    // Recurse into node children.
1417
    if (isset($node->children[0])) {
1418
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1419
      $node->children = $mergedChildNodes;
1420
    }
1421

    
1422
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1423
      unset($node);
1424
    }
1425

    
1426
  }
1427

    
1428
  return $featureNodes;
1429
}
1430

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

    
1467
  static $cacheL1 = array();
1468

    
1469
  // Transform the given uri path or pattern into a proper webservice uri.
1470
  if (!$absoluteURI) {
1471
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1472
  }
1473

    
1474
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1475
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1476

    
1477
  if (array_key_exists($uri, $cacheL1)) {
1478
    $cacheL1_obj = $cacheL1[$uri];
1479
  }
1480

    
1481
  $set_cacheL1 = FALSE;
1482
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1483
    $set_cacheL1 = TRUE;
1484
  }
1485

    
1486
  // Only cache cdm webservice URIs.
1487
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1488
  $cacheL2_entry = FALSE;
1489

    
1490
  if ($use_cacheL2) {
1491
    // Try to get object from cacheL2.
1492
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1493
  }
1494

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

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

    
1530
    // Parse data and create object.
1531
    $obj = cdm_load_obj($datastr);
1532

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

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

    
1579
  static $initial_time = NULL;
1580
  if(!$initial_time) {
1581
    $initial_time = microtime(TRUE);
1582
  }
1583
  $time = microtime(TRUE) - $initial_time;
1584

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

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

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

    
1643
  // Mark this page as being uncacheable.
1644
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1645
  drupal_page_is_cacheable(FALSE);
1646

    
1647
  // Messages not set when DB connection fails.
1648
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1649
}
1650

    
1651
/**
1652
 * @todo Please document this function.
1653
 * @see http://drupal.org/node/1354
1654
 */
1655
function cdm_load_obj($datastr) {
1656
  $obj = json_decode($datastr);
1657

    
1658
  if (!(is_object($obj) || is_array($obj))) {
1659
    ob_start();
1660
    $obj_dump = ob_get_contents();
1661
    ob_clean();
1662
    return FALSE;
1663
  }
1664

    
1665
  return $obj;
1666
}
1667

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

    
1703
  if (!$acceptLanguage) {
1704
    if (function_exists('apache_request_headers')) {
1705
      $headers = apache_request_headers();
1706
      if (isset($headers['Accept-Language'])) {
1707
        $acceptLanguage = $headers['Accept-Language'];
1708
      }
1709
    }
1710
    if (!$acceptLanguage) {
1711
      // DEFAULT TODO make configurable.
1712
      $acceptLanguage = "en";
1713
    }
1714
  }
1715

    
1716
  if ($method != "GET" && $method != "POST") {
1717
    $method = "GET";
1718
  }
1719

    
1720
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1721
    $header['Accept'] = 'application/json';
1722
    $header['Accept-Language'] = $acceptLanguage;
1723
    $header['Accept-Charset'] = 'UTF-8';
1724
  }
1725

    
1726
  return drupal_http_request($uri, array(
1727
      'headers' => $header,
1728
      'method' => $method,
1729
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1730
      )
1731
   );
1732
}
1733

    
1734
/**
1735
 * @todo Please document this function.
1736
 * @see http://drupal.org/node/1354
1737
 */
1738
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1739
  $out = '';
1740

    
1741
  foreach ($rootNode->children as $featureNode) {
1742
    $out .= ($out ? $separator : '');
1743
    $out .= $featureNode->feature->representation_L10n;
1744
    if (is_array($featureNode->children)) {
1745
      $childlabels = '';
1746
      foreach ($featureNode->children as $childNode) {
1747
        $childlabels .= ($childlabels ? $separator : '');
1748
      }
1749
      $childlabels .= _featureTree_elements_toString($childNode);
1750
    }
1751
    if ($childlabels) {
1752
      $out .= '[' . $childlabels . ' ]';
1753
    }
1754
  }
1755
  return $out;
1756
}
1757

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

    
1792
/**
1793
 * Returns an array with all available FeatureTrees and the representations of the selected
1794
 * FeatureTree as a detail view.
1795
 *
1796
 * @param boolean $add_default_feature_free
1797
 * @return array
1798
 *  associative array with following keys:
1799
 *  -options: Returns an array with all available Feature Trees
1800
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1801
 *
1802
 */
1803
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1804

    
1805
  $options = array();
1806
  $tree_representations = array();
1807
  $feature_trees = array();
1808

    
1809
  // Set tree that contains all features.
1810
  if ($add_default_feature_free) {
1811
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1812
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1813
  }
1814

    
1815
  // Get feature trees from database.
1816
  $persited_trees = cdm_ws_get(CDM_WS_FEATURETREES);
1817
  if (is_array($persited_trees)) {
1818
    $feature_trees = array_merge($feature_trees, $persited_trees);
1819
  }
1820

    
1821
  foreach ($feature_trees as $featureTree) {
1822

    
1823
    // Do not add the DEFAULT_FEATURETREE again,
1824
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1825
      $options[$featureTree->uuid] = $featureTree->titleCache;
1826
    }
1827

    
1828
    // Render the hierarchic tree structure
1829
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1830

    
1831
      // Render the hierarchic tree structure.
1832
      $treeDetails = '<div class="featuretree_structure">'
1833
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1834
        . '</div>';
1835

    
1836
      $form = array();
1837
      $form['featureTree-' .  $featureTree->uuid] = array(
1838
        '#type' => 'fieldset',
1839
        '#title' => 'Show details',
1840
        '#attributes' => array('class' => array('collapsible collapsed')),
1841
        // '#collapsible' => TRUE,
1842
        // '#collapsed' => TRUE,
1843
      );
1844
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1845
        '#markup' => $treeDetails,
1846
      );
1847

    
1848
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1849
    }
1850

    
1851
  } // END loop over feature trees
1852

    
1853
  // return $options;
1854
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1855
}
1856

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

    
1875
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1876

    
1877
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1878
  $default_classification_label = '';
1879

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

    
1901
  // now set the labels
1902
  //   for none
1903
  if ($add_none_option) {
1904
    $taxonomic_tree_options['NONE'] = t('-- None --');
1905
  }
1906

    
1907
  //   for default_classification
1908
  if (is_uuid($default_classification_uuid)) {
1909
    $taxonomic_tree_options[$default_classification_uuid] =
1910
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1911
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1912
  }
1913

    
1914
  return $taxonomic_tree_options;
1915
}
1916

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

    
1943
/**
1944
 * @todo Please document this function.
1945
 * @see http://drupal.org/node/1354
1946
 */
1947
function cdm_api_secref_cache_get($secUuid) {
1948
  global $_cdm_api_secref_cache;
1949
  if (!is_array($_cdm_api_secref_cache)) {
1950
    $_cdm_api_secref_cache = array();
1951
  }
1952
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1953
    _cdm_api_secref_cache_add($secUuid);
1954
  }
1955
  return $_cdm_api_secref_cache[$secUuid];
1956
}
1957

    
1958
/**
1959
 * @todo Please document this function.
1960
 * @see http://drupal.org/node/1354
1961
 */
1962
function cdm_api_secref_cache_clear() {
1963
  global $_cdm_api_secref_cache;
1964
  $_cdm_api_secref_cache = array();
1965
}
1966

    
1967
/**
1968
 * Validates if the given string is a uuid.
1969
 *
1970
 * @param string $str
1971
 *   The string to validate.
1972
 *
1973
 * return bool
1974
 *   TRUE if the string is a UUID.
1975
 */
1976
function is_uuid($str) {
1977
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1978
}
1979

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

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

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

    
2031
/**
2032
 * @todo Please document this function.
2033
 * @see http://drupal.org/node/1354
2034
 */
2035
function queryString($elements) {
2036
  $query = '';
2037
  foreach ($elements as $key => $value) {
2038
    if (is_array($value)) {
2039
      foreach ($value as $v) {
2040
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2041
      }
2042
    }
2043
    else {
2044
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2045
    }
2046
  }
2047
  return $query;
2048
}
2049

    
2050
/**
2051
 * Implementation of the magic method __clone to allow deep cloning of objects
2052
 * and arrays.
2053
 */
2054
function __clone() {
2055
  foreach ($this as $name => $value) {
2056
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2057
      $this->$name = clone($this->$name);
2058
    }
2059
  }
2060
}
2061

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

    
2096
/**
2097
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2098
 *
2099
 */
2100
function _add_js_ws_debug() {
2101

    
2102
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js',
2103
    array(
2104
      'type' => 'file',
2105
      'weight' => JS_LIBRARY,
2106
      'cache' => TRUE)
2107
    );
2108

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

    
2118
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2119
    array(
2120
      'type' => 'file',
2121
      'weight' => JS_LIBRARY,
2122
      'cache' => TRUE)
2123
    );
2124

    
2125
}
2126

    
2127
/**
2128
 * @todo Please document this function.
2129
 * @see http://drupal.org/node/1354
2130
 */
2131
function _no_classfication_uuid_message() {
2132
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2133
    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.');
2134
  }
2135
  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.');
2136
}
2137

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