Project

General

Profile

Download (73.2 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', 'enums');
28
  module_load_include('php', 'cdm_api', 'webservice_uris');
29
  module_load_include('php', 'cdm_api', 'cdm_node');
30

    
31
  /**
32
   * Timeout 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_current_classification_uuid() {
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_feature_tree() {
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_current_classification_uuid();
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_current_classification_uuid();
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
 * Returns the localized representation for the given term.
1210
 *
1211
 * @param Object $definedTermBase
1212
 * 	  of cdm type DefinedTermBase
1213
 * @return string
1214
 * 	  the localized representation_L10n of the term,
1215
 *    otherwise the titleCache as fall back,
1216
 *    otherwise the default_representation which defaults to an empty string
1217
 */
1218
function cdm_term_representation($definedTermBase, $default_representation = '') {
1219
  if ( isset($definedTermBase->representation_L10n) ) {
1220
    return $definedTermBase->representation_L10n;
1221
  } elseif ( isset($definedTermBase->titleCache)) {
1222
    return $definedTermBase->titleCache;
1223
  }
1224
  return $default_representation;
1225
}
1226

    
1227
/**
1228
 * Returns the abbreviated localized representation for the given term.
1229
 *
1230
 * @param Object $definedTermBase
1231
 * 	  of cdm type DefinedTermBase
1232
 * @return string
1233
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1234
 *    if this representation is not available the function delegates the
1235
 *    call to cdm_term_representation()
1236
 */
1237
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1238
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1239
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1240
  } else {
1241
    cdm_term_representation($definedTermBase, $default_representation);
1242
  }
1243
}
1244

    
1245
/**
1246
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1247
 *
1248
 * The options array is suitable for drupal form API elements that allow multiple choices.
1249
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1250
 *
1251
 * @param array $terms
1252
 *   a list of CDM DefinedTermBase instances
1253
 *
1254
 * @param $sort_by
1255
 *  Optionally sort option SORT_ORDER_ID (default: sorts after the cdm order index ),
1256
 *  to sort alphabetically: SORT_ASC, SORT_DESC
1257
 *
1258
 * @param $term_label_callback
1259
 *   A callback function to override the term representations
1260
 *
1261
 * @return array
1262
 *   the terms in an array as options for a form element that allows multiple choices.
1263
 */
1264
function cdm_terms_as_options($terms, $sort_by = SORT_ORDER_ID, $term_label_callback = NULL){
1265
  $options = array();
1266
  if(isset($terms) && is_array($terms)){
1267
    foreach ($terms as $term){
1268
      if ($term_label_callback && function_exists($term_label_callback)) {
1269
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1270
      } else {
1271
        //TODO use cdm_term_representation() here?
1272
        $options[$term->uuid] = t($term->representation_L10n);
1273
      }
1274
    }
1275
  }
1276
  switch($sort_by){
1277
    case SORT_ORDER_ID: array_reverse($options);
1278
      break;
1279
    default: array_multisort($options, SORT_ASC);
1280
  }
1281

    
1282
  return $options;
1283
}
1284

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

    
1292
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1293
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1294
    $vocabularyOptions[$vocabularyUuid] = cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1295
  }
1296

    
1297
  $options = $vocabularyOptions[$vocabularyUuid];
1298
  if($default_option !== FALSE){
1299
    array_unshift ($options, "");
1300
  }
1301
  return $options;
1302
}
1303

    
1304
/**
1305
 * @param $term_type one of
1306
 *  - Unknown
1307
 *  - Language
1308
 *  - NamedArea
1309
 *  - Rank
1310
 *  - Feature
1311
 *  - AnnotationType
1312
 *  - MarkerType
1313
 *  - ExtensionType
1314
 *  - DerivationEventType
1315
 *  - PresenceAbsenceTerm
1316
 *  - NomenclaturalStatusType
1317
 *  - NameRelationshipType
1318
 *  - HybridRelationshipType
1319
 *  - SynonymRelationshipType
1320
 *  - TaxonRelationshipType
1321
 *  - NameTypeDesignationStatus
1322
 *  - SpecimenTypeDesignationStatus
1323
 *  - InstitutionType
1324
 *  - NamedAreaType
1325
 *  - NamedAreaLevel
1326
 *  - RightsType
1327
 *  - MeasurementUnit
1328
 *  - StatisticalMeasure
1329
 *  - MaterialOrMethod
1330
 *  - Material
1331
 *  - Method
1332
 *  - Modifier
1333
 *  - Scope
1334
 *  - Stage
1335
 *  - KindOfUnit
1336
 *  - Sex
1337
 *  - ReferenceSystem
1338
 *  - State
1339
 *  - NaturalLanguageTerm
1340
 *  - TextFormat
1341
 *  - DeterminationModifier
1342
 *  - DnaMarker
1343
 */
1344
function cdm_terms_by_type_as_option($term_type, $sort_by = SORT_ORDER_ID, $term_label_callback = NULL){
1345
  $terms = cdm_ws_fetch_all(CDM_WS_TERM, array('class' => $term_type));
1346
  return cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1347
}
1348

    
1349
/**
1350
 * @todo Please document this function.
1351
 * @see http://drupal.org/node/1354
1352
 */
1353
function cdm_rankVocabulary_as_option() {
1354
  $options = cdm_Vocabulary_as_option(UUID_RANK, NULL, "");
1355
  return $options;
1356
}
1357

    
1358
/**
1359
 * @todo Please document this function.
1360
 * @see http://drupal.org/node/1354
1361
 */
1362
function _cdm_relationship_type_term_label_callback($term) {
1363
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1364
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1365
  }
1366
else {
1367
    return t($term->representation_L10n);
1368
  }
1369
}
1370

    
1371
// ========================================================================================== //
1372
/**
1373
 * @todo Improve documentation of this function.
1374
 *
1375
 * eu.etaxonomy.cdm.model.description.
1376
 * CategoricalData
1377
 * CommonTaxonName
1378
 * Distribution
1379
 * IndividualsAssociation
1380
 * QuantitativeData
1381
 * TaxonInteraction
1382
 * TextData
1383
 */
1384
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1385
  static $types = array(
1386
    "CategoricalData",
1387
    "CommonTaxonName",
1388
    "Distribution",
1389
    "IndividualsAssociation",
1390
    "QuantitativeData",
1391
    "TaxonInteraction",
1392
    "TextData",
1393
  );
1394

    
1395
  static $options = NULL;
1396
  if ($options == NULL) {
1397
    $options = array();
1398
    if ($prependEmptyElement) {
1399
      $options[' '] = '';
1400
    }
1401
    foreach ($types as $type) {
1402
      // No internatianalization here since these are purely technical terms.
1403
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1404
    }
1405
  }
1406
  return $options;
1407
}
1408

    
1409

    
1410
/**
1411
 * Fetches all TaxonDescription descriptions elements wich are accociated to the
1412
 * Taxon specified by the $taxon_uuid and megres the elements into the given
1413
 * feature tree.
1414
 * @param $feature_tree
1415
 *     The CDM FeatureTree to be used as template
1416
 * @param $taxon_uuid
1417
 *     The UUID of the taxon
1418
 * @param $excludes
1419
 *     UUIDs of features to be excluded
1420
 * @return$feature_tree
1421
 *     The CDM FeatureTree wich was given as parameter merged tree wheras the
1422
 *     CDM FeatureNodes are extended by an additinal field 'descriptionElements'
1423
 *     witch will hold the accoding $descriptionElements.
1424
 */
1425
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1426

    
1427
  if (!$feature_tree) {
1428
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1429
      In order to see the species profiles of your taxa, please select a
1430
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1431
    return FALSE;
1432
  }
1433

    
1434
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1435
      array(
1436
      'taxon' => $taxon_uuid,
1437
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1438
      ),
1439
      'POST'
1440
  );
1441

    
1442
  // Combine all descriptions into one feature tree.
1443
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1444
  $feature_tree->root->childNodes = $merged_nodes;
1445

    
1446
  return $feature_tree;
1447
}
1448

    
1449
/**
1450
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1451
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1452
 * be requested for the annotations.
1453
 *
1454
 * @param string $cdmBase
1455
 *   An annotatable cdm entity.
1456
 * @param array $includeTypes
1457
 *   If an array of annotation type uuids is supplied by this parameter the
1458
 *   list of annotations is resticted to those which belong to this type.
1459
 *
1460
 * @return array
1461
 *   An array of Annotation objects or an empty array.
1462
 */
1463
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1464

    
1465
  if(!isset($cdmBase->annotations)){
1466
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1467
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1468
  }
1469

    
1470
  $annotations = array();
1471
  foreach ($cdmBase->annotations as $annotation) {
1472
    if ($includeTypes) {
1473
      if (
1474
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1475
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1476
      ) {
1477
        $annotations[] = $annotation;
1478
      }
1479
    }
1480
    else {
1481
      $annotations[] = $annotation;
1482
    }
1483
  }
1484
  return $annotations;
1485

    
1486
}
1487

    
1488
/**
1489
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1490
 *
1491
 * @param object $annotatable_entity
1492
 *   The CDM AnnotatableEntity to load annotations for
1493
 */
1494
function cdm_load_annotations(&$annotatable_entity) {
1495
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1496
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1497
    if (is_array($annotations)) {
1498
      $annotatable_entity->annotations = $annotations;
1499
    }
1500
  }
1501
}
1502

    
1503
/**
1504
 * Get a NomenclaturalReference string.
1505
 *
1506
 * Returns the NomenclaturalReference string with correctly placed
1507
 * microreference (= reference detail) e.g.
1508
 * in Phytotaxa 43: 1-48. 2012.
1509
 *
1510
 * @param string $referenceUuid
1511
 *   UUID of the reference.
1512
 * @param string $microreference
1513
 *   Reference detail.
1514
 *
1515
 * @return string
1516
 *   a NomenclaturalReference.
1517
 */
1518
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1519
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1520
    $referenceUuid,
1521
  ), "microReference=" . urlencode($microreference));
1522

    
1523
  if ($obj) {
1524
    return $obj->String;
1525
  }
1526
  else {
1527
    return NULL;
1528
  }
1529
}
1530

    
1531
/**
1532
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1533
 *
1534
 * @param $feature_tree_nodes
1535
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1536
 * @param $feature_uuid
1537
 *    The UUID of the Feature
1538
 * @return returns the FeatureNode or null
1539
 */
1540
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1541

    
1542
  // 1. scan this level
1543
  foreach ($feature_tree_nodes as $node){
1544
    if($node->feature->uuid == $feature_uuid){
1545
      return $node;
1546
    }
1547
  }
1548

    
1549
  // 2. descend into childen
1550
  foreach ($feature_tree_nodes as $node){
1551
    if(is_array($node->childNodes)){
1552
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1553
      if($node) {
1554
        return $node;
1555
      }
1556
    }
1557
  }
1558
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1559
  return $null_var;
1560
}
1561

    
1562
/**
1563
 * Merges the given featureNodes structure with the descriptionElements.
1564
 *
1565
 * This method is used in preparation for rendering the descriptionElements.
1566
 * The descriptionElements which belong to a specific feature node are appended
1567
 * to a the feature node by creating a new field:
1568
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1569
 * The descriptionElements will be cleared in advance in order to allow reusing the
1570
 * same feature tree without the risk of mixing sets of description elements.
1571
 *
1572
 * which originally is not existing in the cdm.
1573
 *
1574
 *
1575
 *
1576
 * @param array $featureNodes
1577
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1578
 *    may have children.
1579
 * @param array $descriptionElements
1580
 *    An flat array of cdm DescriptionElements
1581
 * @return array
1582
 *    The $featureNodes structure enriched with the according $descriptionElements
1583
 */
1584
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1585

    
1586
  foreach ($featureNodes as &$node) {
1587
    // since the $featureNodes array is reused for each description
1588
    // it is necessary to clear the custom node fields in advance
1589
    if(isset($node->descriptionElements)){
1590
      unset($node->descriptionElements);
1591
    }
1592

    
1593
    // Append corresponding elements to an additional node field:
1594
    // $node->descriptionElements.
1595
    foreach ($descriptionElements as $element) {
1596
      if ($element->feature->uuid == $node->feature->uuid) {
1597
        if (!isset($node->descriptionElements)) {
1598
          $node->descriptionElements = array();
1599
        }
1600
        $node->descriptionElements[] = $element;
1601
      }
1602
    }
1603

    
1604
    // Recurse into node children.
1605
    if (isset($node->childNodes[0])) {
1606
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1607
      $node->childNodes = $mergedChildNodes;
1608
    }
1609

    
1610
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1611
      unset($node);
1612
    }
1613

    
1614
  }
1615

    
1616
  return $featureNodes;
1617
}
1618

    
1619
/**
1620
 * Sends a GET or POST request to a CDM RESTService and returns a deserialized object.
1621
 *
1622
 * The response from the HTTP GET request is returned as object.
1623
 * The response objects coming from the webservice configured in the
1624
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1625
 *  in a level 2 (L2) cache.
1626
 *
1627
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1628
 * function, this cache persists only per each single page execution.
1629
 * Any object coming from the webservice is stored into it by default.
1630
 * In contrast to this default caching mechanism the L2 cache only is used if
1631
 * the 'cdm_webservice_cache' variable is set to TRUE,
1632
 * which can be set using the modules administrative settings section.
1633
 * Objects stored in this L2 cache are serialized and stored
1634
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1635
 * objects that are stored in the database will persist as
1636
 * long as the drupal cache is not beeing cleared and are available across
1637
 * multiple script executions.
1638
 *
1639
 * @param string $uri
1640
 *   URL to the webservice.
1641
 * @param array $pathParameters
1642
 *   An array of path parameters.
1643
 * @param string $query
1644
 *   A query string to be appended to the URL.
1645
 * @param string $method
1646
 *   The HTTP method to use, valid values are "GET" or "POST";
1647
 * @param bool $absoluteURI
1648
 *   TRUE when the URL should be treated as absolute URL.
1649
 *
1650
 * @return object
1651
 *   The deserialized webservice response object.
1652
 */
1653
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1654

    
1655
  static $cacheL1 = array();
1656

    
1657
  $data = NULL;
1658
  // store query string in $data and clear the query, $data will be set as HTTP request body
1659
  if($method == 'POST'){
1660
    $data = $query;
1661
    $query = NULL;
1662
  }
1663

    
1664
  // Transform the given uri path or pattern into a proper webservice uri.
1665
  if (!$absoluteURI) {
1666
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1667
  }
1668

    
1669
  // read request parameter 'cacheL2_refresh'
1670
  // which allows refreshig the level 2 cache
1671
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1672

    
1673
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1674
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1675

    
1676
  if($method == 'GET'){
1677
    $cache_key = $uri;
1678
  } else {
1679
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1680
    // crc32 is faster but creates much shorter hashes
1681
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1682
  }
1683

    
1684
  if (array_key_exists($cache_key, $cacheL1)) {
1685
    $cacheL1_obj = $cacheL1[$uri];
1686
  }
1687

    
1688
  $set_cacheL1 = FALSE;
1689
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1690
    $set_cacheL1 = TRUE;
1691
  }
1692

    
1693
  // Only cache cdm webservice URIs.
1694
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1695
  $cacheL2_entry = FALSE;
1696

    
1697
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1698
    // Try to get object from cacheL2.
1699
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1700
  }
1701

    
1702
  if (isset($cacheL1_obj)) {
1703
    //
1704
    // The object has been found in the L1 cache.
1705
    //
1706
    $obj = $cacheL1_obj;
1707
    if (cdm_debug_block_visible()) {
1708
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1709
    }
1710
  }
1711
  elseif ($cacheL2_entry) {
1712
    //
1713
    // The object has been found in the L2 cache.
1714
    //
1715
    $duration_parse_start = microtime(TRUE);
1716
    $obj = unserialize($cacheL2_entry->data);
1717
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1718

    
1719
    if (cdm_debug_block_visible()) {
1720
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1721
    }
1722
  }
1723
  else {
1724
    //
1725
    // Get the object from the webservice and cache it.
1726
    //
1727
    $duration_fetch_start = microtime(TRUE);
1728
    // Request data from webservice JSON or XML.
1729
    $response = cdm_http_request($uri, $method, $data);
1730
    $response_body = NULL;
1731
    if (isset($response->data)) {
1732
      $response_body = $response->data;
1733
    }
1734
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1735
    $duration_parse_start = microtime(TRUE);
1736

    
1737
    // Parse data and create object.
1738
    $obj = cdm_load_obj($response_body);
1739

    
1740
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1741

    
1742
    if (cdm_debug_block_visible()) {
1743
      if ($obj || $response_body == "[]") {
1744
        $status = 'valid';
1745
      }
1746
      else {
1747
        $status = 'invalid';
1748
      }
1749
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1750
    }
1751
    if ($set_cacheL2) {
1752
      // Store the object in cache L2.
1753
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1754
      // flag serialized is set properly in the cache table.
1755
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1756
    }
1757
  }
1758
  if ($obj) {
1759
    // Store the object in cache L1.
1760
    if ($set_cacheL1) {
1761
      $cacheL1[$cache_key] = $obj;
1762
    }
1763
  }
1764
  return $obj;
1765
}
1766

    
1767
/**
1768
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1769
 *
1770
 * The cdm_ws_debug block will display the debug information.
1771
 *
1772
 * @param $uri
1773
 *    The CDM REST URI to which the request has been send
1774
 * @param string $method
1775
 *    The HTTP request method, either 'GET' or 'POST'
1776
 * @param string $post_data
1777
 *    The datastring send with a post request
1778
 * @param $duration_fetch
1779
 *    The time in seconds it took to fetch the data from the web service
1780
 * @param $duration_parse
1781
 *    Time in seconds which was needed to parse the json response
1782
 * @param $datasize
1783
 *    Size of the data received from the server
1784
 * @param $status
1785
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1786
 * @return bool
1787
 *    TRUE if adding the debug information was successful
1788
 */
1789
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1790

    
1791
  static $initial_time = NULL;
1792
  if(!$initial_time) {
1793
    $initial_time = microtime(TRUE);
1794
  }
1795
  $time = microtime(TRUE) - $initial_time;
1796

    
1797
  // Decompose uri into path and query element.
1798
  $uri_parts = explode("?", $uri);
1799
  $query = array();
1800
  if (count($uri_parts) == 2) {
1801
    $path = $uri_parts[0];
1802
  }
1803
  else {
1804
    $path = $uri;
1805
  }
1806

    
1807
  if(strpos($uri, '?') > 0){
1808
    $json_uri = str_replace('?', '.json?', $uri);
1809
    $xml_uri = str_replace('?', '.xml?', $uri);
1810
  } else {
1811
    $json_uri = $uri . '.json';
1812
    $xml_uri = $json_uri . '.xml';
1813
  }
1814

    
1815
  // data links to make data accecsible as json and xml
1816
  $data_links = '';
1817
  if (_is_cdm_ws_uri($path)) {
1818

    
1819
    // see ./js/http-method-link.js
1820

    
1821
    if($method == 'GET'){
1822
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1823
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1824
      $data_links .= '<br/>';
1825
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1826
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1827
    } else {
1828
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1829
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1830
      $data_links .= '<br/>';
1831
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1832
    }
1833
  }
1834
  else {
1835
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1836
  }
1837

    
1838
  //
1839
  $data = array(
1840
      'ws_uri' => $uri,
1841
      'method' => $method,
1842
      'post_data' => $post_data,
1843
      'time' => sprintf('%3.3f', $time),
1844
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1845
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1846
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1847
      'status' => $status,
1848
      'data_links' => $data_links
1849
  );
1850
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1851
    $_SESSION['cdm']['ws_debug'] = array();
1852
  }
1853
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1854

    
1855
  // Mark this page as being uncacheable.
1856
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1857
  drupal_page_is_cacheable(FALSE);
1858

    
1859
  // Messages not set when DB connection fails.
1860
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1861
}
1862

    
1863
/**
1864
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1865
 * the visibility depends on whether
1866
 *  - the block is enabled
1867
 *  - the visibility restrictions in the block settings are satisfied
1868
 */
1869
function cdm_debug_block_visible() {
1870
  static $is_visible = null;
1871

    
1872
  if($is_visible === null){
1873
      $block = block_load('cdm_api', 'cdm_ws_debug');
1874
      $is_visible = isset($block->status) && $block->status == 1;
1875
      if($is_visible){
1876
        $blocks = array($block);
1877
        // Checks the page, user role, and user-specific visibilty settings.
1878
        block_block_list_alter($blocks);
1879
        $is_visible = count($blocks) > 0;
1880
      }
1881
  }
1882
  return $is_visible;
1883
}
1884

    
1885
/**
1886
 * @todo Please document this function.
1887
 * @see http://drupal.org/node/1354
1888
 */
1889
function cdm_load_obj($response_body) {
1890
  $obj = json_decode($response_body);
1891

    
1892
  if (!(is_object($obj) || is_array($obj))) {
1893
    ob_start();
1894
    $obj_dump = ob_get_contents();
1895
    ob_clean();
1896
    return FALSE;
1897
  }
1898

    
1899
  return $obj;
1900
}
1901

    
1902
/**
1903
 * Do a http request to a CDM RESTful web service.
1904
 *
1905
 * @param string $uri
1906
 *   The webservice url.
1907
 * @param string $method
1908
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1909
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1910
 * @param $data: A string containing the request body, formatted as
1911
 *     'param=value&param=value&...'. Defaults to NULL.
1912
 *
1913
 * @return object
1914
 *   The object as returned by drupal_http_request():
1915
 *   An object that can have one or more of the following components:
1916
 *   - request: A string containing the request body that was sent.
1917
 *   - code: An integer containing the response status code, or the error code
1918
 *     if an error occurred.
1919
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1920
 *   - status_message: The status message from the response, if a response was
1921
 *     received.
1922
 *   - redirect_code: If redirected, an integer containing the initial response
1923
 *     status code.
1924
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1925
 *     target.
1926
 *   - error: If an error occurred, the error message. Otherwise not set.
1927
 *   - headers: An array containing the response headers as name/value pairs.
1928
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1929
 *     easy access the array keys are returned in lower case.
1930
 *   - data: A string containing the response body that was received.
1931
 */
1932
function cdm_http_request($uri, $method = "GET", $data = NULL) {
1933
  static $acceptLanguage = NULL;
1934
  $header = array();
1935

    
1936
  if (!$acceptLanguage) {
1937
    if (function_exists('apache_request_headers')) {
1938
      $headers = apache_request_headers();
1939
      if (isset($headers['Accept-Language'])) {
1940
        $acceptLanguage = $headers['Accept-Language'];
1941
      }
1942
    }
1943
    if (!$acceptLanguage) {
1944
      // DEFAULT TODO make configurable.
1945
      $acceptLanguage = "en";
1946
    }
1947
  }
1948

    
1949
  if ($method != "GET" && $method != "POST") {
1950
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
1951
  }
1952

    
1953
  if (_is_cdm_ws_uri($uri)) {
1954
    $header['Accept'] = 'application/json';
1955
    $header['Accept-Language'] = $acceptLanguage;
1956
    $header['Accept-Charset'] = 'UTF-8';
1957
  }
1958

    
1959
  if($method == "POST") {
1960
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
1961
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
1962
  }
1963

    
1964

    
1965
  cdm_dd($uri);
1966
  return drupal_http_request($uri, array(
1967
      'headers' => $header,
1968
      'method' => $method,
1969
      'data' => $data,
1970
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1971
      )
1972
   );
1973
}
1974

    
1975
/**
1976
 * Concatenates recursively the fields of all features contained in the given
1977
 * CDM FeatureTree root node.
1978
 *
1979
 * @param $rootNode
1980
 *     A CDM FeatureTree node
1981
 * @param
1982
 *     The character to be used as glue for concatenation, default is ', '
1983
 * @param $field_name
1984
 *     The field name of the CDM Features
1985
 * @param $excludes
1986
 *     Allows defining a set of values to be excluded. This refers to the values
1987
 *     in the field denoted by the $field_name parameter
1988
 *
1989
 */
1990
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
1991
  $out = '';
1992

    
1993
  $pre_child_separator = $separator;
1994
  $post_child_separator = '';
1995

    
1996
  foreach ($root_node->childNodes as $feature_node) {
1997
    $out .= ($out ? $separator : '');
1998
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
1999
      $out .= $feature_node->feature->$field_name;
2000
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2001
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2002
        if (strlen($childlabels)) {
2003
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2004
        }
2005
      }
2006
    }
2007
  }
2008
  return $out;
2009
}
2010

    
2011
/**
2012
 * Create a one-dimensional form options array.
2013
 *
2014
 * Creates an array of all features in the feature tree of feature nodes,
2015
 * the node labels are indented by $node_char and $childIndent depending on the
2016
 * hierachy level.
2017
 *
2018
 * @param - $rootNode
2019
 * @param - $node_char
2020
 * @param - $childIndentStr
2021
 * @param - $childIndent
2022
 *   ONLY USED INTERNALLY!
2023
 *
2024
 * @return array
2025
 *   A one dimensional Drupal form options array.
2026
 */
2027
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2028
  $options = array();
2029
  foreach ($rootNode->childNodes as $featureNode) {
2030
    $indent_prefix = '';
2031
    if ($childIndent) {
2032
      $indent_prefix = $childIndent . $node_char . " ";
2033
    }
2034
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2035
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2036
      // Foreach ($featureNode->childNodes as $childNode){
2037
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2038
      $options = array_merge_recursive($options, $childList);
2039
      // }
2040
    }
2041
  }
2042
  return $options;
2043
}
2044

    
2045
/**
2046
 * Returns an array with all available FeatureTrees and the representations of the selected
2047
 * FeatureTree as a detail view.
2048
 *
2049
 * @param boolean $add_default_feature_free
2050
 * @return array
2051
 *  associative array with following keys:
2052
 *  -options: Returns an array with all available Feature Trees
2053
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2054
 *
2055
 */
2056
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2057

    
2058
  $options = array();
2059
  $tree_representations = array();
2060
  $feature_trees = array();
2061

    
2062
  // Set tree that contains all features.
2063
  if ($add_default_feature_free) {
2064
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2065
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2066
  }
2067

    
2068
  // Get feature trees from database.
2069
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2070
  if (is_array($persited_trees)) {
2071
    $feature_trees = array_merge($feature_trees, $persited_trees);
2072
  }
2073

    
2074
  foreach ($feature_trees as $featureTree) {
2075

    
2076
    if(!is_object($featureTree)){
2077
      continue;
2078
    }
2079
    // Do not add the DEFAULT_FEATURETREE again,
2080
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2081
      $options[$featureTree->uuid] = $featureTree->titleCache;
2082
    }
2083

    
2084
    // Render the hierarchic tree structure
2085
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2086

    
2087
      // Render the hierarchic tree structure.
2088
      $treeDetails = '<div class="featuretree_structure">'
2089
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2090
        . '</div>';
2091

    
2092
      $form = array();
2093
      $form['featureTree-' .  $featureTree->uuid] = array(
2094
        '#type' => 'fieldset',
2095
        '#title' => 'Show details',
2096
        '#attributes' => array('class' => array('collapsible collapsed')),
2097
        // '#collapsible' => TRUE,
2098
        // '#collapsed' => TRUE,
2099
      );
2100
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2101
        '#markup' => $treeDetails,
2102
      );
2103

    
2104
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2105
    }
2106

    
2107
  } // END loop over feature trees
2108

    
2109
  // return $options;
2110
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2111
}
2112

    
2113
/**
2114
 * Provides the list of availbale classifications in form of an options array.
2115
 *
2116
 * The options array is suitable for drupal form API elements that allow multiple choices.
2117
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2118
 *
2119
 * The classifications are ordered alphabetically whereas the classification
2120
 * chosen as default will always appear on top of the array, followed by a
2121
 * blank line below.
2122
 *
2123
 * @param bool $add_none_option
2124
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2125
 *
2126
 * @return array
2127
 *   classifications in an array as options for a form element that allows multiple choices.
2128
 */
2129
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2130

    
2131
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2132

    
2133
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2134
  $default_classification_label = '';
2135

    
2136
  // add all classifications
2137
  $taxonomic_tree_options = array();
2138
  if ($add_none_option) {
2139
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2140
  }
2141
  if ($taxonTrees) {
2142
    foreach ($taxonTrees as $tree) {
2143
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2144
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2145
      } else {
2146
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2147
        $default_classification_label = $tree->titleCache;
2148
      }
2149
    }
2150
  }
2151
  // oder alphabetically the space
2152
  asort($taxonomic_tree_options);
2153

    
2154
  // now set the labels
2155
  //   for none
2156
  if ($add_none_option) {
2157
    $taxonomic_tree_options['NONE'] = '-- ' . t('ALL (incl. w/o classification)') . ' --';
2158
  }
2159

    
2160
  //   for default_classification
2161
  if (is_uuid($default_classification_uuid)) {
2162
    $taxonomic_tree_options[$default_classification_uuid] =
2163
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2164
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2165
  }
2166

    
2167
  return $taxonomic_tree_options;
2168
}
2169

    
2170
/**
2171
 * @todo Please document this function.
2172
 * @see http://drupal.org/node/1354
2173
 */
2174
function cdm_api_secref_cache_prefetch(&$secUuids) {
2175
  // Comment @WA: global variables should start with a single underscore
2176
  // followed by the module and another underscore.
2177
  global $_cdm_api_secref_cache;
2178
  if (!is_array($_cdm_api_secref_cache)) {
2179
    $_cdm_api_secref_cache = array();
2180
  }
2181
  $uniqueUuids = array_unique($secUuids);
2182
  $i = 0;
2183
  $param = '';
2184
  while ($i++ < count($uniqueUuids)) {
2185
    $param .= $secUuids[$i] . ',';
2186
    if (strlen($param) + 37 > 2000) {
2187
      _cdm_api_secref_cache_add($param);
2188
      $param = '';
2189
    }
2190
  }
2191
  if ($param) {
2192
    _cdm_api_secref_cache_add($param);
2193
  }
2194
}
2195

    
2196
/**
2197
 * @todo Please document this function.
2198
 * @see http://drupal.org/node/1354
2199
 */
2200
function cdm_api_secref_cache_get($secUuid) {
2201
  global $_cdm_api_secref_cache;
2202
  if (!is_array($_cdm_api_secref_cache)) {
2203
    $_cdm_api_secref_cache = array();
2204
  }
2205
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2206
    _cdm_api_secref_cache_add($secUuid);
2207
  }
2208
  return $_cdm_api_secref_cache[$secUuid];
2209
}
2210

    
2211
/**
2212
 * @todo Please document this function.
2213
 * @see http://drupal.org/node/1354
2214
 */
2215
function cdm_api_secref_cache_clear() {
2216
  global $_cdm_api_secref_cache;
2217
  $_cdm_api_secref_cache = array();
2218
}
2219

    
2220

    
2221
/**
2222
 * Validates if the given string is a uuid.
2223
 *
2224
 * @param string $str
2225
 *   The string to validate.
2226
 *
2227
 * return bool
2228
 *   TRUE if the string is a UUID.
2229
 */
2230
function is_uuid($str) {
2231
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2232
}
2233

    
2234
/**
2235
 * Checks if the given $object is a valid cdm entity.
2236
 *
2237
 * An object is considered a cdm entity if it has a string field $object->class
2238
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2239
 * The function is null save.
2240
 *
2241
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2242
 *
2243
 * @param mixed $object
2244
 *   The object to validate
2245
 *
2246
 * @return bool
2247
 *   True if the object is a cdm entity.
2248
 */
2249
function is_cdm_entity($object) {
2250
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2251
}
2252

    
2253
/**
2254
 * @todo Please document this function.
2255
 * @see http://drupal.org/node/1354
2256
 */
2257
function _cdm_api_secref_cache_add($secUuidsStr) {
2258
  global $_cdm_api_secref_cache;
2259
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2260
  // Batch fetching not jet reimplemented thus:
2261
  /*
2262
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2263
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2264
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2265
  */
2266
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2267
}
2268

    
2269
/**
2270
 * Checks if the given uri starts with a cdm webservice url.
2271
 *
2272
 * Checks if the uri starts with the cdm webservice url stored in the
2273
 * Drupal variable 'cdm_webservice_url'.
2274
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2275
 *
2276
 * @param string $uri
2277
 *   The URI to test.
2278
 *
2279
 * @return bool
2280
 *   True if the uri starts with a cdm webservice url.
2281
 */
2282
function _is_cdm_ws_uri($uri) {
2283
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2284
}
2285

    
2286
/**
2287
 * @todo Please document this function.
2288
 * @see http://drupal.org/node/1354
2289
 */
2290
function queryString($elements) {
2291
  $query = '';
2292
  foreach ($elements as $key => $value) {
2293
    if (is_array($value)) {
2294
      foreach ($value as $v) {
2295
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2296
      }
2297
    }
2298
    else {
2299
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2300
    }
2301
  }
2302
  return $query;
2303
}
2304

    
2305
/**
2306
 * Implementation of the magic method __clone to allow deep cloning of objects
2307
 * and arrays.
2308
 */
2309
function __clone() {
2310
  foreach ($this as $name => $value) {
2311
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2312
      $this->$name = clone($this->$name);
2313
    }
2314
  }
2315
}
2316

    
2317
/**
2318
 * Compares the given CDM Term instances by the  representationL10n.
2319
 *
2320
 * Can also be used with TermDTOs. To be used in usort()
2321
 *
2322
 * @see http://php.net/manual/en/function.usort.php
2323
 *
2324
 * @param $term1
2325
 *   The first CDM Term instance
2326
 * @param $term2
2327
 *   The second CDM Term instance
2328
 * @return int
2329
 *   The result of the comparison
2330
 */
2331
function compare_terms_by_representationL10n($term1, $term2) {
2332

    
2333
  if (!isset($term1->representation_L10n)) {
2334
    $term1->representationL10n = '';
2335
  }
2336
  if (!isset($term2->representation_L10n)) {
2337
    $term2->representationL10n = '';
2338
  }
2339

    
2340
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2341
}
2342

    
2343

    
2344
/**
2345
 * Make a 'deep copy' of an array.
2346
 *
2347
 * Make a complete deep copy of an array replacing
2348
 * references with deep copies until a certain depth is reached
2349
 * ($maxdepth) whereupon references are copied as-is...
2350
 *
2351
 * @see http://us3.php.net/manual/en/ref.array.php
2352
 *
2353
 * @param array $array
2354
 * @param array $copy passed by reference
2355
 * @param int $maxdepth
2356
 * @param int $depth
2357
 */
2358
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2359
  if ($depth > $maxdepth) {
2360
    $copy = $array;
2361
    return;
2362
  }
2363
  if (!is_array($copy)) {
2364
    $copy = array();
2365
  }
2366
  foreach ($array as $k => &$v) {
2367
    if (is_array($v)) {
2368
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2369
    }
2370
    else {
2371
      $copy[$k] = $v;
2372
    }
2373
  }
2374
}
2375

    
2376
/**
2377
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2378
 *
2379
 */
2380
function _add_js_ws_debug() {
2381

    
2382
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2383
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2384
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2385
    // use the developer versions of js libs
2386
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2387
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2388
  }
2389
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2390
    array(
2391
      'type' => 'file',
2392
      'weight' => JS_LIBRARY,
2393
      'cache' => TRUE)
2394
    );
2395

    
2396
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2397
    array(
2398
      'type' => 'file',
2399
      'weight' => JS_LIBRARY,
2400
      'cache' => TRUE)
2401
    );
2402
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2403
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2404

    
2405
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2406
    array(
2407
      'type' => 'file',
2408
      'weight' => JS_LIBRARY,
2409
      'cache' => TRUE)
2410
    );
2411
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2412
    array(
2413
    'type' => 'file',
2414
    'weight' => JS_LIBRARY,
2415
    'cache' => TRUE)
2416
    );
2417

    
2418
}
2419

    
2420
/**
2421
 * @todo Please document this function.
2422
 * @see http://drupal.org/node/1354
2423
 */
2424
function _no_classfication_uuid_message() {
2425
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2426
    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.');
2427
  }
2428
  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.');
2429
}
2430

    
2431
/**
2432
 * Implementation of hook flush_caches
2433
 *
2434
 * Add custom cache tables to the list of cache tables that
2435
 * will be cleared by the Clear button on the Performance page or whenever
2436
 * drupal_flush_all_caches is invoked.
2437
 *
2438
 * @author W.Addink <waddink@eti.uva.nl>
2439
 *
2440
 * @return array
2441
 *   An array with custom cache tables to include.
2442
 */
2443
function cdm_api_flush_caches() {
2444
  return array('cache_cdm_ws');
2445
}
2446

    
2447
/**
2448
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2449
 *
2450
 * @param $data
2451
 *   The variable to log to the drupal_debug.txt log file.
2452
 * @param $label
2453
 *   (optional) If set, a label to output before $data in the log file.
2454
 *
2455
 * @return
2456
 *   No return value if successful, FALSE if the log file could not be written
2457
 *   to.
2458
 *
2459
 * @see cdm_dataportal_init() where the log file is reset on each requests
2460
 * @see dd()
2461
 * @see http://drupal.org/node/314112
2462
 *
2463
 */
2464
function cdm_dd($data, $label = NULL) {
2465
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2466
    return dd($data, $label);
2467
  }
2468
}
2469

    
(5-5/11)