Project

General

Profile

Download (66.3 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
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1113
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1114
      }
1115
      else {
1116
        // Check if taxonomictree_uuid is valid.
1117
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1118
        if ($test == NULL) {
1119
          // The default set by the admin seems to be invalid or is not even set.
1120
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1121
        }
1122
      }
1123
    }
1124

    
1125
  return $response;
1126
}
1127

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

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

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

    
1171
  return $response;
1172
}
1173

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

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

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

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

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

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

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

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

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

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

    
1300
  $merged_trees = array();
1301

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

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

    
1314
  return $feature_tree;
1315
}
1316

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

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

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

    
1351
}
1352

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

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

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

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

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

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

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

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

    
1448
  }
1449

    
1450
  return $featureNodes;
1451
}
1452

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

    
1489
  static $cacheL1 = array();
1490

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

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

    
1503
  // read request parameter 'cacheL2_refresh'
1504
  // which allows refreshig the level 2 cache
1505
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1506

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1733
  return $obj;
1734
}
1735

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1900
  foreach ($feature_trees as $featureTree) {
1901

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

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

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

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

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

    
1930
  } // END loop over feature trees
1931

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

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

    
1954
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1955

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

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

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

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

    
1993
  return $taxonomic_tree_options;
1994
}
1995

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2215
}
2216

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

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