Project

General

Profile

Download (69.5 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_media_caption':
857
          $variables = array(
858
          'media' => $obj,
859
          // $args[0] is set in taxon_image_gallery_default in
860
          // cdm_dataportal.page.theme.
861
          'elements' => isset($args[0]) ? $args[0] : array(
862
          'title',
863
          'description',
864
          'artist',
865
          'location',
866
          'rights',
867
          ),
868
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
869
          );
870
          $reponse_data = theme($hook, $variables);
871
          break;
872

    
873
        default:
874
          drupal_set_message(t(
875
          'Theme !theme is not supported yet by function !function.', array(
876
          '!theme' => $hook,
877
          '!function' => __FUNCTION__,
878
          )), 'error');
879
          break;
880
      } // END of theme hook switch
881
    } // END of tread as theme hook
882

    
883

    
884
    if($do_gzip){
885
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
886
      drupal_add_http_header('Content-Encoding', 'gzip');
887
    }
888
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
889
    drupal_add_http_header('Content-Length', strlen($reponse_data));
890

    
891
    print $reponse_data;
892
  } // END of handle $hook either as compose ot theme hook
893

    
894
}
895

    
896
/**
897
 * @todo Please document this function.
898
 * @see http://drupal.org/node/1354
899
 */
900
function setvalue_session() {
901
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
902
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
903
    $keys = explode('][', $keys);
904
  }
905
  else {
906
    return;
907
  }
908
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
909

    
910
  // Prevent from malicous tags.
911
  $val = strip_tags($val);
912

    
913
  $var = &$_SESSION;
914
  $i = 0;
915
  foreach ($keys as $key) {
916
    $hasMoreKeys = ++$i < count($var);
917
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
918
      $var[$key] = array();
919
    }
920
    $var = &$var[$key];
921
  }
922
  $var = $val;
923
  if (isset($_REQUEST['destination'])) {
924
    drupal_goto($_REQUEST['destination']);
925
  }
926
}
927

    
928
/**
929
 * @todo Please document this function.
930
 * @see http://drupal.org/node/1354
931
 */
932
function uri_uriByProxy($uri, $theme = FALSE) {
933
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
934
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
935
}
936

    
937
/**
938
 * Composes the the absolute REST service URI to the annotations pager
939
 * for the given CDM entity.
940
 *
941
 * NOTE: Not all CDM Base types are yet supported.
942
 *
943
 * @param $cdmBase
944
 *   The CDM entity to construct the annotations pager uri for
945
 */
946
function cdm_compose_annotations_uri($cdmBase) {
947
  if (!$cdmBase->uuid) {
948
    return;
949
  }
950

    
951
  $ws_base_uri = NULL;
952
  switch ($cdmBase->class) {
953
    case 'TaxonBase':
954
    case 'Taxon':
955
    case 'Synonym':
956
      $ws_base_uri = CDM_WS_TAXON;
957
      break;
958

    
959
    case 'TaxonNameBase':
960
    case 'NonViralName':
961
    case 'BacterialName':
962
    case 'BotanicalName':
963
    case 'CultivarPlantName':
964
    case 'ZoologicalName':
965
    case 'ViralName':
966
      $ws_base_uri = CDM_WS_NAME;
967
      break;
968

    
969
    case 'Media':
970
      $ws_base_uri = CDM_WS_MEDIA;
971
      break;
972

    
973
    case 'Reference':
974
      $ws_base_uri = CDM_WS_REFERENCE;
975
      break;
976

    
977
    case 'Distribution':
978
    case 'TextData':
979
    case 'TaxonInteraction':
980
    case 'QuantitativeData':
981
    case 'IndividualsAssociation':
982
    case 'Distribution':
983
    case 'CommonTaxonName':
984
    case 'CategoricalData':
985
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
986
      break;
987

    
988
    case 'PolytomousKey':
989
    case 'MediaKey':
990
    case 'MultiAccessKey':
991
      $ws_base_uri = $cdmBase->class;
992
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
993
      break;
994

    
995
    default:
996
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
997
      return;
998
  }
999
  return cdm_compose_url($ws_base_uri, array(
1000
    $cdmBase->uuid,
1001
    'annotations',
1002
  ));
1003
}
1004

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

    
1029
  $query['pageNumber'] = $pageNumber;
1030
  $query['pageSize'] = $pageSize;
1031

    
1032
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1033
}
1034

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

    
1056
  while ($page_index !== FALSE){
1057
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1058
    if(isset($pager->records) && is_array($pager->records)) {
1059
      $entities = $pager->records;
1060
      if(!empty($pager->nextIndex)){
1061
        $page_index = $pager->nextIndex;
1062
      } else {
1063
        $page_index = FALSE;
1064
      }
1065
    } else {
1066
      $page_index = FALSE;
1067
    }
1068
  }
1069
  return $entities;
1070
}
1071

    
1072
/*
1073
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1074
  $viewrank = _cdm_taxonomy_compose_viewrank();
1075
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1076
  ? '/' . $path : '') ;
1077
}
1078
*/
1079

    
1080
/**
1081
 * @todo Enter description here...
1082
 *
1083
 * @param string $taxon_uuid
1084
 *  The UUID of a cdm taxon instance
1085
 * @param string $ignore_rank_limit
1086
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1087
 *
1088
 * @return A cdm REST service URL path to a Classification
1089
 */
1090
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1091

    
1092
  $view_uuid = get_taxonomictree_uuid_selected();
1093
  $rank_uuid = NULL;
1094
  if (!$ignore_rank_limit) {
1095
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1096
  }
1097

    
1098
  if (!empty($taxon_uuid)) {
1099
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1100
      $view_uuid,
1101
      $taxon_uuid,
1102
    ));
1103
  }
1104
  else {
1105
    if (!empty($rank_uuid)) {
1106
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1107
        $view_uuid,
1108
        $rank_uuid,
1109
      ));
1110
    }
1111
    else {
1112
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1113
        $view_uuid,
1114
      ));
1115
    }
1116
  }
1117
}
1118

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

    
1140
    $response = NULL;
1141

    
1142
    // 1st try
1143
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1144

    
1145
    if ($response == NULL) {
1146
      // 2dn try by ignoring the rank limit
1147
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1148
    }
1149

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

    
1169
  return $response;
1170
}
1171

    
1172
/**
1173
 * @todo Enter description here...
1174
 *
1175
 * @param string $taxon_uuid
1176
 *
1177
 * @return unknown
1178
 */
1179
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1180
  $view_uuid = get_taxonomictree_uuid_selected();
1181
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1182

    
1183
  $response = NULL;
1184
  if ($rank_uuid) {
1185
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1186
      $view_uuid,
1187
      $taxon_uuid,
1188
      $rank_uuid,
1189
    ));
1190
  }
1191
  else {
1192
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1193
      $view_uuid,
1194
      $taxon_uuid,
1195
    ));
1196
  }
1197

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

    
1215
  return $response;
1216
}
1217

    
1218
/**
1219
 * @todo Please document this function.
1220
 * @see http://drupal.org/node/1354
1221
 */
1222
function cdm_rankVocabulary_as_option() {
1223
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1224
  array_unshift ($options, "");
1225
  return $options;
1226
}
1227

    
1228
/**
1229
 *
1230
 * @param Object $definedTermBase
1231
 * 	  of cdm type DefinedTermBase
1232
 * @return string
1233
 * 	  the localized representation_L10n of the term,
1234
 *    otherwise the titleCache as fall back,
1235
 *    otherwise an empty string
1236
 */
1237
function cdm_term_representation($definedTermBase) {
1238
  if ( isset($definedTermBase->representation_L10n) ) {
1239
    return $definedTermBase->representation_L10n;
1240
  } elseif ( isset($definedTermBase->titleCache)) {
1241
    return $definedTermBase->titleCache;
1242
  }
1243
  return '';
1244
}
1245

    
1246
/**
1247
 * @todo Improve documentation of this function.
1248
 *
1249
 * eu.etaxonomy.cdm.model.description.
1250
 * CategoricalData
1251
 * CommonTaxonName
1252
 * Distribution
1253
 * IndividualsAssociation
1254
 * QuantitativeData
1255
 * TaxonInteraction
1256
 * TextData
1257
 */
1258
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1259
  static $types = array(
1260
    "CategoricalData",
1261
    "CommonTaxonName",
1262
    "Distribution",
1263
    "IndividualsAssociation",
1264
    "QuantitativeData",
1265
    "TaxonInteraction",
1266
    "TextData",
1267
  );
1268

    
1269
  static $options = NULL;
1270
  if ($options == NULL) {
1271
    $options = array();
1272
    if ($prependEmptyElement) {
1273
      $options[' '] = '';
1274
    }
1275
    foreach ($types as $type) {
1276
      // No internatianalization here since these are purely technical terms.
1277
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1278
    }
1279
  }
1280
  return $options;
1281
}
1282

    
1283
/**
1284
 * @todo Please document this function.
1285
 * @see http://drupal.org/node/1354
1286
 */
1287
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1288
  static $vocabularyOptions = array();
1289

    
1290
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1291
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1292
    $vocabularyOptions[$vocabularyUuid] = array();
1293

    
1294
    if ($terms) {
1295
      foreach ($terms as $term) {
1296
        if ($term_label_callback && function_exists($term_label_callback)) {
1297
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1298
        }
1299
        else {
1300
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1301
        }
1302
      }
1303
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1304
    }
1305
  }
1306
  return $vocabularyOptions[$vocabularyUuid];
1307
}
1308

    
1309
/**
1310
 * @todo Please document this function.
1311
 * @see http://drupal.org/node/1354
1312
 */
1313
function _cdm_relationship_type_term_label_callback($term) {
1314
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1315
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1316
  }
1317
  else {
1318
    return t($term->representation_L10n);
1319
  }
1320
}
1321

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

    
1339
  if (!$feature_tree) {
1340
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1341
      In order to see the species profiles of your taxa, please select a
1342
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1343
    return FALSE;
1344
  }
1345

    
1346
  $merged_trees = array();
1347

    
1348
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1349
      array(
1350
      'taxon' => $taxon_uuid,
1351
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1352
      ),
1353
      'POST'
1354
  );
1355

    
1356
  // Combine all descripions into one feature tree.
1357
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1358
  $feature_tree->root->childNodes = $merged_nodes;
1359

    
1360
  return $feature_tree;
1361
}
1362

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

    
1379
  if(!isset($cdmBase->annotations)){
1380
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1381
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1382
  }
1383

    
1384
  $annotations = array();
1385
  foreach ($cdmBase->annotations as $annotation) {
1386
    if ($includeTypes) {
1387
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1388
        $annotations[] = $annotation;
1389
      }
1390
    }
1391
    else {
1392
      $annotations[] = $annotation;
1393
    }
1394
  }
1395
  return $annotations;
1396

    
1397
}
1398

    
1399
/**
1400
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1401
 *
1402
 * @param object $annotatable_entity
1403
 *   The CDM AnnotatableEntity to load annotations for
1404
 */
1405
function cdm_load_annotations(&$annotatable_entity) {
1406
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1407
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1408
    if (is_array($annotations)) {
1409
      $annotatable_entity->annotations = $annotations;
1410
    }
1411
  }
1412
}
1413

    
1414
/**
1415
 * Get a NomenclaturalReference string.
1416
 *
1417
 * Returns the NomenclaturalReference string with correctly placed
1418
 * microreference (= reference detail) e.g.
1419
 * in Phytotaxa 43: 1-48. 2012.
1420
 *
1421
 * @param string $referenceUuid
1422
 *   UUID of the reference.
1423
 * @param string $microreference
1424
 *   Reference detail.
1425
 *
1426
 * @return string
1427
 *   a NomenclaturalReference.
1428
 */
1429
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1430
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1431
    $referenceUuid,
1432
  ), "microReference=" . urlencode($microreference));
1433

    
1434
  if ($obj) {
1435
    return $obj->String;
1436
  }
1437
  else {
1438
    return NULL;
1439
  }
1440
}
1441

    
1442
/**
1443
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1444
 *
1445
 * @param $feature_tree_nodes
1446
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1447
 * @param $feature_uuid
1448
 *    The UUID of the Feature
1449
 * @return returns the FeatureNode or null
1450
 */
1451
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1452

    
1453
  // 1. scan this level
1454
  foreach ($feature_tree_nodes as $node){
1455
    if($node->feature->uuid == $feature_uuid){
1456
      return $node;
1457
    }
1458
  }
1459

    
1460
  // 2. descend into childen
1461
  foreach ($feature_tree_nodes as $node){
1462
    if(is_array($node->childNodes)){
1463
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1464
      if($node) {
1465
        return $node;
1466
      }
1467
    }
1468
  }
1469
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1470
  return $null_var;
1471
}
1472

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

    
1497
  foreach ($featureNodes as &$node) {
1498
    // since the $featureNodes array is reused for each description
1499
    // it is nessecary to clear the custom node fields in advance
1500
    if(isset($node->descriptionElements)){
1501
      unset($node->descriptionElements);
1502
    }
1503

    
1504
    // Append corresponding elements to an additional node field:
1505
    // $node->descriptionElements.
1506
    foreach ($descriptionElements as $element) {
1507
      if ($element->feature->uuid == $node->feature->uuid) {
1508
        if (!isset($node->descriptionElements)) {
1509
          $node->descriptionElements = array();
1510
        }
1511
        $node->descriptionElements[] = $element;
1512
      }
1513
    }
1514

    
1515
    // Recurse into node children.
1516
    if (isset($node->childNodes[0])) {
1517
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1518
      $node->childNodes = $mergedChildNodes;
1519
    }
1520

    
1521
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1522
      unset($node);
1523
    }
1524

    
1525
  }
1526

    
1527
  return $featureNodes;
1528
}
1529

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

    
1566
  static $cacheL1 = array();
1567

    
1568
  $data = NULL;
1569
  // store query string in $data and clear the query, $data will be set as HTTP request body
1570
  if($method == 'POST'){
1571
    $data = $query;
1572
    $query = NULL;
1573
  }
1574

    
1575
  // Transform the given uri path or pattern into a proper webservice uri.
1576
  if (!$absoluteURI) {
1577
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1578
  }
1579

    
1580
  // read request parameter 'cacheL2_refresh'
1581
  // which allows refreshig the level 2 cache
1582
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1583

    
1584
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1585
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1586

    
1587
  if($method == 'GET'){
1588
    $cache_key = $uri;
1589
  } else {
1590
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1591
    // crc32 is faster but creates much shorter hashes
1592
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1593
  }
1594

    
1595
  if (array_key_exists($cache_key, $cacheL1)) {
1596
    $cacheL1_obj = $cacheL1[$uri];
1597
  }
1598

    
1599
  $set_cacheL1 = FALSE;
1600
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1601
    $set_cacheL1 = TRUE;
1602
  }
1603

    
1604
  // Only cache cdm webservice URIs.
1605
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1606
  $cacheL2_entry = FALSE;
1607

    
1608
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1609
    // Try to get object from cacheL2.
1610
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1611
  }
1612

    
1613
  if (isset($cacheL1_obj)) {
1614
    //
1615
    // The object has been found in the L1 cache.
1616
    //
1617
    $obj = $cacheL1_obj;
1618
    if (cdm_debug_block_visible()) {
1619
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1620
    }
1621
  }
1622
  elseif ($cacheL2_entry) {
1623
    //
1624
    // The object has been found in the L2 cache.
1625
    //
1626
    $duration_parse_start = microtime(TRUE);
1627
    $obj = unserialize($cacheL2_entry->data);
1628
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1629

    
1630
    if (cdm_debug_block_visible()) {
1631
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1632
    }
1633
  }
1634
  else {
1635
    //
1636
    // Get the object from the webservice and cache it.
1637
    //
1638
    $duration_fetch_start = microtime(TRUE);
1639
    // Request data from webservice JSON or XML.
1640
    $response = cdm_http_request($uri, $method, $data);
1641
    $response_body = NULL;
1642
    if (isset($response->data)) {
1643
      $response_body = $response->data;
1644
    }
1645
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1646
    $duration_parse_start = microtime(TRUE);
1647

    
1648
    // Parse data and create object.
1649
    $obj = cdm_load_obj($response_body);
1650

    
1651
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1652

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

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

    
1702
  static $initial_time = NULL;
1703
  if(!$initial_time) {
1704
    $initial_time = microtime(TRUE);
1705
  }
1706
  $time = microtime(TRUE) - $initial_time;
1707

    
1708
  // Decompose uri into path and query element.
1709
  $uri_parts = explode("?", $uri);
1710
  $query = array();
1711
  if (count($uri_parts) == 2) {
1712
    $path = $uri_parts[0];
1713
  }
1714
  else {
1715
    $path = $uri;
1716
  }
1717

    
1718
  if(strpos($uri, '?') > 0){
1719
    $json_uri = str_replace('?', '.json?', $uri);
1720
    $xml_uri = str_replace('?', '.xml?', $uri);
1721
  } else {
1722
    $json_uri = $uri . '.json';
1723
    $xml_uri = $json_uri . '.xml';
1724
  }
1725

    
1726
  // data links to make data accecsible as json and xml
1727
  $data_links = '';
1728
  if (_is_cdm_ws_uri($path)) {
1729

    
1730
    // see ./js/http-method-link.js
1731

    
1732
    if($method == 'GET'){
1733
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1734
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1735
      $data_links .= '<br/>';
1736
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1737
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1738
    } else {
1739
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1740
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1741
      $data_links .= '<br/>';
1742
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1743
    }
1744
  }
1745
  else {
1746
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1747
  }
1748

    
1749
  //
1750
  $data = array(
1751
      'ws_uri' => $uri,
1752
      'method' => $method,
1753
      'post_data' => $post_data,
1754
      'time' => sprintf('%3.3f', $time),
1755
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1756
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1757
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1758
      'status' => $status,
1759
      'data_links' => $data_links
1760
  );
1761
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1762
    $_SESSION['cdm']['ws_debug'] = array();
1763
  }
1764
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1765

    
1766
  // Mark this page as being uncacheable.
1767
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1768
  drupal_page_is_cacheable(FALSE);
1769

    
1770
  // Messages not set when DB connection fails.
1771
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1772
}
1773

    
1774
/**
1775
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1776
 * the visibility depends on whether
1777
 *  - the block is enabled
1778
 *  - the visibility restrictions in the block settings are satisfied
1779
 */
1780
function cdm_debug_block_visible() {
1781
  static $is_visible = null;
1782

    
1783
  if($is_visible === null){
1784
      $block = block_load('cdm_api', 'cdm_ws_debug');
1785
      $is_visible = isset($block->status) && $block->status == 1;
1786
      if($is_visible){
1787
        $blocks = array($block);
1788
        // Checks the page, user role, and user-specific visibilty settings.
1789
        block_block_list_alter($blocks);
1790
        $is_visible = count($blocks) > 0;
1791
      }
1792
  }
1793
  return $is_visible;
1794
}
1795

    
1796
/**
1797
 * @todo Please document this function.
1798
 * @see http://drupal.org/node/1354
1799
 */
1800
function cdm_load_obj($response_body) {
1801
  $obj = json_decode($response_body);
1802

    
1803
  if (!(is_object($obj) || is_array($obj))) {
1804
    ob_start();
1805
    $obj_dump = ob_get_contents();
1806
    ob_clean();
1807
    return FALSE;
1808
  }
1809

    
1810
  return $obj;
1811
}
1812

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

    
1847
  if (!$acceptLanguage) {
1848
    if (function_exists('apache_request_headers')) {
1849
      $headers = apache_request_headers();
1850
      if (isset($headers['Accept-Language'])) {
1851
        $acceptLanguage = $headers['Accept-Language'];
1852
      }
1853
    }
1854
    if (!$acceptLanguage) {
1855
      // DEFAULT TODO make configurable.
1856
      $acceptLanguage = "en";
1857
    }
1858
  }
1859

    
1860
  if ($method != "GET" && $method != "POST") {
1861
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1862
  }
1863

    
1864
  if (_is_cdm_ws_uri($uri)) {
1865
    $header['Accept'] = 'application/json';
1866
    $header['Accept-Language'] = $acceptLanguage;
1867
    $header['Accept-Charset'] = 'UTF-8';
1868
  }
1869

    
1870
  if($method == "POST") {
1871
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1872
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1873
  }
1874

    
1875

    
1876
  cdm_dd($uri);
1877
  return drupal_http_request($uri, array(
1878
      'headers' => $header,
1879
      'method' => $method,
1880
      'data' => $data,
1881
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1882
      )
1883
   );
1884
}
1885

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

    
1904
  $pre_child_separator = $separator;
1905
  $post_child_separator = '';
1906

    
1907
  foreach ($root_node->childNodes as $feature_node) {
1908
    $out .= ($out ? $separator : '');
1909
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
1910
      $out .= $feature_node->feature->$field_name;
1911
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
1912
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1913
        if (strlen($childlabels)) {
1914
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1915
        }
1916
      }
1917
    }
1918
  }
1919
  return $out;
1920
}
1921

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

    
1956
/**
1957
 * Returns an array with all available FeatureTrees and the representations of the selected
1958
 * FeatureTree as a detail view.
1959
 *
1960
 * @param boolean $add_default_feature_free
1961
 * @return array
1962
 *  associative array with following keys:
1963
 *  -options: Returns an array with all available Feature Trees
1964
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1965
 *
1966
 */
1967
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1968

    
1969
  $options = array();
1970
  $tree_representations = array();
1971
  $feature_trees = array();
1972

    
1973
  // Set tree that contains all features.
1974
  if ($add_default_feature_free) {
1975
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1976
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1977
  }
1978

    
1979
  // Get feature trees from database.
1980
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1981
  if (is_array($persited_trees)) {
1982
    $feature_trees = array_merge($feature_trees, $persited_trees);
1983
  }
1984

    
1985
  foreach ($feature_trees as $featureTree) {
1986

    
1987
    // Do not add the DEFAULT_FEATURETREE again,
1988
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1989
      $options[$featureTree->uuid] = $featureTree->titleCache;
1990
    }
1991

    
1992
    // Render the hierarchic tree structure
1993
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
1994

    
1995
      // Render the hierarchic tree structure.
1996
      $treeDetails = '<div class="featuretree_structure">'
1997
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1998
        . '</div>';
1999

    
2000
      $form = array();
2001
      $form['featureTree-' .  $featureTree->uuid] = array(
2002
        '#type' => 'fieldset',
2003
        '#title' => 'Show details',
2004
        '#attributes' => array('class' => array('collapsible collapsed')),
2005
        // '#collapsible' => TRUE,
2006
        // '#collapsed' => TRUE,
2007
      );
2008
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2009
        '#markup' => $treeDetails,
2010
      );
2011

    
2012
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2013
    }
2014

    
2015
  } // END loop over feature trees
2016

    
2017
  // return $options;
2018
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2019
}
2020

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

    
2039
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2040

    
2041
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2042
  $default_classification_label = '';
2043

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

    
2062
  // now set the labels
2063
  //   for none
2064
  if ($add_none_option) {
2065
    $taxonomic_tree_options['NONE'] = t('-- None --');
2066
  }
2067

    
2068
  //   for default_classification
2069
  if (is_uuid($default_classification_uuid)) {
2070
    $taxonomic_tree_options[$default_classification_uuid] =
2071
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2072
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2073
  }
2074

    
2075
  return $taxonomic_tree_options;
2076
}
2077

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

    
2104
/**
2105
 * @todo Please document this function.
2106
 * @see http://drupal.org/node/1354
2107
 */
2108
function cdm_api_secref_cache_get($secUuid) {
2109
  global $_cdm_api_secref_cache;
2110
  if (!is_array($_cdm_api_secref_cache)) {
2111
    $_cdm_api_secref_cache = array();
2112
  }
2113
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2114
    _cdm_api_secref_cache_add($secUuid);
2115
  }
2116
  return $_cdm_api_secref_cache[$secUuid];
2117
}
2118

    
2119
/**
2120
 * @todo Please document this function.
2121
 * @see http://drupal.org/node/1354
2122
 */
2123
function cdm_api_secref_cache_clear() {
2124
  global $_cdm_api_secref_cache;
2125
  $_cdm_api_secref_cache = array();
2126
}
2127

    
2128

    
2129
/**
2130
 * Validates if the given string is a uuid.
2131
 *
2132
 * @param string $str
2133
 *   The string to validate.
2134
 *
2135
 * return bool
2136
 *   TRUE if the string is a UUID.
2137
 */
2138
function is_uuid($str) {
2139
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2140
}
2141

    
2142
/**
2143
 * Checks if the given $object is a valid cdm entity.
2144
 *
2145
 * An object is considered a cdm entity if it has a string field $object->class
2146
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2147
 *
2148
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2149
 *
2150
 * @param mixed $object
2151
 *   The object to validate
2152
 *
2153
 * @return bool
2154
 *   True if the object is a cdm entity.
2155
 */
2156
function is_cdm_entity($object) {
2157
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2158
}
2159

    
2160
/**
2161
 * @todo Please document this function.
2162
 * @see http://drupal.org/node/1354
2163
 */
2164
function _cdm_api_secref_cache_add($secUuidsStr) {
2165
  global $_cdm_api_secref_cache;
2166
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2167
  // Batch fetching not jet reimplemented thus:
2168
  /*
2169
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2170
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2171
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2172
  */
2173
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2174
}
2175

    
2176
/**
2177
 * Checks if the given uri starts with a cdm webservice url.
2178
 *
2179
 * Checks if the uri starts with the cdm webservice url stored in the
2180
 * Drupal variable 'cdm_webservice_url'.
2181
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2182
 *
2183
 * @param string $uri
2184
 *   The URI to test.
2185
 *
2186
 * @return bool
2187
 *   True if the uri starts with a cdm webservice url.
2188
 */
2189
function _is_cdm_ws_uri($uri) {
2190
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2191
}
2192

    
2193
/**
2194
 * @todo Please document this function.
2195
 * @see http://drupal.org/node/1354
2196
 */
2197
function queryString($elements) {
2198
  $query = '';
2199
  foreach ($elements as $key => $value) {
2200
    if (is_array($value)) {
2201
      foreach ($value as $v) {
2202
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2203
      }
2204
    }
2205
    else {
2206
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2207
    }
2208
  }
2209
  return $query;
2210
}
2211

    
2212
/**
2213
 * Implementation of the magic method __clone to allow deep cloning of objects
2214
 * and arrays.
2215
 */
2216
function __clone() {
2217
  foreach ($this as $name => $value) {
2218
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2219
      $this->$name = clone($this->$name);
2220
    }
2221
  }
2222
}
2223

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

    
2256
/**
2257
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2258
 *
2259
 */
2260
function _add_js_ws_debug() {
2261

    
2262
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2263
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2264
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2265
    // use the developer versions of js libs
2266
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2267
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2268
  }
2269
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2270
    array(
2271
      'type' => 'file',
2272
      'weight' => JS_LIBRARY,
2273
      'cache' => TRUE)
2274
    );
2275

    
2276
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2277
    array(
2278
      'type' => 'file',
2279
      'weight' => JS_LIBRARY,
2280
      'cache' => TRUE)
2281
    );
2282
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2283
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2284

    
2285
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2286
    array(
2287
      'type' => 'file',
2288
      'weight' => JS_LIBRARY,
2289
      'cache' => TRUE)
2290
    );
2291
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2292
    array(
2293
    'type' => 'file',
2294
    'weight' => JS_LIBRARY,
2295
    'cache' => TRUE)
2296
    );
2297

    
2298
}
2299

    
2300
/**
2301
 * @todo Please document this function.
2302
 * @see http://drupal.org/node/1354
2303
 */
2304
function _no_classfication_uuid_message() {
2305
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2306
    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.');
2307
  }
2308
  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.');
2309
}
2310

    
2311
/**
2312
 * Implementation of hook flush_caches
2313
 *
2314
 * Add custom cache tables to the list of cache tables that
2315
 * will be cleared by the Clear button on the Performance page or whenever
2316
 * drupal_flush_all_caches is invoked.
2317
 *
2318
 * @author W.Addink <waddink@eti.uva.nl>
2319
 *
2320
 * @return array
2321
 *   An array with custom cache tables to include.
2322
 */
2323
function cdm_api_flush_caches() {
2324
  return array('cache_cdm_ws');
2325
}
2326

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

    
(5-5/10)