Project

General

Profile

Download (71.4 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
 * Returns the FeatureTree for structured descriptions
298
 *
299
 * The FeatureTree returned is the one that has been set in the
300
 * dataportal settings (layout->taxon:profile).
301
 * When the chosen FeatureTree is not found in the database,
302
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
303
 *
304
 * @return mixed
305
 *   A cdm FeatureTree object.
306
 */
307
function get_structured_description_featureTree() {
308
  static $structured_description_featureTree;
309

    
310
  if($structured_description_featureTree == NULL) {
311
    $structured_description_featureTree = cdm_ws_get(
312
        CDM_WS_FEATURETREE,
313
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
314
    );
315
    if (!$structured_description_featureTree) {
316
      $structured_description_featureTree = cdm_ws_get(
317
          CDM_WS_FEATURETREE,
318
          UUID_DEFAULT_FEATURETREE
319
      );
320
    }
321
  }
322
  return $structured_description_featureTree;
323
}
324

    
325
/**
326
 * @todo Please document this function.
327
 * @see http://drupal.org/node/1354
328
 */
329
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
330
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
331
}
332

    
333
/**
334
 * @todo Please document this function.
335
 * @see http://drupal.org/node/1354
336
 */
337
function reset_taxonomictree_uuid($taxonomictree_uuid) {
338
  unset($_SESSION['cdm']['taxonomictree_uuid']);
339
}
340

    
341
/**
342
 * @todo Please document this function.
343
 * @see http://drupal.org/node/1354
344
 */
345
function set_last_taxon_page_tab($taxonPageTab) {
346
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
347
}
348

    
349
/**
350
 * @todo Please document this function.
351
 * @see http://drupal.org/node/1354
352
 */
353
function get_last_taxon_page_tab() {
354
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
355
    return $_SESSION['cdm']['taxon_page_tab'];
356
  }
357
  else {
358
    return FALSE;
359
  }
360
}
361

    
362
/**
363
 * @todo Improve the documentation of this function.
364
 *
365
 * media Array [4]
366
 * representations Array [3]
367
 * mimeType image/jpeg
368
 * representationParts Array [1]
369
 * duration 0
370
 * heigth 0
371
 * size 0
372
 * uri
373
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
374
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
375
 * width 0
376
 * suffix jpg
377
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
378
 * title
379
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
380
 *
381
 * @param object $media
382
 * @param array $mimeTypes
383
 * @param int $width
384
 * @param int $height
385
 *
386
 * @return array
387
 *   An array with preferred media representations or else an empty array.
388
 */
389
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
390
  $prefRepr = array();
391
  if (!isset($media->representations[0])) {
392
    return $prefRepr;
393
  }
394

    
395
  while (count($mimeTypes) > 0) {
396
    // getRepresentationByMimeType
397
    $mimeType = array_shift($mimeTypes);
398

    
399
    foreach ($media->representations as &$representation) {
400
      // If the mimetype is not known, try inferring it.
401
      if (!$representation->mimeType) {
402
        if (isset($representation->parts[0])) {
403
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
404
        }
405
      }
406

    
407
      if ($representation->mimeType == $mimeType) {
408
        // Preferred mimetype found -> erase all remaining mimetypes
409
        // to end loop.
410
        $mimeTypes = array();
411
        $dwa = 0;
412
        $dw = 0;
413
        // Look for part with the best matching size.
414
        foreach ($representation->parts as $part) {
415
          if (isset($part->width) && isset($part->height)) {
416
            $dw = $part->width * $part->height - $height * $width;
417
          }
418
          if ($dw < 0) {
419
            $dw *= -1;
420
          }
421
          $dwa += $dw;
422
        }
423
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
424
        $prefRepr[$dwa . '_'] = $representation;
425
      }
426
    }
427
  }
428
  // Sort the array.
429
  krsort($prefRepr);
430
  return $prefRepr;
431
}
432

    
433
/**
434
 * Infers the mime type of a file using the filename extension.
435
 *
436
 * The filename extension is used to infer the mime type.
437
 *
438
 * @param string $filepath
439
 *   The path to the respective file.
440
 *
441
 * @return string
442
 *   The mimetype for the file or FALSE if the according mime type could
443
 *   not be found.
444
 */
445
function infer_mime_type($filepath) {
446
  static $mimemap = NULL;
447
  if (!$mimemap) {
448
    $mimemap = array(
449
      'jpg' => 'image/jpeg',
450
      'jpeg' => 'image/jpeg',
451
      'png' => 'image/png',
452
      'gif' => 'image/gif',
453
      'giff' => 'image/gif',
454
      'tif' => 'image/tif',
455
      'tiff' => 'image/tif',
456
      'pdf' => 'application/pdf',
457
      'html' => 'text/html',
458
      'htm' => 'text/html',
459
    );
460
  }
461
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
462
  if (isset($mimemap[$extension])) {
463
    return $mimemap[$extension];
464
  }
465
  else {
466
    // FIXME remove this hack just return FALSE;
467
    return 'text/html';
468
  }
469
}
470

    
471
/**
472
 * Converts an ISO 8601 org.joda.time.Partial to a year.
473
 *
474
 * The function expects an ISO 8601 time representation of a
475
 * org.joda.time.Partial of the form yyyy-MM-dd.
476
 *
477
 * @param string $partial
478
 *   ISO 8601 time representation of a org.joda.time.Partial.
479
 *
480
 * @return string
481
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
482
 */
483
function partialToYear($partial) {
484
  if (is_string($partial)) {
485
    $year = substr($partial, 0, 4);
486
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
487
      return $year;
488
    }
489
  }
490
  return;
491
}
492

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

    
516
/**
517
 * Converts an ISO 8601 org.joda.time.Partial to a day.
518
 *
519
 * This function expects an ISO 8601 time representation of a
520
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
521
 * In case the day 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 day.
528
 */
529
function partialToDay($partial) {
530
  if (is_string($partial)) {
531
    $day = substr($partial, 8, 2);
532
    if (preg_match("/[0-9][0-9]/", $day)) {
533
      return $day;
534
    }
535
  }
536
  return;
537
}
538

    
539
/**
540
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
541
 *
542
 * This function expects an ISO 8601 time representations of a
543
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
544
 * four digit year, month and day with dashes:
545
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
546
 *
547
 * The partial may contain question marks eg: "1973-??-??",
548
 * these are turned in to '00' or are stripped depending of the $stripZeros
549
 * parameter.
550
 *
551
 * @param string $partial
552
 *   org.joda.time.Partial.
553
 * @param bool $stripZeros
554
 *   If set to TRUE the zero (00) month and days will be hidden:
555
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
556
 * @param string @format
557
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
558
 *    - "YYYY": Year only
559
 *    - "YYYY-MM-DD": this is the default
560
 *
561
 * @return string
562
 *   YYYY-MM-DD formatted year, month, day.
563
 */
564
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
565

    
566
  $y = NULL; $m = NULL; $d = NULL;
567

    
568
  if(strpos($format, 'YY') !== FALSE){
569
    $y = partialToYear($partial);
570
  }
571
  if(strpos($format, 'MM') !== FALSE){
572
    $m = partialToMonth($partial);
573
  }
574
  if(strpos($format, 'DD') !== FALSE){
575
    $d = partialToDay($partial);
576
  }
577

    
578
  $y = $y ? $y : '00';
579
  $m = $m ? $m : '00';
580
  $d = $d ? $d : '00';
581

    
582
  $date = '';
583

    
584
  if ($y == '00' && $stripZeros) {
585
    return;
586
  }
587
  else {
588
    $date = $y;
589
  }
590

    
591
  if ($m == '00' && $stripZeros) {
592
    return $date;
593
  }
594
  else {
595
    $date .= "-" . $m;
596
  }
597

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

    
607
/**
608
 * Converts a time period to a string.
609
 *
610
 * See also partialToDate($partial, $stripZeros).
611
 *
612
 * @param object $period
613
 *   An JodaTime org.joda.time.Period object.
614
 * @param bool $stripZeros
615
 *   If set to True, the zero (00) month and days will be hidden:
616
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
617
 * @param string @format
618
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
619
 *    - "YYYY": Year only
620
 *    - "YYYY-MM-DD": this is the default
621
 *
622
 * @return string
623
 *   Returns a date in the form of a string.
624
 */
625
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
626
  $dateString = '';
627
  if ($period->start) {
628
    $dateString = partialToDate($period->start, $stripZeros, $format);
629
  }
630
  if ($period->end) {
631
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
632
  }
633
  return $dateString;
634
}
635

    
636
/**
637
 * returns the earliest date available in the $period in a normalized
638
 * form suitable for sorting, e.g.:
639
 *
640
 *  - 1956-00-00
641
 *  - 0000-00-00
642
 *  - 1957-03-00
643
 *
644
 * that is either the start date is returned if set otherwise the
645
 * end date
646
 *
647
 * @param  $period
648
 *    An JodaTime org.joda.time.Period object.
649
 * @return string normalized form of the date
650
 *   suitable for sorting
651
 */
652
function timePeriodAsOrderKey($period) {
653
  $dateString = '';
654
  if ($period->start) {
655
    $dateString = partialToDate($period->start, false);
656
  }
657
  if ($period->end) {
658
    $dateString .= partialToDate($period->end, false);
659
  }
660
  return $dateString;
661
}
662

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

    
682
  $request_params = '';
683
  $path_params = '';
684

    
685
  // (1)
686
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
687
  // according element of the $pathParameters array.
688
  static $helperArray = array();
689
  if (isset($pathParameters) && !is_array($pathParameters)) {
690
    $helperArray[0] = $pathParameters;
691
    $pathParameters = $helperArray;
692
  }
693

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

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

    
720
  // (3)
721
  // Append the query string supplied by $query.
722
  if (isset($query)) {
723
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
724
  }
725

    
726
  $path = $uri_pattern;
727

    
728
  $uri = variable_get('cdm_webservice_url', '') . $path;
729
  return $uri;
730
}
731

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

    
751
  $args = func_get_args();
752
  $do_gzip = function_exists('gzencode');
753
  $uriEncoded = array_shift($args);
754
  $uri = urldecode($uriEncoded);
755
  $hook = array_shift($args);
756
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
757

    
758
  $post_data = null;
759

    
760
  if ($request_method == "POST" || $request_method == "PUT") {
761
    // read response body via inputstream module
762
    $post_data = file_get_contents("php://input");
763
  }
764

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

    
774
  // In all these cases perform a simple get request.
775
  // TODO reconsider caching logic in this function.
776

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

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

    
806
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
807

    
808
    $reponse_data = NULL;
809

    
810
    if (function_exists('compose_' . $hook)){
811
      // call compose hook
812

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

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

    
833
        case 'cdm_list_of_taxa':
834
            $variables = array(
835
              'records' => $obj,
836
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
837
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
838
            $reponse_data = theme($hook, $variables);
839
            break;
840

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

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

    
868

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

    
876
    print $reponse_data;
877
  } // END of handle $hook either as compose ot theme hook
878

    
879
}
880

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

    
895
  // Prevent from malicous tags.
896
  $val = strip_tags($val);
897

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

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

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

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

    
944
    case 'TaxonNameBase':
945
    case 'NonViralName':
946
    case 'BacterialName':
947
    case 'BotanicalName':
948
    case 'CultivarPlantName':
949
    case 'ZoologicalName':
950
    case 'ViralName':
951
      $ws_base_uri = CDM_WS_NAME;
952
      break;
953

    
954
    case 'Media':
955
      $ws_base_uri = CDM_WS_MEDIA;
956
      break;
957

    
958
    case 'Reference':
959
      $ws_base_uri = CDM_WS_REFERENCE;
960
      break;
961

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

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

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

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

    
1014
  $query['pageNumber'] = $pageNumber;
1015
  $query['pageSize'] = $pageSize;
1016

    
1017
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1018
}
1019

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

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

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

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

    
1077
  $view_uuid = get_taxonomictree_uuid_selected();
1078
  $rank_uuid = NULL;
1079
  if (!$ignore_rank_limit) {
1080
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1081
  }
1082

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

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

    
1125
    $response = NULL;
1126

    
1127
    // 1st try
1128
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1129

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

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

    
1154
  return $response;
1155
}
1156

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

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

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

    
1200
  return $response;
1201
}
1202

    
1203

    
1204
// =============================Terms and Vocabularies ========================================= //
1205

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

    
1224
/**
1225
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1226
 *
1227
 * The options array is suitable for drupal form API elements that allow multiple choices.
1228
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1229
 *
1230
 * @param array $terms
1231
 *   a list of CDM DefinedTermBase instances
1232
 *
1233
 * @param $sort_by
1234
 *  Optionally sort option SORT_NATURAL (default: sorts after the cdm order index ),
1235
 *  to sort alphabetically: SORT_ASC, SORT_DESC
1236
 *
1237
 * @param $term_label_callback
1238
 *   A callback function to override the term representations
1239
 *
1240
 * @return array
1241
 *   the terms in an array as options for a form element that allows multiple choices.
1242
 */
1243
function cdm_terms_as_options($terms, $sort_by = SORT_NATURAL, $term_label_callback = NULL){
1244
  $options = array();
1245
  if(isset($terms) && is_array($terms)){
1246
    foreach ($terms as $term){
1247
      if ($term_label_callback && function_exists($term_label_callback)) {
1248
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1249
      } else {
1250
        //TODO use cdm_term_representation() here?
1251
        $options[$term->uuid] = t($term->representation_L10n);
1252
      }
1253
    }
1254
  }
1255
  switch($sort_by){
1256
    case SORT_NATURAL: array_reverse($options);
1257
      break;
1258
    default: array_multisort($options, SORT_ASC);
1259
  }
1260

    
1261
  return $options;
1262
}
1263

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

    
1271
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1272
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1273
    $vocabularyOptions[$vocabularyUuid] = cdm_terms_as_options($terms, SORT_NATURAL, $term_label_callback);
1274
  }
1275
  return $vocabularyOptions[$vocabularyUuid];
1276
}
1277

    
1278
/**
1279
 * @param $term_type one of
1280
 *  - Unknown
1281
 *  - Language
1282
 *  - NamedArea
1283
 *  - Rank
1284
 *  - Feature
1285
 *  - AnnotationType
1286
 *  - MarkerType
1287
 *  - ExtensionType
1288
 *  - DerivationEventType
1289
 *  - PresenceAbsenceTerm
1290
 *  - NomenclaturalStatusType
1291
 *  - NameRelationshipType
1292
 *  - HybridRelationshipType
1293
 *  - SynonymRelationshipType
1294
 *  - TaxonRelationshipType
1295
 *  - NameTypeDesignationStatus
1296
 *  - SpecimenTypeDesignationStatus
1297
 *  - InstitutionType
1298
 *  - NamedAreaType
1299
 *  - NamedAreaLevel
1300
 *  - RightsType
1301
 *  - MeasurementUnit
1302
 *  - StatisticalMeasure
1303
 *  - MaterialOrMethod
1304
 *  - Material
1305
 *  - Method
1306
 *  - Modifier
1307
 *  - Scope
1308
 *  - Stage
1309
 *  - KindOfUnit
1310
 *  - Sex
1311
 *  - ReferenceSystem
1312
 *  - State
1313
 *  - NaturalLanguageTerm
1314
 *  - TextFormat
1315
 *  - DeterminationModifier
1316
 *  - DnaMarker
1317
 */
1318
function cdm_terms_by_type_as_option($term_type, $sort_by = SORT_NATURAL, $term_label_callback = NULL){
1319
  $terms = cdm_ws_fetch_all(CDM_WS_TERM, array('class' => $term_type));
1320
  return cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1321
}
1322

    
1323
/**
1324
 * @todo Please document this function.
1325
 * @see http://drupal.org/node/1354
1326
 */
1327
function cdm_rankVocabulary_as_option() {
1328
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1329
  array_unshift ($options, "");
1330
  return $options;
1331
}
1332

    
1333
/**
1334
 * @todo Please document this function.
1335
 * @see http://drupal.org/node/1354
1336
 */
1337
function _cdm_relationship_type_term_label_callback($term) {
1338
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1339
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1340
  }
1341
else {
1342
    return t($term->representation_L10n);
1343
  }
1344
}
1345

    
1346
// ========================================================================================== //
1347
/**
1348
 * @todo Improve documentation of this function.
1349
 *
1350
 * eu.etaxonomy.cdm.model.description.
1351
 * CategoricalData
1352
 * CommonTaxonName
1353
 * Distribution
1354
 * IndividualsAssociation
1355
 * QuantitativeData
1356
 * TaxonInteraction
1357
 * TextData
1358
 */
1359
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1360
  static $types = array(
1361
    "CategoricalData",
1362
    "CommonTaxonName",
1363
    "Distribution",
1364
    "IndividualsAssociation",
1365
    "QuantitativeData",
1366
    "TaxonInteraction",
1367
    "TextData",
1368
  );
1369

    
1370
  static $options = NULL;
1371
  if ($options == NULL) {
1372
    $options = array();
1373
    if ($prependEmptyElement) {
1374
      $options[' '] = '';
1375
    }
1376
    foreach ($types as $type) {
1377
      // No internatianalization here since these are purely technical terms.
1378
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1379
    }
1380
  }
1381
  return $options;
1382
}
1383

    
1384

    
1385
/**
1386
 * Fetches all TaxonDescription descriptions elements wich are accociated to the
1387
 * Taxon specified by the $taxon_uuid and megres the elements into the given
1388
 * feature tree.
1389
 * @param $feature_tree
1390
 *     The CDM FeatureTree to be used as template
1391
 * @param $taxon_uuid
1392
 *     The UUID of the taxon
1393
 * @param $excludes
1394
 *     UUIDs of features to be excluded
1395
 * @return$feature_tree
1396
 *     The CDM FeatureTree wich was given as parameter merged tree wheras the
1397
 *     CDM FeatureNodes are extended by an additinal field 'descriptionElements'
1398
 *     witch will hold the accoding $descriptionElements.
1399
 */
1400
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1401

    
1402
  if (!$feature_tree) {
1403
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1404
      In order to see the species profiles of your taxa, please select a
1405
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1406
    return FALSE;
1407
  }
1408

    
1409
  $merged_trees = array();
1410

    
1411
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1412
      array(
1413
      'taxon' => $taxon_uuid,
1414
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1415
      ),
1416
      'POST'
1417
  );
1418

    
1419
  // Combine all descripions into one feature tree.
1420
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1421
  $feature_tree->root->childNodes = $merged_nodes;
1422

    
1423
  return $feature_tree;
1424
}
1425

    
1426
/**
1427
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1428
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1429
 * be requested for the annotations.
1430
 *
1431
 * @param string $cdmBase
1432
 *   An annotatable cdm entity.
1433
 * @param array $includeTypes
1434
 *   If an array of annotation type uuids is supplied by this parameter the
1435
 *   list of annotations is resticted to those which belong to this type.
1436
 *
1437
 * @return array
1438
 *   An array of Annotation objects or an empty array.
1439
 */
1440
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1441

    
1442
  if(!isset($cdmBase->annotations)){
1443
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1444
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1445
  }
1446

    
1447
  $annotations = array();
1448
  foreach ($cdmBase->annotations as $annotation) {
1449
    if ($includeTypes) {
1450
      if (
1451
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1452
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1453
      ) {
1454
        $annotations[] = $annotation;
1455
      }
1456
    }
1457
    else {
1458
      $annotations[] = $annotation;
1459
    }
1460
  }
1461
  return $annotations;
1462

    
1463
}
1464

    
1465
/**
1466
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1467
 *
1468
 * @param object $annotatable_entity
1469
 *   The CDM AnnotatableEntity to load annotations for
1470
 */
1471
function cdm_load_annotations(&$annotatable_entity) {
1472
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1473
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1474
    if (is_array($annotations)) {
1475
      $annotatable_entity->annotations = $annotations;
1476
    }
1477
  }
1478
}
1479

    
1480
/**
1481
 * Get a NomenclaturalReference string.
1482
 *
1483
 * Returns the NomenclaturalReference string with correctly placed
1484
 * microreference (= reference detail) e.g.
1485
 * in Phytotaxa 43: 1-48. 2012.
1486
 *
1487
 * @param string $referenceUuid
1488
 *   UUID of the reference.
1489
 * @param string $microreference
1490
 *   Reference detail.
1491
 *
1492
 * @return string
1493
 *   a NomenclaturalReference.
1494
 */
1495
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1496
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1497
    $referenceUuid,
1498
  ), "microReference=" . urlencode($microreference));
1499

    
1500
  if ($obj) {
1501
    return $obj->String;
1502
  }
1503
  else {
1504
    return NULL;
1505
  }
1506
}
1507

    
1508
/**
1509
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1510
 *
1511
 * @param $feature_tree_nodes
1512
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1513
 * @param $feature_uuid
1514
 *    The UUID of the Feature
1515
 * @return returns the FeatureNode or null
1516
 */
1517
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1518

    
1519
  // 1. scan this level
1520
  foreach ($feature_tree_nodes as $node){
1521
    if($node->feature->uuid == $feature_uuid){
1522
      return $node;
1523
    }
1524
  }
1525

    
1526
  // 2. descend into childen
1527
  foreach ($feature_tree_nodes as $node){
1528
    if(is_array($node->childNodes)){
1529
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1530
      if($node) {
1531
        return $node;
1532
      }
1533
    }
1534
  }
1535
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1536
  return $null_var;
1537
}
1538

    
1539
/**
1540
 * Merges the given featureNodes structure with the descriptionElements.
1541
 *
1542
 * This method is used in preparation for rendering the descriptionElements.
1543
 * The descriptionElements wich belong to a specific feature node are appended
1544
 * to a the feature node by creating a new field:
1545
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1546
 * The descriptionElements will be cleared in advance in order to allow reusing the
1547
 * same feature tree without the risk of mixing sets of descrition elemens.
1548
 *
1549
 * which originally is not existing in the cdm.
1550
 *
1551
 *
1552
 *
1553
 * @param array $featureNodes
1554
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1555
 *    may have children.
1556
 * @param array $descriptionElements
1557
 *    An flat array of cdm DescriptionElements
1558
 * @return array
1559
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1560
 */
1561
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1562

    
1563
  foreach ($featureNodes as &$node) {
1564
    // since the $featureNodes array is reused for each description
1565
    // it is nessecary to clear the custom node fields in advance
1566
    if(isset($node->descriptionElements)){
1567
      unset($node->descriptionElements);
1568
    }
1569

    
1570
    // Append corresponding elements to an additional node field:
1571
    // $node->descriptionElements.
1572
    foreach ($descriptionElements as $element) {
1573
      if ($element->feature->uuid == $node->feature->uuid) {
1574
        if (!isset($node->descriptionElements)) {
1575
          $node->descriptionElements = array();
1576
        }
1577
        $node->descriptionElements[] = $element;
1578
      }
1579
    }
1580

    
1581
    // Recurse into node children.
1582
    if (isset($node->childNodes[0])) {
1583
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1584
      $node->childNodes = $mergedChildNodes;
1585
    }
1586

    
1587
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1588
      unset($node);
1589
    }
1590

    
1591
  }
1592

    
1593
  return $featureNodes;
1594
}
1595

    
1596
/**
1597
 * Sends a GET or POST request to a CDM RESTService and returns a deserialized object.
1598
 *
1599
 * The response from the HTTP GET request is returned as object.
1600
 * The response objects coming from the webservice configured in the
1601
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1602
 *  in a level 2 (L2) cache.
1603
 *
1604
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1605
 * function, this cache persists only per each single page execution.
1606
 * Any object coming from the webservice is stored into it by default.
1607
 * In contrast to this default caching mechanism the L2 cache only is used if
1608
 * the 'cdm_webservice_cache' variable is set to TRUE,
1609
 * which can be set using the modules administrative settings section.
1610
 * Objects stored in this L2 cache are serialized and stored
1611
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1612
 * objects that are stored in the database will persist as
1613
 * long as the drupal cache is not beeing cleared and are available across
1614
 * multiple script executions.
1615
 *
1616
 * @param string $uri
1617
 *   URL to the webservice.
1618
 * @param array $pathParameters
1619
 *   An array of path parameters.
1620
 * @param string $query
1621
 *   A query string to be appended to the URL.
1622
 * @param string $method
1623
 *   The HTTP method to use, valid values are "GET" or "POST";
1624
 * @param bool $absoluteURI
1625
 *   TRUE when the URL should be treated as absolute URL.
1626
 *
1627
 * @return object
1628
 *   The deserialized webservice response object.
1629
 */
1630
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1631

    
1632
  static $cacheL1 = array();
1633

    
1634
  $data = NULL;
1635
  // store query string in $data and clear the query, $data will be set as HTTP request body
1636
  if($method == 'POST'){
1637
    $data = $query;
1638
    $query = NULL;
1639
  }
1640

    
1641
  // Transform the given uri path or pattern into a proper webservice uri.
1642
  if (!$absoluteURI) {
1643
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1644
  }
1645

    
1646
  // read request parameter 'cacheL2_refresh'
1647
  // which allows refreshig the level 2 cache
1648
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1649

    
1650
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1651
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1652

    
1653
  if($method == 'GET'){
1654
    $cache_key = $uri;
1655
  } else {
1656
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1657
    // crc32 is faster but creates much shorter hashes
1658
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1659
  }
1660

    
1661
  if (array_key_exists($cache_key, $cacheL1)) {
1662
    $cacheL1_obj = $cacheL1[$uri];
1663
  }
1664

    
1665
  $set_cacheL1 = FALSE;
1666
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1667
    $set_cacheL1 = TRUE;
1668
  }
1669

    
1670
  // Only cache cdm webservice URIs.
1671
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1672
  $cacheL2_entry = FALSE;
1673

    
1674
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1675
    // Try to get object from cacheL2.
1676
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1677
  }
1678

    
1679
  if (isset($cacheL1_obj)) {
1680
    //
1681
    // The object has been found in the L1 cache.
1682
    //
1683
    $obj = $cacheL1_obj;
1684
    if (cdm_debug_block_visible()) {
1685
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1686
    }
1687
  }
1688
  elseif ($cacheL2_entry) {
1689
    //
1690
    // The object has been found in the L2 cache.
1691
    //
1692
    $duration_parse_start = microtime(TRUE);
1693
    $obj = unserialize($cacheL2_entry->data);
1694
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1695

    
1696
    if (cdm_debug_block_visible()) {
1697
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1698
    }
1699
  }
1700
  else {
1701
    //
1702
    // Get the object from the webservice and cache it.
1703
    //
1704
    $duration_fetch_start = microtime(TRUE);
1705
    // Request data from webservice JSON or XML.
1706
    $response = cdm_http_request($uri, $method, $data);
1707
    $response_body = NULL;
1708
    if (isset($response->data)) {
1709
      $response_body = $response->data;
1710
    }
1711
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1712
    $duration_parse_start = microtime(TRUE);
1713

    
1714
    // Parse data and create object.
1715
    $obj = cdm_load_obj($response_body);
1716

    
1717
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1718

    
1719
    if (cdm_debug_block_visible()) {
1720
      if ($obj || $response_body == "[]") {
1721
        $status = 'valid';
1722
      }
1723
      else {
1724
        $status = 'invalid';
1725
      }
1726
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1727
    }
1728
    if ($set_cacheL2) {
1729
      // Store the object in cache L2.
1730
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1731
      // flag serialized is set properly in the cache table.
1732
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1733
    }
1734
  }
1735
  if ($obj) {
1736
    // Store the object in cache L1.
1737
    if ($set_cacheL1) {
1738
      $cacheL1[$cache_key] = $obj;
1739
    }
1740
  }
1741
  return $obj;
1742
}
1743

    
1744
/**
1745
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1746
 *
1747
 * The cdm_ws_debug block will display the debug information.
1748
 *
1749
 * @param $uri
1750
 *    The CDM REST URI to which the request has been send
1751
 * @param string $method
1752
 *    The HTTP request method, either 'GET' or 'POST'
1753
 * @param string $post_data
1754
 *    The datastring send with a post request
1755
 * @param $duration_fetch
1756
 *    The time in seconds it took to fetch the data from the web service
1757
 * @param $duration_parse
1758
 *    Time in seconds which was needed to parse the json response
1759
 * @param $datasize
1760
 *    Size of the data received from the server
1761
 * @param $status
1762
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1763
 * @return bool
1764
 *    TRUE if adding the debug information was successful
1765
 */
1766
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1767

    
1768
  static $initial_time = NULL;
1769
  if(!$initial_time) {
1770
    $initial_time = microtime(TRUE);
1771
  }
1772
  $time = microtime(TRUE) - $initial_time;
1773

    
1774
  // Decompose uri into path and query element.
1775
  $uri_parts = explode("?", $uri);
1776
  $query = array();
1777
  if (count($uri_parts) == 2) {
1778
    $path = $uri_parts[0];
1779
  }
1780
  else {
1781
    $path = $uri;
1782
  }
1783

    
1784
  if(strpos($uri, '?') > 0){
1785
    $json_uri = str_replace('?', '.json?', $uri);
1786
    $xml_uri = str_replace('?', '.xml?', $uri);
1787
  } else {
1788
    $json_uri = $uri . '.json';
1789
    $xml_uri = $json_uri . '.xml';
1790
  }
1791

    
1792
  // data links to make data accecsible as json and xml
1793
  $data_links = '';
1794
  if (_is_cdm_ws_uri($path)) {
1795

    
1796
    // see ./js/http-method-link.js
1797

    
1798
    if($method == 'GET'){
1799
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1800
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1801
      $data_links .= '<br/>';
1802
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1803
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1804
    } else {
1805
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1806
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1807
      $data_links .= '<br/>';
1808
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1809
    }
1810
  }
1811
  else {
1812
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1813
  }
1814

    
1815
  //
1816
  $data = array(
1817
      'ws_uri' => $uri,
1818
      'method' => $method,
1819
      'post_data' => $post_data,
1820
      'time' => sprintf('%3.3f', $time),
1821
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1822
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1823
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1824
      'status' => $status,
1825
      'data_links' => $data_links
1826
  );
1827
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1828
    $_SESSION['cdm']['ws_debug'] = array();
1829
  }
1830
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1831

    
1832
  // Mark this page as being uncacheable.
1833
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1834
  drupal_page_is_cacheable(FALSE);
1835

    
1836
  // Messages not set when DB connection fails.
1837
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1838
}
1839

    
1840
/**
1841
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1842
 * the visibility depends on whether
1843
 *  - the block is enabled
1844
 *  - the visibility restrictions in the block settings are satisfied
1845
 */
1846
function cdm_debug_block_visible() {
1847
  static $is_visible = null;
1848

    
1849
  if($is_visible === null){
1850
      $block = block_load('cdm_api', 'cdm_ws_debug');
1851
      $is_visible = isset($block->status) && $block->status == 1;
1852
      if($is_visible){
1853
        $blocks = array($block);
1854
        // Checks the page, user role, and user-specific visibilty settings.
1855
        block_block_list_alter($blocks);
1856
        $is_visible = count($blocks) > 0;
1857
      }
1858
  }
1859
  return $is_visible;
1860
}
1861

    
1862
/**
1863
 * @todo Please document this function.
1864
 * @see http://drupal.org/node/1354
1865
 */
1866
function cdm_load_obj($response_body) {
1867
  $obj = json_decode($response_body);
1868

    
1869
  if (!(is_object($obj) || is_array($obj))) {
1870
    ob_start();
1871
    $obj_dump = ob_get_contents();
1872
    ob_clean();
1873
    return FALSE;
1874
  }
1875

    
1876
  return $obj;
1877
}
1878

    
1879
/**
1880
 * Do a http request to a CDM RESTful web service.
1881
 *
1882
 * @param string $uri
1883
 *   The webservice url.
1884
 * @param string $method
1885
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1886
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1887
 * @param $data: A string containing the request body, formatted as
1888
 *     'param=value&param=value&...'. Defaults to NULL.
1889
 *
1890
 * @return object
1891
 *   The object as returned by drupal_http_request():
1892
 *   An object that can have one or more of the following components:
1893
 *   - request: A string containing the request body that was sent.
1894
 *   - code: An integer containing the response status code, or the error code
1895
 *     if an error occurred.
1896
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1897
 *   - status_message: The status message from the response, if a response was
1898
 *     received.
1899
 *   - redirect_code: If redirected, an integer containing the initial response
1900
 *     status code.
1901
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1902
 *     target.
1903
 *   - error: If an error occurred, the error message. Otherwise not set.
1904
 *   - headers: An array containing the response headers as name/value pairs.
1905
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1906
 *     easy access the array keys are returned in lower case.
1907
 *   - data: A string containing the response body that was received.
1908
 */
1909
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1910
  static $acceptLanguage = NULL;
1911
  $header = array();
1912

    
1913
  if (!$acceptLanguage) {
1914
    if (function_exists('apache_request_headers')) {
1915
      $headers = apache_request_headers();
1916
      if (isset($headers['Accept-Language'])) {
1917
        $acceptLanguage = $headers['Accept-Language'];
1918
      }
1919
    }
1920
    if (!$acceptLanguage) {
1921
      // DEFAULT TODO make configurable.
1922
      $acceptLanguage = "en";
1923
    }
1924
  }
1925

    
1926
  if ($method != "GET" && $method != "POST") {
1927
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1928
  }
1929

    
1930
  if (_is_cdm_ws_uri($uri)) {
1931
    $header['Accept'] = 'application/json';
1932
    $header['Accept-Language'] = $acceptLanguage;
1933
    $header['Accept-Charset'] = 'UTF-8';
1934
  }
1935

    
1936
  if($method == "POST") {
1937
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1938
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1939
  }
1940

    
1941

    
1942
  cdm_dd($uri);
1943
  return drupal_http_request($uri, array(
1944
      'headers' => $header,
1945
      'method' => $method,
1946
      'data' => $data,
1947
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1948
      )
1949
   );
1950
}
1951

    
1952
/**
1953
 * Concatenates recursively the fields of all features contained in the given
1954
 * CDM FeatureTree root node.
1955
 *
1956
 * @param $rootNode
1957
 *     A CDM FeatureTree node
1958
 * @param
1959
 *     The character to be used as glue for concatenation, default is ', '
1960
 * @param $field_name
1961
 *     The field name of the CDM Features
1962
 * @param $excludes
1963
 *     Allows defining a set of values to be excluded. This refers to the values
1964
 *     in the field denoted by the $field_name parameter
1965
 *
1966
 */
1967
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
1968
  $out = '';
1969

    
1970
  $pre_child_separator = $separator;
1971
  $post_child_separator = '';
1972

    
1973
  foreach ($root_node->childNodes as $feature_node) {
1974
    $out .= ($out ? $separator : '');
1975
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
1976
      $out .= $feature_node->feature->$field_name;
1977
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
1978
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
1979
        if (strlen($childlabels)) {
1980
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
1981
        }
1982
      }
1983
    }
1984
  }
1985
  return $out;
1986
}
1987

    
1988
/**
1989
 * Create a one-dimensional form options array.
1990
 *
1991
 * Creates an array of all features in the feature tree of feature nodes,
1992
 * the node labels are indented by $node_char and $childIndent depending on the
1993
 * hierachy level.
1994
 *
1995
 * @param - $rootNode
1996
 * @param - $node_char
1997
 * @param - $childIndentStr
1998
 * @param - $childIndent
1999
 *   ONLY USED INTERNALLY!
2000
 *
2001
 * @return array
2002
 *   A one dimensional Drupal form options array.
2003
 */
2004
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2005
  $options = array();
2006
  foreach ($rootNode->childNodes as $featureNode) {
2007
    $indent_prefix = '';
2008
    if ($childIndent) {
2009
      $indent_prefix = $childIndent . $node_char . " ";
2010
    }
2011
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2012
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2013
      // Foreach ($featureNode->childNodes as $childNode){
2014
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2015
      $options = array_merge_recursive($options, $childList);
2016
      // }
2017
    }
2018
  }
2019
  return $options;
2020
}
2021

    
2022
/**
2023
 * Returns an array with all available FeatureTrees and the representations of the selected
2024
 * FeatureTree as a detail view.
2025
 *
2026
 * @param boolean $add_default_feature_free
2027
 * @return array
2028
 *  associative array with following keys:
2029
 *  -options: Returns an array with all available Feature Trees
2030
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2031
 *
2032
 */
2033
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2034

    
2035
  $options = array();
2036
  $tree_representations = array();
2037
  $feature_trees = array();
2038

    
2039
  // Set tree that contains all features.
2040
  if ($add_default_feature_free) {
2041
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2042
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2043
  }
2044

    
2045
  // Get feature trees from database.
2046
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2047
  if (is_array($persited_trees)) {
2048
    $feature_trees = array_merge($feature_trees, $persited_trees);
2049
  }
2050

    
2051
  foreach ($feature_trees as $featureTree) {
2052

    
2053
    // Do not add the DEFAULT_FEATURETREE again,
2054
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2055
      $options[$featureTree->uuid] = $featureTree->titleCache;
2056
    }
2057

    
2058
    // Render the hierarchic tree structure
2059
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2060

    
2061
      // Render the hierarchic tree structure.
2062
      $treeDetails = '<div class="featuretree_structure">'
2063
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2064
        . '</div>';
2065

    
2066
      $form = array();
2067
      $form['featureTree-' .  $featureTree->uuid] = array(
2068
        '#type' => 'fieldset',
2069
        '#title' => 'Show details',
2070
        '#attributes' => array('class' => array('collapsible collapsed')),
2071
        // '#collapsible' => TRUE,
2072
        // '#collapsed' => TRUE,
2073
      );
2074
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2075
        '#markup' => $treeDetails,
2076
      );
2077

    
2078
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2079
    }
2080

    
2081
  } // END loop over feature trees
2082

    
2083
  // return $options;
2084
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2085
}
2086

    
2087
/**
2088
 * Provides the list of availbale classifications in form of an options array.
2089
 *
2090
 * The options array is suitable for drupal form API elements that allow multiple choices.
2091
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2092
 *
2093
 * The classifications are ordered alphabetically whereas the classification
2094
 * chosen as default will always appear on top of the array, followed by a
2095
 * blank line below.
2096
 *
2097
 * @param bool $add_none_option
2098
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2099
 *
2100
 * @return array
2101
 *   classifications in an array as options for a form element that allows multiple choices.
2102
 */
2103
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2104

    
2105
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2106

    
2107
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2108
  $default_classification_label = '';
2109

    
2110
  // add all classifications
2111
  $taxonomic_tree_options = array();
2112
  if ($add_none_option) {
2113
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2114
  }
2115
  if ($taxonTrees) {
2116
    foreach ($taxonTrees as $tree) {
2117
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2118
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2119
      } else {
2120
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2121
        $default_classification_label = $tree->titleCache;
2122
      }
2123
    }
2124
  }
2125
  // oder alphabetically the space
2126
  asort($taxonomic_tree_options);
2127

    
2128
  // now set the labels
2129
  //   for none
2130
  if ($add_none_option) {
2131
    $taxonomic_tree_options['NONE'] = t('-- None --');
2132
  }
2133

    
2134
  //   for default_classification
2135
  if (is_uuid($default_classification_uuid)) {
2136
    $taxonomic_tree_options[$default_classification_uuid] =
2137
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2138
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2139
  }
2140

    
2141
  return $taxonomic_tree_options;
2142
}
2143

    
2144
/**
2145
 * @todo Please document this function.
2146
 * @see http://drupal.org/node/1354
2147
 */
2148
function cdm_api_secref_cache_prefetch(&$secUuids) {
2149
  // Comment @WA: global variables should start with a single underscore
2150
  // followed by the module and another underscore.
2151
  global $_cdm_api_secref_cache;
2152
  if (!is_array($_cdm_api_secref_cache)) {
2153
    $_cdm_api_secref_cache = array();
2154
  }
2155
  $uniqueUuids = array_unique($secUuids);
2156
  $i = 0;
2157
  $param = '';
2158
  while ($i++ < count($uniqueUuids)) {
2159
    $param .= $secUuids[$i] . ',';
2160
    if (strlen($param) + 37 > 2000) {
2161
      _cdm_api_secref_cache_add($param);
2162
      $param = '';
2163
    }
2164
  }
2165
  if ($param) {
2166
    _cdm_api_secref_cache_add($param);
2167
  }
2168
}
2169

    
2170
/**
2171
 * @todo Please document this function.
2172
 * @see http://drupal.org/node/1354
2173
 */
2174
function cdm_api_secref_cache_get($secUuid) {
2175
  global $_cdm_api_secref_cache;
2176
  if (!is_array($_cdm_api_secref_cache)) {
2177
    $_cdm_api_secref_cache = array();
2178
  }
2179
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2180
    _cdm_api_secref_cache_add($secUuid);
2181
  }
2182
  return $_cdm_api_secref_cache[$secUuid];
2183
}
2184

    
2185
/**
2186
 * @todo Please document this function.
2187
 * @see http://drupal.org/node/1354
2188
 */
2189
function cdm_api_secref_cache_clear() {
2190
  global $_cdm_api_secref_cache;
2191
  $_cdm_api_secref_cache = array();
2192
}
2193

    
2194

    
2195
/**
2196
 * Validates if the given string is a uuid.
2197
 *
2198
 * @param string $str
2199
 *   The string to validate.
2200
 *
2201
 * return bool
2202
 *   TRUE if the string is a UUID.
2203
 */
2204
function is_uuid($str) {
2205
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2206
}
2207

    
2208
/**
2209
 * Checks if the given $object is a valid cdm entity.
2210
 *
2211
 * An object is considered a cdm entity if it has a string field $object->class
2212
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2213
 * The function is null save.
2214
 *
2215
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2216
 *
2217
 * @param mixed $object
2218
 *   The object to validate
2219
 *
2220
 * @return bool
2221
 *   True if the object is a cdm entity.
2222
 */
2223
function is_cdm_entity($object) {
2224
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2225
}
2226

    
2227
/**
2228
 * @todo Please document this function.
2229
 * @see http://drupal.org/node/1354
2230
 */
2231
function _cdm_api_secref_cache_add($secUuidsStr) {
2232
  global $_cdm_api_secref_cache;
2233
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2234
  // Batch fetching not jet reimplemented thus:
2235
  /*
2236
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2237
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2238
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2239
  */
2240
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2241
}
2242

    
2243
/**
2244
 * Checks if the given uri starts with a cdm webservice url.
2245
 *
2246
 * Checks if the uri starts with the cdm webservice url stored in the
2247
 * Drupal variable 'cdm_webservice_url'.
2248
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2249
 *
2250
 * @param string $uri
2251
 *   The URI to test.
2252
 *
2253
 * @return bool
2254
 *   True if the uri starts with a cdm webservice url.
2255
 */
2256
function _is_cdm_ws_uri($uri) {
2257
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2258
}
2259

    
2260
/**
2261
 * @todo Please document this function.
2262
 * @see http://drupal.org/node/1354
2263
 */
2264
function queryString($elements) {
2265
  $query = '';
2266
  foreach ($elements as $key => $value) {
2267
    if (is_array($value)) {
2268
      foreach ($value as $v) {
2269
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2270
      }
2271
    }
2272
    else {
2273
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2274
    }
2275
  }
2276
  return $query;
2277
}
2278

    
2279
/**
2280
 * Implementation of the magic method __clone to allow deep cloning of objects
2281
 * and arrays.
2282
 */
2283
function __clone() {
2284
  foreach ($this as $name => $value) {
2285
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2286
      $this->$name = clone($this->$name);
2287
    }
2288
  }
2289
}
2290

    
2291
/**
2292
 * Make a 'deep copy' of an array.
2293
 *
2294
 * Make a complete deep copy of an array replacing
2295
 * references with deep copies until a certain depth is reached
2296
 * ($maxdepth) whereupon references are copied as-is...
2297
 *
2298
 * @see http://us3.php.net/manual/en/ref.array.php
2299
 *
2300
 * @param array $array
2301
 * @param array $copy passed by reference
2302
 * @param int $maxdepth
2303
 * @param int $depth
2304
 */
2305
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2306
  if ($depth > $maxdepth) {
2307
    $copy = $array;
2308
    return;
2309
  }
2310
  if (!is_array($copy)) {
2311
    $copy = array();
2312
  }
2313
  foreach ($array as $k => &$v) {
2314
    if (is_array($v)) {
2315
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2316
    }
2317
    else {
2318
      $copy[$k] = $v;
2319
    }
2320
  }
2321
}
2322

    
2323
/**
2324
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2325
 *
2326
 */
2327
function _add_js_ws_debug() {
2328

    
2329
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2330
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2331
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2332
    // use the developer versions of js libs
2333
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2334
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2335
  }
2336
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2337
    array(
2338
      'type' => 'file',
2339
      'weight' => JS_LIBRARY,
2340
      'cache' => TRUE)
2341
    );
2342

    
2343
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2344
    array(
2345
      'type' => 'file',
2346
      'weight' => JS_LIBRARY,
2347
      'cache' => TRUE)
2348
    );
2349
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2350
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2351

    
2352
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2353
    array(
2354
      'type' => 'file',
2355
      'weight' => JS_LIBRARY,
2356
      'cache' => TRUE)
2357
    );
2358
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2359
    array(
2360
    'type' => 'file',
2361
    'weight' => JS_LIBRARY,
2362
    'cache' => TRUE)
2363
    );
2364

    
2365
}
2366

    
2367
/**
2368
 * @todo Please document this function.
2369
 * @see http://drupal.org/node/1354
2370
 */
2371
function _no_classfication_uuid_message() {
2372
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2373
    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.');
2374
  }
2375
  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.');
2376
}
2377

    
2378
/**
2379
 * Implementation of hook flush_caches
2380
 *
2381
 * Add custom cache tables to the list of cache tables that
2382
 * will be cleared by the Clear button on the Performance page or whenever
2383
 * drupal_flush_all_caches is invoked.
2384
 *
2385
 * @author W.Addink <waddink@eti.uva.nl>
2386
 *
2387
 * @return array
2388
 *   An array with custom cache tables to include.
2389
 */
2390
function cdm_api_flush_caches() {
2391
  return array('cache_cdm_ws');
2392
}
2393

    
2394
/**
2395
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2396
 *
2397
 * @param $data
2398
 *   The variable to log to the drupal_debug.txt log file.
2399
 * @param $label
2400
 *   (optional) If set, a label to output before $data in the log file.
2401
 *
2402
 * @return
2403
 *   No return value if successful, FALSE if the log file could not be written
2404
 *   to.
2405
 *
2406
 * @see cdm_dataportal_init() where the log file is reset on each requests
2407
 * @see dd()
2408
 * @see http://drupal.org/node/314112
2409
 *
2410
 */
2411
function cdm_dd($data, $label = NULL) {
2412
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2413
    return dd($data, $label);
2414
  }
2415
}
2416

    
(5-5/10)