Project

General

Profile

Download (69 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

    
267
  return $profile_featureTree;
268
}
269

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

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

    
296
/**
297
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
298
 *
299
 * The options array is suitable for drupal form API elements that allow multiple choices.
300
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
301
 *
302
 * @param array $terms
303
 *   a list of CDM DefinedTermBase instances
304
 *
305
 * @return array
306
 *   the terms in an array as options for a form element that allows multiple choices.
307
 */
308
function cdm_terms_as_options($terms){
309
  $options = array();
310
  if(isset($terms) && is_array($terms)){
311
    foreach ($terms as $term){
312
      $options[$term->uuid] = $term->representation_L10n;
313
    }
314
  }
315
  array_multisort($options, SORT_ASC);
316
  return $options;
317
}
318

    
319
/**
320
 * Returns the FeatureTree for structured descriptions
321
 *
322
 * The FeatureTree returned is the one that has been set in the
323
 * dataportal settings (layout->taxon:profile).
324
 * When the chosen FeatureTree is not found in the database,
325
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
326
 *
327
 * @return mixed
328
 *   A cdm FeatureTree object.
329
 */
330
function get_structured_description_featureTree() {
331
  static $structured_description_featureTree;
332

    
333
  if($structured_description_featureTree == NULL) {
334
    $structured_description_featureTree = cdm_ws_get(
335
        CDM_WS_FEATURETREE,
336
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
337
    );
338
    if (!$structured_description_featureTree) {
339
      $structured_description_featureTree = cdm_ws_get(
340
          CDM_WS_FEATURETREE,
341
          UUID_DEFAULT_FEATURETREE
342
      );
343
    }
344
  }
345
  return $structured_description_featureTree;
346
}
347

    
348
/**
349
 * @todo Please document this function.
350
 * @see http://drupal.org/node/1354
351
 */
352
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
353
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
354
}
355

    
356
/**
357
 * @todo Please document this function.
358
 * @see http://drupal.org/node/1354
359
 */
360
function reset_taxonomictree_uuid($taxonomictree_uuid) {
361
  unset($_SESSION['cdm']['taxonomictree_uuid']);
362
}
363

    
364
/**
365
 * @todo Please document this function.
366
 * @see http://drupal.org/node/1354
367
 */
368
function set_last_taxon_page_tab($taxonPageTab) {
369
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
370
}
371

    
372
/**
373
 * @todo Please document this function.
374
 * @see http://drupal.org/node/1354
375
 */
376
function get_last_taxon_page_tab() {
377
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
378
    return $_SESSION['cdm']['taxon_page_tab'];
379
  }
380
  else {
381
    return FALSE;
382
  }
383
}
384

    
385
/**
386
 * @todo Improve the documentation of this function.
387
 *
388
 * media Array [4]
389
 * representations Array [3]
390
 * mimeType image/jpeg
391
 * representationParts Array [1]
392
 * duration 0
393
 * heigth 0
394
 * size 0
395
 * uri
396
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
397
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
398
 * width 0
399
 * suffix jpg
400
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
401
 * title
402
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
403
 *
404
 * @param object $media
405
 * @param array $mimeTypes
406
 * @param int $width
407
 * @param int $height
408
 *
409
 * @return array
410
 *   An array with preferred media representations or else an empty array.
411
 */
412
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
413
  $prefRepr = array();
414
  if (!isset($media->representations[0])) {
415
    return $prefRepr;
416
  }
417

    
418
  while (count($mimeTypes) > 0) {
419
    // getRepresentationByMimeType
420
    $mimeType = array_shift($mimeTypes);
421

    
422
    foreach ($media->representations as &$representation) {
423
      // If the mimetype is not known, try inferring it.
424
      if (!$representation->mimeType) {
425
        if (isset($representation->parts[0])) {
426
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
427
        }
428
      }
429

    
430
      if ($representation->mimeType == $mimeType) {
431
        // Preferred mimetype found -> erase all remaining mimetypes
432
        // to end loop.
433
        $mimeTypes = array();
434
        $dwa = 0;
435
        $dw = 0;
436
        // Look for part with the best matching size.
437
        foreach ($representation->parts as $part) {
438
          if (isset($part->width) && isset($part->height)) {
439
            $dw = $part->width * $part->height - $height * $width;
440
          }
441
          if ($dw < 0) {
442
            $dw *= -1;
443
          }
444
          $dwa += $dw;
445
        }
446
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
447
        $prefRepr[$dwa . '_'] = $representation;
448
      }
449
    }
450
  }
451
  // Sort the array.
452
  krsort($prefRepr);
453
  return $prefRepr;
454
}
455

    
456
/**
457
 * Infers the mime type of a file using the filename extension.
458
 *
459
 * The filename extension is used to infer the mime type.
460
 *
461
 * @param string $filepath
462
 *   The path to the respective file.
463
 *
464
 * @return string
465
 *   The mimetype for the file or FALSE if the according mime type could
466
 *   not be found.
467
 */
468
function infer_mime_type($filepath) {
469
  static $mimemap = NULL;
470
  if (!$mimemap) {
471
    $mimemap = array(
472
      'jpg' => 'image/jpeg',
473
      'jpeg' => 'image/jpeg',
474
      'png' => 'image/png',
475
      'gif' => 'image/gif',
476
      'giff' => 'image/gif',
477
      'tif' => 'image/tif',
478
      'tiff' => 'image/tif',
479
      'pdf' => 'application/pdf',
480
      'html' => 'text/html',
481
      'htm' => 'text/html',
482
    );
483
  }
484
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
485
  if (isset($mimemap[$extension])) {
486
    return $mimemap[$extension];
487
  }
488
  else {
489
    // FIXME remove this hack just return FALSE;
490
    return 'text/html';
491
  }
492
}
493

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

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

    
539
/**
540
 * Converts an ISO 8601 org.joda.time.Partial to a day.
541
 *
542
 * This function expects an ISO 8601 time representation of a
543
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
544
 * In case the day is unknown (= ???) NULL is returned.
545
 *
546
 * @param string $partial
547
 *   ISO 8601 time representation of a org.joda.time.Partial.
548
 *
549
 * @return string
550
 *   A day.
551
 */
552
function partialToDay($partial) {
553
  if (is_string($partial)) {
554
    $day = substr($partial, 8, 2);
555
    if (preg_match("/[0-9][0-9]/", $day)) {
556
      return $day;
557
    }
558
  }
559
  return;
560
}
561

    
562
/**
563
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
564
 *
565
 * This function expects an ISO 8601 time representations of a
566
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
567
 * four digit year, month and day with dashes:
568
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
569
 *
570
 * The partial may contain question marks eg: "1973-??-??",
571
 * these are turned in to '00' or are stripped depending of the $stripZeros
572
 * parameter.
573
 *
574
 * @param string $partial
575
 *   org.joda.time.Partial.
576
 * @param bool $stripZeros
577
 *   If set to TRUE the zero (00) month and days will be hidden:
578
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
579
 *
580
 * @return string
581
 *   YYYY-MM-DD formatted year, month, day.
582
 */
583
function partialToDate($partial, $stripZeros = TRUE) {
584
  $y = partialToYear($partial);
585
  $m = partialToMonth($partial);
586
  $d = partialToDay($partial);
587

    
588
  $y = $y ? $y : '00';
589
  $m = $m ? $m : '00';
590
  $d = $d ? $d : '00';
591

    
592
  $date = '';
593

    
594
  if ($y == '00' && $stripZeros) {
595
    return;
596
  }
597
  else {
598
    $date = $y;
599
  }
600

    
601
  if ($m == '00' && $stripZeros) {
602
    return $date;
603
  }
604
  else {
605
    $date .= "-" . $m;
606
  }
607

    
608
  if ($d == '00' && $stripZeros) {
609
    return $date;
610
  }
611
  else {
612
    $date .= "-" . $d;
613
  }
614
  return $date;
615
}
616

    
617
/**
618
 * Converts a time period to a string.
619
 *
620
 * See also partialToDate($partial, $stripZeros).
621
 *
622
 * @param object $period
623
 *   An JodaTime org.joda.time.Period object.
624
 * @param bool $stripZeros
625
 *   If set to True, the zero (00) month and days will be hidden:
626
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
627
 *
628
 * @return string
629
 *   Returns a date in the form of a string.
630
 */
631
function timePeriodToString($period, $stripZeros = TRUE) {
632
  $dateString = '';
633
  if ($period->start) {
634
    $dateString = partialToDate($period->start, $stripZeros);
635
  }
636
  if ($period->end) {
637
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
638
  }
639
  return $dateString;
640
}
641
/**
642
 * returns the earliest date available in the $period in a normalized
643
 * form suitable for sorting, e.g.:
644
 *
645
 *  - 1956-00-00
646
 *  - 0000-00-00
647
 *  - 1957-03-00
648
 *
649
 * that is either the start date is returned if set otherwise the
650
 * end date
651
 *
652
 * @param  $period
653
 *    An JodaTime org.joda.time.Period object.
654
 * @return string normalized form of the date
655
 *   suitable for sorting
656
 */
657
function timePeriodAsOrderKey($period) {
658
  $dateString = '';
659
  if ($period->start) {
660
    $dateString = partialToDate($period->start, false);
661
  }
662
  if ($period->end) {
663
    $dateString .= partialToDate($period->end, false);
664
  }
665
  return $dateString;
666
}
667

    
668
/**
669
 * Composes a absolute CDM web service URI with parameters and querystring.
670
 *
671
 * @param string $uri_pattern
672
 *   String with place holders ($0, $1, ..) that should be replaced by the
673
 *   according element of the $pathParameters array.
674
 * @param array $pathParameters
675
 *   An array of path elements, or a single element.
676
 * @param string $query
677
 *   A query string to append to the URL.
678
 *
679
 * @return string
680
 *   A complete URL with parameters to a CDM webservice.
681
 */
682
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
683
  if (empty($pathParameters)) {
684
    $pathParameters = array();
685
  }
686

    
687
  $request_params = '';
688
  $path_params = '';
689

    
690
  // (1)
691
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
692
  // according element of the $pathParameters array.
693
  static $helperArray = array();
694
  if (isset($pathParameters) && !is_array($pathParameters)) {
695
    $helperArray[0] = $pathParameters;
696
    $pathParameters = $helperArray;
697
  }
698

    
699
  $i = 0;
700
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
701
    if (count($pathParameters) <= $i) {
702
      if (module_exists("user") && user_access('administer')) {
703
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
704
      }
705
      break;
706
    }
707
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
708
    ++$i;
709
  }
710

    
711
  // (2)
712
  // Append all remaining element of the $pathParameters array as path
713
  // elements.
714
  if (count($pathParameters) > $i) {
715
    // Strip trailing slashes.
716
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
717
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
718
    }
719
    while (count($pathParameters) > $i) {
720
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
721
      ++$i;
722
    }
723
  }
724

    
725
  // (3)
726
  // Append the query string supplied by $query.
727
  if (isset($query)) {
728
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
729
  }
730

    
731
  $path = $uri_pattern;
732

    
733
  $uri = variable_get('cdm_webservice_url', '') . $path;
734
  return $uri;
735
}
736

    
737
/**
738
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
739
 *     together with a theme name to such a proxy function?
740
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
741
 *     Maybe we want to have two different proxy functions, one with theming and one without?
742
 *
743
 * @param string $uri
744
 *     A URI to a CDM Rest service from which to retrieve an object
745
 * @param string|null $hook
746
 *     (optional) The hook name to which the retrieved object should be passed.
747
 *     Hooks can either be a theme_hook() or compose_hook() implementation
748
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
749
 *     suitable for drupal_render()
750
 *
751
 * @todo Please document this function.
752
 * @see http://drupal.org/node/1354
753
 */
754
function proxy_content($uri, $hook = NULL) {
755

    
756
  $args = func_get_args();
757
  $do_gzip = function_exists('gzencode');
758
  $uriEncoded = array_shift($args);
759
  $uri = urldecode($uriEncoded);
760
  $hook = array_shift($args);
761
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
762

    
763
  $post_data = null;
764

    
765
  if ($request_method == "POST" || $request_method == "PUT") {
766
    // read response body via inputstream module
767
    $post_data = file_get_contents("php://input");
768
  }
769

    
770
  // Find and deserialize arrays.
771
  foreach ($args as &$arg) {
772
    // FIXME use regex to find serialized arrays.
773
    //       or should we accept json instead of php serializations?
774
    if (strpos($arg, "a:") === 0) {
775
      $arg = unserialize($arg);
776
    }
777
  }
778

    
779
  // In all these cases perform a simple get request.
780
  // TODO reconsider caching logic in this function.
781

    
782
  if (empty($hook)) {
783
    // simply return the webservice response
784
    // Print out JSON, the cache cannot be used since it contains objects.
785
    $http_response = cdm_http_request($uri, $request_method, $post_data);
786
    if (isset($http_response->headers)) {
787
      foreach ($http_response->headers as $hname => $hvalue) {
788
        drupal_add_http_header($hname, $hvalue);
789
      }
790
    }
791
    if (isset($http_response->data)) {
792
      print $http_response->data;
793
      flush();
794
    }
795
    exit(); // leave drupal here
796
  } else {
797
    // $hook has been supplied
798
    // handle $hook either as compose ot theme hook
799
    // pass through theme or comose hook
800

    
801
    // do a security check since the $uri will be passed
802
    // as absolute URI to cdm_ws_get()
803
    if( !_is_cdm_ws_uri($uri)) {
804
      drupal_set_message(
805
      'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
806
      'error'
807
          );
808
          return '';
809
    }
810

    
811
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
812

    
813
    $reponse_data = NULL;
814

    
815
    if (function_exists('compose_' . $hook)){
816
      // call compose hook
817

    
818
      $elements =  call_user_func('compose_' . $hook, $obj);
819
      // pass the render array to drupal_render()
820
      $reponse_data = drupal_render($elements);
821
    } else {
822
      // call theme hook
823

    
824
      // TODO use theme registry to get the registered hook info and
825
      //    use these defaults
826
      switch($hook) {
827
        case 'cdm_taxontree':
828
          $variables = array(
829
          'tree' => $obj,
830
          'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
831
          'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
832
          'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
833
          'element_name'=> isset($args[3]) ? $args[3] : FALSE,
834
          );
835
          $reponse_data = theme($hook, $variables);
836
          break;
837

    
838
        case 'cdm_media_caption':
839
          $variables = array(
840
          'media' => $obj,
841
          // $args[0] is set in taxon_image_gallery_default in
842
          // cdm_dataportal.page.theme.
843
          'elements' => isset($args[0]) ? $args[0] : array(
844
          'title',
845
          'description',
846
          'artist',
847
          'location',
848
          'rights',
849
          ),
850
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
851
          );
852
          $reponse_data = theme($hook, $variables);
853
          break;
854

    
855
        default:
856
          drupal_set_message(t(
857
          'Theme !theme is not supported yet by function !function.', array(
858
          '!theme' => $hook,
859
          '!function' => __FUNCTION__,
860
          )), 'error');
861
          break;
862
      } // END of theme hook switch
863
    } // END of tread as theme hook
864

    
865

    
866
    if($do_gzip){
867
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
868
      drupal_add_http_header('Content-Encoding', 'gzip');
869
    }
870
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
871
    drupal_add_http_header('Content-Length', strlen($reponse_data));
872

    
873
    print $reponse_data;
874
  } // END of handle $hook either as compose ot theme hook
875

    
876
}
877

    
878
/**
879
 * @todo Please document this function.
880
 * @see http://drupal.org/node/1354
881
 */
882
function setvalue_session() {
883
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
884
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
885
    $keys = explode('][', $keys);
886
  }
887
  else {
888
    return;
889
  }
890
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
891

    
892
  // Prevent from malicous tags.
893
  $val = strip_tags($val);
894

    
895
  $var = &$_SESSION;
896
  $i = 0;
897
  foreach ($keys as $key) {
898
    $hasMoreKeys = ++$i < count($var);
899
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
900
      $var[$key] = array();
901
    }
902
    $var = &$var[$key];
903
  }
904
  $var = $val;
905
  if (isset($_REQUEST['destination'])) {
906
    drupal_goto($_REQUEST['destination']);
907
  }
908
}
909

    
910
/**
911
 * @todo Please document this function.
912
 * @see http://drupal.org/node/1354
913
 */
914
function uri_uriByProxy($uri, $theme = FALSE) {
915
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
916
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
917
}
918

    
919
/**
920
 * Composes the the absolute REST service URI to the annotations pager
921
 * for the given CDM entity.
922
 *
923
 * NOTE: Not all CDM Base types are yet supported.
924
 *
925
 * @param $cdmBase
926
 *   The CDM entity to construct the annotations pager uri for
927
 */
928
function cdm_compose_annotations_uri($cdmBase) {
929
  if (!$cdmBase->uuid) {
930
    return;
931
  }
932

    
933
  $ws_base_uri = NULL;
934
  switch ($cdmBase->class) {
935
    case 'TaxonBase':
936
    case 'Taxon':
937
    case 'Synonym':
938
      $ws_base_uri = CDM_WS_TAXON;
939
      break;
940

    
941
    case 'TaxonNameBase':
942
    case 'NonViralName':
943
    case 'BacterialName':
944
    case 'BotanicalName':
945
    case 'CultivarPlantName':
946
    case 'ZoologicalName':
947
    case 'ViralName':
948
      $ws_base_uri = CDM_WS_NAME;
949
      break;
950

    
951
    case 'Media':
952
      $ws_base_uri = CDM_WS_MEDIA;
953
      break;
954

    
955
    case 'Reference':
956
      $ws_base_uri = CDM_WS_REFERENCE;
957
      break;
958

    
959
    case 'Distribution':
960
    case 'TextData':
961
    case 'TaxonInteraction':
962
    case 'QuantitativeData':
963
    case 'IndividualsAssociation':
964
    case 'Distribution':
965
    case 'CommonTaxonName':
966
    case 'CategoricalData':
967
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
968
      break;
969

    
970
    case 'PolytomousKey':
971
    case 'MediaKey':
972
    case 'MultiAccessKey':
973
      $ws_base_uri = $cdmBase->class;
974
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
975
      break;
976

    
977
    default:
978
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
979
      return;
980
  }
981
  return cdm_compose_url($ws_base_uri, array(
982
    $cdmBase->uuid,
983
    'annotations',
984
  ));
985
}
986

    
987
/**
988
 * Enter description here...
989
 *
990
 * @param string $resourceURI
991
 * @param int $pageSize
992
 *   The maximum number of entities returned per page.
993
 *   The default page size as configured in the cdm server
994
 *   will be used if set to NULL
995
 *   to return all entities in a single page).
996
 * @param int $pageNumber
997
 *   The number of the page to be returned, the first page has the
998
 *   pageNumber = 0
999
 * @param array $query
1000
 *   A array holding the HTTP request query parameters for the request
1001
 * @param string $method
1002
 *   The HTTP method to use, valid values are "GET" or "POST"
1003
 * @param bool $absoluteURI
1004
 *   TRUE when the URL should be treated as absolute URL.
1005
 *
1006
 * @return the a CDM Pager object
1007
 *
1008
 */
1009
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1010

    
1011
  $query['pageNumber'] = $pageNumber;
1012
  $query['pageSize'] = $pageSize;
1013

    
1014
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1015
}
1016

    
1017
/**
1018
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1019
 *
1020
 * @param string $resourceURI
1021
 * @param array $query
1022
 *   A array holding the HTTP request query parameters for the request
1023
 * @param string $method
1024
 *   The HTTP method to use, valid values are "GET" or "POST";
1025
 * @param bool $absoluteURI
1026
 *   TRUE when the URL should be treated as absolute URL.
1027
 *
1028
 * @return array
1029
 *     A list of CDM entitites
1030
 *
1031
 */
1032
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1033
  $page_index = 0;
1034
  // using a bigger page size to avoid to many multiple requests
1035
  $page_size = 500;
1036
  $entities = array();
1037

    
1038
  while ($page_index !== FALSE){
1039
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1040
    if(isset($pager->records) && is_array($pager->records)) {
1041
      $entities = $pager->records;
1042
      if(!empty($pager->nextIndex)){
1043
        $page_index = $pager->nextIndex;
1044
      } else {
1045
        $page_index = FALSE;
1046
      }
1047
    } else {
1048
      $page_index = FALSE;
1049
    }
1050
  }
1051
  return $entities;
1052
}
1053

    
1054
/*
1055
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1056
  $viewrank = _cdm_taxonomy_compose_viewrank();
1057
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1058
  ? '/' . $path : '') ;
1059
}
1060
*/
1061

    
1062
/**
1063
 * @todo Enter description here...
1064
 *
1065
 * @param string $taxon_uuid
1066
 *  The UUID of a cdm taxon instance
1067
 * @param string $ignore_rank_limit
1068
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1069
 *
1070
 * @return A cdm REST service URL path to a Classification
1071
 */
1072
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1073

    
1074
  $view_uuid = get_taxonomictree_uuid_selected();
1075
  $rank_uuid = NULL;
1076
  if (!$ignore_rank_limit) {
1077
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1078
  }
1079

    
1080
  if (!empty($taxon_uuid)) {
1081
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1082
      $view_uuid,
1083
      $taxon_uuid,
1084
    ));
1085
  }
1086
  else {
1087
    if (!empty($rank_uuid)) {
1088
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1089
        $view_uuid,
1090
        $rank_uuid,
1091
      ));
1092
    }
1093
    else {
1094
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1095
        $view_uuid,
1096
      ));
1097
    }
1098
  }
1099
}
1100

    
1101
/**
1102
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1103
 *
1104
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1105
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1106
 *
1107
 * Operates in two modes depending on whether the parameter
1108
 * $taxon_uuid is set or NULL.
1109
 *
1110
 * A) $taxon_uuid = NULL:
1111
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1112
 *  2. otherwise return the default classification as defined by the admin via the settings
1113
 *
1114
 * b) $taxon_uuid is set:
1115
 *   return the classification to whcih the taxon belongs to.
1116
 *
1117
 * @param UUID $taxon_uuid
1118
 *   The UUID of a cdm taxon instance
1119
 */
1120
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1121

    
1122
    $response = NULL;
1123

    
1124
    // 1st try
1125
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1126

    
1127
    if ($response == NULL) {
1128
      // 2dn try by ignoring the rank limit
1129
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1130
    }
1131

    
1132
    if ($response == NULL) {
1133
      // 3rd try, last fallback:
1134
      //    return the default classification
1135
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1136
        // Delete the session value and try again with the default.
1137
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1138
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1139
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1140
      }
1141
      else {
1142
        // Check if taxonomictree_uuid is valid.
1143
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1144
        if ($test == NULL) {
1145
          // The default set by the admin seems to be invalid or is not even set.
1146
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1147
        }
1148
      }
1149
    }
1150

    
1151
  return $response;
1152
}
1153

    
1154
/**
1155
 * @todo Enter description here...
1156
 *
1157
 * @param string $taxon_uuid
1158
 *
1159
 * @return unknown
1160
 */
1161
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1162
  $view_uuid = get_taxonomictree_uuid_selected();
1163
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1164

    
1165
  $response = NULL;
1166
  if ($rank_uuid) {
1167
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1168
      $view_uuid,
1169
      $taxon_uuid,
1170
      $rank_uuid,
1171
    ));
1172
  }
1173
  else {
1174
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1175
      $view_uuid,
1176
      $taxon_uuid,
1177
    ));
1178
  }
1179

    
1180
  if ($response == NULL) {
1181
    // Error handing.
1182
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1183
      // Delete the session value and try again with the default.
1184
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1185
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1186
    }
1187
    else {
1188
      // Check if taxonomictree_uuid is valid.
1189
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1190
      if ($test == NULL) {
1191
        // The default set by the admin seems to be invalid or is not even set.
1192
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1193
      }
1194
    }
1195
  }
1196

    
1197
  return $response;
1198
}
1199

    
1200
/**
1201
 * @todo Please document this function.
1202
 * @see http://drupal.org/node/1354
1203
 */
1204
function cdm_rankVocabulary_as_option() {
1205
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1206
  array_unshift ($options, "");
1207
  return $options;
1208
}
1209

    
1210
/**
1211
 *
1212
 * @param Object $definedTermBase
1213
 * 	  of cdm type DefinedTermBase
1214
 * @return string
1215
 * 	  the localized representation_L10n of the term,
1216
 *    otherwise the titleCache as fall back,
1217
 *    otherwise an empty string
1218
 */
1219
function cdm_term_representation($definedTermBase) {
1220
  if ( isset($definedTermBase->representation_L10n) ) {
1221
    return $definedTermBase->representation_L10n;
1222
  } elseif ( isset($definedTermBase->titleCache)) {
1223
    return $definedTermBase->titleCache;
1224
  }
1225
  return '';
1226
}
1227

    
1228
/**
1229
 * @todo Improve documentation of this function.
1230
 *
1231
 * eu.etaxonomy.cdm.model.description.
1232
 * CategoricalData
1233
 * CommonTaxonName
1234
 * Distribution
1235
 * IndividualsAssociation
1236
 * QuantitativeData
1237
 * TaxonInteraction
1238
 * TextData
1239
 */
1240
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1241
  static $types = array(
1242
    "CategoricalData",
1243
    "CommonTaxonName",
1244
    "Distribution",
1245
    "IndividualsAssociation",
1246
    "QuantitativeData",
1247
    "TaxonInteraction",
1248
    "TextData",
1249
  );
1250

    
1251
  static $options = NULL;
1252
  if ($options == NULL) {
1253
    $options = array();
1254
    if ($prependEmptyElement) {
1255
      $options[' '] = '';
1256
    }
1257
    foreach ($types as $type) {
1258
      // No internatianalization here since these are purely technical terms.
1259
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1260
    }
1261
  }
1262
  return $options;
1263
}
1264

    
1265
/**
1266
 * @todo Please document this function.
1267
 * @see http://drupal.org/node/1354
1268
 */
1269
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1270
  static $vocabularyOptions = array();
1271

    
1272
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1273
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1274
    $vocabularyOptions[$vocabularyUuid] = array();
1275

    
1276
    if ($terms) {
1277
      foreach ($terms as $term) {
1278
        if ($term_label_callback && function_exists($term_label_callback)) {
1279
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1280
        }
1281
        else {
1282
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1283
        }
1284
      }
1285
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1286
    }
1287
  }
1288
  return $vocabularyOptions[$vocabularyUuid];
1289
}
1290

    
1291
/**
1292
 * @todo Please document this function.
1293
 * @see http://drupal.org/node/1354
1294
 */
1295
function _cdm_relationship_type_term_label_callback($term) {
1296
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1297
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1298
  }
1299
  else {
1300
    return t($term->representation_L10n);
1301
  }
1302
}
1303

    
1304
/**
1305
 * Fetches all TaxonDescription descriptions elements wich are accociated to the
1306
 * Taxon specified by the $taxon_uuid and megres the elements into the given
1307
 * feature tree.
1308
 * @param $feature_tree
1309
 *     The CDM FeatureTree to be used as template
1310
 * @param $taxon_uuid
1311
 *     The UUID of the taxon
1312
 * @param $excludes
1313
 *     UUIDs of features to be excluded
1314
 * @return$feature_tree
1315
 *     The CDM FeatureTree wich was given as parameter merged tree wheras the
1316
 *     CDM FeatureNodes are extended by an additinal field 'descriptionElements'
1317
 *     witch will hold the accoding $descriptionElements.
1318
 */
1319
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1320

    
1321
  if (!$feature_tree) {
1322
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1323
      In order to see the species profiles of your taxa, please select a
1324
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1325
    return FALSE;
1326
  }
1327

    
1328
  $merged_trees = array();
1329

    
1330
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1331
      array(
1332
      'taxon' => $taxon_uuid,
1333
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1334
      ),
1335
      'POST'
1336
  );
1337

    
1338
  // Combine all descripions into one feature tree.
1339
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1340
  $feature_tree->root->childNodes = $merged_nodes;
1341

    
1342
  return $feature_tree;
1343
}
1344

    
1345
/**
1346
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1347
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1348
 * be requested for the annotations.
1349
 *
1350
 * @param string $cdmBase
1351
 *   An annotatable cdm entity.
1352
 * @param array $includeTypes
1353
 *   If an array of annotation type uuids is supplied by this parameter the
1354
 *   list of annotations is resticted to those which belong to this type.
1355
 *
1356
 * @return array
1357
 *   An array of Annotation objects or an empty array.
1358
 */
1359
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1360

    
1361
  if(!isset($cdmBase->annotations)){
1362
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1363
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1364
  }
1365

    
1366
  $annotations = array();
1367
  foreach ($cdmBase->annotations as $annotation) {
1368
    if ($includeTypes) {
1369
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1370
        $annotations[] = $annotation;
1371
      }
1372
    }
1373
    else {
1374
      $annotations[] = $annotation;
1375
    }
1376
  }
1377
  return $annotations;
1378

    
1379
}
1380

    
1381
/**
1382
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1383
 *
1384
 * @param object $annotatable_entity
1385
 *   The CDM AnnotatableEntity to load annotations for
1386
 */
1387
function cdm_load_annotations(&$annotatable_entity) {
1388
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1389
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1390
    if (is_array($annotations)) {
1391
      $annotatable_entity->annotations = $annotations;
1392
    }
1393
  }
1394
}
1395

    
1396
/**
1397
 * Get a NomenclaturalReference string.
1398
 *
1399
 * Returns the NomenclaturalReference string with correctly placed
1400
 * microreference (= reference detail) e.g.
1401
 * in Phytotaxa 43: 1-48. 2012.
1402
 *
1403
 * @param string $referenceUuid
1404
 *   UUID of the reference.
1405
 * @param string $microreference
1406
 *   Reference detail.
1407
 *
1408
 * @return string
1409
 *   a NomenclaturalReference.
1410
 */
1411
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1412
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1413
    $referenceUuid,
1414
  ), "microReference=" . urlencode($microreference));
1415

    
1416
  if ($obj) {
1417
    return $obj->String;
1418
  }
1419
  else {
1420
    return NULL;
1421
  }
1422
}
1423

    
1424
/**
1425
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1426
 *
1427
 * @param $feature_tree_nodes
1428
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1429
 * @param $feature_uuid
1430
 *    The UUID of the Feature
1431
 * @return returns the FeatureNode or null
1432
 */
1433
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1434

    
1435
  // 1. scan this level
1436
  foreach ($feature_tree_nodes as $node){
1437
    if($node->feature->uuid == $feature_uuid){
1438
      return $node;
1439
    }
1440
  }
1441

    
1442
  // 2. descend into childen
1443
  foreach ($feature_tree_nodes as $node){
1444
    if(is_array($node->childNodes)){
1445
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1446
      if($node) {
1447
        return $node;
1448
      }
1449
    }
1450
  }
1451
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1452
  return $null_var;
1453
}
1454

    
1455
/**
1456
 * Merges the given featureNodes structure with the descriptionElements.
1457
 *
1458
 * This method is used in preparation for rendering the descriptionElements.
1459
 * The descriptionElements wich belong to a specific feature node are appended
1460
 * to a the feature node by creating a new field:
1461
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1462
 * The descriptionElements will be cleared in advance in order to allow reusing the
1463
 * same feature tree without the risk of mixing sets of descrition elemens.
1464
 *
1465
 * which originally is not existing in the cdm.
1466
 *
1467
 *
1468
 *
1469
 * @param array $featureNodes
1470
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1471
 *    may have children.
1472
 * @param array $descriptionElements
1473
 *    An flat array of cdm DescriptionElements
1474
 * @return array
1475
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1476
 */
1477
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1478

    
1479
  foreach ($featureNodes as &$node) {
1480
    // since the $featureNodes array is reused for each description
1481
    // it is nessecary to clear the custom node fields in advance
1482
    if(isset($node->descriptionElements)){
1483
      unset($node->descriptionElements);
1484
    }
1485

    
1486
    // Append corresponding elements to an additional node field:
1487
    // $node->descriptionElements.
1488
    foreach ($descriptionElements as $element) {
1489
      if ($element->feature->uuid == $node->feature->uuid) {
1490
        if (!isset($node->descriptionElements)) {
1491
          $node->descriptionElements = array();
1492
        }
1493
        $node->descriptionElements[] = $element;
1494
      }
1495
    }
1496

    
1497
    // Recurse into node children.
1498
    if (isset($node->childNodes[0])) {
1499
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1500
      $node->childNodes = $mergedChildNodes;
1501
    }
1502

    
1503
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1504
      unset($node);
1505
    }
1506

    
1507
  }
1508

    
1509
  return $featureNodes;
1510
}
1511

    
1512
/**
1513
 * Sends a GET or POST request to a CDM RESTService and returns a deserialized object.
1514
 *
1515
 * The response from the HTTP GET request is returned as object.
1516
 * The response objects coming from the webservice configured in the
1517
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1518
 *  in a level 2 (L2) cache.
1519
 *
1520
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1521
 * function, this cache persists only per each single page execution.
1522
 * Any object coming from the webservice is stored into it by default.
1523
 * In contrast to this default caching mechanism the L2 cache only is used if
1524
 * the 'cdm_webservice_cache' variable is set to TRUE,
1525
 * which can be set using the modules administrative settings section.
1526
 * Objects stored in this L2 cache are serialized and stored
1527
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1528
 * objects that are stored in the database will persist as
1529
 * long as the drupal cache is not beeing cleared and are available across
1530
 * multiple script executions.
1531
 *
1532
 * @param string $uri
1533
 *   URL to the webservice.
1534
 * @param array $pathParameters
1535
 *   An array of path parameters.
1536
 * @param string $query
1537
 *   A query string to be appended to the URL.
1538
 * @param string $method
1539
 *   The HTTP method to use, valid values are "GET" or "POST";
1540
 * @param bool $absoluteURI
1541
 *   TRUE when the URL should be treated as absolute URL.
1542
 *
1543
 * @return object
1544
 *   The deserialized webservice response object.
1545
 */
1546
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1547

    
1548
  static $cacheL1 = array();
1549

    
1550
  $data = NULL;
1551
  // store query string in $data and clear the query, $data will be set as HTTP request body
1552
  if($method == 'POST'){
1553
    $data = $query;
1554
    $query = NULL;
1555
  }
1556

    
1557
  // Transform the given uri path or pattern into a proper webservice uri.
1558
  if (!$absoluteURI) {
1559
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1560
  }
1561

    
1562
  // read request parameter 'cacheL2_refresh'
1563
  // which allows refreshig the level 2 cache
1564
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1565

    
1566
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1567
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1568

    
1569
  if($method == 'GET'){
1570
    $cache_key = $uri;
1571
  } else {
1572
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1573
    // crc32 is faster but creates much shorter hashes
1574
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1575
  }
1576

    
1577
  if (array_key_exists($cache_key, $cacheL1)) {
1578
    $cacheL1_obj = $cacheL1[$uri];
1579
  }
1580

    
1581
  $set_cacheL1 = FALSE;
1582
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1583
    $set_cacheL1 = TRUE;
1584
  }
1585

    
1586
  // Only cache cdm webservice URIs.
1587
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1588
  $cacheL2_entry = FALSE;
1589

    
1590
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1591
    // Try to get object from cacheL2.
1592
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1593
  }
1594

    
1595
  if (isset($cacheL1_obj)) {
1596
    //
1597
    // The object has been found in the L1 cache.
1598
    //
1599
    $obj = $cacheL1_obj;
1600
    if (cdm_debug_block_visible()) {
1601
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1602
    }
1603
  }
1604
  elseif ($cacheL2_entry) {
1605
    //
1606
    // The object has been found in the L2 cache.
1607
    //
1608
    $duration_parse_start = microtime(TRUE);
1609
    $obj = unserialize($cacheL2_entry->data);
1610
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1611

    
1612
    if (cdm_debug_block_visible()) {
1613
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1614
    }
1615
  }
1616
  else {
1617
    //
1618
    // Get the object from the webservice and cache it.
1619
    //
1620
    $duration_fetch_start = microtime(TRUE);
1621
    // Request data from webservice JSON or XML.
1622
    $response = cdm_http_request($uri, $method, $data);
1623
    $response_body = NULL;
1624
    if (isset($response->data)) {
1625
      $response_body = $response->data;
1626
    }
1627
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1628
    $duration_parse_start = microtime(TRUE);
1629

    
1630
    // Parse data and create object.
1631
    $obj = cdm_load_obj($response_body);
1632

    
1633
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1634

    
1635
    if (cdm_debug_block_visible()) {
1636
      if ($obj || $response_body == "[]") {
1637
        $status = 'valid';
1638
      }
1639
      else {
1640
        $status = 'invalid';
1641
      }
1642
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1643
    }
1644
    if ($set_cacheL2) {
1645
      // Store the object in cache L2.
1646
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1647
      // flag serialized is set properly in the cache table.
1648
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1649
    }
1650
  }
1651
  if ($obj) {
1652
    // Store the object in cache L1.
1653
    if ($set_cacheL1) {
1654
      $cacheL1[$cache_key] = $obj;
1655
    }
1656
  }
1657
  return $obj;
1658
}
1659

    
1660
/**
1661
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1662
 *
1663
 * The cdm_ws_debug block will display the debug information.
1664
 *
1665
 * @param $uri
1666
 *    The CDM REST URI to which the request has been send
1667
 * @param string $method
1668
 *    The HTTP request method, either 'GET' or 'POST'
1669
 * @param string $post_data
1670
 *    The datastring send with a post request
1671
 * @param $duration_fetch
1672
 *    The time in seconds it took to fetch the data from the web service
1673
 * @param $duration_parse
1674
 *    Time in seconds which was needed to parse the json response
1675
 * @param $datasize
1676
 *    Size of the data received from the server
1677
 * @param $status
1678
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1679
 * @return bool
1680
 *    TRUE if adding the debug information was successful
1681
 */
1682
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1683

    
1684
  static $initial_time = NULL;
1685
  if(!$initial_time) {
1686
    $initial_time = microtime(TRUE);
1687
  }
1688
  $time = microtime(TRUE) - $initial_time;
1689

    
1690
  // Decompose uri into path and query element.
1691
  $uri_parts = explode("?", $uri);
1692
  $query = array();
1693
  if (count($uri_parts) == 2) {
1694
    $path = $uri_parts[0];
1695
  }
1696
  else {
1697
    $path = $uri;
1698
  }
1699

    
1700
  if(strpos($uri, '?') > 0){
1701
    $json_uri = str_replace('?', '.json?', $uri);
1702
    $xml_uri = str_replace('?', '.xml?', $uri);
1703
  } else {
1704
    $json_uri = $uri . '.json';
1705
    $xml_uri = $json_uri . '.xml';
1706
  }
1707

    
1708
  // data links to make data accecsible as json and xml
1709
  $data_links = '';
1710
  if (_is_cdm_ws_uri($path)) {
1711

    
1712
    // see ./js/http-method-link.js
1713

    
1714
    if($method == 'GET'){
1715
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1716
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1717
      $data_links .= '<br/>';
1718
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1719
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1720
    } else {
1721
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1722
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1723
      $data_links .= '<br/>';
1724
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1725
    }
1726
  }
1727
  else {
1728
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1729
  }
1730

    
1731
  //
1732
  $data = array(
1733
      'ws_uri' => $uri,
1734
      'method' => $method,
1735
      'post_data' => $post_data,
1736
      'time' => sprintf('%3.3f', $time),
1737
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1738
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1739
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1740
      'status' => $status,
1741
      'data_links' => $data_links
1742
  );
1743
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1744
    $_SESSION['cdm']['ws_debug'] = array();
1745
  }
1746
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1747

    
1748
  // Mark this page as being uncacheable.
1749
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1750
  drupal_page_is_cacheable(FALSE);
1751

    
1752
  // Messages not set when DB connection fails.
1753
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1754
}
1755

    
1756
/**
1757
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1758
 * the visibility depends on whether
1759
 *  - the block is enabled
1760
 *  - the visibility restrictions in the block settings are satisfied
1761
 */
1762
function cdm_debug_block_visible() {
1763
  static $is_visible = null;
1764

    
1765
  if($is_visible === null){
1766
      $block = block_load('cdm_api', 'cdm_ws_debug');
1767
      $is_visible = isset($block->status) && $block->status == 1;
1768
      if($is_visible){
1769
        $blocks = array($block);
1770
        // Checks the page, user role, and user-specific visibilty settings.
1771
        block_block_list_alter($blocks);
1772
        $is_visible = count($blocks) > 0;
1773
      }
1774
  }
1775
  return $is_visible;
1776
}
1777

    
1778
/**
1779
 * @todo Please document this function.
1780
 * @see http://drupal.org/node/1354
1781
 */
1782
function cdm_load_obj($response_body) {
1783
  $obj = json_decode($response_body);
1784

    
1785
  if (!(is_object($obj) || is_array($obj))) {
1786
    ob_start();
1787
    $obj_dump = ob_get_contents();
1788
    ob_clean();
1789
    return FALSE;
1790
  }
1791

    
1792
  return $obj;
1793
}
1794

    
1795
/**
1796
 * Do a http request to a CDM RESTful web service.
1797
 *
1798
 * @param string $uri
1799
 *   The webservice url.
1800
 * @param string $method
1801
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1802
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1803
 * @param $data: A string containing the request body, formatted as
1804
 *     'param=value&param=value&...'. Defaults to NULL.
1805
 *
1806
 * @return object
1807
 *   The object as returned by drupal_http_request():
1808
 *   An object that can have one or more of the following components:
1809
 *   - request: A string containing the request body that was sent.
1810
 *   - code: An integer containing the response status code, or the error code
1811
 *     if an error occurred.
1812
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1813
 *   - status_message: The status message from the response, if a response was
1814
 *     received.
1815
 *   - redirect_code: If redirected, an integer containing the initial response
1816
 *     status code.
1817
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1818
 *     target.
1819
 *   - error: If an error occurred, the error message. Otherwise not set.
1820
 *   - headers: An array containing the response headers as name/value pairs.
1821
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1822
 *     easy access the array keys are returned in lower case.
1823
 *   - data: A string containing the response body that was received.
1824
 */
1825
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1826
  static $acceptLanguage = NULL;
1827
  $header = array();
1828

    
1829
  if (!$acceptLanguage) {
1830
    if (function_exists('apache_request_headers')) {
1831
      $headers = apache_request_headers();
1832
      if (isset($headers['Accept-Language'])) {
1833
        $acceptLanguage = $headers['Accept-Language'];
1834
      }
1835
    }
1836
    if (!$acceptLanguage) {
1837
      // DEFAULT TODO make configurable.
1838
      $acceptLanguage = "en";
1839
    }
1840
  }
1841

    
1842
  if ($method != "GET" && $method != "POST") {
1843
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1844
  }
1845

    
1846
  if (_is_cdm_ws_uri($uri)) {
1847
    $header['Accept'] = 'application/json';
1848
    $header['Accept-Language'] = $acceptLanguage;
1849
    $header['Accept-Charset'] = 'UTF-8';
1850
  }
1851

    
1852
  if($method == "POST") {
1853
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1854
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1855
  }
1856

    
1857

    
1858
  cdm_dd($uri);
1859
  return drupal_http_request($uri, array(
1860
      'headers' => $header,
1861
      'method' => $method,
1862
      'data' => $data,
1863
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1864
      )
1865
   );
1866
}
1867

    
1868
/**
1869
 * Concatenates recursively the fields of all features contained in the given
1870
 * CDM FeatureTree root node.
1871
 *
1872
 * @param $rootNode
1873
 *     A CDM FeatureTree node
1874
 * @param
1875
 *     The character to be used as glue for concatenation, default is ', '
1876
 * @param $field_name
1877
 *     The field name of the CDM Features
1878
 * @param $excludes
1879
 *     Allows defining a set of values to be excluded. This refers to the values
1880
 *     in the field denoted by the $field_name parameter
1881
 *
1882
 */
1883
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
1884
  $out = '';
1885

    
1886
  $pre_child_separator = $separator;
1887
  $post_child_separator = '';
1888

    
1889
  foreach ($root_node->childNodes as $feature_node) {
1890
    $out .= ($out ? $separator : '');
1891
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
1892
      $out .= $feature_node->feature->$field_name;
1893
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
1894
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1895
        if (strlen($childlabels)) {
1896
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1897
        }
1898
      }
1899
    }
1900
  }
1901
  return $out;
1902
}
1903

    
1904
/**
1905
 * Create a one-dimensional form options array.
1906
 *
1907
 * Creates an array of all features in the feature tree of feature nodes,
1908
 * the node labels are indented by $node_char and $childIndent depending on the
1909
 * hierachy level.
1910
 *
1911
 * @param - $rootNode
1912
 * @param - $node_char
1913
 * @param - $childIndentStr
1914
 * @param - $childIndent
1915
 *   ONLY USED INTERNALLY!
1916
 *
1917
 * @return array
1918
 *   A one dimensional Drupal form options array.
1919
 */
1920
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1921
  $options = array();
1922
  foreach ($rootNode->childNodes as $featureNode) {
1923
    $indent_prefix = '';
1924
    if ($childIndent) {
1925
      $indent_prefix = $childIndent . $node_char . " ";
1926
    }
1927
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1928
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
1929
      // Foreach ($featureNode->childNodes as $childNode){
1930
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1931
      $options = array_merge_recursive($options, $childList);
1932
      // }
1933
    }
1934
  }
1935
  return $options;
1936
}
1937

    
1938
/**
1939
 * Returns an array with all available FeatureTrees and the representations of the selected
1940
 * FeatureTree as a detail view.
1941
 *
1942
 * @param boolean $add_default_feature_free
1943
 * @return array
1944
 *  associative array with following keys:
1945
 *  -options: Returns an array with all available Feature Trees
1946
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1947
 *
1948
 */
1949
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1950

    
1951
  $options = array();
1952
  $tree_representations = array();
1953
  $feature_trees = array();
1954

    
1955
  // Set tree that contains all features.
1956
  if ($add_default_feature_free) {
1957
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1958
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1959
  }
1960

    
1961
  // Get feature trees from database.
1962
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1963
  if (is_array($persited_trees)) {
1964
    $feature_trees = array_merge($feature_trees, $persited_trees);
1965
  }
1966

    
1967
  foreach ($feature_trees as $featureTree) {
1968

    
1969
    // Do not add the DEFAULT_FEATURETREE again,
1970
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1971
      $options[$featureTree->uuid] = $featureTree->titleCache;
1972
    }
1973

    
1974
    // Render the hierarchic tree structure
1975
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
1976

    
1977
      // Render the hierarchic tree structure.
1978
      $treeDetails = '<div class="featuretree_structure">'
1979
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1980
        . '</div>';
1981

    
1982
      $form = array();
1983
      $form['featureTree-' .  $featureTree->uuid] = array(
1984
        '#type' => 'fieldset',
1985
        '#title' => 'Show details',
1986
        '#attributes' => array('class' => array('collapsible collapsed')),
1987
        // '#collapsible' => TRUE,
1988
        // '#collapsed' => TRUE,
1989
      );
1990
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1991
        '#markup' => $treeDetails,
1992
      );
1993

    
1994
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1995
    }
1996

    
1997
  } // END loop over feature trees
1998

    
1999
  // return $options;
2000
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2001
}
2002

    
2003
/**
2004
 * Provides the list of availbale classifications in form of an options array.
2005
 *
2006
 * The options array is suitable for drupal form API elements that allow multiple choices.
2007
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2008
 *
2009
 * The classifications are ordered alphabetically whereas the classification
2010
 * chosen as default will always appear on top of the array, followed by a
2011
 * blank line below.
2012
 *
2013
 * @param bool $add_none_option
2014
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2015
 *
2016
 * @return array
2017
 *   classifications in an array as options for a form element that allows multiple choices.
2018
 */
2019
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2020

    
2021
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
2022

    
2023
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2024
  $default_classification_label = '';
2025

    
2026
  // add all classifications
2027
  $taxonomic_tree_options = array();
2028
  if ($add_none_option) {
2029
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2030
  }
2031
  if ($taxonTrees) {
2032
    foreach ($taxonTrees as $tree) {
2033
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2034
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2035
      } else {
2036
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2037
        if (count($taxonTrees) > 1) {
2038
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
2039
        }
2040
        $default_classification_label = $tree->titleCache;
2041
      }
2042
    }
2043
  }
2044
  // oder alphabetically the space
2045
  asort($taxonomic_tree_options);
2046

    
2047
  // now set the labels
2048
  //   for none
2049
  if ($add_none_option) {
2050
    $taxonomic_tree_options['NONE'] = t('-- None --');
2051
  }
2052

    
2053
  //   for default_classification
2054
  if (is_uuid($default_classification_uuid)) {
2055
    $taxonomic_tree_options[$default_classification_uuid] =
2056
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2057
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2058
  }
2059

    
2060
  return $taxonomic_tree_options;
2061
}
2062

    
2063
/**
2064
 * @todo Please document this function.
2065
 * @see http://drupal.org/node/1354
2066
 */
2067
function cdm_api_secref_cache_prefetch(&$secUuids) {
2068
  // Comment @WA: global variables should start with a single underscore
2069
  // followed by the module and another underscore.
2070
  global $_cdm_api_secref_cache;
2071
  if (!is_array($_cdm_api_secref_cache)) {
2072
    $_cdm_api_secref_cache = array();
2073
  }
2074
  $uniqueUuids = array_unique($secUuids);
2075
  $i = 0;
2076
  $param = '';
2077
  while ($i++ < count($uniqueUuids)) {
2078
    $param .= $secUuids[$i] . ',';
2079
    if (strlen($param) + 37 > 2000) {
2080
      _cdm_api_secref_cache_add($param);
2081
      $param = '';
2082
    }
2083
  }
2084
  if ($param) {
2085
    _cdm_api_secref_cache_add($param);
2086
  }
2087
}
2088

    
2089
/**
2090
 * @todo Please document this function.
2091
 * @see http://drupal.org/node/1354
2092
 */
2093
function cdm_api_secref_cache_get($secUuid) {
2094
  global $_cdm_api_secref_cache;
2095
  if (!is_array($_cdm_api_secref_cache)) {
2096
    $_cdm_api_secref_cache = array();
2097
  }
2098
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2099
    _cdm_api_secref_cache_add($secUuid);
2100
  }
2101
  return $_cdm_api_secref_cache[$secUuid];
2102
}
2103

    
2104
/**
2105
 * @todo Please document this function.
2106
 * @see http://drupal.org/node/1354
2107
 */
2108
function cdm_api_secref_cache_clear() {
2109
  global $_cdm_api_secref_cache;
2110
  $_cdm_api_secref_cache = array();
2111
}
2112

    
2113

    
2114
/**
2115
 * Validates if the given string is a uuid.
2116
 *
2117
 * @param string $str
2118
 *   The string to validate.
2119
 *
2120
 * return bool
2121
 *   TRUE if the string is a UUID.
2122
 */
2123
function is_uuid($str) {
2124
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2125
}
2126

    
2127
/**
2128
 * Checks if the given $object is a valid cdm entity.
2129
 *
2130
 * An object is considered a cdm entity if it has a string field $object->class
2131
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2132
 *
2133
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2134
 *
2135
 * @param mixed $object
2136
 *   The object to validate
2137
 *
2138
 * @return bool
2139
 *   True if the object is a cdm entity.
2140
 */
2141
function is_cdm_entity($object) {
2142
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2143
}
2144

    
2145
/**
2146
 * @todo Please document this function.
2147
 * @see http://drupal.org/node/1354
2148
 */
2149
function _cdm_api_secref_cache_add($secUuidsStr) {
2150
  global $_cdm_api_secref_cache;
2151
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2152
  // Batch fetching not jet reimplemented thus:
2153
  /*
2154
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2155
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2156
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2157
  */
2158
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2159
}
2160

    
2161
/**
2162
 * Checks if the given uri starts with a cdm webservice url.
2163
 *
2164
 * Checks if the uri starts with the cdm webservice url stored in the
2165
 * Drupal variable 'cdm_webservice_url'.
2166
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2167
 *
2168
 * @param string $uri
2169
 *   The URI to test.
2170
 *
2171
 * @return bool
2172
 *   True if the uri starts with a cdm webservice url.
2173
 */
2174
function _is_cdm_ws_uri($uri) {
2175
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2176
}
2177

    
2178
/**
2179
 * @todo Please document this function.
2180
 * @see http://drupal.org/node/1354
2181
 */
2182
function queryString($elements) {
2183
  $query = '';
2184
  foreach ($elements as $key => $value) {
2185
    if (is_array($value)) {
2186
      foreach ($value as $v) {
2187
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2188
      }
2189
    }
2190
    else {
2191
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2192
    }
2193
  }
2194
  return $query;
2195
}
2196

    
2197
/**
2198
 * Implementation of the magic method __clone to allow deep cloning of objects
2199
 * and arrays.
2200
 */
2201
function __clone() {
2202
  foreach ($this as $name => $value) {
2203
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2204
      $this->$name = clone($this->$name);
2205
    }
2206
  }
2207
}
2208

    
2209
/**
2210
 * Make a 'deep copy' of an array.
2211
 *
2212
 * Make a complete deep copy of an array replacing
2213
 * references with deep copies until a certain depth is reached
2214
 * ($maxdepth) whereupon references are copied as-is...
2215
 *
2216
 * @see http://us3.php.net/manual/en/ref.array.php
2217
 *
2218
 * @param array $array
2219
 * @param array $copy passed by reference
2220
 * @param int $maxdepth
2221
 * @param int $depth
2222
 */
2223
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2224
  if ($depth > $maxdepth) {
2225
    $copy = $array;
2226
    return;
2227
  }
2228
  if (!is_array($copy)) {
2229
    $copy = array();
2230
  }
2231
  foreach ($array as $k => &$v) {
2232
    if (is_array($v)) {
2233
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2234
    }
2235
    else {
2236
      $copy[$k] = $v;
2237
    }
2238
  }
2239
}
2240

    
2241
/**
2242
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2243
 *
2244
 */
2245
function _add_js_ws_debug() {
2246

    
2247
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2248
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2249
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2250
    // use the developer versions of js libs
2251
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2252
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2253
  }
2254
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2255
    array(
2256
      'type' => 'file',
2257
      'weight' => JS_LIBRARY,
2258
      'cache' => TRUE)
2259
    );
2260

    
2261
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2262
    array(
2263
      'type' => 'file',
2264
      'weight' => JS_LIBRARY,
2265
      'cache' => TRUE)
2266
    );
2267
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2268
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2269

    
2270
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2271
    array(
2272
      'type' => 'file',
2273
      'weight' => JS_LIBRARY,
2274
      'cache' => TRUE)
2275
    );
2276
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2277
    array(
2278
    'type' => 'file',
2279
    'weight' => JS_LIBRARY,
2280
    'cache' => TRUE)
2281
    );
2282

    
2283
}
2284

    
2285
/**
2286
 * @todo Please document this function.
2287
 * @see http://drupal.org/node/1354
2288
 */
2289
function _no_classfication_uuid_message() {
2290
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2291
    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.');
2292
  }
2293
  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.');
2294
}
2295

    
2296
/**
2297
 * Implementation of hook flush_caches
2298
 *
2299
 * Add custom cache tables to the list of cache tables that
2300
 * will be cleared by the Clear button on the Performance page or whenever
2301
 * drupal_flush_all_caches is invoked.
2302
 *
2303
 * @author W.Addink <waddink@eti.uva.nl>
2304
 *
2305
 * @return array
2306
 *   An array with custom cache tables to include.
2307
 */
2308
function cdm_api_flush_caches() {
2309
  return array('cache_cdm_ws');
2310
}
2311

    
2312
/**
2313
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2314
 *
2315
 * @param $data
2316
 *   The variable to log to the drupal_debug.txt log file.
2317
 * @param $label
2318
 *   (optional) If set, a label to output before $data in the log file.
2319
 *
2320
 * @return
2321
 *   No return value if successful, FALSE if the log file could not be written
2322
 *   to.
2323
 *
2324
 * @see cdm_dataportal_init() where the log file is reset on each requests
2325
 * @see dd()
2326
 * @see http://drupal.org/node/314112
2327
 *
2328
 */
2329
function cdm_dd($data, $label = NULL) {
2330
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2331
    return dd($data, $label);
2332
  }
2333
}
2334

    
(5-5/10)