Project

General

Profile

Download (69.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
 * @param string @format
580
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
581
 *    - "YYYY": Year only
582
 *    - "YYYY-MM-DD": this is the default
583
 *
584
 * @return string
585
 *   YYYY-MM-DD formatted year, month, day.
586
 */
587
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
588

    
589
  $y = NULL; $m = NULL; $d = NULL;
590

    
591
  if(strpos($format, 'YY') !== FALSE){
592
    $y = partialToYear($partial);
593
  }
594
  if(strpos($format, 'MM') !== FALSE){
595
    $m = partialToMonth($partial);
596
  }
597
  if(strpos($format, 'DD') !== FALSE){
598
    $d = partialToDay($partial);
599
  }
600

    
601
  $y = $y ? $y : '00';
602
  $m = $m ? $m : '00';
603
  $d = $d ? $d : '00';
604

    
605
  $date = '';
606

    
607
  if ($y == '00' && $stripZeros) {
608
    return;
609
  }
610
  else {
611
    $date = $y;
612
  }
613

    
614
  if ($m == '00' && $stripZeros) {
615
    return $date;
616
  }
617
  else {
618
    $date .= "-" . $m;
619
  }
620

    
621
  if ($d == '00' && $stripZeros) {
622
    return $date;
623
  }
624
  else {
625
    $date .= "-" . $d;
626
  }
627
  return $date;
628
}
629

    
630
/**
631
 * Converts a time period to a string.
632
 *
633
 * See also partialToDate($partial, $stripZeros).
634
 *
635
 * @param object $period
636
 *   An JodaTime org.joda.time.Period object.
637
 * @param bool $stripZeros
638
 *   If set to True, the zero (00) month and days will be hidden:
639
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
640
 * @param string @format
641
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
642
 *    - "YYYY": Year only
643
 *    - "YYYY-MM-DD": this is the default
644
 *
645
 * @return string
646
 *   Returns a date in the form of a string.
647
 */
648
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
649
  $dateString = '';
650
  if ($period->start) {
651
    $dateString = partialToDate($period->start, $stripZeros, $format);
652
  }
653
  if ($period->end) {
654
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
655
  }
656
  return $dateString;
657
}
658

    
659
/**
660
 * returns the earliest date available in the $period in a normalized
661
 * form suitable for sorting, e.g.:
662
 *
663
 *  - 1956-00-00
664
 *  - 0000-00-00
665
 *  - 1957-03-00
666
 *
667
 * that is either the start date is returned if set otherwise the
668
 * end date
669
 *
670
 * @param  $period
671
 *    An JodaTime org.joda.time.Period object.
672
 * @return string normalized form of the date
673
 *   suitable for sorting
674
 */
675
function timePeriodAsOrderKey($period) {
676
  $dateString = '';
677
  if ($period->start) {
678
    $dateString = partialToDate($period->start, false);
679
  }
680
  if ($period->end) {
681
    $dateString .= partialToDate($period->end, false);
682
  }
683
  return $dateString;
684
}
685

    
686
/**
687
 * Composes a absolute CDM web service URI with parameters and querystring.
688
 *
689
 * @param string $uri_pattern
690
 *   String with place holders ($0, $1, ..) that should be replaced by the
691
 *   according element of the $pathParameters array.
692
 * @param array $pathParameters
693
 *   An array of path elements, or a single element.
694
 * @param string $query
695
 *   A query string to append to the URL.
696
 *
697
 * @return string
698
 *   A complete URL with parameters to a CDM webservice.
699
 */
700
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
701
  if (empty($pathParameters)) {
702
    $pathParameters = array();
703
  }
704

    
705
  $request_params = '';
706
  $path_params = '';
707

    
708
  // (1)
709
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
710
  // according element of the $pathParameters array.
711
  static $helperArray = array();
712
  if (isset($pathParameters) && !is_array($pathParameters)) {
713
    $helperArray[0] = $pathParameters;
714
    $pathParameters = $helperArray;
715
  }
716

    
717
  $i = 0;
718
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
719
    if (count($pathParameters) <= $i) {
720
      if (module_exists("user") && user_access('administer')) {
721
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
722
      }
723
      break;
724
    }
725
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
726
    ++$i;
727
  }
728

    
729
  // (2)
730
  // Append all remaining element of the $pathParameters array as path
731
  // elements.
732
  if (count($pathParameters) > $i) {
733
    // Strip trailing slashes.
734
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
735
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
736
    }
737
    while (count($pathParameters) > $i) {
738
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
739
      ++$i;
740
    }
741
  }
742

    
743
  // (3)
744
  // Append the query string supplied by $query.
745
  if (isset($query)) {
746
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
747
  }
748

    
749
  $path = $uri_pattern;
750

    
751
  $uri = variable_get('cdm_webservice_url', '') . $path;
752
  return $uri;
753
}
754

    
755
/**
756
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
757
 *     together with a theme name to such a proxy function?
758
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
759
 *     Maybe we want to have two different proxy functions, one with theming and one without?
760
 *
761
 * @param string $uri
762
 *     A URI to a CDM Rest service from which to retrieve an object
763
 * @param string|null $hook
764
 *     (optional) The hook name to which the retrieved object should be passed.
765
 *     Hooks can either be a theme_hook() or compose_hook() implementation
766
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
767
 *     suitable for drupal_render()
768
 *
769
 * @todo Please document this function.
770
 * @see http://drupal.org/node/1354
771
 */
772
function proxy_content($uri, $hook = NULL) {
773

    
774
  $args = func_get_args();
775
  $do_gzip = function_exists('gzencode');
776
  $uriEncoded = array_shift($args);
777
  $uri = urldecode($uriEncoded);
778
  $hook = array_shift($args);
779
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
780

    
781
  $post_data = null;
782

    
783
  if ($request_method == "POST" || $request_method == "PUT") {
784
    // read response body via inputstream module
785
    $post_data = file_get_contents("php://input");
786
  }
787

    
788
  // Find and deserialize arrays.
789
  foreach ($args as &$arg) {
790
    // FIXME use regex to find serialized arrays.
791
    //       or should we accept json instead of php serializations?
792
    if (strpos($arg, "a:") === 0) {
793
      $arg = unserialize($arg);
794
    }
795
  }
796

    
797
  // In all these cases perform a simple get request.
798
  // TODO reconsider caching logic in this function.
799

    
800
  if (empty($hook)) {
801
    // simply return the webservice response
802
    // Print out JSON, the cache cannot be used since it contains objects.
803
    $http_response = cdm_http_request($uri, $request_method, $post_data);
804
    if (isset($http_response->headers)) {
805
      foreach ($http_response->headers as $hname => $hvalue) {
806
        drupal_add_http_header($hname, $hvalue);
807
      }
808
    }
809
    if (isset($http_response->data)) {
810
      print $http_response->data;
811
      flush();
812
    }
813
    exit(); // leave drupal here
814
  } else {
815
    // $hook has been supplied
816
    // handle $hook either as compose ot theme hook
817
    // pass through theme or comose hook
818

    
819
    // do a security check since the $uri will be passed
820
    // as absolute URI to cdm_ws_get()
821
    if( !_is_cdm_ws_uri($uri)) {
822
      drupal_set_message(
823
      'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
824
      'error'
825
          );
826
          return '';
827
    }
828

    
829
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
830

    
831
    $reponse_data = NULL;
832

    
833
    if (function_exists('compose_' . $hook)){
834
      // call compose hook
835

    
836
      $elements =  call_user_func('compose_' . $hook, $obj);
837
      // pass the render array to drupal_render()
838
      $reponse_data = drupal_render($elements);
839
    } else {
840
      // call theme hook
841

    
842
      // TODO use theme registry to get the registered hook info and
843
      //    use these defaults
844
      switch($hook) {
845
        case 'cdm_taxontree':
846
          $variables = array(
847
            'tree' => $obj,
848
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
849
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
850
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
851
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
852
            );
853
          $reponse_data = theme($hook, $variables);
854
          break;
855

    
856
        case 'cdm_list_of_taxa':
857
            $variables = array(
858
              'records' => $obj,
859
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
860
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
861
            $reponse_data = theme($hook, $variables);
862
            break;
863

    
864
        case 'cdm_media_caption':
865
          $variables = array(
866
          'media' => $obj,
867
          // $args[0] is set in taxon_image_gallery_default in
868
          // cdm_dataportal.page.theme.
869
          'elements' => isset($args[0]) ? $args[0] : array(
870
          'title',
871
          'description',
872
          'artist',
873
          'location',
874
          'rights',
875
          ),
876
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
877
          );
878
          $reponse_data = theme($hook, $variables);
879
          break;
880

    
881
        default:
882
          drupal_set_message(t(
883
          'Theme !theme is not yet supported by the function !function.', array(
884
          '!theme' => $hook,
885
          '!function' => __FUNCTION__,
886
          )), 'error');
887
          break;
888
      } // END of theme hook switch
889
    } // END of tread as theme hook
890

    
891

    
892
    if($do_gzip){
893
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
894
      drupal_add_http_header('Content-Encoding', 'gzip');
895
    }
896
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
897
    drupal_add_http_header('Content-Length', strlen($reponse_data));
898

    
899
    print $reponse_data;
900
  } // END of handle $hook either as compose ot theme hook
901

    
902
}
903

    
904
/**
905
 * @todo Please document this function.
906
 * @see http://drupal.org/node/1354
907
 */
908
function setvalue_session() {
909
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
910
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
911
    $keys = explode('][', $keys);
912
  }
913
  else {
914
    return;
915
  }
916
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
917

    
918
  // Prevent from malicous tags.
919
  $val = strip_tags($val);
920

    
921
  $var = &$_SESSION;
922
  $i = 0;
923
  foreach ($keys as $key) {
924
    $hasMoreKeys = ++$i < count($var);
925
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
926
      $var[$key] = array();
927
    }
928
    $var = &$var[$key];
929
  }
930
  $var = $val;
931
  if (isset($_REQUEST['destination'])) {
932
    drupal_goto($_REQUEST['destination']);
933
  }
934
}
935

    
936
/**
937
 * @todo Please document this function.
938
 * @see http://drupal.org/node/1354
939
 */
940
function uri_uriByProxy($uri, $theme = FALSE) {
941
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
942
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
943
}
944

    
945
/**
946
 * Composes the the absolute REST service URI to the annotations pager
947
 * for the given CDM entity.
948
 *
949
 * NOTE: Not all CDM Base types are yet supported.
950
 *
951
 * @param $cdmBase
952
 *   The CDM entity to construct the annotations pager uri for
953
 */
954
function cdm_compose_annotations_uri($cdmBase) {
955
  if (!$cdmBase->uuid) {
956
    return;
957
  }
958

    
959
  $ws_base_uri = NULL;
960
  switch ($cdmBase->class) {
961
    case 'TaxonBase':
962
    case 'Taxon':
963
    case 'Synonym':
964
      $ws_base_uri = CDM_WS_TAXON;
965
      break;
966

    
967
    case 'TaxonNameBase':
968
    case 'NonViralName':
969
    case 'BacterialName':
970
    case 'BotanicalName':
971
    case 'CultivarPlantName':
972
    case 'ZoologicalName':
973
    case 'ViralName':
974
      $ws_base_uri = CDM_WS_NAME;
975
      break;
976

    
977
    case 'Media':
978
      $ws_base_uri = CDM_WS_MEDIA;
979
      break;
980

    
981
    case 'Reference':
982
      $ws_base_uri = CDM_WS_REFERENCE;
983
      break;
984

    
985
    case 'Distribution':
986
    case 'TextData':
987
    case 'TaxonInteraction':
988
    case 'QuantitativeData':
989
    case 'IndividualsAssociation':
990
    case 'Distribution':
991
    case 'CommonTaxonName':
992
    case 'CategoricalData':
993
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
994
      break;
995

    
996
    case 'PolytomousKey':
997
    case 'MediaKey':
998
    case 'MultiAccessKey':
999
      $ws_base_uri = $cdmBase->class;
1000
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1001
      break;
1002

    
1003
    default:
1004
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1005
      return;
1006
  }
1007
  return cdm_compose_url($ws_base_uri, array(
1008
    $cdmBase->uuid,
1009
    'annotations',
1010
  ));
1011
}
1012

    
1013
/**
1014
 * Enter description here...
1015
 *
1016
 * @param string $resourceURI
1017
 * @param int $pageSize
1018
 *   The maximum number of entities returned per page.
1019
 *   The default page size as configured in the cdm server
1020
 *   will be used if set to NULL
1021
 *   to return all entities in a single page).
1022
 * @param int $pageNumber
1023
 *   The number of the page to be returned, the first page has the
1024
 *   pageNumber = 0
1025
 * @param array $query
1026
 *   A array holding the HTTP request query parameters for the request
1027
 * @param string $method
1028
 *   The HTTP method to use, valid values are "GET" or "POST"
1029
 * @param bool $absoluteURI
1030
 *   TRUE when the URL should be treated as absolute URL.
1031
 *
1032
 * @return the a CDM Pager object
1033
 *
1034
 */
1035
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1036

    
1037
  $query['pageNumber'] = $pageNumber;
1038
  $query['pageSize'] = $pageSize;
1039

    
1040
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1041
}
1042

    
1043
/**
1044
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1045
 *
1046
 * @param string $resourceURI
1047
 * @param array $query
1048
 *   A array holding the HTTP request query parameters for the request
1049
 * @param string $method
1050
 *   The HTTP method to use, valid values are "GET" or "POST";
1051
 * @param bool $absoluteURI
1052
 *   TRUE when the URL should be treated as absolute URL.
1053
 *
1054
 * @return array
1055
 *     A list of CDM entitites
1056
 *
1057
 */
1058
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1059
  $page_index = 0;
1060
  // using a bigger page size to avoid to many multiple requests
1061
  $page_size = 500;
1062
  $entities = array();
1063

    
1064
  while ($page_index !== FALSE){
1065
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1066
    if(isset($pager->records) && is_array($pager->records)) {
1067
      $entities = $pager->records;
1068
      if(!empty($pager->nextIndex)){
1069
        $page_index = $pager->nextIndex;
1070
      } else {
1071
        $page_index = FALSE;
1072
      }
1073
    } else {
1074
      $page_index = FALSE;
1075
    }
1076
  }
1077
  return $entities;
1078
}
1079

    
1080
/*
1081
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1082
  $viewrank = _cdm_taxonomy_compose_viewrank();
1083
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1084
  ? '/' . $path : '') ;
1085
}
1086
*/
1087

    
1088
/**
1089
 * @todo Enter description here...
1090
 *
1091
 * @param string $taxon_uuid
1092
 *  The UUID of a cdm taxon instance
1093
 * @param string $ignore_rank_limit
1094
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1095
 *
1096
 * @return A cdm REST service URL path to a Classification
1097
 */
1098
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1099

    
1100
  $view_uuid = get_taxonomictree_uuid_selected();
1101
  $rank_uuid = NULL;
1102
  if (!$ignore_rank_limit) {
1103
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1104
  }
1105

    
1106
  if (!empty($taxon_uuid)) {
1107
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1108
      $view_uuid,
1109
      $taxon_uuid,
1110
    ));
1111
  }
1112
  else {
1113
    if (!empty($rank_uuid)) {
1114
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1115
        $view_uuid,
1116
        $rank_uuid,
1117
      ));
1118
    }
1119
    else {
1120
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1121
        $view_uuid,
1122
      ));
1123
    }
1124
  }
1125
}
1126

    
1127
/**
1128
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1129
 *
1130
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1131
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1132
 *
1133
 * Operates in two modes depending on whether the parameter
1134
 * $taxon_uuid is set or NULL.
1135
 *
1136
 * A) $taxon_uuid = NULL:
1137
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1138
 *  2. otherwise return the default classification as defined by the admin via the settings
1139
 *
1140
 * b) $taxon_uuid is set:
1141
 *   return the classification to whcih the taxon belongs to.
1142
 *
1143
 * @param UUID $taxon_uuid
1144
 *   The UUID of a cdm taxon instance
1145
 */
1146
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1147

    
1148
    $response = NULL;
1149

    
1150
    // 1st try
1151
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1152

    
1153
    if ($response == NULL) {
1154
      // 2dn try by ignoring the rank limit
1155
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1156
    }
1157

    
1158
    if ($response == NULL) {
1159
      // 3rd try, last fallback:
1160
      //    return the default classification
1161
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1162
        // Delete the session value and try again with the default.
1163
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1164
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1165
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1166
      }
1167
      else {
1168
        // Check if taxonomictree_uuid is valid.
1169
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1170
        if ($test == NULL) {
1171
          // The default set by the admin seems to be invalid or is not even set.
1172
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1173
        }
1174
      }
1175
    }
1176

    
1177
  return $response;
1178
}
1179

    
1180
/**
1181
 * @todo Enter description here...
1182
 *
1183
 * @param string $taxon_uuid
1184
 *
1185
 * @return unknown
1186
 */
1187
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1188
  $view_uuid = get_taxonomictree_uuid_selected();
1189
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1190

    
1191
  $response = NULL;
1192
  if ($rank_uuid) {
1193
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1194
      $view_uuid,
1195
      $taxon_uuid,
1196
      $rank_uuid,
1197
    ));
1198
  }
1199
  else {
1200
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1201
      $view_uuid,
1202
      $taxon_uuid,
1203
    ));
1204
  }
1205

    
1206
  if ($response == NULL) {
1207
    // Error handing.
1208
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1209
      // Delete the session value and try again with the default.
1210
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1211
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1212
    }
1213
    else {
1214
      // Check if taxonomictree_uuid is valid.
1215
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1216
      if ($test == NULL) {
1217
        // The default set by the admin seems to be invalid or is not even set.
1218
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1219
      }
1220
    }
1221
  }
1222

    
1223
  return $response;
1224
}
1225

    
1226
/**
1227
 * @todo Please document this function.
1228
 * @see http://drupal.org/node/1354
1229
 */
1230
function cdm_rankVocabulary_as_option() {
1231
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1232
  array_unshift ($options, "");
1233
  return $options;
1234
}
1235

    
1236
/**
1237
 *
1238
 * @param Object $definedTermBase
1239
 * 	  of cdm type DefinedTermBase
1240
 * @return string
1241
 * 	  the localized representation_L10n of the term,
1242
 *    otherwise the titleCache as fall back,
1243
 *    otherwise an empty string
1244
 */
1245
function cdm_term_representation($definedTermBase) {
1246
  if ( isset($definedTermBase->representation_L10n) ) {
1247
    return $definedTermBase->representation_L10n;
1248
  } elseif ( isset($definedTermBase->titleCache)) {
1249
    return $definedTermBase->titleCache;
1250
  }
1251
  return '';
1252
}
1253

    
1254
/**
1255
 * @todo Improve documentation of this function.
1256
 *
1257
 * eu.etaxonomy.cdm.model.description.
1258
 * CategoricalData
1259
 * CommonTaxonName
1260
 * Distribution
1261
 * IndividualsAssociation
1262
 * QuantitativeData
1263
 * TaxonInteraction
1264
 * TextData
1265
 */
1266
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1267
  static $types = array(
1268
    "CategoricalData",
1269
    "CommonTaxonName",
1270
    "Distribution",
1271
    "IndividualsAssociation",
1272
    "QuantitativeData",
1273
    "TaxonInteraction",
1274
    "TextData",
1275
  );
1276

    
1277
  static $options = NULL;
1278
  if ($options == NULL) {
1279
    $options = array();
1280
    if ($prependEmptyElement) {
1281
      $options[' '] = '';
1282
    }
1283
    foreach ($types as $type) {
1284
      // No internatianalization here since these are purely technical terms.
1285
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1286
    }
1287
  }
1288
  return $options;
1289
}
1290

    
1291
/**
1292
 * @todo Please document this function.
1293
 * @see http://drupal.org/node/1354
1294
 */
1295
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1296
  static $vocabularyOptions = array();
1297

    
1298
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1299
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1300
    $vocabularyOptions[$vocabularyUuid] = array();
1301

    
1302
    if ($terms) {
1303
      foreach ($terms as $term) {
1304
        if ($term_label_callback && function_exists($term_label_callback)) {
1305
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1306
        }
1307
        else {
1308
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1309
        }
1310
      }
1311
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1312
    }
1313
  }
1314
  return $vocabularyOptions[$vocabularyUuid];
1315
}
1316

    
1317
/**
1318
 * @todo Please document this function.
1319
 * @see http://drupal.org/node/1354
1320
 */
1321
function _cdm_relationship_type_term_label_callback($term) {
1322
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1323
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1324
  }
1325
  else {
1326
    return t($term->representation_L10n);
1327
  }
1328
}
1329

    
1330
/**
1331
 * Fetches all TaxonDescription descriptions elements wich are accociated to the
1332
 * Taxon specified by the $taxon_uuid and megres the elements into the given
1333
 * feature tree.
1334
 * @param $feature_tree
1335
 *     The CDM FeatureTree to be used as template
1336
 * @param $taxon_uuid
1337
 *     The UUID of the taxon
1338
 * @param $excludes
1339
 *     UUIDs of features to be excluded
1340
 * @return$feature_tree
1341
 *     The CDM FeatureTree wich was given as parameter merged tree wheras the
1342
 *     CDM FeatureNodes are extended by an additinal field 'descriptionElements'
1343
 *     witch will hold the accoding $descriptionElements.
1344
 */
1345
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1346

    
1347
  if (!$feature_tree) {
1348
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1349
      In order to see the species profiles of your taxa, please select a
1350
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1351
    return FALSE;
1352
  }
1353

    
1354
  $merged_trees = array();
1355

    
1356
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1357
      array(
1358
      'taxon' => $taxon_uuid,
1359
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1360
      ),
1361
      'POST'
1362
  );
1363

    
1364
  // Combine all descripions into one feature tree.
1365
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1366
  $feature_tree->root->childNodes = $merged_nodes;
1367

    
1368
  return $feature_tree;
1369
}
1370

    
1371
/**
1372
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1373
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1374
 * be requested for the annotations.
1375
 *
1376
 * @param string $cdmBase
1377
 *   An annotatable cdm entity.
1378
 * @param array $includeTypes
1379
 *   If an array of annotation type uuids is supplied by this parameter the
1380
 *   list of annotations is resticted to those which belong to this type.
1381
 *
1382
 * @return array
1383
 *   An array of Annotation objects or an empty array.
1384
 */
1385
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1386

    
1387
  if(!isset($cdmBase->annotations)){
1388
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1389
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1390
  }
1391

    
1392
  $annotations = array();
1393
  foreach ($cdmBase->annotations as $annotation) {
1394
    if ($includeTypes) {
1395
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1396
        $annotations[] = $annotation;
1397
      }
1398
    }
1399
    else {
1400
      $annotations[] = $annotation;
1401
    }
1402
  }
1403
  return $annotations;
1404

    
1405
}
1406

    
1407
/**
1408
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1409
 *
1410
 * @param object $annotatable_entity
1411
 *   The CDM AnnotatableEntity to load annotations for
1412
 */
1413
function cdm_load_annotations(&$annotatable_entity) {
1414
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1415
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1416
    if (is_array($annotations)) {
1417
      $annotatable_entity->annotations = $annotations;
1418
    }
1419
  }
1420
}
1421

    
1422
/**
1423
 * Get a NomenclaturalReference string.
1424
 *
1425
 * Returns the NomenclaturalReference string with correctly placed
1426
 * microreference (= reference detail) e.g.
1427
 * in Phytotaxa 43: 1-48. 2012.
1428
 *
1429
 * @param string $referenceUuid
1430
 *   UUID of the reference.
1431
 * @param string $microreference
1432
 *   Reference detail.
1433
 *
1434
 * @return string
1435
 *   a NomenclaturalReference.
1436
 */
1437
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1438
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1439
    $referenceUuid,
1440
  ), "microReference=" . urlencode($microreference));
1441

    
1442
  if ($obj) {
1443
    return $obj->String;
1444
  }
1445
  else {
1446
    return NULL;
1447
  }
1448
}
1449

    
1450
/**
1451
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1452
 *
1453
 * @param $feature_tree_nodes
1454
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1455
 * @param $feature_uuid
1456
 *    The UUID of the Feature
1457
 * @return returns the FeatureNode or null
1458
 */
1459
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1460

    
1461
  // 1. scan this level
1462
  foreach ($feature_tree_nodes as $node){
1463
    if($node->feature->uuid == $feature_uuid){
1464
      return $node;
1465
    }
1466
  }
1467

    
1468
  // 2. descend into childen
1469
  foreach ($feature_tree_nodes as $node){
1470
    if(is_array($node->childNodes)){
1471
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1472
      if($node) {
1473
        return $node;
1474
      }
1475
    }
1476
  }
1477
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1478
  return $null_var;
1479
}
1480

    
1481
/**
1482
 * Merges the given featureNodes structure with the descriptionElements.
1483
 *
1484
 * This method is used in preparation for rendering the descriptionElements.
1485
 * The descriptionElements wich belong to a specific feature node are appended
1486
 * to a the feature node by creating a new field:
1487
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1488
 * The descriptionElements will be cleared in advance in order to allow reusing the
1489
 * same feature tree without the risk of mixing sets of descrition elemens.
1490
 *
1491
 * which originally is not existing in the cdm.
1492
 *
1493
 *
1494
 *
1495
 * @param array $featureNodes
1496
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1497
 *    may have children.
1498
 * @param array $descriptionElements
1499
 *    An flat array of cdm DescriptionElements
1500
 * @return array
1501
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1502
 */
1503
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1504

    
1505
  foreach ($featureNodes as &$node) {
1506
    // since the $featureNodes array is reused for each description
1507
    // it is nessecary to clear the custom node fields in advance
1508
    if(isset($node->descriptionElements)){
1509
      unset($node->descriptionElements);
1510
    }
1511

    
1512
    // Append corresponding elements to an additional node field:
1513
    // $node->descriptionElements.
1514
    foreach ($descriptionElements as $element) {
1515
      if ($element->feature->uuid == $node->feature->uuid) {
1516
        if (!isset($node->descriptionElements)) {
1517
          $node->descriptionElements = array();
1518
        }
1519
        $node->descriptionElements[] = $element;
1520
      }
1521
    }
1522

    
1523
    // Recurse into node children.
1524
    if (isset($node->childNodes[0])) {
1525
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1526
      $node->childNodes = $mergedChildNodes;
1527
    }
1528

    
1529
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1530
      unset($node);
1531
    }
1532

    
1533
  }
1534

    
1535
  return $featureNodes;
1536
}
1537

    
1538
/**
1539
 * Sends a GET or POST request to a CDM RESTService and returns a deserialized object.
1540
 *
1541
 * The response from the HTTP GET request is returned as object.
1542
 * The response objects coming from the webservice configured in the
1543
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1544
 *  in a level 2 (L2) cache.
1545
 *
1546
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1547
 * function, this cache persists only per each single page execution.
1548
 * Any object coming from the webservice is stored into it by default.
1549
 * In contrast to this default caching mechanism the L2 cache only is used if
1550
 * the 'cdm_webservice_cache' variable is set to TRUE,
1551
 * which can be set using the modules administrative settings section.
1552
 * Objects stored in this L2 cache are serialized and stored
1553
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1554
 * objects that are stored in the database will persist as
1555
 * long as the drupal cache is not beeing cleared and are available across
1556
 * multiple script executions.
1557
 *
1558
 * @param string $uri
1559
 *   URL to the webservice.
1560
 * @param array $pathParameters
1561
 *   An array of path parameters.
1562
 * @param string $query
1563
 *   A query string to be appended to the URL.
1564
 * @param string $method
1565
 *   The HTTP method to use, valid values are "GET" or "POST";
1566
 * @param bool $absoluteURI
1567
 *   TRUE when the URL should be treated as absolute URL.
1568
 *
1569
 * @return object
1570
 *   The deserialized webservice response object.
1571
 */
1572
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1573

    
1574
  static $cacheL1 = array();
1575

    
1576
  $data = NULL;
1577
  // store query string in $data and clear the query, $data will be set as HTTP request body
1578
  if($method == 'POST'){
1579
    $data = $query;
1580
    $query = NULL;
1581
  }
1582

    
1583
  // Transform the given uri path or pattern into a proper webservice uri.
1584
  if (!$absoluteURI) {
1585
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1586
  }
1587

    
1588
  // read request parameter 'cacheL2_refresh'
1589
  // which allows refreshig the level 2 cache
1590
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1591

    
1592
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1593
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1594

    
1595
  if($method == 'GET'){
1596
    $cache_key = $uri;
1597
  } else {
1598
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1599
    // crc32 is faster but creates much shorter hashes
1600
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1601
  }
1602

    
1603
  if (array_key_exists($cache_key, $cacheL1)) {
1604
    $cacheL1_obj = $cacheL1[$uri];
1605
  }
1606

    
1607
  $set_cacheL1 = FALSE;
1608
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1609
    $set_cacheL1 = TRUE;
1610
  }
1611

    
1612
  // Only cache cdm webservice URIs.
1613
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1614
  $cacheL2_entry = FALSE;
1615

    
1616
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1617
    // Try to get object from cacheL2.
1618
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1619
  }
1620

    
1621
  if (isset($cacheL1_obj)) {
1622
    //
1623
    // The object has been found in the L1 cache.
1624
    //
1625
    $obj = $cacheL1_obj;
1626
    if (cdm_debug_block_visible()) {
1627
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1628
    }
1629
  }
1630
  elseif ($cacheL2_entry) {
1631
    //
1632
    // The object has been found in the L2 cache.
1633
    //
1634
    $duration_parse_start = microtime(TRUE);
1635
    $obj = unserialize($cacheL2_entry->data);
1636
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1637

    
1638
    if (cdm_debug_block_visible()) {
1639
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1640
    }
1641
  }
1642
  else {
1643
    //
1644
    // Get the object from the webservice and cache it.
1645
    //
1646
    $duration_fetch_start = microtime(TRUE);
1647
    // Request data from webservice JSON or XML.
1648
    $response = cdm_http_request($uri, $method, $data);
1649
    $response_body = NULL;
1650
    if (isset($response->data)) {
1651
      $response_body = $response->data;
1652
    }
1653
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1654
    $duration_parse_start = microtime(TRUE);
1655

    
1656
    // Parse data and create object.
1657
    $obj = cdm_load_obj($response_body);
1658

    
1659
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1660

    
1661
    if (cdm_debug_block_visible()) {
1662
      if ($obj || $response_body == "[]") {
1663
        $status = 'valid';
1664
      }
1665
      else {
1666
        $status = 'invalid';
1667
      }
1668
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1669
    }
1670
    if ($set_cacheL2) {
1671
      // Store the object in cache L2.
1672
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1673
      // flag serialized is set properly in the cache table.
1674
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1675
    }
1676
  }
1677
  if ($obj) {
1678
    // Store the object in cache L1.
1679
    if ($set_cacheL1) {
1680
      $cacheL1[$cache_key] = $obj;
1681
    }
1682
  }
1683
  return $obj;
1684
}
1685

    
1686
/**
1687
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1688
 *
1689
 * The cdm_ws_debug block will display the debug information.
1690
 *
1691
 * @param $uri
1692
 *    The CDM REST URI to which the request has been send
1693
 * @param string $method
1694
 *    The HTTP request method, either 'GET' or 'POST'
1695
 * @param string $post_data
1696
 *    The datastring send with a post request
1697
 * @param $duration_fetch
1698
 *    The time in seconds it took to fetch the data from the web service
1699
 * @param $duration_parse
1700
 *    Time in seconds which was needed to parse the json response
1701
 * @param $datasize
1702
 *    Size of the data received from the server
1703
 * @param $status
1704
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1705
 * @return bool
1706
 *    TRUE if adding the debug information was successful
1707
 */
1708
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1709

    
1710
  static $initial_time = NULL;
1711
  if(!$initial_time) {
1712
    $initial_time = microtime(TRUE);
1713
  }
1714
  $time = microtime(TRUE) - $initial_time;
1715

    
1716
  // Decompose uri into path and query element.
1717
  $uri_parts = explode("?", $uri);
1718
  $query = array();
1719
  if (count($uri_parts) == 2) {
1720
    $path = $uri_parts[0];
1721
  }
1722
  else {
1723
    $path = $uri;
1724
  }
1725

    
1726
  if(strpos($uri, '?') > 0){
1727
    $json_uri = str_replace('?', '.json?', $uri);
1728
    $xml_uri = str_replace('?', '.xml?', $uri);
1729
  } else {
1730
    $json_uri = $uri . '.json';
1731
    $xml_uri = $json_uri . '.xml';
1732
  }
1733

    
1734
  // data links to make data accecsible as json and xml
1735
  $data_links = '';
1736
  if (_is_cdm_ws_uri($path)) {
1737

    
1738
    // see ./js/http-method-link.js
1739

    
1740
    if($method == 'GET'){
1741
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1742
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1743
      $data_links .= '<br/>';
1744
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1745
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1746
    } else {
1747
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1748
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1749
      $data_links .= '<br/>';
1750
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1751
    }
1752
  }
1753
  else {
1754
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1755
  }
1756

    
1757
  //
1758
  $data = array(
1759
      'ws_uri' => $uri,
1760
      'method' => $method,
1761
      'post_data' => $post_data,
1762
      'time' => sprintf('%3.3f', $time),
1763
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1764
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1765
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1766
      'status' => $status,
1767
      'data_links' => $data_links
1768
  );
1769
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1770
    $_SESSION['cdm']['ws_debug'] = array();
1771
  }
1772
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1773

    
1774
  // Mark this page as being uncacheable.
1775
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1776
  drupal_page_is_cacheable(FALSE);
1777

    
1778
  // Messages not set when DB connection fails.
1779
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1780
}
1781

    
1782
/**
1783
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1784
 * the visibility depends on whether
1785
 *  - the block is enabled
1786
 *  - the visibility restrictions in the block settings are satisfied
1787
 */
1788
function cdm_debug_block_visible() {
1789
  static $is_visible = null;
1790

    
1791
  if($is_visible === null){
1792
      $block = block_load('cdm_api', 'cdm_ws_debug');
1793
      $is_visible = isset($block->status) && $block->status == 1;
1794
      if($is_visible){
1795
        $blocks = array($block);
1796
        // Checks the page, user role, and user-specific visibilty settings.
1797
        block_block_list_alter($blocks);
1798
        $is_visible = count($blocks) > 0;
1799
      }
1800
  }
1801
  return $is_visible;
1802
}
1803

    
1804
/**
1805
 * @todo Please document this function.
1806
 * @see http://drupal.org/node/1354
1807
 */
1808
function cdm_load_obj($response_body) {
1809
  $obj = json_decode($response_body);
1810

    
1811
  if (!(is_object($obj) || is_array($obj))) {
1812
    ob_start();
1813
    $obj_dump = ob_get_contents();
1814
    ob_clean();
1815
    return FALSE;
1816
  }
1817

    
1818
  return $obj;
1819
}
1820

    
1821
/**
1822
 * Do a http request to a CDM RESTful web service.
1823
 *
1824
 * @param string $uri
1825
 *   The webservice url.
1826
 * @param string $method
1827
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1828
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1829
 * @param $data: A string containing the request body, formatted as
1830
 *     'param=value&param=value&...'. Defaults to NULL.
1831
 *
1832
 * @return object
1833
 *   The object as returned by drupal_http_request():
1834
 *   An object that can have one or more of the following components:
1835
 *   - request: A string containing the request body that was sent.
1836
 *   - code: An integer containing the response status code, or the error code
1837
 *     if an error occurred.
1838
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1839
 *   - status_message: The status message from the response, if a response was
1840
 *     received.
1841
 *   - redirect_code: If redirected, an integer containing the initial response
1842
 *     status code.
1843
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1844
 *     target.
1845
 *   - error: If an error occurred, the error message. Otherwise not set.
1846
 *   - headers: An array containing the response headers as name/value pairs.
1847
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1848
 *     easy access the array keys are returned in lower case.
1849
 *   - data: A string containing the response body that was received.
1850
 */
1851
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1852
  static $acceptLanguage = NULL;
1853
  $header = array();
1854

    
1855
  if (!$acceptLanguage) {
1856
    if (function_exists('apache_request_headers')) {
1857
      $headers = apache_request_headers();
1858
      if (isset($headers['Accept-Language'])) {
1859
        $acceptLanguage = $headers['Accept-Language'];
1860
      }
1861
    }
1862
    if (!$acceptLanguage) {
1863
      // DEFAULT TODO make configurable.
1864
      $acceptLanguage = "en";
1865
    }
1866
  }
1867

    
1868
  if ($method != "GET" && $method != "POST") {
1869
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1870
  }
1871

    
1872
  if (_is_cdm_ws_uri($uri)) {
1873
    $header['Accept'] = 'application/json';
1874
    $header['Accept-Language'] = $acceptLanguage;
1875
    $header['Accept-Charset'] = 'UTF-8';
1876
  }
1877

    
1878
  if($method == "POST") {
1879
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1880
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1881
  }
1882

    
1883

    
1884
  cdm_dd($uri);
1885
  return drupal_http_request($uri, array(
1886
      'headers' => $header,
1887
      'method' => $method,
1888
      'data' => $data,
1889
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1890
      )
1891
   );
1892
}
1893

    
1894
/**
1895
 * Concatenates recursively the fields of all features contained in the given
1896
 * CDM FeatureTree root node.
1897
 *
1898
 * @param $rootNode
1899
 *     A CDM FeatureTree node
1900
 * @param
1901
 *     The character to be used as glue for concatenation, default is ', '
1902
 * @param $field_name
1903
 *     The field name of the CDM Features
1904
 * @param $excludes
1905
 *     Allows defining a set of values to be excluded. This refers to the values
1906
 *     in the field denoted by the $field_name parameter
1907
 *
1908
 */
1909
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
1910
  $out = '';
1911

    
1912
  $pre_child_separator = $separator;
1913
  $post_child_separator = '';
1914

    
1915
  foreach ($root_node->childNodes as $feature_node) {
1916
    $out .= ($out ? $separator : '');
1917
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
1918
      $out .= $feature_node->feature->$field_name;
1919
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
1920
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1921
        if (strlen($childlabels)) {
1922
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1923
        }
1924
      }
1925
    }
1926
  }
1927
  return $out;
1928
}
1929

    
1930
/**
1931
 * Create a one-dimensional form options array.
1932
 *
1933
 * Creates an array of all features in the feature tree of feature nodes,
1934
 * the node labels are indented by $node_char and $childIndent depending on the
1935
 * hierachy level.
1936
 *
1937
 * @param - $rootNode
1938
 * @param - $node_char
1939
 * @param - $childIndentStr
1940
 * @param - $childIndent
1941
 *   ONLY USED INTERNALLY!
1942
 *
1943
 * @return array
1944
 *   A one dimensional Drupal form options array.
1945
 */
1946
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1947
  $options = array();
1948
  foreach ($rootNode->childNodes as $featureNode) {
1949
    $indent_prefix = '';
1950
    if ($childIndent) {
1951
      $indent_prefix = $childIndent . $node_char . " ";
1952
    }
1953
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1954
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
1955
      // Foreach ($featureNode->childNodes as $childNode){
1956
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1957
      $options = array_merge_recursive($options, $childList);
1958
      // }
1959
    }
1960
  }
1961
  return $options;
1962
}
1963

    
1964
/**
1965
 * Returns an array with all available FeatureTrees and the representations of the selected
1966
 * FeatureTree as a detail view.
1967
 *
1968
 * @param boolean $add_default_feature_free
1969
 * @return array
1970
 *  associative array with following keys:
1971
 *  -options: Returns an array with all available Feature Trees
1972
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1973
 *
1974
 */
1975
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1976

    
1977
  $options = array();
1978
  $tree_representations = array();
1979
  $feature_trees = array();
1980

    
1981
  // Set tree that contains all features.
1982
  if ($add_default_feature_free) {
1983
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1984
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1985
  }
1986

    
1987
  // Get feature trees from database.
1988
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1989
  if (is_array($persited_trees)) {
1990
    $feature_trees = array_merge($feature_trees, $persited_trees);
1991
  }
1992

    
1993
  foreach ($feature_trees as $featureTree) {
1994

    
1995
    // Do not add the DEFAULT_FEATURETREE again,
1996
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1997
      $options[$featureTree->uuid] = $featureTree->titleCache;
1998
    }
1999

    
2000
    // Render the hierarchic tree structure
2001
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2002

    
2003
      // Render the hierarchic tree structure.
2004
      $treeDetails = '<div class="featuretree_structure">'
2005
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2006
        . '</div>';
2007

    
2008
      $form = array();
2009
      $form['featureTree-' .  $featureTree->uuid] = array(
2010
        '#type' => 'fieldset',
2011
        '#title' => 'Show details',
2012
        '#attributes' => array('class' => array('collapsible collapsed')),
2013
        // '#collapsible' => TRUE,
2014
        // '#collapsed' => TRUE,
2015
      );
2016
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2017
        '#markup' => $treeDetails,
2018
      );
2019

    
2020
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2021
    }
2022

    
2023
  } // END loop over feature trees
2024

    
2025
  // return $options;
2026
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2027
}
2028

    
2029
/**
2030
 * Provides the list of availbale classifications in form of an options array.
2031
 *
2032
 * The options array is suitable for drupal form API elements that allow multiple choices.
2033
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2034
 *
2035
 * The classifications are ordered alphabetically whereas the classification
2036
 * chosen as default will always appear on top of the array, followed by a
2037
 * blank line below.
2038
 *
2039
 * @param bool $add_none_option
2040
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2041
 *
2042
 * @return array
2043
 *   classifications in an array as options for a form element that allows multiple choices.
2044
 */
2045
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2046

    
2047
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2048

    
2049
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2050
  $default_classification_label = '';
2051

    
2052
  // add all classifications
2053
  $taxonomic_tree_options = array();
2054
  if ($add_none_option) {
2055
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2056
  }
2057
  if ($taxonTrees) {
2058
    foreach ($taxonTrees as $tree) {
2059
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2060
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2061
      } else {
2062
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2063
        $default_classification_label = $tree->titleCache;
2064
      }
2065
    }
2066
  }
2067
  // oder alphabetically the space
2068
  asort($taxonomic_tree_options);
2069

    
2070
  // now set the labels
2071
  //   for none
2072
  if ($add_none_option) {
2073
    $taxonomic_tree_options['NONE'] = t('-- None --');
2074
  }
2075

    
2076
  //   for default_classification
2077
  if (is_uuid($default_classification_uuid)) {
2078
    $taxonomic_tree_options[$default_classification_uuid] =
2079
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2080
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2081
  }
2082

    
2083
  return $taxonomic_tree_options;
2084
}
2085

    
2086
/**
2087
 * @todo Please document this function.
2088
 * @see http://drupal.org/node/1354
2089
 */
2090
function cdm_api_secref_cache_prefetch(&$secUuids) {
2091
  // Comment @WA: global variables should start with a single underscore
2092
  // followed by the module and another underscore.
2093
  global $_cdm_api_secref_cache;
2094
  if (!is_array($_cdm_api_secref_cache)) {
2095
    $_cdm_api_secref_cache = array();
2096
  }
2097
  $uniqueUuids = array_unique($secUuids);
2098
  $i = 0;
2099
  $param = '';
2100
  while ($i++ < count($uniqueUuids)) {
2101
    $param .= $secUuids[$i] . ',';
2102
    if (strlen($param) + 37 > 2000) {
2103
      _cdm_api_secref_cache_add($param);
2104
      $param = '';
2105
    }
2106
  }
2107
  if ($param) {
2108
    _cdm_api_secref_cache_add($param);
2109
  }
2110
}
2111

    
2112
/**
2113
 * @todo Please document this function.
2114
 * @see http://drupal.org/node/1354
2115
 */
2116
function cdm_api_secref_cache_get($secUuid) {
2117
  global $_cdm_api_secref_cache;
2118
  if (!is_array($_cdm_api_secref_cache)) {
2119
    $_cdm_api_secref_cache = array();
2120
  }
2121
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2122
    _cdm_api_secref_cache_add($secUuid);
2123
  }
2124
  return $_cdm_api_secref_cache[$secUuid];
2125
}
2126

    
2127
/**
2128
 * @todo Please document this function.
2129
 * @see http://drupal.org/node/1354
2130
 */
2131
function cdm_api_secref_cache_clear() {
2132
  global $_cdm_api_secref_cache;
2133
  $_cdm_api_secref_cache = array();
2134
}
2135

    
2136

    
2137
/**
2138
 * Validates if the given string is a uuid.
2139
 *
2140
 * @param string $str
2141
 *   The string to validate.
2142
 *
2143
 * return bool
2144
 *   TRUE if the string is a UUID.
2145
 */
2146
function is_uuid($str) {
2147
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2148
}
2149

    
2150
/**
2151
 * Checks if the given $object is a valid cdm entity.
2152
 *
2153
 * An object is considered a cdm entity if it has a string field $object->class
2154
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2155
 * The function is null save.
2156
 *
2157
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2158
 *
2159
 * @param mixed $object
2160
 *   The object to validate
2161
 *
2162
 * @return bool
2163
 *   True if the object is a cdm entity.
2164
 */
2165
function is_cdm_entity($object) {
2166
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2167
}
2168

    
2169
/**
2170
 * @todo Please document this function.
2171
 * @see http://drupal.org/node/1354
2172
 */
2173
function _cdm_api_secref_cache_add($secUuidsStr) {
2174
  global $_cdm_api_secref_cache;
2175
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2176
  // Batch fetching not jet reimplemented thus:
2177
  /*
2178
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2179
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2180
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2181
  */
2182
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2183
}
2184

    
2185
/**
2186
 * Checks if the given uri starts with a cdm webservice url.
2187
 *
2188
 * Checks if the uri starts with the cdm webservice url stored in the
2189
 * Drupal variable 'cdm_webservice_url'.
2190
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2191
 *
2192
 * @param string $uri
2193
 *   The URI to test.
2194
 *
2195
 * @return bool
2196
 *   True if the uri starts with a cdm webservice url.
2197
 */
2198
function _is_cdm_ws_uri($uri) {
2199
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2200
}
2201

    
2202
/**
2203
 * @todo Please document this function.
2204
 * @see http://drupal.org/node/1354
2205
 */
2206
function queryString($elements) {
2207
  $query = '';
2208
  foreach ($elements as $key => $value) {
2209
    if (is_array($value)) {
2210
      foreach ($value as $v) {
2211
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2212
      }
2213
    }
2214
    else {
2215
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2216
    }
2217
  }
2218
  return $query;
2219
}
2220

    
2221
/**
2222
 * Implementation of the magic method __clone to allow deep cloning of objects
2223
 * and arrays.
2224
 */
2225
function __clone() {
2226
  foreach ($this as $name => $value) {
2227
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2228
      $this->$name = clone($this->$name);
2229
    }
2230
  }
2231
}
2232

    
2233
/**
2234
 * Make a 'deep copy' of an array.
2235
 *
2236
 * Make a complete deep copy of an array replacing
2237
 * references with deep copies until a certain depth is reached
2238
 * ($maxdepth) whereupon references are copied as-is...
2239
 *
2240
 * @see http://us3.php.net/manual/en/ref.array.php
2241
 *
2242
 * @param array $array
2243
 * @param array $copy passed by reference
2244
 * @param int $maxdepth
2245
 * @param int $depth
2246
 */
2247
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2248
  if ($depth > $maxdepth) {
2249
    $copy = $array;
2250
    return;
2251
  }
2252
  if (!is_array($copy)) {
2253
    $copy = array();
2254
  }
2255
  foreach ($array as $k => &$v) {
2256
    if (is_array($v)) {
2257
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2258
    }
2259
    else {
2260
      $copy[$k] = $v;
2261
    }
2262
  }
2263
}
2264

    
2265
/**
2266
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2267
 *
2268
 */
2269
function _add_js_ws_debug() {
2270

    
2271
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2272
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2273
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2274
    // use the developer versions of js libs
2275
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2276
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2277
  }
2278
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2279
    array(
2280
      'type' => 'file',
2281
      'weight' => JS_LIBRARY,
2282
      'cache' => TRUE)
2283
    );
2284

    
2285
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2286
    array(
2287
      'type' => 'file',
2288
      'weight' => JS_LIBRARY,
2289
      'cache' => TRUE)
2290
    );
2291
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2292
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2293

    
2294
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2295
    array(
2296
      'type' => 'file',
2297
      'weight' => JS_LIBRARY,
2298
      'cache' => TRUE)
2299
    );
2300
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2301
    array(
2302
    'type' => 'file',
2303
    'weight' => JS_LIBRARY,
2304
    'cache' => TRUE)
2305
    );
2306

    
2307
}
2308

    
2309
/**
2310
 * @todo Please document this function.
2311
 * @see http://drupal.org/node/1354
2312
 */
2313
function _no_classfication_uuid_message() {
2314
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2315
    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.');
2316
  }
2317
  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.');
2318
}
2319

    
2320
/**
2321
 * Implementation of hook flush_caches
2322
 *
2323
 * Add custom cache tables to the list of cache tables that
2324
 * will be cleared by the Clear button on the Performance page or whenever
2325
 * drupal_flush_all_caches is invoked.
2326
 *
2327
 * @author W.Addink <waddink@eti.uva.nl>
2328
 *
2329
 * @return array
2330
 *   An array with custom cache tables to include.
2331
 */
2332
function cdm_api_flush_caches() {
2333
  return array('cache_cdm_ws');
2334
}
2335

    
2336
/**
2337
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2338
 *
2339
 * @param $data
2340
 *   The variable to log to the drupal_debug.txt log file.
2341
 * @param $label
2342
 *   (optional) If set, a label to output before $data in the log file.
2343
 *
2344
 * @return
2345
 *   No return value if successful, FALSE if the log file could not be written
2346
 *   to.
2347
 *
2348
 * @see cdm_dataportal_init() where the log file is reset on each requests
2349
 * @see dd()
2350
 * @see http://drupal.org/node/314112
2351
 *
2352
 */
2353
function cdm_dd($data, $label = NULL) {
2354
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2355
    return dd($data, $label);
2356
  }
2357
}
2358

    
(5-5/10)