Project

General

Profile

Download (65.1 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
      if($data['method'] == 'POST'){
113
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
114
      }
115

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

    
125
    _add_js_ws_debug();
126

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

    
138
    return $block;
139
  }
140
}
141

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

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

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

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

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

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

    
240
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
241
}
242

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

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

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

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

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

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

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

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

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

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

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

    
394
  while (count($mimeTypes) > 0) {
395
    // getRepresentationByMimeType
396
    $mimeType = array_shift($mimeTypes);
397

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

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

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

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

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

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

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

    
564
  $y = $y ? $y : '00';
565
  $m = $m ? $m : '00';
566
  $d = $d ? $d : '00';
567

    
568
  $date = '';
569

    
570
  if ($y == '00' && $stripZeros) {
571
    return;
572
  }
573
  else {
574
    $date = $y;
575
  }
576

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

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

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

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

    
663
  $request_params = '';
664
  $path_params = '';
665

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

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

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

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

    
707
  $path = $uri_pattern;
708

    
709
  $uri = variable_get('cdm_webservice_url', '') . $path;
710
  return $uri;
711
}
712

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

    
732
  $args = func_get_args();
733
  $do_gzip = function_exists('gzencode');
734
  $uriEncoded = array_shift($args);
735
  $uri = urldecode($uriEncoded);
736
  $hook = array_shift($args);
737
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
738

    
739
  if ($request_method == "POST" || $request_method == "PUT") {
740
    // read response body via inputstream module
741
    $post_data = file_get_contents("php://input");
742
  }
743

    
744
  // Find and deserialize arrays.
745
  foreach ($args as &$arg) {
746
    // FIXME use regex to find serialized arrays.
747
    //       or should we accept json instead of php serializations?
748
    if (strpos($arg, "a:") === 0) {
749
      $arg = unserialize($arg);
750
    }
751
  }
752

    
753
  // In all these cases perform a simple get request.
754
  // TODO reconsider caching logic in this function.
755

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

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

    
785
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
786

    
787
    $reponse_data = NULL;
788

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

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

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

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

    
829
        default:
830
          drupal_set_message(t(
831
          'Theme !theme is not supported yet by function !function.', array(
832
          '!theme' => $hook,
833
          '!function' => __FUNCTION__,
834
          )), 'error');
835
          break;
836
      } // END of theme hook switch
837
    } // END of tread as theme hook
838

    
839

    
840
    if($do_gzip){
841
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
842
      drupal_add_http_header('Content-Encoding', 'gzip');
843
    }
844
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
845
    drupal_add_http_header('Content-Length', strlen($reponse_data));
846

    
847
    print $reponse_data;
848
  } // END of handle $hook either as compose ot theme hook
849

    
850
}
851

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

    
866
  // Prevent from malicous tags.
867
  $val = strip_tags($val);
868

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

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

    
893
/**
894
 * Composes the the absolute REST service URI to the annotations pager
895
 * for the given CDM entity.
896
 *
897
 * NOTE: Not all CDM Base types are yet supported.
898
 *
899
 * @param $cdmBase
900
 *   The CDM entity to construct the annotations pager uri for
901
 */
902
function cdm_compose_annotations_uri($cdmBase) {
903
  if (!$cdmBase->uuid) {
904
    return;
905
  }
906

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

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

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

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

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

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

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

    
961
/**
962
 * Enter description here...
963
 *
964
 * @param string $resourceURI
965
 * @param int $pageSize
966
 *   The maximum number of entities returned per page.
967
 *   The default page size as configured in the cdm server
968
 *   will be used if set to NULL
969
 *   to return all entities in a single page).
970
 * @param int $pageNumber
971
 *   The number of the page to be returned, the first page has the
972
 *   pageNumber = 0
973
 * @param array $query
974
 *   A array holding the HTTP request query parameters for the request
975
 * @param string $method
976
 *   The HTTP method to use, valid values are "GET" or "POST"
977
 * @param bool $absoluteURI
978
 *   TRUE when the URL should be treated as absolute URL.
979
 *
980
 * @return the a CDM Pager object
981
 *
982
 */
983
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
984

    
985
  $query['pageNumber'] = $pageNumber;
986
  $query['pageSize'] = $pageSize;
987

    
988
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
989
}
990

    
991
/**
992
 * Fetches all entities from the given REST endpoint using the pager mechanism.
993
 *
994
 * @param string $resourceURI
995
 * @param array $query
996
 *   A array holding the HTTP request query parameters for the request
997
 * @param string $method
998
 *   The HTTP method to use, valid values are "GET" or "POST";
999
 * @param bool $absoluteURI
1000
 *   TRUE when the URL should be treated as absolute URL.
1001
 *
1002
 * @return array
1003
 *     A list of CDM entitites
1004
 *
1005
 */
1006
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1007
  $page_index = 0;
1008
  // using a bigger page size to avoid to many multiple requests
1009
  $page_size = 500;
1010
  $entities = array();
1011

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

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

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

    
1048
  $view_uuid = get_taxonomictree_uuid_selected();
1049
  $rank_uuid = NULL;
1050
  if (!$ignore_rank_limit) {
1051
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1052
  }
1053

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

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

    
1096
    $response = NULL;
1097

    
1098
    // 1st try
1099
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1100

    
1101
    if ($response == NULL) {
1102
      // 2dn try by ignoring the rank limit
1103
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1104
    }
1105

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

    
1124
  return $response;
1125
}
1126

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

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

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

    
1170
  return $response;
1171
}
1172

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

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

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

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

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

    
1245
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1246
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1247
    $vocabularyOptions[$vocabularyUuid] = array();
1248

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

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

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

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

    
1299
  $merged_trees = array();
1300

    
1301
  $description_elemens = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1302
      array(
1303
      'taxon' => $taxon_uuid,
1304
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid')
1305
      ),
1306
      'POST'
1307
  );
1308

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

    
1313
  return $feature_tree;
1314
}
1315

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

    
1332
  if(!isset($cdmBase->annotations)){
1333
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1334
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1335
  }
1336

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

    
1350
}
1351

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

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

    
1387
  if ($obj) {
1388
    return $obj->String;
1389
  }
1390
  else {
1391
    return NULL;
1392
  }
1393
}
1394

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

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

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

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

    
1443
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1444
      unset($node);
1445
    }
1446

    
1447
  }
1448

    
1449
  return $featureNodes;
1450
}
1451

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

    
1488
  static $cacheL1 = array();
1489

    
1490
  $data = NULL;
1491
  // store query string in $data and clear the query, $data will be set as HTTP request body
1492
  if($method == 'POST'){
1493
    $data = $query;
1494
    $query = NULL;
1495
  }
1496

    
1497
  // Transform the given uri path or pattern into a proper webservice uri.
1498
  if (!$absoluteURI) {
1499
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1500
  }
1501

    
1502
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1503
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1504

    
1505
  if($method == 'GET'){
1506
    $cache_key = $uri;
1507
  } else {
1508
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1509
    // crc32 is faster but creates much shorter hashes
1510
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1511
  }
1512

    
1513
  if (array_key_exists($cache_key, $cacheL1)) {
1514
    $cacheL1_obj = $cacheL1[$uri];
1515
  }
1516

    
1517
  $set_cacheL1 = FALSE;
1518
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1519
    $set_cacheL1 = TRUE;
1520
  }
1521

    
1522
  // Only cache cdm webservice URIs.
1523
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1524
  $cacheL2_entry = FALSE;
1525

    
1526
  if ($use_cacheL2) {
1527
    // Try to get object from cacheL2.
1528
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1529
  }
1530

    
1531
  if (isset($cacheL1_obj)) {
1532
    //
1533
    // The object has been found in the L1 cache.
1534
    //
1535
    $obj = $cacheL1_obj;
1536
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1537
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1538
    }
1539
  }
1540
  elseif ($cacheL2_entry) {
1541
    //
1542
    // The object has been found in the L2 cache.
1543
    //
1544
    $duration_parse_start = microtime(TRUE);
1545
    $obj = unserialize($cacheL2_entry->data);
1546
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1547

    
1548
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1549
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1550
    }
1551
  }
1552
  else {
1553
    //
1554
    // Get the object from the webservice and cache it.
1555
    //
1556
    $duration_fetch_start = microtime(TRUE);
1557
    // Request data from webservice JSON or XML.
1558
    $response = cdm_http_request($uri, $method, $data);
1559
    $response_body = NULL;
1560
    if (isset($response->data)) {
1561
      $response_body = $response->data;
1562
    }
1563
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1564
    $duration_parse_start = microtime(TRUE);
1565

    
1566
    // Parse data and create object.
1567
    $obj = cdm_load_obj($response_body);
1568

    
1569
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1570
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1571
      if ($obj || $response_body == "[]") {
1572
        $status = 'valid';
1573
      }
1574
      else {
1575
        $status = 'invalid';
1576
      }
1577
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1578
    }
1579
    if ($set_cacheL2) {
1580
      // Store the object in cache L2.
1581
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1582
      // flag serialized is set properly in the cache table.
1583
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1584
    }
1585
  }
1586
  if ($obj) {
1587
    // Store the object in cache L1.
1588
    if ($set_cacheL1) {
1589
      $cacheL1[$cache_key] = $obj;
1590
    }
1591
  }
1592
  return $obj;
1593
}
1594

    
1595
/**
1596
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1597
 *
1598
 * The cdm_ws_debug block will display the debug information.
1599
 *
1600
 * @param $uri
1601
 *    The CDM REST URI to which the request has been send
1602
 * @param string $method
1603
 *    The HTTP request method, either 'GET' or 'POST'
1604
 * @param string $post_data
1605
 *    The datastring send with a post request
1606
 * @param $duration_fetch
1607
 *    The time in seconds it took to fetch the data from the web service
1608
 * @param $duration_parse
1609
 *    Time in seconds which was needed to parse the json response
1610
 * @param $datasize
1611
 *    Size of the data received from the server
1612
 * @param $status
1613
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1614
 * @return bool
1615
 *    TRUE if adding the debug information was successful
1616
 */
1617
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1618

    
1619
  static $initial_time = NULL;
1620
  if(!$initial_time) {
1621
    $initial_time = microtime(TRUE);
1622
  }
1623
  $time = microtime(TRUE) - $initial_time;
1624

    
1625
  // Decompose uri into path and query element.
1626
  $uri_parts = explode("?", $uri);
1627
  $query = array();
1628
  if (count($uri_parts) == 2) {
1629
    $path = $uri_parts[0];
1630
  }
1631
  else {
1632
    $path = $uri;
1633
  }
1634

    
1635
  if(strpos($uri, '?') > 0){
1636
    $json_uri = str_replace('?', '.json?', $uri);
1637
    $xml_uri = str_replace('?', '.xml?', $uri);
1638
  } else {
1639
    $json_uri = $uri . '.json';
1640
    $xml_uri = $json_uri . '.xml';
1641
  }
1642

    
1643
  // data links to make data accecsible as json and xml
1644
  $data_links = '';
1645
  if (_is_cdm_ws_uri($path)) {
1646

    
1647
    // see ./js/http-method-link.js
1648

    
1649
    if($method == 'GET'){
1650
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1651
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1652
      $data_links .= '<br/>';
1653
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1654
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1655
    } else {
1656
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1657
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1658
      $data_links .= '<br/>';
1659
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1660
    }
1661
  }
1662
  else {
1663
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1664
  }
1665

    
1666
  //
1667
  $data = array(
1668
      'ws_uri' => $uri,
1669
      'method' => $method,
1670
      'post_data' => $post_data,
1671
      'time' => sprintf('%3.3f', $time),
1672
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1673
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1674
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1675
      'status' => $status,
1676
      'data_links' => $data_links
1677
  );
1678
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1679
    $_SESSION['cdm']['ws_debug'] = array();
1680
  }
1681
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1682

    
1683
  // Mark this page as being uncacheable.
1684
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1685
  drupal_page_is_cacheable(FALSE);
1686

    
1687
  // Messages not set when DB connection fails.
1688
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1689
}
1690

    
1691
/**
1692
 * @todo Please document this function.
1693
 * @see http://drupal.org/node/1354
1694
 */
1695
function cdm_load_obj($response_body) {
1696
  $obj = json_decode($response_body);
1697

    
1698
  if (!(is_object($obj) || is_array($obj))) {
1699
    ob_start();
1700
    $obj_dump = ob_get_contents();
1701
    ob_clean();
1702
    return FALSE;
1703
  }
1704

    
1705
  return $obj;
1706
}
1707

    
1708
/**
1709
 * Do a http request to a CDM RESTful web service.
1710
 *
1711
 * @param string $uri
1712
 *   The webservice url.
1713
 * @param string $method
1714
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1715
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1716
 * @param $data: A string containing the request body, formatted as
1717
 *     'param=value&param=value&...'. Defaults to NULL.
1718
 *
1719
 * @return object
1720
 *   The object as returned by drupal_http_request():
1721
 *   An object that can have one or more of the following components:
1722
 *   - request: A string containing the request body that was sent.
1723
 *   - code: An integer containing the response status code, or the error code
1724
 *     if an error occurred.
1725
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1726
 *   - status_message: The status message from the response, if a response was
1727
 *     received.
1728
 *   - redirect_code: If redirected, an integer containing the initial response
1729
 *     status code.
1730
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1731
 *     target.
1732
 *   - error: If an error occurred, the error message. Otherwise not set.
1733
 *   - headers: An array containing the response headers as name/value pairs.
1734
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1735
 *     easy access the array keys are returned in lower case.
1736
 *   - data: A string containing the response body that was received.
1737
 */
1738
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1739
  static $acceptLanguage = NULL;
1740
  $header = array();
1741

    
1742
  if (!$acceptLanguage) {
1743
    if (function_exists('apache_request_headers')) {
1744
      $headers = apache_request_headers();
1745
      if (isset($headers['Accept-Language'])) {
1746
        $acceptLanguage = $headers['Accept-Language'];
1747
      }
1748
    }
1749
    if (!$acceptLanguage) {
1750
      // DEFAULT TODO make configurable.
1751
      $acceptLanguage = "en";
1752
    }
1753
  }
1754

    
1755
  if ($method != "GET" && $method != "POST") {
1756
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1757
  }
1758

    
1759
  if (_is_cdm_ws_uri($uri)) {
1760
    $header['Accept'] = 'application/json';
1761
    $header['Accept-Language'] = $acceptLanguage;
1762
    $header['Accept-Charset'] = 'UTF-8';
1763
  }
1764

    
1765
  if($method == "POST") {
1766
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1767
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1768
  }
1769

    
1770
  return drupal_http_request($uri, array(
1771
      'headers' => $header,
1772
      'method' => $method,
1773
      'data' => $data,
1774
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1775
      )
1776
   );
1777
}
1778

    
1779
/**
1780
 * Concatenates recursively the fields of all features contained in the given
1781
 * CDM FeatureTree root node.
1782
 *
1783
 * @param $rootNode
1784
 *     A CDM FeatureTree node
1785
 * @param
1786
 *     The character to be used as glue for concatenation, default is ', '
1787
 * @param $field_name
1788
 *     The field name of the CDM Features
1789
 */
1790
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n') {
1791
  $out = '';
1792

    
1793
  $pre_child_separator = $separator;
1794
  $post_child_separator = '';
1795

    
1796
  foreach ($root_node->children as $feature_node) {
1797
    $out .= ($out ? $separator : '');
1798
    $out .= $feature_node->feature->$field_name;
1799
    if (is_array($feature_node->children) && count($feature_node->children) > 0) {
1800
      $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1801
      if (strlen($childlabels)) {
1802
          $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1803
      }
1804
    }
1805
  }
1806
  return $out;
1807
}
1808

    
1809
/**
1810
 * Create a one-dimensional form options array.
1811
 *
1812
 * Creates an array of all features in the feature tree of feature nodes,
1813
 * the node labels are indented by $node_char and $childIndent depending on the
1814
 * hierachy level.
1815
 *
1816
 * @param - $rootNode
1817
 * @param - $node_char
1818
 * @param - $childIndentStr
1819
 * @param - $childIndent
1820
 *   ONLY USED INTERNALLY!
1821
 *
1822
 * @return array
1823
 *   A one dimensional Drupal form options array.
1824
 */
1825
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1826
  $options = array();
1827
  foreach ($rootNode->children as $featureNode) {
1828
    $indent_prefix = '';
1829
    if ($childIndent) {
1830
      $indent_prefix = $childIndent . $node_char . " ";
1831
    }
1832
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1833
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1834
      // Foreach ($featureNode->children as $childNode){
1835
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1836
      $options = array_merge_recursive($options, $childList);
1837
      // }
1838
    }
1839
  }
1840
  return $options;
1841
}
1842

    
1843
/**
1844
 * Returns an array with all available FeatureTrees and the representations of the selected
1845
 * FeatureTree as a detail view.
1846
 *
1847
 * @param boolean $add_default_feature_free
1848
 * @return array
1849
 *  associative array with following keys:
1850
 *  -options: Returns an array with all available Feature Trees
1851
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1852
 *
1853
 */
1854
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1855

    
1856
  $options = array();
1857
  $tree_representations = array();
1858
  $feature_trees = array();
1859

    
1860
  // Set tree that contains all features.
1861
  if ($add_default_feature_free) {
1862
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1863
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1864
  }
1865

    
1866
  // Get feature trees from database.
1867
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1868
  if (is_array($persited_trees)) {
1869
    $feature_trees = array_merge($feature_trees, $persited_trees);
1870
  }
1871

    
1872
  foreach ($feature_trees as $featureTree) {
1873

    
1874
    // Do not add the DEFAULT_FEATURETREE again,
1875
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1876
      $options[$featureTree->uuid] = $featureTree->titleCache;
1877
    }
1878

    
1879
    // Render the hierarchic tree structure
1880
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1881

    
1882
      // Render the hierarchic tree structure.
1883
      $treeDetails = '<div class="featuretree_structure">'
1884
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1885
        . '</div>';
1886

    
1887
      $form = array();
1888
      $form['featureTree-' .  $featureTree->uuid] = array(
1889
        '#type' => 'fieldset',
1890
        '#title' => 'Show details',
1891
        '#attributes' => array('class' => array('collapsible collapsed')),
1892
        // '#collapsible' => TRUE,
1893
        // '#collapsed' => TRUE,
1894
      );
1895
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1896
        '#markup' => $treeDetails,
1897
      );
1898

    
1899
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1900
    }
1901

    
1902
  } // END loop over feature trees
1903

    
1904
  // return $options;
1905
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1906
}
1907

    
1908
/**
1909
 * Provides the list of availbale classifications in form of an options array.
1910
 *
1911
 * The options array is suitable for drupal form API elements that allow multiple choices.
1912
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1913
 *
1914
 * The classifications are ordered alphabetically whereas the classification
1915
 * chosen as default will always appear on top of the array, followed by a
1916
 * blank line below.
1917
 *
1918
 * @param bool $add_none_option
1919
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1920
 *
1921
 * @return array
1922
 *   classifications in an array as options for a form element that allows multiple choices.
1923
 */
1924
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1925

    
1926
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1927

    
1928
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1929
  $default_classification_label = '';
1930

    
1931
  // add all classifications
1932
  $taxonomic_tree_options = array();
1933
  if ($add_none_option) {
1934
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1935
  }
1936
  if ($taxonTrees) {
1937
    foreach ($taxonTrees as $tree) {
1938
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1939
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1940
      } else {
1941
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1942
        if (count($taxonTrees) > 1) {
1943
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1944
        }
1945
        $default_classification_label = $tree->titleCache;
1946
      }
1947
    }
1948
  }
1949
  // oder alphabetically the space
1950
  asort($taxonomic_tree_options);
1951

    
1952
  // now set the labels
1953
  //   for none
1954
  if ($add_none_option) {
1955
    $taxonomic_tree_options['NONE'] = t('-- None --');
1956
  }
1957

    
1958
  //   for default_classification
1959
  if (is_uuid($default_classification_uuid)) {
1960
    $taxonomic_tree_options[$default_classification_uuid] =
1961
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1962
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1963
  }
1964

    
1965
  return $taxonomic_tree_options;
1966
}
1967

    
1968
/**
1969
 * @todo Please document this function.
1970
 * @see http://drupal.org/node/1354
1971
 */
1972
function cdm_api_secref_cache_prefetch(&$secUuids) {
1973
  // Comment @WA: global variables should start with a single underscore
1974
  // followed by the module and another underscore.
1975
  global $_cdm_api_secref_cache;
1976
  if (!is_array($_cdm_api_secref_cache)) {
1977
    $_cdm_api_secref_cache = array();
1978
  }
1979
  $uniqueUuids = array_unique($secUuids);
1980
  $i = 0;
1981
  $param = '';
1982
  while ($i++ < count($uniqueUuids)) {
1983
    $param .= $secUuids[$i] . ',';
1984
    if (strlen($param) + 37 > 2000) {
1985
      _cdm_api_secref_cache_add($param);
1986
      $param = '';
1987
    }
1988
  }
1989
  if ($param) {
1990
    _cdm_api_secref_cache_add($param);
1991
  }
1992
}
1993

    
1994
/**
1995
 * @todo Please document this function.
1996
 * @see http://drupal.org/node/1354
1997
 */
1998
function cdm_api_secref_cache_get($secUuid) {
1999
  global $_cdm_api_secref_cache;
2000
  if (!is_array($_cdm_api_secref_cache)) {
2001
    $_cdm_api_secref_cache = array();
2002
  }
2003
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2004
    _cdm_api_secref_cache_add($secUuid);
2005
  }
2006
  return $_cdm_api_secref_cache[$secUuid];
2007
}
2008

    
2009
/**
2010
 * @todo Please document this function.
2011
 * @see http://drupal.org/node/1354
2012
 */
2013
function cdm_api_secref_cache_clear() {
2014
  global $_cdm_api_secref_cache;
2015
  $_cdm_api_secref_cache = array();
2016
}
2017

    
2018
/**
2019
 * Validates if the given string is a uuid.
2020
 *
2021
 * @param string $str
2022
 *   The string to validate.
2023
 *
2024
 * return bool
2025
 *   TRUE if the string is a UUID.
2026
 */
2027
function is_uuid($str) {
2028
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2029
}
2030

    
2031
/**
2032
 * Checks if the given $object is a valid cdm entity.
2033
 *
2034
 * An object is considered a cdm entity if it has a string field $object->class
2035
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2036
 *
2037
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2038
 *
2039
 * @param mixed $object
2040
 *   The object to validate
2041
 *
2042
 * @return bool
2043
 *   True if the object is a cdm entity.
2044
 */
2045
function is_cdm_entity($object) {
2046
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2047
}
2048

    
2049
/**
2050
 * @todo Please document this function.
2051
 * @see http://drupal.org/node/1354
2052
 */
2053
function _cdm_api_secref_cache_add($secUuidsStr) {
2054
  global $_cdm_api_secref_cache;
2055
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2056
  // Batch fetching not jet reimplemented thus:
2057
  /*
2058
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2059
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2060
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2061
  */
2062
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2063
}
2064

    
2065
/**
2066
 * Checks if the given uri starts with a cdm webservice url.
2067
 *
2068
 * Checks if the uri starts with the cdm webservice url stored in the
2069
 * Drupal variable 'cdm_webservice_url'.
2070
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2071
 *
2072
 * @param string $uri
2073
 *   The URI to test.
2074
 *
2075
 * @return bool
2076
 *   True if the uri starts with a cdm webservice url.
2077
 */
2078
function _is_cdm_ws_uri($uri) {
2079
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2080
}
2081

    
2082
/**
2083
 * @todo Please document this function.
2084
 * @see http://drupal.org/node/1354
2085
 */
2086
function queryString($elements) {
2087
  $query = '';
2088
  foreach ($elements as $key => $value) {
2089
    if (is_array($value)) {
2090
      foreach ($value as $v) {
2091
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2092
      }
2093
    }
2094
    else {
2095
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2096
    }
2097
  }
2098
  return $query;
2099
}
2100

    
2101
/**
2102
 * Implementation of the magic method __clone to allow deep cloning of objects
2103
 * and arrays.
2104
 */
2105
function __clone() {
2106
  foreach ($this as $name => $value) {
2107
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2108
      $this->$name = clone($this->$name);
2109
    }
2110
  }
2111
}
2112

    
2113
/**
2114
 * Make a 'deep copy' of an array.
2115
 *
2116
 * Make a complete deep copy of an array replacing
2117
 * references with deep copies until a certain depth is reached
2118
 * ($maxdepth) whereupon references are copied as-is...
2119
 *
2120
 * @see http://us3.php.net/manual/en/ref.array.php
2121
 *
2122
 * @param array $array
2123
 * @param array $copy
2124
 * @param int $maxdepth
2125
 * @param int $depth
2126
 *
2127
 * @return void
2128
 */
2129
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2130
  if ($depth > $maxdepth) {
2131
    $copy = $array;
2132
    return;
2133
  }
2134
  if (!is_array($copy)) {
2135
    $copy = array();
2136
  }
2137
  foreach ($array as $k => &$v) {
2138
    if (is_array($v)) {
2139
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2140
    }
2141
    else {
2142
      $copy[$k] = $v;
2143
    }
2144
  }
2145
}
2146

    
2147
/**
2148
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2149
 *
2150
 */
2151
function _add_js_ws_debug() {
2152

    
2153
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js',
2154
    array(
2155
      'type' => 'file',
2156
      'weight' => JS_LIBRARY,
2157
      'cache' => TRUE)
2158
    );
2159

    
2160
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/jquery.colorbox-min.js',
2161
    array(
2162
      'type' => 'file',
2163
      'weight' => JS_LIBRARY,
2164
      'cache' => TRUE)
2165
    );
2166
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2167
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2168

    
2169
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2170
    array(
2171
      'type' => 'file',
2172
      'weight' => JS_LIBRARY,
2173
      'cache' => TRUE)
2174
    );
2175
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2176
    array(
2177
    'type' => 'file',
2178
    'weight' => JS_LIBRARY,
2179
    'cache' => TRUE)
2180
    );
2181

    
2182
}
2183

    
2184
/**
2185
 * @todo Please document this function.
2186
 * @see http://drupal.org/node/1354
2187
 */
2188
function _no_classfication_uuid_message() {
2189
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2190
    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.');
2191
  }
2192
  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.');
2193
}
2194

    
2195
/**
2196
 * Implementation of hook flush_caches
2197
 *
2198
 * Add custom cache tables to the list of cache tables that
2199
 * will be cleared by the Clear button on the Performance page or whenever
2200
 * drupal_flush_all_caches is invoked.
2201
 *
2202
 * @author W.Addink <waddink@eti.uva.nl>
2203
 *
2204
 * @return array
2205
 *   An array with custom cache tables to include.
2206
 */
2207
function cdm_api_flush_caches() {
2208
  return array('cache_cdm_ws');
2209
}
(4-4/9)