Project

General

Profile

Download (71.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
define('SORT_ORDER_ID', 'sort_by_order_id');
41

    
42
/**
43
 * Implements hook_menu().
44
 */
45
function cdm_api_menu() {
46
  $items = array();
47

    
48
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
49
  $items['cdm_api/proxy'] = array(
50
    'page callback' => 'proxy_content',
51
    'access arguments' => array(
52
      'access content',
53
    ),
54
    'type' => MENU_CALLBACK,
55
  );
56

    
57
  $items['cdm_api/setvalue/session'] = array(
58
    'page callback' => 'setvalue_session',
59
    'access arguments' => array(
60
      'access content',
61
    ),
62
    'type' => MENU_CALLBACK,
63
  );
64

    
65
  return $items;
66
}
67

    
68
/**
69
 * Implements hook_block_info().
70
 */
71
function cdm_api_block_info() {
72

    
73
  $block['cdm_ws_debug'] = array(
74
      "info" => t("CDM web service debug"),
75
      "cache" => DRUPAL_NO_CACHE
76
  );
77
  return $block;
78
}
79

    
80
/**
81
 * Implements hook_block_view().
82
 */
83
function cdm_api_block_view($delta) {
84
  switch ($delta) {
85
    case 'cdm_ws_debug':
86

    
87
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
88

    
89
    $field_map = array(
90
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
91
        'time' => t('Time'),
92
        'fetch_seconds' => t('Fetching [s]'),
93
        'parse_seconds' => t('Parsing [s]'),
94
        'size_kb' => t('Size [kb]'),
95
        'status' => t('Status'),
96
        'data_links' =>  t('Links'),
97
    );
98

    
99

    
100
    if (!isset($_SESSION['cdm']['ws_debug'])) {
101
      $_SESSION['cdm']['ws_debug'] = array();
102
    }
103

    
104
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
105
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
106
    $rows = array();
107

    
108
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
109

    
110
      $data = unserialize($data);
111

    
112
      // stip of webservice base url
113
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
114
      if($data['method'] == 'POST'){
115
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
116
      }
117

    
118
      $cells = array();
119
      foreach ($field_map as $field => $label){
120
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
121
      }
122
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
123
    }
124
    // clear session again
125
    $_SESSION['cdm']['ws_debug'] = array();
126

    
127
    _add_js_ws_debug();
128

    
129
    $block['subject'] = ''; // no subject, title in content for having a defined element id
130
    // otherwise it would depend on the theme
131
    $block['content'] =
132
        '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
133
          // cannot use theme_table() since table footer is not jet supported in D7
134
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
135
        . $header
136
        . '<tbody>' . join('', $rows) . '</tbody>'
137
        . $footer
138
        . '</table></div>';
139

    
140
    return $block;
141
  }
142
}
143

    
144
/**
145
 * Implements hook_cron().
146
 *
147
 * Expire outdated cache entries.
148
 */
149
function cdm_api_cron() {
150
  cache_clear_all(NULL, 'cache_cdm_ws');
151
}
152

    
153
/**
154
 * @todo Please document this function.
155
 * @see http://drupal.org/node/1354
156
 */
157
function cdm_api_permission() {
158
  return array(
159
    'administer cdm_api' => array(
160
      'title' => t('administer cdm_api'),
161
      'description' => t("TODO Add a description for 'administer cdm_api'"),
162
    ),
163
  );
164
}
165

    
166
/**
167
 * Converts an array of TaggedText items into corresponding html tags.
168
 *
169
 * Each item is provided with a class attribute which is set to the key of the
170
 * TaggedText item.
171
 *
172
 * @param array $taggedtxt
173
 *   Array with text items to convert.
174
 * @param string $tag
175
 *   Html tag name to convert the items into, default is 'span'.
176
 * @param string $glue
177
 *   The string by which the chained text tokens are concatenated together.
178
 *   Default is a blank character.
179
 *
180
 * @return string
181
 *   A string with HTML.
182
 */
183
function cdm_taggedtext2html(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
184
  $out = '';
185
  $i = 0;
186
  foreach ($taggedtxt as $tt) {
187
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
188
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '') . '<' . $tag . ' class="' . $tt->type . '">' . t($tt->text) . '</' . $tag . '>';
189
    }
190
  }
191
  return $out;
192
}
193

    
194
/**
195
 * Finds the text tagged with $tag_type in an array of taggedText instances.
196
 *
197
 * Comment @WA: this function seems unused.
198
 *
199
 * @param array $taggedtxt
200
 *   Array with text items.
201
 * @param string $tag_type
202
 *   The type of tag for which to find text items in the $taggedtxt array.
203
 *
204
 * @return array
205
 *   An array with the texts mapped by $tag_type.
206
 */
207
function cdm_taggedtext_values(array $taggedtxt, $tag_type) {
208
  $tokens = array();
209
  if (!empty($taggedtxt)) {
210
    foreach ($taggedtxt as $tagtxt) {
211
      if ($tagtxt->type == $tag_type) {
212
        $tokens[] = $tagtxt->text;
213
      }
214
    }
215
  }
216
  return $tokens;
217
}
218

    
219
/**
220
 * Returns the currently classification tree in use.
221
 */
222
function get_taxonomictree_uuid_selected() {
223
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
224
    return $_SESSION['cdm']['taxonomictree_uuid'];
225
  }
226
  else {
227
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
228
  }
229
}
230

    
231
/**
232
 * Lists the classifications a taxon belongs to
233
 *
234
 * @param CDM type Taxon $taxon
235
 *   the taxon
236
 *
237
 * @return array
238
 *   aray of CDM instances of Type Classification
239
 */
240
function get_classifications_for_taxon($taxon) {
241

    
242
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
243
}
244

    
245
/**
246
 * Returns the chosen FeatureTree for the taxon profile.
247
 *
248
 * The FeatureTree profile returned is the one that has been set in the
249
 * dataportal settings (layout->taxon:profile).
250
 * When the chosen FeatureTree is not found in the database,
251
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
252
 *
253
 * @return mixed
254
 *   A cdm FeatureTree object.
255
 */
256
function get_profile_featureTree() {
257
  static $profile_featureTree;
258

    
259
  if($profile_featureTree == NULL) {
260
    $profile_featureTree = cdm_ws_get(
261
      CDM_WS_FEATURETREE,
262
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
263
    );
264
    if (!$profile_featureTree) {
265
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
266
    }
267
  }
268

    
269
  return $profile_featureTree;
270
}
271

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
568
  $y = NULL; $m = NULL; $d = NULL;
569

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

    
580
  $y = $y ? $y : '00';
581
  $m = $m ? $m : '00';
582
  $d = $d ? $d : '00';
583

    
584
  $date = '';
585

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

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

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

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

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

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

    
684
  $request_params = '';
685
  $path_params = '';
686

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

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

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

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

    
728
  $path = $uri_pattern;
729

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

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

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

    
760
  $post_data = null;
761

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

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

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

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

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

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

    
810
    $reponse_data = NULL;
811

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

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

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

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

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

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

    
870

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

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

    
881
}
882

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

    
897
  // Prevent from malicous tags.
898
  $val = strip_tags($val);
899

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

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

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

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

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

    
956
    case 'Media':
957
      $ws_base_uri = CDM_WS_MEDIA;
958
      break;
959

    
960
    case 'Reference':
961
      $ws_base_uri = CDM_WS_REFERENCE;
962
      break;
963

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

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

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

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

    
1016
  $query['pageNumber'] = $pageNumber;
1017
  $query['pageSize'] = $pageSize;
1018

    
1019
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1020
}
1021

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

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

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

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

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

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

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

    
1127
    $response = NULL;
1128

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

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

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

    
1156
  return $response;
1157
}
1158

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

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

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

    
1202
  return $response;
1203
}
1204

    
1205

    
1206
// =============================Terms and Vocabularies ========================================= //
1207

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

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

    
1263
  return $options;
1264
}
1265

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

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

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

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

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

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

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

    
1386

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

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

    
1411
  $merged_trees = array();
1412

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

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

    
1425
  return $feature_tree;
1426
}
1427

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

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

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

    
1465
}
1466

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

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

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

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

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

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

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

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

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

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

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

    
1593
  }
1594

    
1595
  return $featureNodes;
1596
}
1597

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

    
1634
  static $cacheL1 = array();
1635

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

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

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

    
1652
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1653
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1654

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

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

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

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

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

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

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

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

    
1719
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1720

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

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

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

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

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

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

    
1798
    // see ./js/http-method-link.js
1799

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

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

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

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

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

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

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

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

    
1878
  return $obj;
1879
}
1880

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

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

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

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

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

    
1943

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

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

    
1972
  $pre_child_separator = $separator;
1973
  $post_child_separator = '';
1974

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

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

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

    
2037
  $options = array();
2038
  $tree_representations = array();
2039
  $feature_trees = array();
2040

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

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

    
2053
  foreach ($feature_trees as $featureTree) {
2054

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

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

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

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

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

    
2083
  } // END loop over feature trees
2084

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

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

    
2107
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2108

    
2109
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2110
  $default_classification_label = '';
2111

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

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

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

    
2143
  return $taxonomic_tree_options;
2144
}
2145

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

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

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

    
2196

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

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

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

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

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

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

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

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

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

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

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

    
2367
}
2368

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

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

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

    
(5-5/10)