Project

General

Profile

Download (68.9 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
  if ($request_method == "POST" || $request_method == "PUT") {
764
    // read response body via inputstream module
765
    $post_data = file_get_contents("php://input");
766
  }
767

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

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

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

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

    
809
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
810

    
811
    $reponse_data = NULL;
812

    
813
    if (function_exists('compose_' . $hook)){
814
      // call compose hook
815

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

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

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

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

    
863

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

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

    
874
}
875

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

    
890
  // Prevent from malicous tags.
891
  $val = strip_tags($val);
892

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

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

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

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

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

    
949
    case 'Media':
950
      $ws_base_uri = CDM_WS_MEDIA;
951
      break;
952

    
953
    case 'Reference':
954
      $ws_base_uri = CDM_WS_REFERENCE;
955
      break;
956

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

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

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

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

    
1009
  $query['pageNumber'] = $pageNumber;
1010
  $query['pageSize'] = $pageSize;
1011

    
1012
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1013
}
1014

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

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

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

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

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

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

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

    
1120
    $response = NULL;
1121

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

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

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

    
1149
  return $response;
1150
}
1151

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

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

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

    
1195
  return $response;
1196
}
1197

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

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

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

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

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

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

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

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

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

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

    
1326
  $merged_trees = array();
1327

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

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

    
1340
  return $feature_tree;
1341
}
1342

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

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

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

    
1377
}
1378

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

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

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

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

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

    
1440
  // 2. descend into childen
1441
  foreach ($feature_tree_nodes as $node){
1442
    if(is_array($node->childNodes)){
1443
      $node = cdm_feature_tree_find_node($node->children);
1444
      if($node) {
1445
        return $node;
1446
      }
1447
    }
1448
  }
1449

    
1450
  return null;
1451
}
1452

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

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

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

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

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

    
1505
  }
1506

    
1507
  return $featureNodes;
1508
}
1509

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

    
1546
  static $cacheL1 = array();
1547

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

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

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

    
1564
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1565
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1566

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

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

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

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

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

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

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

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

    
1631
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1632

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

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

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

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

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

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

    
1710
    // see ./js/http-method-link.js
1711

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

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

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

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

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

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

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

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

    
1790
  return $obj;
1791
}
1792

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

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

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

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

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

    
1855

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

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

    
1884
  $pre_child_separator = $separator;
1885
  $post_child_separator = '';
1886

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

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

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

    
1949
  $options = array();
1950
  $tree_representations = array();
1951
  $feature_trees = array();
1952

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

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

    
1965
  foreach ($feature_trees as $featureTree) {
1966

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

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

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

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

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

    
1995
  } // END loop over feature trees
1996

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

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

    
2019
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
2020

    
2021
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2022
  $default_classification_label = '';
2023

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

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

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

    
2058
  return $taxonomic_tree_options;
2059
}
2060

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

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

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

    
2111

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

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

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

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

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

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

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

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

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

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

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

    
2281
}
2282

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

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

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

    
(5-5/10)