Project

General

Profile

Download (66.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
  // read request parameter 'cacheL2_refresh'
1503
  // which allows refreshig the level 2 cache
1504
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1505

    
1506
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1507
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1508

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

    
1517
  if (array_key_exists($cache_key, $cacheL1)) {
1518
    $cacheL1_obj = $cacheL1[$uri];
1519
  }
1520

    
1521
  $set_cacheL1 = FALSE;
1522
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1523
    $set_cacheL1 = TRUE;
1524
  }
1525

    
1526
  // Only cache cdm webservice URIs.
1527
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1528
  $cacheL2_entry = FALSE;
1529

    
1530
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1531
    // Try to get object from cacheL2.
1532
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1533
  }
1534

    
1535
  if (isset($cacheL1_obj)) {
1536
    //
1537
    // The object has been found in the L1 cache.
1538
    //
1539
    $obj = $cacheL1_obj;
1540
    if (cdm_debug_block_visible()) {
1541
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1542
    }
1543
  }
1544
  elseif ($cacheL2_entry) {
1545
    //
1546
    // The object has been found in the L2 cache.
1547
    //
1548
    $duration_parse_start = microtime(TRUE);
1549
    $obj = unserialize($cacheL2_entry->data);
1550
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1551

    
1552
    if (cdm_debug_block_visible()) {
1553
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1554
    }
1555
  }
1556
  else {
1557
    //
1558
    // Get the object from the webservice and cache it.
1559
    //
1560
    $duration_fetch_start = microtime(TRUE);
1561
    // Request data from webservice JSON or XML.
1562
    $response = cdm_http_request($uri, $method, $data);
1563
    $response_body = NULL;
1564
    if (isset($response->data)) {
1565
      $response_body = $response->data;
1566
    }
1567
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1568
    $duration_parse_start = microtime(TRUE);
1569

    
1570
    // Parse data and create object.
1571
    $obj = cdm_load_obj($response_body);
1572

    
1573
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1574

    
1575
    if (cdm_debug_block_visible()) {
1576
      if ($obj || $response_body == "[]") {
1577
        $status = 'valid';
1578
      }
1579
      else {
1580
        $status = 'invalid';
1581
      }
1582
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1583
    }
1584
    if ($set_cacheL2) {
1585
      // Store the object in cache L2.
1586
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1587
      // flag serialized is set properly in the cache table.
1588
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1589
    }
1590
  }
1591
  if ($obj) {
1592
    // Store the object in cache L1.
1593
    if ($set_cacheL1) {
1594
      $cacheL1[$cache_key] = $obj;
1595
    }
1596
  }
1597
  return $obj;
1598
}
1599

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

    
1624
  static $initial_time = NULL;
1625
  if(!$initial_time) {
1626
    $initial_time = microtime(TRUE);
1627
  }
1628
  $time = microtime(TRUE) - $initial_time;
1629

    
1630
  // Decompose uri into path and query element.
1631
  $uri_parts = explode("?", $uri);
1632
  $query = array();
1633
  if (count($uri_parts) == 2) {
1634
    $path = $uri_parts[0];
1635
  }
1636
  else {
1637
    $path = $uri;
1638
  }
1639

    
1640
  if(strpos($uri, '?') > 0){
1641
    $json_uri = str_replace('?', '.json?', $uri);
1642
    $xml_uri = str_replace('?', '.xml?', $uri);
1643
  } else {
1644
    $json_uri = $uri . '.json';
1645
    $xml_uri = $json_uri . '.xml';
1646
  }
1647

    
1648
  // data links to make data accecsible as json and xml
1649
  $data_links = '';
1650
  if (_is_cdm_ws_uri($path)) {
1651

    
1652
    // see ./js/http-method-link.js
1653

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

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

    
1688
  // Mark this page as being uncacheable.
1689
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1690
  drupal_page_is_cacheable(FALSE);
1691

    
1692
  // Messages not set when DB connection fails.
1693
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1694
}
1695

    
1696
/**
1697
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1698
 * the visibility depends on whether
1699
 *  - the block is enabled
1700
 *  - the visibility restrictions in the block settings are satisfied
1701
 */
1702
function cdm_debug_block_visible() {
1703
  static $is_visible = null;
1704

    
1705
  if($is_visible === null){
1706
      $block = block_load('cdm_api', 'cdm_ws_debug');
1707
      $is_visible = $block->status == 1;
1708
      if($is_visible){
1709
        $blocks = array($block);
1710
        // Checks the page, user role, and user-specific visibilty settings.
1711
        block_block_list_alter($blocks);
1712
        $is_visible = count($blocks) > 0;
1713
      }
1714
  }
1715
  return $is_visible;
1716
}
1717

    
1718
/**
1719
 * @todo Please document this function.
1720
 * @see http://drupal.org/node/1354
1721
 */
1722
function cdm_load_obj($response_body) {
1723
  $obj = json_decode($response_body);
1724

    
1725
  if (!(is_object($obj) || is_array($obj))) {
1726
    ob_start();
1727
    $obj_dump = ob_get_contents();
1728
    ob_clean();
1729
    return FALSE;
1730
  }
1731

    
1732
  return $obj;
1733
}
1734

    
1735
/**
1736
 * Do a http request to a CDM RESTful web service.
1737
 *
1738
 * @param string $uri
1739
 *   The webservice url.
1740
 * @param string $method
1741
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1742
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1743
 * @param $data: A string containing the request body, formatted as
1744
 *     'param=value&param=value&...'. Defaults to NULL.
1745
 *
1746
 * @return object
1747
 *   The object as returned by drupal_http_request():
1748
 *   An object that can have one or more of the following components:
1749
 *   - request: A string containing the request body that was sent.
1750
 *   - code: An integer containing the response status code, or the error code
1751
 *     if an error occurred.
1752
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1753
 *   - status_message: The status message from the response, if a response was
1754
 *     received.
1755
 *   - redirect_code: If redirected, an integer containing the initial response
1756
 *     status code.
1757
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1758
 *     target.
1759
 *   - error: If an error occurred, the error message. Otherwise not set.
1760
 *   - headers: An array containing the response headers as name/value pairs.
1761
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1762
 *     easy access the array keys are returned in lower case.
1763
 *   - data: A string containing the response body that was received.
1764
 */
1765
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1766
  static $acceptLanguage = NULL;
1767
  $header = array();
1768

    
1769
  if (!$acceptLanguage) {
1770
    if (function_exists('apache_request_headers')) {
1771
      $headers = apache_request_headers();
1772
      if (isset($headers['Accept-Language'])) {
1773
        $acceptLanguage = $headers['Accept-Language'];
1774
      }
1775
    }
1776
    if (!$acceptLanguage) {
1777
      // DEFAULT TODO make configurable.
1778
      $acceptLanguage = "en";
1779
    }
1780
  }
1781

    
1782
  if ($method != "GET" && $method != "POST") {
1783
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1784
  }
1785

    
1786
  if (_is_cdm_ws_uri($uri)) {
1787
    $header['Accept'] = 'application/json';
1788
    $header['Accept-Language'] = $acceptLanguage;
1789
    $header['Accept-Charset'] = 'UTF-8';
1790
  }
1791

    
1792
  if($method == "POST") {
1793
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1794
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1795
  }
1796

    
1797
  return drupal_http_request($uri, array(
1798
      'headers' => $header,
1799
      'method' => $method,
1800
      'data' => $data,
1801
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1802
      )
1803
   );
1804
}
1805

    
1806
/**
1807
 * Concatenates recursively the fields of all features contained in the given
1808
 * CDM FeatureTree root node.
1809
 *
1810
 * @param $rootNode
1811
 *     A CDM FeatureTree node
1812
 * @param
1813
 *     The character to be used as glue for concatenation, default is ', '
1814
 * @param $field_name
1815
 *     The field name of the CDM Features
1816
 */
1817
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n') {
1818
  $out = '';
1819

    
1820
  $pre_child_separator = $separator;
1821
  $post_child_separator = '';
1822

    
1823
  foreach ($root_node->children as $feature_node) {
1824
    $out .= ($out ? $separator : '');
1825
    $out .= $feature_node->feature->$field_name;
1826
    if (is_array($feature_node->children) && count($feature_node->children) > 0) {
1827
      $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1828
      if (strlen($childlabels)) {
1829
          $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1830
      }
1831
    }
1832
  }
1833
  return $out;
1834
}
1835

    
1836
/**
1837
 * Create a one-dimensional form options array.
1838
 *
1839
 * Creates an array of all features in the feature tree of feature nodes,
1840
 * the node labels are indented by $node_char and $childIndent depending on the
1841
 * hierachy level.
1842
 *
1843
 * @param - $rootNode
1844
 * @param - $node_char
1845
 * @param - $childIndentStr
1846
 * @param - $childIndent
1847
 *   ONLY USED INTERNALLY!
1848
 *
1849
 * @return array
1850
 *   A one dimensional Drupal form options array.
1851
 */
1852
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1853
  $options = array();
1854
  foreach ($rootNode->children as $featureNode) {
1855
    $indent_prefix = '';
1856
    if ($childIndent) {
1857
      $indent_prefix = $childIndent . $node_char . " ";
1858
    }
1859
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1860
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1861
      // Foreach ($featureNode->children as $childNode){
1862
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1863
      $options = array_merge_recursive($options, $childList);
1864
      // }
1865
    }
1866
  }
1867
  return $options;
1868
}
1869

    
1870
/**
1871
 * Returns an array with all available FeatureTrees and the representations of the selected
1872
 * FeatureTree as a detail view.
1873
 *
1874
 * @param boolean $add_default_feature_free
1875
 * @return array
1876
 *  associative array with following keys:
1877
 *  -options: Returns an array with all available Feature Trees
1878
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1879
 *
1880
 */
1881
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1882

    
1883
  $options = array();
1884
  $tree_representations = array();
1885
  $feature_trees = array();
1886

    
1887
  // Set tree that contains all features.
1888
  if ($add_default_feature_free) {
1889
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1890
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1891
  }
1892

    
1893
  // Get feature trees from database.
1894
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1895
  if (is_array($persited_trees)) {
1896
    $feature_trees = array_merge($feature_trees, $persited_trees);
1897
  }
1898

    
1899
  foreach ($feature_trees as $featureTree) {
1900

    
1901
    // Do not add the DEFAULT_FEATURETREE again,
1902
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1903
      $options[$featureTree->uuid] = $featureTree->titleCache;
1904
    }
1905

    
1906
    // Render the hierarchic tree structure
1907
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1908

    
1909
      // Render the hierarchic tree structure.
1910
      $treeDetails = '<div class="featuretree_structure">'
1911
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1912
        . '</div>';
1913

    
1914
      $form = array();
1915
      $form['featureTree-' .  $featureTree->uuid] = array(
1916
        '#type' => 'fieldset',
1917
        '#title' => 'Show details',
1918
        '#attributes' => array('class' => array('collapsible collapsed')),
1919
        // '#collapsible' => TRUE,
1920
        // '#collapsed' => TRUE,
1921
      );
1922
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1923
        '#markup' => $treeDetails,
1924
      );
1925

    
1926
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1927
    }
1928

    
1929
  } // END loop over feature trees
1930

    
1931
  // return $options;
1932
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1933
}
1934

    
1935
/**
1936
 * Provides the list of availbale classifications in form of an options array.
1937
 *
1938
 * The options array is suitable for drupal form API elements that allow multiple choices.
1939
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1940
 *
1941
 * The classifications are ordered alphabetically whereas the classification
1942
 * chosen as default will always appear on top of the array, followed by a
1943
 * blank line below.
1944
 *
1945
 * @param bool $add_none_option
1946
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1947
 *
1948
 * @return array
1949
 *   classifications in an array as options for a form element that allows multiple choices.
1950
 */
1951
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1952

    
1953
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1954

    
1955
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1956
  $default_classification_label = '';
1957

    
1958
  // add all classifications
1959
  $taxonomic_tree_options = array();
1960
  if ($add_none_option) {
1961
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1962
  }
1963
  if ($taxonTrees) {
1964
    foreach ($taxonTrees as $tree) {
1965
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1966
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1967
      } else {
1968
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1969
        if (count($taxonTrees) > 1) {
1970
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1971
        }
1972
        $default_classification_label = $tree->titleCache;
1973
      }
1974
    }
1975
  }
1976
  // oder alphabetically the space
1977
  asort($taxonomic_tree_options);
1978

    
1979
  // now set the labels
1980
  //   for none
1981
  if ($add_none_option) {
1982
    $taxonomic_tree_options['NONE'] = t('-- None --');
1983
  }
1984

    
1985
  //   for default_classification
1986
  if (is_uuid($default_classification_uuid)) {
1987
    $taxonomic_tree_options[$default_classification_uuid] =
1988
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1989
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1990
  }
1991

    
1992
  return $taxonomic_tree_options;
1993
}
1994

    
1995
/**
1996
 * @todo Please document this function.
1997
 * @see http://drupal.org/node/1354
1998
 */
1999
function cdm_api_secref_cache_prefetch(&$secUuids) {
2000
  // Comment @WA: global variables should start with a single underscore
2001
  // followed by the module and another underscore.
2002
  global $_cdm_api_secref_cache;
2003
  if (!is_array($_cdm_api_secref_cache)) {
2004
    $_cdm_api_secref_cache = array();
2005
  }
2006
  $uniqueUuids = array_unique($secUuids);
2007
  $i = 0;
2008
  $param = '';
2009
  while ($i++ < count($uniqueUuids)) {
2010
    $param .= $secUuids[$i] . ',';
2011
    if (strlen($param) + 37 > 2000) {
2012
      _cdm_api_secref_cache_add($param);
2013
      $param = '';
2014
    }
2015
  }
2016
  if ($param) {
2017
    _cdm_api_secref_cache_add($param);
2018
  }
2019
}
2020

    
2021
/**
2022
 * @todo Please document this function.
2023
 * @see http://drupal.org/node/1354
2024
 */
2025
function cdm_api_secref_cache_get($secUuid) {
2026
  global $_cdm_api_secref_cache;
2027
  if (!is_array($_cdm_api_secref_cache)) {
2028
    $_cdm_api_secref_cache = array();
2029
  }
2030
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2031
    _cdm_api_secref_cache_add($secUuid);
2032
  }
2033
  return $_cdm_api_secref_cache[$secUuid];
2034
}
2035

    
2036
/**
2037
 * @todo Please document this function.
2038
 * @see http://drupal.org/node/1354
2039
 */
2040
function cdm_api_secref_cache_clear() {
2041
  global $_cdm_api_secref_cache;
2042
  $_cdm_api_secref_cache = array();
2043
}
2044

    
2045
/**
2046
 * Validates if the given string is a uuid.
2047
 *
2048
 * @param string $str
2049
 *   The string to validate.
2050
 *
2051
 * return bool
2052
 *   TRUE if the string is a UUID.
2053
 */
2054
function is_uuid($str) {
2055
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2056
}
2057

    
2058
/**
2059
 * Checks if the given $object is a valid cdm entity.
2060
 *
2061
 * An object is considered a cdm entity if it has a string field $object->class
2062
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2063
 *
2064
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2065
 *
2066
 * @param mixed $object
2067
 *   The object to validate
2068
 *
2069
 * @return bool
2070
 *   True if the object is a cdm entity.
2071
 */
2072
function is_cdm_entity($object) {
2073
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2074
}
2075

    
2076
/**
2077
 * @todo Please document this function.
2078
 * @see http://drupal.org/node/1354
2079
 */
2080
function _cdm_api_secref_cache_add($secUuidsStr) {
2081
  global $_cdm_api_secref_cache;
2082
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2083
  // Batch fetching not jet reimplemented thus:
2084
  /*
2085
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2086
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2087
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2088
  */
2089
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2090
}
2091

    
2092
/**
2093
 * Checks if the given uri starts with a cdm webservice url.
2094
 *
2095
 * Checks if the uri starts with the cdm webservice url stored in the
2096
 * Drupal variable 'cdm_webservice_url'.
2097
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2098
 *
2099
 * @param string $uri
2100
 *   The URI to test.
2101
 *
2102
 * @return bool
2103
 *   True if the uri starts with a cdm webservice url.
2104
 */
2105
function _is_cdm_ws_uri($uri) {
2106
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2107
}
2108

    
2109
/**
2110
 * @todo Please document this function.
2111
 * @see http://drupal.org/node/1354
2112
 */
2113
function queryString($elements) {
2114
  $query = '';
2115
  foreach ($elements as $key => $value) {
2116
    if (is_array($value)) {
2117
      foreach ($value as $v) {
2118
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2119
      }
2120
    }
2121
    else {
2122
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2123
    }
2124
  }
2125
  return $query;
2126
}
2127

    
2128
/**
2129
 * Implementation of the magic method __clone to allow deep cloning of objects
2130
 * and arrays.
2131
 */
2132
function __clone() {
2133
  foreach ($this as $name => $value) {
2134
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2135
      $this->$name = clone($this->$name);
2136
    }
2137
  }
2138
}
2139

    
2140
/**
2141
 * Make a 'deep copy' of an array.
2142
 *
2143
 * Make a complete deep copy of an array replacing
2144
 * references with deep copies until a certain depth is reached
2145
 * ($maxdepth) whereupon references are copied as-is...
2146
 *
2147
 * @see http://us3.php.net/manual/en/ref.array.php
2148
 *
2149
 * @param array $array
2150
 * @param array $copy passed by reference
2151
 * @param int $maxdepth
2152
 * @param int $depth
2153
 */
2154
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2155
  if ($depth > $maxdepth) {
2156
    $copy = $array;
2157
    return;
2158
  }
2159
  if (!is_array($copy)) {
2160
    $copy = array();
2161
  }
2162
  foreach ($array as $k => &$v) {
2163
    if (is_array($v)) {
2164
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2165
    }
2166
    else {
2167
      $copy[$k] = $v;
2168
    }
2169
  }
2170
}
2171

    
2172
/**
2173
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2174
 *
2175
 */
2176
function _add_js_ws_debug() {
2177

    
2178
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2179
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2180
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2181
    // use the developer versions of js libs
2182
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2183
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2184
  }
2185
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2186
    array(
2187
      'type' => 'file',
2188
      'weight' => JS_LIBRARY,
2189
      'cache' => TRUE)
2190
    );
2191

    
2192
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2193
    array(
2194
      'type' => 'file',
2195
      'weight' => JS_LIBRARY,
2196
      'cache' => TRUE)
2197
    );
2198
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2199
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2200

    
2201
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2202
    array(
2203
      'type' => 'file',
2204
      'weight' => JS_LIBRARY,
2205
      'cache' => TRUE)
2206
    );
2207
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2208
    array(
2209
    'type' => 'file',
2210
    'weight' => JS_LIBRARY,
2211
    'cache' => TRUE)
2212
    );
2213

    
2214
}
2215

    
2216
/**
2217
 * @todo Please document this function.
2218
 * @see http://drupal.org/node/1354
2219
 */
2220
function _no_classfication_uuid_message() {
2221
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2222
    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.');
2223
  }
2224
  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.');
2225
}
2226

    
2227
/**
2228
 * Implementation of hook flush_caches
2229
 *
2230
 * Add custom cache tables to the list of cache tables that
2231
 * will be cleared by the Clear button on the Performance page or whenever
2232
 * drupal_flush_all_caches is invoked.
2233
 *
2234
 * @author W.Addink <waddink@eti.uva.nl>
2235
 *
2236
 * @return array
2237
 *   An array with custom cache tables to include.
2238
 */
2239
function cdm_api_flush_caches() {
2240
  return array('cache_cdm_ws');
2241
}
(5-5/10)