Project

General

Profile

Download (77.7 KB) Statistics
| Branch: | Tag: | Revision:
1 6657531f Andreas Kohlbecker
<?php
2 54cfa718 Andreas Kohlbecker
  /**
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 6657531f Andreas Kohlbecker
24 54cfa718 Andreas Kohlbecker
  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 6657531f Andreas Kohlbecker
31 54cfa718 Andreas Kohlbecker
  /**
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 1042dbc0 Andreas Kohlbecker
40 7ca5ef1e Andreas Kohlbecker
41
42
/**
43
 * orderBy webservice query parameter value
44
 */
45 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_ID_ASC', 'BY_ID_ASC');
46 7ca5ef1e Andreas Kohlbecker
47
/**
48
 * orderBy webservice query parameter value
49
 */
50 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_ID_DESC', 'BY_ID_DESC');
51 7ca5ef1e Andreas Kohlbecker
/**
52
 * orderBy webservice query parameter value
53
 */
54 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'BY_TITLE_CACHE_ASC');
55 7ca5ef1e Andreas Kohlbecker
/**
56
 * orderBy webservice query parameter value
57
 */
58 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'BY_TITLE_CACHE_DESC');
59 7ca5ef1e Andreas Kohlbecker
/**
60
 * orderBy webservice query parameter value
61
 */
62 a33be830 Andreas Kohlbecker
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_ASC', 'BY_NOMENCLATURAL_ORDER_ASC');
63 7ca5ef1e Andreas Kohlbecker
/**
64
 * orderBy webservice query parameter value
65
 */
66 a33be830 Andreas Kohlbecker
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_DESC', 'BY_NOMENCLATURAL_ORDER_DESC');
67 7ca5ef1e Andreas Kohlbecker
/**
68
 * orderBy webservice query parameter value
69
 */
70
define('CDM_ORDER_BY_ORDER_INDEX_ASC', 'BY_ORDER_INDEX_ASC');
71
/**
72
 * orderBy webservice query parameter value
73
 */
74
define('CDM_ORDER_BY_ORDER_INDEX_DESC', 'BY_ORDER_INDEX_DESC');
75
76 fa782b11 Andreas Kohlbecker
77 6657531f Andreas Kohlbecker
/**
78
 * Implements hook_menu().
79
 */
80
function cdm_api_menu() {
81
  $items = array();
82
83
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
84
  $items['cdm_api/proxy'] = array(
85
    'page callback' => 'proxy_content',
86
    'access arguments' => array(
87
      'access content',
88
    ),
89
    'type' => MENU_CALLBACK,
90
  );
91
92
  $items['cdm_api/setvalue/session'] = array(
93
    'page callback' => 'setvalue_session',
94
    'access arguments' => array(
95
      'access content',
96
    ),
97
    'type' => MENU_CALLBACK,
98
  );
99
100
  return $items;
101
}
102
103 e2464cf8 Andreas Kohlbecker
/**
104
 * Implements hook_block_info().
105
 */
106
function cdm_api_block_info() {
107
108
  $block['cdm_ws_debug'] = array(
109
      "info" => t("CDM web service debug"),
110
      "cache" => DRUPAL_NO_CACHE
111
  );
112
  return $block;
113
}
114
115
/**
116
 * Implements hook_block_view().
117
 */
118
function cdm_api_block_view($delta) {
119
  switch ($delta) {
120
    case 'cdm_ws_debug':
121
122 6b5815cd Andreas Kohlbecker
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
123
124 e2464cf8 Andreas Kohlbecker
    $field_map = array(
125 6b5815cd Andreas Kohlbecker
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
126 e2464cf8 Andreas Kohlbecker
        'time' => t('Time'),
127
        'fetch_seconds' => t('Fetching [s]'),
128
        'parse_seconds' => t('Parsing [s]'),
129
        'size_kb' => t('Size [kb]'),
130
        'status' => t('Status'),
131
        'data_links' =>  t('Links'),
132
    );
133
134
135
    if (!isset($_SESSION['cdm']['ws_debug'])) {
136
      $_SESSION['cdm']['ws_debug'] = array();
137
    }
138
139
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
140
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
141
    $rows = array();
142
143
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
144 6b5815cd Andreas Kohlbecker
145 e2464cf8 Andreas Kohlbecker
      $data = unserialize($data);
146 6b5815cd Andreas Kohlbecker
147
      // stip of webservice base url
148
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
149 2ebf0428 Andreas Kohlbecker
      if($data['method'] == 'POST'){
150
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
151
      }
152 6b5815cd Andreas Kohlbecker
153
      $cells = array();
154 e2464cf8 Andreas Kohlbecker
      foreach ($field_map as $field => $label){
155
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
156
      }
157
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
158
    }
159
    // clear session again
160
    $_SESSION['cdm']['ws_debug'] = array();
161
162
    _add_js_ws_debug();
163
164 86b65fa0 Andreas Kohlbecker
    $block['subject'] = ''; // no subject, title in content for having a defined element id
165
    // otherwise it would depend on the theme
166 e2464cf8 Andreas Kohlbecker
    $block['content'] =
167 86b65fa0 Andreas Kohlbecker
        '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
168
          // cannot use theme_table() since table footer is not jet supported in D7
169
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
170 e2464cf8 Andreas Kohlbecker
        . $header
171
        . '<tbody>' . join('', $rows) . '</tbody>'
172
        . $footer
173 86b65fa0 Andreas Kohlbecker
        . '</table></div>';
174 e2464cf8 Andreas Kohlbecker
175
    return $block;
176
  }
177
}
178
179 6657531f Andreas Kohlbecker
/**
180
 * Implements hook_cron().
181
 *
182
 * Expire outdated cache entries.
183
 */
184
function cdm_api_cron() {
185
  cache_clear_all(NULL, 'cache_cdm_ws');
186
}
187
188
/**
189
 * @todo Please document this function.
190
 * @see http://drupal.org/node/1354
191
 */
192
function cdm_api_permission() {
193
  return array(
194
    'administer cdm_api' => array(
195
      'title' => t('administer cdm_api'),
196
      'description' => t("TODO Add a description for 'administer cdm_api'"),
197
    ),
198
  );
199
}
200
201 e90899ac Andreas Kohlbecker
// ===================== Tagged Text functions ================== //
202
203 6657531f Andreas Kohlbecker
/**
204
 * Converts an array of TaggedText items into corresponding html tags.
205
 *
206
 * Each item is provided with a class attribute which is set to the key of the
207
 * TaggedText item.
208
 *
209
 * @param array $taggedtxt
210
 *   Array with text items to convert.
211
 * @param string $tag
212
 *   Html tag name to convert the items into, default is 'span'.
213
 * @param string $glue
214
 *   The string by which the chained text tokens are concatenated together.
215
 *   Default is a blank character.
216
 *
217
 * @return string
218
 *   A string with HTML.
219
 */
220 e90899ac Andreas Kohlbecker
function cdm_tagged_text_to_markup(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
221 6657531f Andreas Kohlbecker
  $out = '';
222
  $i = 0;
223
  foreach ($taggedtxt as $tt) {
224
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
225
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '') . '<' . $tag . ' class="' . $tt->type . '">' . t($tt->text) . '</' . $tag . '>';
226
    }
227
  }
228
  return $out;
229
}
230
231 6aad9da8 Andreas Kohlbecker
232 6657531f Andreas Kohlbecker
/**
233
 * Finds the text tagged with $tag_type in an array of taggedText instances.
234
 *
235 e90899ac Andreas Kohlbecker
 * Note: This function is currently unused.
236 6657531f Andreas Kohlbecker
 *
237
 * @param array $taggedtxt
238
 *   Array with text items.
239
 * @param string $tag_type
240 6aad9da8 Andreas Kohlbecker
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
241
 *   to return all texts.
242 6657531f Andreas Kohlbecker
 *
243
 * @return array
244
 *   An array with the texts mapped by $tag_type.
245
 */
246 6aad9da8 Andreas Kohlbecker
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
247 6657531f Andreas Kohlbecker
  $tokens = array();
248
  if (!empty($taggedtxt)) {
249
    foreach ($taggedtxt as $tagtxt) {
250 6aad9da8 Andreas Kohlbecker
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
251 6657531f Andreas Kohlbecker
        $tokens[] = $tagtxt->text;
252
      }
253
    }
254
  }
255
  return $tokens;
256
}
257
258 e90899ac Andreas Kohlbecker
/**
259
 * Preprocess the taggedTitle arrays.
260
 *
261
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
262
 * into tag type "name"
263
 *
264
 * Step 2: Two taggedTexts which have the same type and which have
265
 * a separator between them are merged together.
266
 *
267
 * @param array $taggedTextList
268
 *    An array of TaggedText objects
269
 */
270
function normalize_tagged_text(&$taggedTextList) {
271
272
  if (is_array($taggedTextList)) {
273
274
    // First pass: rename.
275
    for ($i = 0; $i < count($taggedTextList); $i++) {
276
277
      if ($taggedTextList[$i]->type == "hybridSign") {
278
        $taggedTextList[$i]->type = "name";
279
      }
280
    }
281
282
    // Second pass: resolve separators.
283
    $taggedNameListNew = array();
284
    for ($i = 0; $i < count($taggedTextList); $i++) {
285
286
      // elements of the same type concatenated by a separator should be merged together
287
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
288
        $taggedName = clone $taggedTextList[$i];
289
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
290
        $taggedNameListNew[] = $taggedName;
291
        ++$i;
292
        ++$i;
293
        continue;
294
      }
295
      // no special handling
296
      $taggedNameListNew[] = $taggedTextList[$i];
297
298
    }
299
    $taggedTextList = $taggedNameListNew;
300
  }
301
}
302
303 1d0407b7 Andreas Kohlbecker
function split_secref_from_tagged_text(&$tagged_text) {
304
305
  $extracted_tt = array();
306
  if (is_array($tagged_text)) {
307
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
308
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
309
        $extracted_tt[0] = $tagged_text[$i];
310
        $extracted_tt[1] = $tagged_text[$i + 1];
311
        unset($tagged_text[$i]);
312
        unset($tagged_text[$i + 1]);
313
        break;
314 e90899ac Andreas Kohlbecker
      }
315
    }
316
  }
317 1d0407b7 Andreas Kohlbecker
  return $extracted_tt;
318 e90899ac Andreas Kohlbecker
}
319
320
321 1d0407b7 Andreas Kohlbecker
function split_nomstatus_from_tagged_text(&$tagged_text) {
322 e90899ac Andreas Kohlbecker
323 1d0407b7 Andreas Kohlbecker
  $extracted_tt = array();
324
  if (is_array($tagged_text)) {
325
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
326
      if ($tagged_text[$i]->type == "nomStatus"){
327
        $extracted_tt[] = $tagged_text[$i];
328
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
329
          $extracted_tt[] = $tagged_text[$i + 1];
330
          unset($tagged_text[$i + 1]);
331
        }
332
        if ($tagged_text[$i - 1]->type == "separator"){
333
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
334
          unset($tagged_text[$i - 1]);
335 e90899ac Andreas Kohlbecker
        }
336 1d0407b7 Andreas Kohlbecker
        unset($tagged_text[$i]);
337
        break;
338 e90899ac Andreas Kohlbecker
      }
339
    }
340
  }
341 1d0407b7 Andreas Kohlbecker
  return $extracted_tt;
342 e90899ac Andreas Kohlbecker
}
343
344
function find_tagged_text_elements($taggedTextList, $type){
345
  $matching_elements = array();
346
  if (is_array($taggedTextList)) {
347
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
348
      if($taggedTextList[$i]->type == $type){
349
        $matching_elements[] = $taggedTextList[$i];
350
      }
351
    }
352
  }
353
  return $matching_elements;
354
}
355
356
// ===================== END of Tagged Text functions ================== //
357
358 6657531f Andreas Kohlbecker
/**
359
 * Returns the currently classification tree in use.
360
 */
361 7663cd0b Andreas Kohlbecker
function get_current_classification_uuid() {
362 6657531f Andreas Kohlbecker
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
363
    return $_SESSION['cdm']['taxonomictree_uuid'];
364
  }
365
  else {
366
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
367
  }
368
}
369
370 61b6ee11 Andreas Kohlbecker
/**
371
 * Lists the classifications a taxon belongs to
372
 *
373
 * @param CDM type Taxon $taxon
374
 *   the taxon
375
 *
376
 * @return array
377
 *   aray of CDM instances of Type Classification
378
 */
379
function get_classifications_for_taxon($taxon) {
380
381
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
382
}
383
384 6657531f Andreas Kohlbecker
/**
385 bfb2b81a Andreas Kohlbecker
 * Returns the chosen FeatureTree for the taxon profile.
386 6657531f Andreas Kohlbecker
 *
387
 * The FeatureTree profile returned is the one that has been set in the
388
 * dataportal settings (layout->taxon:profile).
389
 * When the chosen FeatureTree is not found in the database,
390
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
391
 *
392
 * @return mixed
393 bfb2b81a Andreas Kohlbecker
 *   A cdm FeatureTree object.
394 6657531f Andreas Kohlbecker
 */
395 642b323b Andreas Kohlbecker
function get_profile_feature_tree() {
396 bfb2b81a Andreas Kohlbecker
  static $profile_featureTree;
397
398
  if($profile_featureTree == NULL) {
399 6657531f Andreas Kohlbecker
    $profile_featureTree = cdm_ws_get(
400
      CDM_WS_FEATURETREE,
401 bfb2b81a Andreas Kohlbecker
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
402 6657531f Andreas Kohlbecker
    );
403 bfb2b81a Andreas Kohlbecker
    if (!$profile_featureTree) {
404
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
405
    }
406 6657531f Andreas Kohlbecker
  }
407 092744e1 Andreas Kohlbecker
408 6657531f Andreas Kohlbecker
  return $profile_featureTree;
409
}
410
411 f19f47fa Andreas Kohlbecker
/**
412
 * Returns the chosen FeatureTree for SpecimenDescriptions.
413
 *
414
 * The FeatureTree returned is the one that has been set in the
415
 * dataportal settings (layout->taxon:specimen).
416
 * When the chosen FeatureTree is not found in the database,
417
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
418
 *
419
 * @return mixed
420
 *   A cdm FeatureTree object.
421 bfb2b81a Andreas Kohlbecker
 */
422 f19f47fa Andreas Kohlbecker
function cdm_get_occurrence_featureTree() {
423 bfb2b81a Andreas Kohlbecker
  static $occurrence_featureTree;
424
425
  if($occurrence_featureTree == NULL) {
426
    $occurrence_featureTree = cdm_ws_get(
427
      CDM_WS_FEATURETREE,
428
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
429
    );
430
    if (!$occurrence_featureTree) {
431
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
432
    }
433
  }
434 f19f47fa Andreas Kohlbecker
  return $occurrence_featureTree;
435 bfb2b81a Andreas Kohlbecker
}
436
437 f19f47fa Andreas Kohlbecker
/**
438
 * Returns the FeatureTree for structured descriptions
439
 *
440
 * The FeatureTree returned is the one that has been set in the
441
 * dataportal settings (layout->taxon:profile).
442
 * When the chosen FeatureTree is not found in the database,
443
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
444
 *
445
 * @return mixed
446
 *   A cdm FeatureTree object.
447
 */
448
function get_structured_description_featureTree() {
449
  static $structured_description_featureTree;
450
451 bfb2b81a Andreas Kohlbecker
  if($structured_description_featureTree == NULL) {
452 f19f47fa Andreas Kohlbecker
    $structured_description_featureTree = cdm_ws_get(
453
        CDM_WS_FEATURETREE,
454
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
455
    );
456
    if (!$structured_description_featureTree) {
457
      $structured_description_featureTree = cdm_ws_get(
458
          CDM_WS_FEATURETREE,
459
          UUID_DEFAULT_FEATURETREE
460
      );
461 bfb2b81a Andreas Kohlbecker
    }
462 f19f47fa Andreas Kohlbecker
  }
463
  return $structured_description_featureTree;
464 bfb2b81a Andreas Kohlbecker
}
465
466 6657531f Andreas Kohlbecker
/**
467
 * @todo Please document this function.
468
 * @see http://drupal.org/node/1354
469
 */
470
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
471
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
472
}
473
474
/**
475
 * @todo Please document this function.
476
 * @see http://drupal.org/node/1354
477
 */
478
function reset_taxonomictree_uuid($taxonomictree_uuid) {
479
  unset($_SESSION['cdm']['taxonomictree_uuid']);
480
}
481
482
/**
483
 * @todo Please document this function.
484
 * @see http://drupal.org/node/1354
485
 */
486
function set_last_taxon_page_tab($taxonPageTab) {
487
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
488
}
489
490
/**
491
 * @todo Please document this function.
492
 * @see http://drupal.org/node/1354
493
 */
494
function get_last_taxon_page_tab() {
495
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
496
    return $_SESSION['cdm']['taxon_page_tab'];
497
  }
498
  else {
499
    return FALSE;
500
  }
501
}
502
503
/**
504
 * @todo Improve the documentation of this function.
505
 *
506
 * media Array [4]
507
 * representations Array [3]
508
 * mimeType image/jpeg
509
 * representationParts Array [1]
510
 * duration 0
511
 * heigth 0
512
 * size 0
513
 * uri
514
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
515
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
516
 * width 0
517
 * suffix jpg
518
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
519
 * title
520
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
521
 *
522
 * @param object $media
523
 * @param array $mimeTypes
524
 * @param int $width
525
 * @param int $height
526
 *
527
 * @return array
528
 *   An array with preferred media representations or else an empty array.
529
 */
530
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
531
  $prefRepr = array();
532
  if (!isset($media->representations[0])) {
533
    return $prefRepr;
534
  }
535
536
  while (count($mimeTypes) > 0) {
537
    // getRepresentationByMimeType
538
    $mimeType = array_shift($mimeTypes);
539
540
    foreach ($media->representations as &$representation) {
541
      // If the mimetype is not known, try inferring it.
542
      if (!$representation->mimeType) {
543
        if (isset($representation->parts[0])) {
544
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
545
        }
546
      }
547
548
      if ($representation->mimeType == $mimeType) {
549
        // Preferred mimetype found -> erase all remaining mimetypes
550
        // to end loop.
551
        $mimeTypes = array();
552
        $dwa = 0;
553
        $dw = 0;
554
        // Look for part with the best matching size.
555
        foreach ($representation->parts as $part) {
556
          if (isset($part->width) && isset($part->height)) {
557
            $dw = $part->width * $part->height - $height * $width;
558
          }
559
          if ($dw < 0) {
560
            $dw *= -1;
561
          }
562
          $dwa += $dw;
563
        }
564
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
565
        $prefRepr[$dwa . '_'] = $representation;
566
      }
567
    }
568
  }
569
  // Sort the array.
570
  krsort($prefRepr);
571
  return $prefRepr;
572
}
573
574
/**
575
 * Infers the mime type of a file using the filename extension.
576
 *
577
 * The filename extension is used to infer the mime type.
578
 *
579
 * @param string $filepath
580
 *   The path to the respective file.
581
 *
582
 * @return string
583
 *   The mimetype for the file or FALSE if the according mime type could
584
 *   not be found.
585
 */
586
function infer_mime_type($filepath) {
587
  static $mimemap = NULL;
588
  if (!$mimemap) {
589
    $mimemap = array(
590
      'jpg' => 'image/jpeg',
591
      'jpeg' => 'image/jpeg',
592
      'png' => 'image/png',
593
      'gif' => 'image/gif',
594
      'giff' => 'image/gif',
595
      'tif' => 'image/tif',
596
      'tiff' => 'image/tif',
597
      'pdf' => 'application/pdf',
598
      'html' => 'text/html',
599
      'htm' => 'text/html',
600
    );
601
  }
602
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
603
  if (isset($mimemap[$extension])) {
604
    return $mimemap[$extension];
605
  }
606
  else {
607
    // FIXME remove this hack just return FALSE;
608
    return 'text/html';
609
  }
610
}
611
612
/**
613
 * Converts an ISO 8601 org.joda.time.Partial to a year.
614
 *
615
 * The function expects an ISO 8601 time representation of a
616
 * org.joda.time.Partial of the form yyyy-MM-dd.
617
 *
618
 * @param string $partial
619
 *   ISO 8601 time representation of a org.joda.time.Partial.
620
 *
621
 * @return string
622
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
623
 */
624
function partialToYear($partial) {
625
  if (is_string($partial)) {
626
    $year = substr($partial, 0, 4);
627
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
628
      return $year;
629
    }
630
  }
631
  return;
632
}
633
634
/**
635
 * Converts an ISO 8601 org.joda.time.Partial to a month.
636
 *
637
 * This function expects an ISO 8601 time representation of a
638
 * org.joda.time.Partial of the form yyyy-MM-dd.
639
 * In case the month is unknown (= ???) NULL is returned.
640
 *
641
 * @param string $partial
642
 *   ISO 8601 time representation of a org.joda.time.Partial.
643
 *
644
 * @return string
645
 *   A month.
646
 */
647
function partialToMonth($partial) {
648
  if (is_string($partial)) {
649
    $month = substr($partial, 5, 2);
650
    if (preg_match("/[0-9][0-9]/", $month)) {
651
      return $month;
652
    }
653
  }
654
  return;
655
}
656
657
/**
658
 * Converts an ISO 8601 org.joda.time.Partial to a day.
659
 *
660
 * This function expects an ISO 8601 time representation of a
661
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
662
 * In case the day is unknown (= ???) NULL is returned.
663
 *
664
 * @param string $partial
665
 *   ISO 8601 time representation of a org.joda.time.Partial.
666
 *
667
 * @return string
668
 *   A day.
669
 */
670
function partialToDay($partial) {
671
  if (is_string($partial)) {
672 7a93702a Andreas Kohlbecker
    $day = substr($partial, 8, 2);
673 6657531f Andreas Kohlbecker
    if (preg_match("/[0-9][0-9]/", $day)) {
674
      return $day;
675
    }
676
  }
677
  return;
678
}
679
680
/**
681
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
682
 *
683
 * This function expects an ISO 8601 time representations of a
684
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
685
 * four digit year, month and day with dashes:
686
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
687
 *
688
 * The partial may contain question marks eg: "1973-??-??",
689
 * these are turned in to '00' or are stripped depending of the $stripZeros
690
 * parameter.
691
 *
692
 * @param string $partial
693
 *   org.joda.time.Partial.
694
 * @param bool $stripZeros
695
 *   If set to TRUE the zero (00) month and days will be hidden:
696
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
697 fe2edf33 Andreas Kohlbecker
 * @param string @format
698
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
699
 *    - "YYYY": Year only
700
 *    - "YYYY-MM-DD": this is the default
701 6657531f Andreas Kohlbecker
 *
702
 * @return string
703
 *   YYYY-MM-DD formatted year, month, day.
704
 */
705 fe2edf33 Andreas Kohlbecker
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
706
707
  $y = NULL; $m = NULL; $d = NULL;
708
709 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'YY') !== FALSE){
710 fe2edf33 Andreas Kohlbecker
    $y = partialToYear($partial);
711
  }
712 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'MM') !== FALSE){
713 fe2edf33 Andreas Kohlbecker
    $m = partialToMonth($partial);
714
  }
715 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'DD') !== FALSE){
716 fe2edf33 Andreas Kohlbecker
    $d = partialToDay($partial);
717
  }
718 6657531f Andreas Kohlbecker
719
  $y = $y ? $y : '00';
720
  $m = $m ? $m : '00';
721
  $d = $d ? $d : '00';
722
723
  $date = '';
724
725
  if ($y == '00' && $stripZeros) {
726
    return;
727
  }
728
  else {
729
    $date = $y;
730
  }
731
732
  if ($m == '00' && $stripZeros) {
733
    return $date;
734
  }
735
  else {
736
    $date .= "-" . $m;
737
  }
738
739
  if ($d == '00' && $stripZeros) {
740
    return $date;
741
  }
742
  else {
743
    $date .= "-" . $d;
744
  }
745
  return $date;
746
}
747
748
/**
749
 * Converts a time period to a string.
750
 *
751
 * See also partialToDate($partial, $stripZeros).
752
 *
753
 * @param object $period
754
 *   An JodaTime org.joda.time.Period object.
755
 * @param bool $stripZeros
756
 *   If set to True, the zero (00) month and days will be hidden:
757
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
758 fe2edf33 Andreas Kohlbecker
 * @param string @format
759
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
760
 *    - "YYYY": Year only
761
 *    - "YYYY-MM-DD": this is the default
762 6657531f Andreas Kohlbecker
 *
763
 * @return string
764
 *   Returns a date in the form of a string.
765
 */
766 fe2edf33 Andreas Kohlbecker
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
767 6657531f Andreas Kohlbecker
  $dateString = '';
768 0a288588 Andreas Kohlbecker
  if($period->freeText){
769
    $dateString = $period->freeText;
770
  } else {
771
    if ($period->start) {
772
      $dateString = partialToDate($period->start, $stripZeros, $format);
773
    }
774
    if ($period->end) {
775
      $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
776
    }
777 6657531f Andreas Kohlbecker
  }
778
  return $dateString;
779
}
780 fe2edf33 Andreas Kohlbecker
781 c2486c6b Andreas Kohlbecker
/**
782
 * returns the earliest date available in the $period in a normalized
783
 * form suitable for sorting, e.g.:
784
 *
785
 *  - 1956-00-00
786
 *  - 0000-00-00
787
 *  - 1957-03-00
788
 *
789
 * that is either the start date is returned if set otherwise the
790
 * end date
791
 *
792
 * @param  $period
793
 *    An JodaTime org.joda.time.Period object.
794
 * @return string normalized form of the date
795
 *   suitable for sorting
796
 */
797
function timePeriodAsOrderKey($period) {
798
  $dateString = '';
799
  if ($period->start) {
800
    $dateString = partialToDate($period->start, false);
801
  }
802
  if ($period->end) {
803
    $dateString .= partialToDate($period->end, false);
804
  }
805
  return $dateString;
806
}
807 6657531f Andreas Kohlbecker
808
/**
809 42f2e1e0 Andreas Kohlbecker
 * Composes a absolute CDM web service URI with parameters and querystring.
810 6657531f Andreas Kohlbecker
 *
811
 * @param string $uri_pattern
812
 *   String with place holders ($0, $1, ..) that should be replaced by the
813
 *   according element of the $pathParameters array.
814
 * @param array $pathParameters
815
 *   An array of path elements, or a single element.
816
 * @param string $query
817
 *   A query string to append to the URL.
818
 *
819
 * @return string
820
 *   A complete URL with parameters to a CDM webservice.
821
 */
822
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
823
  if (empty($pathParameters)) {
824
    $pathParameters = array();
825
  }
826
827
  // (1)
828
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
829
  // according element of the $pathParameters array.
830
  static $helperArray = array();
831
  if (isset($pathParameters) && !is_array($pathParameters)) {
832
    $helperArray[0] = $pathParameters;
833
    $pathParameters = $helperArray;
834
  }
835
836
  $i = 0;
837
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
838
    if (count($pathParameters) <= $i) {
839 df7eab6b Andreas Kohlbecker
        drupal_set_message(t('cdm_compose_url(): missing pathParameter ' . $i .  ' for ' . $uri_pattern), 'error');
840 6657531f Andreas Kohlbecker
      break;
841
    }
842
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
843
    ++$i;
844
  }
845
846
  // (2)
847
  // Append all remaining element of the $pathParameters array as path
848
  // elements.
849
  if (count($pathParameters) > $i) {
850
    // Strip trailing slashes.
851
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
852
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
853
    }
854
    while (count($pathParameters) > $i) {
855
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
856
      ++$i;
857
    }
858
  }
859
860
  // (3)
861
  // Append the query string supplied by $query.
862
  if (isset($query)) {
863
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
864
  }
865
866
  $path = $uri_pattern;
867
868
  $uri = variable_get('cdm_webservice_url', '') . $path;
869
  return $uri;
870
}
871
872
/**
873 5ba85170 Andreas Kohlbecker
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
874
 *     together with a theme name to such a proxy function?
875
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
876
 *     Maybe we want to have two different proxy functions, one with theming and one without?
877 088448e1 Andreas Kohlbecker
 *
878
 * @param string $uri
879
 *     A URI to a CDM Rest service from which to retrieve an object
880 f1f05758 Andreas Kohlbecker
 * @param string|null $hook
881
 *     (optional) The hook name to which the retrieved object should be passed.
882
 *     Hooks can either be a theme_hook() or compose_hook() implementation
883
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
884 088448e1 Andreas Kohlbecker
 *     suitable for drupal_render()
885
 *
886 6657531f Andreas Kohlbecker
 * @todo Please document this function.
887
 * @see http://drupal.org/node/1354
888
 */
889 f1f05758 Andreas Kohlbecker
function proxy_content($uri, $hook = NULL) {
890 2ebf0428 Andreas Kohlbecker
891 6657531f Andreas Kohlbecker
  $args = func_get_args();
892 104dde69 Andreas Kohlbecker
  $do_gzip = function_exists('gzencode');
893 6657531f Andreas Kohlbecker
  $uriEncoded = array_shift($args);
894
  $uri = urldecode($uriEncoded);
895 f1f05758 Andreas Kohlbecker
  $hook = array_shift($args);
896 2ebf0428 Andreas Kohlbecker
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
897
898 68ab2885 Andreas Kohlbecker
  $post_data = null;
899
900 2ebf0428 Andreas Kohlbecker
  if ($request_method == "POST" || $request_method == "PUT") {
901
    // read response body via inputstream module
902
    $post_data = file_get_contents("php://input");
903
  }
904 6657531f Andreas Kohlbecker
905
  // Find and deserialize arrays.
906
  foreach ($args as &$arg) {
907
    // FIXME use regex to find serialized arrays.
908 2ebf0428 Andreas Kohlbecker
    //       or should we accept json instead of php serializations?
909 6657531f Andreas Kohlbecker
    if (strpos($arg, "a:") === 0) {
910
      $arg = unserialize($arg);
911
    }
912
  }
913
914 2ebf0428 Andreas Kohlbecker
  // In all these cases perform a simple get request.
915
  // TODO reconsider caching logic in this function.
916 6657531f Andreas Kohlbecker
917 2ebf0428 Andreas Kohlbecker
  if (empty($hook)) {
918
    // simply return the webservice response
919
    // Print out JSON, the cache cannot be used since it contains objects.
920
    $http_response = cdm_http_request($uri, $request_method, $post_data);
921
    if (isset($http_response->headers)) {
922
      foreach ($http_response->headers as $hname => $hvalue) {
923
        drupal_add_http_header($hname, $hvalue);
924 088448e1 Andreas Kohlbecker
      }
925 2ebf0428 Andreas Kohlbecker
    }
926
    if (isset($http_response->data)) {
927
      print $http_response->data;
928
      flush();
929
    }
930
    exit(); // leave drupal here
931
  } else {
932
    // $hook has been supplied
933
    // handle $hook either as compose ot theme hook
934
    // pass through theme or comose hook
935
936
    // do a security check since the $uri will be passed
937
    // as absolute URI to cdm_ws_get()
938
    if( !_is_cdm_ws_uri($uri)) {
939
      drupal_set_message(
940
      'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
941
      'error'
942
          );
943
          return '';
944
    }
945 088448e1 Andreas Kohlbecker
946 2ebf0428 Andreas Kohlbecker
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
947 2fe78f3c Andreas Kohlbecker
948 2ebf0428 Andreas Kohlbecker
    $reponse_data = NULL;
949 5b3d713e Andreas Kohlbecker
950 2ebf0428 Andreas Kohlbecker
    if (function_exists('compose_' . $hook)){
951
      // call compose hook
952
953
      $elements =  call_user_func('compose_' . $hook, $obj);
954
      // pass the render array to drupal_render()
955
      $reponse_data = drupal_render($elements);
956
    } else {
957
      // call theme hook
958
959
      // TODO use theme registry to get the registered hook info and
960
      //    use these defaults
961
      switch($hook) {
962
        case 'cdm_taxontree':
963
          $variables = array(
964 9c9d11f7 Andreas Kohlbecker
            'tree' => $obj,
965
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
966
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
967
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
968
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
969
            );
970 2ebf0428 Andreas Kohlbecker
          $reponse_data = theme($hook, $variables);
971
          break;
972
973 9c9d11f7 Andreas Kohlbecker
        case 'cdm_list_of_taxa':
974
            $variables = array(
975
              'records' => $obj,
976
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
977
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
978
            $reponse_data = theme($hook, $variables);
979
            break;
980
981 2ebf0428 Andreas Kohlbecker
        case 'cdm_media_caption':
982
          $variables = array(
983
          'media' => $obj,
984
          // $args[0] is set in taxon_image_gallery_default in
985
          // cdm_dataportal.page.theme.
986
          'elements' => isset($args[0]) ? $args[0] : array(
987
          'title',
988
          'description',
989
          'artist',
990
          'location',
991
          'rights',
992
          ),
993
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
994
          );
995
          $reponse_data = theme($hook, $variables);
996
          break;
997
998
        default:
999
          drupal_set_message(t(
1000 9c9d11f7 Andreas Kohlbecker
          'Theme !theme is not yet supported by the function !function.', array(
1001 2ebf0428 Andreas Kohlbecker
          '!theme' => $hook,
1002
          '!function' => __FUNCTION__,
1003
          )), 'error');
1004
          break;
1005
      } // END of theme hook switch
1006
    } // END of tread as theme hook
1007
1008
1009
    if($do_gzip){
1010
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1011
      drupal_add_http_header('Content-Encoding', 'gzip');
1012
    }
1013
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1014
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1015
1016
    print $reponse_data;
1017
  } // END of handle $hook either as compose ot theme hook
1018 5b3d713e Andreas Kohlbecker
1019 6657531f Andreas Kohlbecker
}
1020
1021
/**
1022
 * @todo Please document this function.
1023
 * @see http://drupal.org/node/1354
1024
 */
1025
function setvalue_session() {
1026
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1027
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1028
    $keys = explode('][', $keys);
1029
  }
1030
  else {
1031
    return;
1032
  }
1033 1d69a96c Andreas Kohlbecker
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1034 6657531f Andreas Kohlbecker
1035
  // Prevent from malicous tags.
1036
  $val = strip_tags($val);
1037
1038
  $var = &$_SESSION;
1039
  $i = 0;
1040
  foreach ($keys as $key) {
1041
    $hasMoreKeys = ++$i < count($var);
1042
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
1043
      $var[$key] = array();
1044
    }
1045
    $var = &$var[$key];
1046
  }
1047
  $var = $val;
1048
  if (isset($_REQUEST['destination'])) {
1049
    drupal_goto($_REQUEST['destination']);
1050
  }
1051
}
1052
1053
/**
1054
 * @todo Please document this function.
1055
 * @see http://drupal.org/node/1354
1056
 */
1057
function uri_uriByProxy($uri, $theme = FALSE) {
1058
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1059
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1060
}
1061
1062
/**
1063 42f2e1e0 Andreas Kohlbecker
 * Composes the the absolute REST service URI to the annotations pager
1064
 * for the given CDM entity.
1065
 *
1066
 * NOTE: Not all CDM Base types are yet supported.
1067
 *
1068
 * @param $cdmBase
1069
 *   The CDM entity to construct the annotations pager uri for
1070 6657531f Andreas Kohlbecker
 */
1071 42f2e1e0 Andreas Kohlbecker
function cdm_compose_annotations_uri($cdmBase) {
1072 6657531f Andreas Kohlbecker
  if (!$cdmBase->uuid) {
1073
    return;
1074
  }
1075
1076
  $ws_base_uri = NULL;
1077
  switch ($cdmBase->class) {
1078
    case 'TaxonBase':
1079
    case 'Taxon':
1080
    case 'Synonym':
1081
      $ws_base_uri = CDM_WS_TAXON;
1082
      break;
1083
1084
    case 'TaxonNameBase':
1085
    case 'NonViralName':
1086
    case 'BacterialName':
1087
    case 'BotanicalName':
1088
    case 'CultivarPlantName':
1089
    case 'ZoologicalName':
1090
    case 'ViralName':
1091
      $ws_base_uri = CDM_WS_NAME;
1092
      break;
1093
1094
    case 'Media':
1095
      $ws_base_uri = CDM_WS_MEDIA;
1096
      break;
1097
1098
    case 'Reference':
1099
      $ws_base_uri = CDM_WS_REFERENCE;
1100
      break;
1101
1102
    case 'Distribution':
1103
    case 'TextData':
1104
    case 'TaxonInteraction':
1105
    case 'QuantitativeData':
1106
    case 'IndividualsAssociation':
1107
    case 'Distribution':
1108
    case 'CommonTaxonName':
1109
    case 'CategoricalData':
1110
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1111
      break;
1112
1113
    case 'PolytomousKey':
1114
    case 'MediaKey':
1115
    case 'MultiAccessKey':
1116
      $ws_base_uri = $cdmBase->class;
1117
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1118
      break;
1119
1120
    default:
1121
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1122
      return;
1123
  }
1124
  return cdm_compose_url($ws_base_uri, array(
1125
    $cdmBase->uuid,
1126
    'annotations',
1127
  ));
1128
}
1129
1130
/**
1131
 * Enter description here...
1132
 *
1133
 * @param string $resourceURI
1134 b5dca1e2 Andreas Kohlbecker
 * @param int $pageSize
1135
 *   The maximum number of entities returned per page.
1136
 *   The default page size as configured in the cdm server
1137
 *   will be used if set to NULL
1138 6657531f Andreas Kohlbecker
 *   to return all entities in a single page).
1139
 * @param int $pageNumber
1140
 *   The number of the page to be returned, the first page has the
1141 b5dca1e2 Andreas Kohlbecker
 *   pageNumber = 0
1142 2ebf0428 Andreas Kohlbecker
 * @param array $query
1143
 *   A array holding the HTTP request query parameters for the request
1144
 * @param string $method
1145
 *   The HTTP method to use, valid values are "GET" or "POST"
1146 42f2e1e0 Andreas Kohlbecker
 * @param bool $absoluteURI
1147
 *   TRUE when the URL should be treated as absolute URL.
1148 2ebf0428 Andreas Kohlbecker
 *
1149 b5dca1e2 Andreas Kohlbecker
 * @return the a CDM Pager object
1150 6657531f Andreas Kohlbecker
 *
1151
 */
1152 2ebf0428 Andreas Kohlbecker
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1153
1154
  $query['pageNumber'] = $pageNumber;
1155
  $query['pageSize'] = $pageSize;
1156
1157
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1158 6657531f Andreas Kohlbecker
}
1159
1160 b5dca1e2 Andreas Kohlbecker
/**
1161
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1162
 *
1163
 * @param string $resourceURI
1164 2ebf0428 Andreas Kohlbecker
 * @param array $query
1165
 *   A array holding the HTTP request query parameters for the request
1166
 * @param string $method
1167
 *   The HTTP method to use, valid values are "GET" or "POST";
1168 42f2e1e0 Andreas Kohlbecker
 * @param bool $absoluteURI
1169
 *   TRUE when the URL should be treated as absolute URL.
1170 b5dca1e2 Andreas Kohlbecker
 *
1171
 * @return array
1172
 *     A list of CDM entitites
1173
 *
1174
 */
1175 2ebf0428 Andreas Kohlbecker
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1176 b5dca1e2 Andreas Kohlbecker
  $page_index = 0;
1177
  // using a bigger page size to avoid to many multiple requests
1178 f9da0eb9 Andreas Kohlbecker
  $page_size = 500;
1179 b5dca1e2 Andreas Kohlbecker
  $entities = array();
1180
1181
  while ($page_index !== FALSE){
1182 2ebf0428 Andreas Kohlbecker
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1183 b5dca1e2 Andreas Kohlbecker
    if(isset($pager->records) && is_array($pager->records)) {
1184
      $entities = $pager->records;
1185
      if(!empty($pager->nextIndex)){
1186
        $page_index = $pager->nextIndex;
1187
      } else {
1188
        $page_index = FALSE;
1189
      }
1190
    } else {
1191
      $page_index = FALSE;
1192
    }
1193
  }
1194
  return $entities;
1195
}
1196
1197 6657531f Andreas Kohlbecker
/*
1198
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1199
  $viewrank = _cdm_taxonomy_compose_viewrank();
1200
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1201
  ? '/' . $path : '') ;
1202
}
1203
*/
1204
1205
/**
1206
 * @todo Enter description here...
1207
 *
1208 50172c55 Andreas Kohlbecker
 * @param string $taxon_uuid
1209
 *  The UUID of a cdm taxon instance
1210
 * @param string $ignore_rank_limit
1211
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1212 6657531f Andreas Kohlbecker
 *
1213 50172c55 Andreas Kohlbecker
 * @return A cdm REST service URL path to a Classification
1214 6657531f Andreas Kohlbecker
 */
1215 50172c55 Andreas Kohlbecker
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1216
1217 7663cd0b Andreas Kohlbecker
  $view_uuid = get_current_classification_uuid();
1218 50172c55 Andreas Kohlbecker
  $rank_uuid = NULL;
1219
  if (!$ignore_rank_limit) {
1220
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1221
  }
1222 6657531f Andreas Kohlbecker
1223 50172c55 Andreas Kohlbecker
  if (!empty($taxon_uuid)) {
1224 6657531f Andreas Kohlbecker
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1225 50172c55 Andreas Kohlbecker
      $view_uuid,
1226
      $taxon_uuid,
1227 6657531f Andreas Kohlbecker
    ));
1228
  }
1229
  else {
1230 50172c55 Andreas Kohlbecker
    if (!empty($rank_uuid)) {
1231 6657531f Andreas Kohlbecker
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1232 50172c55 Andreas Kohlbecker
        $view_uuid,
1233
        $rank_uuid,
1234 6657531f Andreas Kohlbecker
      ));
1235
    }
1236
    else {
1237 50172c55 Andreas Kohlbecker
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1238
        $view_uuid,
1239 6657531f Andreas Kohlbecker
      ));
1240
    }
1241
  }
1242
}
1243
1244
/**
1245 50172c55 Andreas Kohlbecker
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1246
 *
1247
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1248
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1249
 *
1250
 * Operates in two modes depending on whether the parameter
1251
 * $taxon_uuid is set or NULL.
1252
 *
1253
 * A) $taxon_uuid = NULL:
1254
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1255
 *  2. otherwise return the default classification as defined by the admin via the settings
1256
 *
1257
 * b) $taxon_uuid is set:
1258
 *   return the classification to whcih the taxon belongs to.
1259
 *
1260
 * @param UUID $taxon_uuid
1261
 *   The UUID of a cdm taxon instance
1262 6657531f Andreas Kohlbecker
 */
1263 50172c55 Andreas Kohlbecker
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1264 6657531f Andreas Kohlbecker
1265 50172c55 Andreas Kohlbecker
    $response = NULL;
1266 6657531f Andreas Kohlbecker
1267 50172c55 Andreas Kohlbecker
    // 1st try
1268 2ebf0428 Andreas Kohlbecker
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1269 50172c55 Andreas Kohlbecker
1270
    if ($response == NULL) {
1271
      // 2dn try by ignoring the rank limit
1272 2ebf0428 Andreas Kohlbecker
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1273 6657531f Andreas Kohlbecker
    }
1274 50172c55 Andreas Kohlbecker
1275
    if ($response == NULL) {
1276
      // 3rd try, last fallback:
1277
      //    return the default classification
1278
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1279
        // Delete the session value and try again with the default.
1280
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1281 795fcdb3 Andreas Kohlbecker
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1282 50172c55 Andreas Kohlbecker
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1283
      }
1284
      else {
1285
        // Check if taxonomictree_uuid is valid.
1286 2ebf0428 Andreas Kohlbecker
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1287 50172c55 Andreas Kohlbecker
        if ($test == NULL) {
1288
          // The default set by the admin seems to be invalid or is not even set.
1289
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1290
        }
1291 6657531f Andreas Kohlbecker
      }
1292
    }
1293
1294
  return $response;
1295
}
1296
1297
/**
1298
 * @todo Enter description here...
1299
 *
1300 50172c55 Andreas Kohlbecker
 * @param string $taxon_uuid
1301 6657531f Andreas Kohlbecker
 *
1302 eb9fdcf7 Andreas Kohlbecker
 * @return array
1303 6657531f Andreas Kohlbecker
 */
1304 50172c55 Andreas Kohlbecker
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1305 7663cd0b Andreas Kohlbecker
  $view_uuid = get_current_classification_uuid();
1306 50172c55 Andreas Kohlbecker
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1307 6657531f Andreas Kohlbecker
1308
  $response = NULL;
1309 50172c55 Andreas Kohlbecker
  if ($rank_uuid) {
1310 6657531f Andreas Kohlbecker
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1311 50172c55 Andreas Kohlbecker
      $view_uuid,
1312
      $taxon_uuid,
1313
      $rank_uuid,
1314 6657531f Andreas Kohlbecker
    ));
1315
  }
1316
  else {
1317
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1318 50172c55 Andreas Kohlbecker
      $view_uuid,
1319
      $taxon_uuid,
1320 6657531f Andreas Kohlbecker
    ));
1321
  }
1322
1323
  if ($response == NULL) {
1324
    // Error handing.
1325
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1326
      // Delete the session value and try again with the default.
1327
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1328 50172c55 Andreas Kohlbecker
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1329 6657531f Andreas Kohlbecker
    }
1330
    else {
1331
      // Check if taxonomictree_uuid is valid.
1332 2ebf0428 Andreas Kohlbecker
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1333 6657531f Andreas Kohlbecker
      if ($test == NULL) {
1334
        // The default set by the admin seems to be invalid or is not even set.
1335
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1336
      }
1337
    }
1338
  }
1339
1340
  return $response;
1341
}
1342
1343 d8e85b2d Andreas Kohlbecker
1344
// =============================Terms and Vocabularies ========================================= //
1345 6657531f Andreas Kohlbecker
1346
/**
1347 0686f307 Andreas Kohlbecker
 * Returns the localized representation for the given term.
1348 6657531f Andreas Kohlbecker
 *
1349
 * @param Object $definedTermBase
1350
 * 	  of cdm type DefinedTermBase
1351
 * @return string
1352
 * 	  the localized representation_L10n of the term,
1353
 *    otherwise the titleCache as fall back,
1354 28c5c87a Andreas Kohlbecker
 *    otherwise the default_representation which defaults to an empty string
1355 6657531f Andreas Kohlbecker
 */
1356 28c5c87a Andreas Kohlbecker
function cdm_term_representation($definedTermBase, $default_representation = '') {
1357 6657531f Andreas Kohlbecker
  if ( isset($definedTermBase->representation_L10n) ) {
1358
    return $definedTermBase->representation_L10n;
1359
  } elseif ( isset($definedTermBase->titleCache)) {
1360
    return $definedTermBase->titleCache;
1361
  }
1362 28c5c87a Andreas Kohlbecker
  return $default_representation;
1363 6657531f Andreas Kohlbecker
}
1364
1365 0686f307 Andreas Kohlbecker
/**
1366
 * Returns the abbreviated localized representation for the given term.
1367
 *
1368
 * @param Object $definedTermBase
1369
 * 	  of cdm type DefinedTermBase
1370
 * @return string
1371
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1372
 *    if this representation is not available the function delegates the
1373
 *    call to cdm_term_representation()
1374
 */
1375
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1376
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1377
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1378
  } else {
1379
    cdm_term_representation($definedTermBase, $default_representation);
1380
  }
1381
}
1382
1383 d8e85b2d Andreas Kohlbecker
/**
1384
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1385
 *
1386
 * The options array is suitable for drupal form API elements that allow multiple choices.
1387
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1388
 *
1389
 * @param array $terms
1390
 *   a list of CDM DefinedTermBase instances
1391
 *
1392
 * @param $term_label_callback
1393
 *   A callback function to override the term representations
1394
 *
1395
 * @return array
1396
 *   the terms in an array as options for a form element that allows multiple choices.
1397
 */
1398 7ca5ef1e Andreas Kohlbecker
function cdm_terms_as_options($terms, $term_label_callback = NULL){
1399 d8e85b2d Andreas Kohlbecker
  $options = array();
1400 7ca5ef1e Andreas Kohlbecker
  if(isset($terms) && is_array($terms)) {
1401
    foreach ($terms as $term) {
1402 d8e85b2d Andreas Kohlbecker
      if ($term_label_callback && function_exists($term_label_callback)) {
1403
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1404
      } else {
1405
        //TODO use cdm_term_representation() here?
1406
        $options[$term->uuid] = t($term->representation_L10n);
1407
      }
1408
    }
1409
  }
1410
1411
  return $options;
1412
}
1413
1414
/**
1415 7ca5ef1e Andreas Kohlbecker
 * Creates and array of options for drupal select form elements.
1416
 *
1417
 * @param $vocabulary_uuid
1418
 *   The UUID of the CDM Term Vocabulary
1419
 * @param $term_label_callback
1420
 *   An optional call back function which can be used to modify the term label
1421
 * @param $default_option
1422
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1423
 *   In order to put an empty element the begining of the options pass an " " as argument.
1424
 * @param $order_by
1425
 *   One of the order by constants defined in this file
1426 d8e85b2d Andreas Kohlbecker
 */
1427 7ca5ef1e Andreas Kohlbecker
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $default_option = FALSE, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1428 d8e85b2d Andreas Kohlbecker
  static $vocabularyOptions = array();
1429
1430 7ca5ef1e Andreas Kohlbecker
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1431
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1432
      array(
1433
        'orderBy' => $order_by
1434
      )
1435
    );
1436
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1437 d8e85b2d Andreas Kohlbecker
  }
1438 f5bc56a0 Andreas Kohlbecker
1439 7ca5ef1e Andreas Kohlbecker
  $options = $vocabularyOptions[$vocabulary_uuid];
1440 f5bc56a0 Andreas Kohlbecker
  if($default_option !== FALSE){
1441
    array_unshift ($options, "");
1442
  }
1443
  return $options;
1444 d8e85b2d Andreas Kohlbecker
}
1445
1446
/**
1447
 * @param $term_type one of
1448
 *  - Unknown
1449
 *  - Language
1450
 *  - NamedArea
1451
 *  - Rank
1452
 *  - Feature
1453
 *  - AnnotationType
1454
 *  - MarkerType
1455
 *  - ExtensionType
1456
 *  - DerivationEventType
1457
 *  - PresenceAbsenceTerm
1458
 *  - NomenclaturalStatusType
1459
 *  - NameRelationshipType
1460
 *  - HybridRelationshipType
1461
 *  - SynonymRelationshipType
1462
 *  - TaxonRelationshipType
1463
 *  - NameTypeDesignationStatus
1464
 *  - SpecimenTypeDesignationStatus
1465
 *  - InstitutionType
1466
 *  - NamedAreaType
1467
 *  - NamedAreaLevel
1468
 *  - RightsType
1469
 *  - MeasurementUnit
1470
 *  - StatisticalMeasure
1471
 *  - MaterialOrMethod
1472
 *  - Material
1473
 *  - Method
1474
 *  - Modifier
1475
 *  - Scope
1476
 *  - Stage
1477
 *  - KindOfUnit
1478
 *  - Sex
1479
 *  - ReferenceSystem
1480
 *  - State
1481
 *  - NaturalLanguageTerm
1482
 *  - TextFormat
1483
 *  - DeterminationModifier
1484
 *  - DnaMarker
1485 7ca5ef1e Andreas Kohlbecker
 *
1486
 * @param  $order_by
1487
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1488
 *  possible values:
1489
 *    - CDM_ORDER_BY_ID_ASC
1490
 *    - CDM_ORDER_BY_ID_DESC
1491
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1492
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1493
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1494
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1495 d8e85b2d Andreas Kohlbecker
 */
1496 7ca5ef1e Andreas Kohlbecker
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL){
1497
  $terms = cdm_ws_fetch_all(
1498
    CDM_WS_TERM,
1499
    array(
1500
      'class' => $term_type,
1501
      'orderBy' => $order_by
1502
    )
1503
  );
1504
  return cdm_terms_as_options($terms, $term_label_callback);
1505 d8e85b2d Andreas Kohlbecker
}
1506
1507
/**
1508
 * @todo Please document this function.
1509
 * @see http://drupal.org/node/1354
1510
 */
1511
function cdm_rankVocabulary_as_option() {
1512 7ca5ef1e Andreas Kohlbecker
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, "");
1513 d8e85b2d Andreas Kohlbecker
  return $options;
1514
}
1515
1516
/**
1517
 * @todo Please document this function.
1518
 * @see http://drupal.org/node/1354
1519
 */
1520
function _cdm_relationship_type_term_label_callback($term) {
1521
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1522
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1523
  }
1524
else {
1525
    return t($term->representation_L10n);
1526
  }
1527
}
1528
1529
// ========================================================================================== //
1530 6657531f Andreas Kohlbecker
/**
1531
 * @todo Improve documentation of this function.
1532
 *
1533
 * eu.etaxonomy.cdm.model.description.
1534
 * CategoricalData
1535
 * CommonTaxonName
1536
 * Distribution
1537
 * IndividualsAssociation
1538
 * QuantitativeData
1539
 * TaxonInteraction
1540
 * TextData
1541
 */
1542
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1543
  static $types = array(
1544
    "CategoricalData",
1545
    "CommonTaxonName",
1546
    "Distribution",
1547
    "IndividualsAssociation",
1548
    "QuantitativeData",
1549
    "TaxonInteraction",
1550
    "TextData",
1551
  );
1552
1553
  static $options = NULL;
1554
  if ($options == NULL) {
1555
    $options = array();
1556
    if ($prependEmptyElement) {
1557
      $options[' '] = '';
1558
    }
1559
    foreach ($types as $type) {
1560
      // No internatianalization here since these are purely technical terms.
1561
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1562
    }
1563
  }
1564
  return $options;
1565
}
1566
1567
1568
/**
1569 8cbbc22a Andreas Kohlbecker
 * Fetches all TaxonDescription descriptions elements which are associated to the
1570
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1571 37252893 Andreas Kohlbecker
 * feature tree.
1572
 * @param $feature_tree
1573
 *     The CDM FeatureTree to be used as template
1574
 * @param $taxon_uuid
1575
 *     The UUID of the taxon
1576 092744e1 Andreas Kohlbecker
 * @param $excludes
1577
 *     UUIDs of features to be excluded
1578 37252893 Andreas Kohlbecker
 * @return$feature_tree
1579 8cbbc22a Andreas Kohlbecker
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1580
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1581
 *     witch will hold the according $descriptionElements.
1582 6657531f Andreas Kohlbecker
 */
1583 092744e1 Andreas Kohlbecker
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1584 37252893 Andreas Kohlbecker
1585
  if (!$feature_tree) {
1586 6657531f Andreas Kohlbecker
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1587
      In order to see the species profiles of your taxa, please select a
1588
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1589
    return FALSE;
1590
  }
1591
1592 092744e1 Andreas Kohlbecker
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1593 37252893 Andreas Kohlbecker
      array(
1594
      'taxon' => $taxon_uuid,
1595 092744e1 Andreas Kohlbecker
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1596 2ebf0428 Andreas Kohlbecker
      ),
1597
      'POST'
1598 37252893 Andreas Kohlbecker
  );
1599 6657531f Andreas Kohlbecker
1600 7508605c Andreas Kohlbecker
  // Combine all descriptions into one feature tree.
1601 092744e1 Andreas Kohlbecker
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1602 fae36a2a Andreas Kohlbecker
  $feature_tree->root->childNodes = $merged_nodes;
1603 6657531f Andreas Kohlbecker
1604 37252893 Andreas Kohlbecker
  return $feature_tree;
1605 6657531f Andreas Kohlbecker
}
1606
1607
/**
1608 4a15731a Andreas Kohlbecker
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1609
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1610
 * be requested for the annotations.
1611 6657531f Andreas Kohlbecker
 *
1612
 * @param string $cdmBase
1613
 *   An annotatable cdm entity.
1614
 * @param array $includeTypes
1615
 *   If an array of annotation type uuids is supplied by this parameter the
1616
 *   list of annotations is resticted to those which belong to this type.
1617
 *
1618
 * @return array
1619
 *   An array of Annotation objects or an empty array.
1620
 */
1621 4a15731a Andreas Kohlbecker
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1622
1623
  if(!isset($cdmBase->annotations)){
1624 42f2e1e0 Andreas Kohlbecker
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1625 75f01b13 Andreas Kohlbecker
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1626 6657531f Andreas Kohlbecker
  }
1627 4a15731a Andreas Kohlbecker
1628 b5dca1e2 Andreas Kohlbecker
  $annotations = array();
1629 4a15731a Andreas Kohlbecker
  foreach ($cdmBase->annotations as $annotation) {
1630
    if ($includeTypes) {
1631 d8e85b2d Andreas Kohlbecker
      if (
1632
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1633
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1634
      ) {
1635 4a15731a Andreas Kohlbecker
        $annotations[] = $annotation;
1636
      }
1637
    }
1638
    else {
1639
      $annotations[] = $annotation;
1640
    }
1641
  }
1642
  return $annotations;
1643
1644 6657531f Andreas Kohlbecker
}
1645
1646 eeb98da8 Andreas Kohlbecker
/**
1647
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1648
 *
1649
 * @param object $annotatable_entity
1650
 *   The CDM AnnotatableEntity to load annotations for
1651
 */
1652
function cdm_load_annotations(&$annotatable_entity) {
1653
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1654
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1655
    if (is_array($annotations)) {
1656
      $annotatable_entity->annotations = $annotations;
1657
    }
1658
  }
1659
}
1660
1661 6657531f Andreas Kohlbecker
/**
1662
 * Get a NomenclaturalReference string.
1663
 *
1664
 * Returns the NomenclaturalReference string with correctly placed
1665
 * microreference (= reference detail) e.g.
1666
 * in Phytotaxa 43: 1-48. 2012.
1667
 *
1668
 * @param string $referenceUuid
1669
 *   UUID of the reference.
1670
 * @param string $microreference
1671
 *   Reference detail.
1672
 *
1673
 * @return string
1674
 *   a NomenclaturalReference.
1675
 */
1676
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1677
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1678
    $referenceUuid,
1679
  ), "microReference=" . urlencode($microreference));
1680
1681
  if ($obj) {
1682
    return $obj->String;
1683
  }
1684
  else {
1685
    return NULL;
1686
  }
1687
}
1688
1689 092744e1 Andreas Kohlbecker
/**
1690
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1691
 *
1692
 * @param $feature_tree_nodes
1693
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1694
 * @param $feature_uuid
1695
 *    The UUID of the Feature
1696
 * @return returns the FeatureNode or null
1697
 */
1698
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1699
1700
  // 1. scan this level
1701
  foreach ($feature_tree_nodes as $node){
1702
    if($node->feature->uuid == $feature_uuid){
1703
      return $node;
1704
    }
1705
  }
1706
1707
  // 2. descend into childen
1708
  foreach ($feature_tree_nodes as $node){
1709
    if(is_array($node->childNodes)){
1710 4b4ae204 Andreas Kohlbecker
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1711 092744e1 Andreas Kohlbecker
      if($node) {
1712
        return $node;
1713
      }
1714
    }
1715
  }
1716 4b4ae204 Andreas Kohlbecker
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1717
  return $null_var;
1718 092744e1 Andreas Kohlbecker
}
1719
1720 6657531f Andreas Kohlbecker
/**
1721 bfb2b81a Andreas Kohlbecker
 * Merges the given featureNodes structure with the descriptionElements.
1722
 *
1723
 * This method is used in preparation for rendering the descriptionElements.
1724 28c5c87a Andreas Kohlbecker
 * The descriptionElements which belong to a specific feature node are appended
1725 fae36a2a Andreas Kohlbecker
 * to a the feature node by creating a new field:
1726 328005fd Andreas Kohlbecker
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1727
 * The descriptionElements will be cleared in advance in order to allow reusing the
1728 28c5c87a Andreas Kohlbecker
 * same feature tree without the risk of mixing sets of description elements.
1729 328005fd Andreas Kohlbecker
 *
1730 bfb2b81a Andreas Kohlbecker
 * which originally is not existing in the cdm.
1731
 *
1732 328005fd Andreas Kohlbecker
 *
1733
 *
1734 bfb2b81a Andreas Kohlbecker
 * @param array $featureNodes
1735 28c5c87a Andreas Kohlbecker
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1736 bfb2b81a Andreas Kohlbecker
 *    may have children.
1737
 * @param array $descriptionElements
1738
 *    An flat array of cdm DescriptionElements
1739
 * @return array
1740 28c5c87a Andreas Kohlbecker
 *    The $featureNodes structure enriched with the according $descriptionElements
1741 6657531f Andreas Kohlbecker
 */
1742
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1743 a67e7364 Andreas Kohlbecker
1744 6657531f Andreas Kohlbecker
  foreach ($featureNodes as &$node) {
1745 a67e7364 Andreas Kohlbecker
    // since the $featureNodes array is reused for each description
1746 28c5c87a Andreas Kohlbecker
    // it is necessary to clear the custom node fields in advance
1747 a67e7364 Andreas Kohlbecker
    if(isset($node->descriptionElements)){
1748
      unset($node->descriptionElements);
1749
    }
1750
1751 6657531f Andreas Kohlbecker
    // Append corresponding elements to an additional node field:
1752
    // $node->descriptionElements.
1753
    foreach ($descriptionElements as $element) {
1754
      if ($element->feature->uuid == $node->feature->uuid) {
1755
        if (!isset($node->descriptionElements)) {
1756
          $node->descriptionElements = array();
1757
        }
1758
        $node->descriptionElements[] = $element;
1759
      }
1760
    }
1761
1762
    // Recurse into node children.
1763 fae36a2a Andreas Kohlbecker
    if (isset($node->childNodes[0])) {
1764
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1765
      $node->childNodes = $mergedChildNodes;
1766 6657531f Andreas Kohlbecker
    }
1767 a67e7364 Andreas Kohlbecker
1768 fae36a2a Andreas Kohlbecker
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1769 328005fd Andreas Kohlbecker
      unset($node);
1770
    }
1771
1772 6657531f Andreas Kohlbecker
  }
1773 a67e7364 Andreas Kohlbecker
1774 6657531f Andreas Kohlbecker
  return $featureNodes;
1775
}
1776
1777
/**
1778 84fdac2a Andreas Kohlbecker
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1779 6657531f Andreas Kohlbecker
 *
1780
 * The response from the HTTP GET request is returned as object.
1781
 * The response objects coming from the webservice configured in the
1782 84fdac2a Andreas Kohlbecker
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1783 6657531f Andreas Kohlbecker
 *  in a level 2 (L2) cache.
1784
 *
1785
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1786
 * function, this cache persists only per each single page execution.
1787
 * Any object coming from the webservice is stored into it by default.
1788
 * In contrast to this default caching mechanism the L2 cache only is used if
1789
 * the 'cdm_webservice_cache' variable is set to TRUE,
1790
 * which can be set using the modules administrative settings section.
1791
 * Objects stored in this L2 cache are serialized and stored
1792
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1793
 * objects that are stored in the database will persist as
1794 84fdac2a Andreas Kohlbecker
 * long as the drupal cache is not being cleared and are available across
1795 6657531f Andreas Kohlbecker
 * multiple script executions.
1796
 *
1797
 * @param string $uri
1798
 *   URL to the webservice.
1799
 * @param array $pathParameters
1800
 *   An array of path parameters.
1801
 * @param string $query
1802
 *   A query string to be appended to the URL.
1803
 * @param string $method
1804
 *   The HTTP method to use, valid values are "GET" or "POST";
1805
 * @param bool $absoluteURI
1806
 *   TRUE when the URL should be treated as absolute URL.
1807
 *
1808 4d3c2389 Andreas Kohlbecker
 * @return object| array
1809 84fdac2a Andreas Kohlbecker
 *   The de-serialized webservice response object.
1810 6657531f Andreas Kohlbecker
 */
1811
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1812 d071bed7 Andreas Kohlbecker
1813 6657531f Andreas Kohlbecker
  static $cacheL1 = array();
1814
1815 2ebf0428 Andreas Kohlbecker
  $data = NULL;
1816
  // store query string in $data and clear the query, $data will be set as HTTP request body
1817
  if($method == 'POST'){
1818
    $data = $query;
1819
    $query = NULL;
1820
  }
1821
1822 088448e1 Andreas Kohlbecker
  // Transform the given uri path or pattern into a proper webservice uri.
1823 6657531f Andreas Kohlbecker
  if (!$absoluteURI) {
1824
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1825
  }
1826
1827 72032ea6 Andreas Kohlbecker
  // read request parameter 'cacheL2_refresh'
1828 84fdac2a Andreas Kohlbecker
  // which allows refreshing the level 2 cache
1829 72032ea6 Andreas Kohlbecker
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1830
1831 6657531f Andreas Kohlbecker
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1832
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1833
1834 2ebf0428 Andreas Kohlbecker
  if($method == 'GET'){
1835
    $cache_key = $uri;
1836
  } else {
1837
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1838
    // crc32 is faster but creates much shorter hashes
1839
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1840
  }
1841
1842
  if (array_key_exists($cache_key, $cacheL1)) {
1843 6657531f Andreas Kohlbecker
    $cacheL1_obj = $cacheL1[$uri];
1844
  }
1845
1846
  $set_cacheL1 = FALSE;
1847
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1848
    $set_cacheL1 = TRUE;
1849
  }
1850
1851
  // Only cache cdm webservice URIs.
1852
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1853
  $cacheL2_entry = FALSE;
1854
1855 72032ea6 Andreas Kohlbecker
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1856 6657531f Andreas Kohlbecker
    // Try to get object from cacheL2.
1857 2ebf0428 Andreas Kohlbecker
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1858 6657531f Andreas Kohlbecker
  }
1859
1860
  if (isset($cacheL1_obj)) {
1861
    //
1862
    // The object has been found in the L1 cache.
1863
    //
1864
    $obj = $cacheL1_obj;
1865 a4f964ee Andreas Kohlbecker
    if (cdm_debug_block_visible()) {
1866 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1867 6657531f Andreas Kohlbecker
    }
1868
  }
1869
  elseif ($cacheL2_entry) {
1870
    //
1871
    // The object has been found in the L2 cache.
1872
    //
1873 e2464cf8 Andreas Kohlbecker
    $duration_parse_start = microtime(TRUE);
1874 6657531f Andreas Kohlbecker
    $obj = unserialize($cacheL2_entry->data);
1875 e2464cf8 Andreas Kohlbecker
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1876 6657531f Andreas Kohlbecker
1877 a4f964ee Andreas Kohlbecker
    if (cdm_debug_block_visible()) {
1878 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1879 6657531f Andreas Kohlbecker
    }
1880
  }
1881
  else {
1882
    //
1883
    // Get the object from the webservice and cache it.
1884
    //
1885 e2464cf8 Andreas Kohlbecker
    $duration_fetch_start = microtime(TRUE);
1886 6657531f Andreas Kohlbecker
    // Request data from webservice JSON or XML.
1887 2ebf0428 Andreas Kohlbecker
    $response = cdm_http_request($uri, $method, $data);
1888
    $response_body = NULL;
1889 2fe78f3c Andreas Kohlbecker
    if (isset($response->data)) {
1890 2ebf0428 Andreas Kohlbecker
      $response_body = $response->data;
1891 2fe78f3c Andreas Kohlbecker
    }
1892 e2464cf8 Andreas Kohlbecker
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1893
    $duration_parse_start = microtime(TRUE);
1894 6657531f Andreas Kohlbecker
1895
    // Parse data and create object.
1896 2ebf0428 Andreas Kohlbecker
    $obj = cdm_load_obj($response_body);
1897 6657531f Andreas Kohlbecker
1898 e2464cf8 Andreas Kohlbecker
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1899 a4f964ee Andreas Kohlbecker
1900
    if (cdm_debug_block_visible()) {
1901 2ebf0428 Andreas Kohlbecker
      if ($obj || $response_body == "[]") {
1902 e2464cf8 Andreas Kohlbecker
        $status = 'valid';
1903 6657531f Andreas Kohlbecker
      }
1904
      else {
1905 e2464cf8 Andreas Kohlbecker
        $status = 'invalid';
1906 6657531f Andreas Kohlbecker
      }
1907 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1908 6657531f Andreas Kohlbecker
    }
1909
    if ($set_cacheL2) {
1910
      // Store the object in cache L2.
1911 2ebf0428 Andreas Kohlbecker
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1912 6657531f Andreas Kohlbecker
      // flag serialized is set properly in the cache table.
1913 2ebf0428 Andreas Kohlbecker
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1914 6657531f Andreas Kohlbecker
    }
1915
  }
1916
  if ($obj) {
1917
    // Store the object in cache L1.
1918
    if ($set_cacheL1) {
1919 2ebf0428 Andreas Kohlbecker
      $cacheL1[$cache_key] = $obj;
1920 6657531f Andreas Kohlbecker
    }
1921
  }
1922
  return $obj;
1923
}
1924
1925
/**
1926 e2464cf8 Andreas Kohlbecker
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1927
 *
1928
 * The cdm_ws_debug block will display the debug information.
1929
 *
1930
 * @param $uri
1931
 *    The CDM REST URI to which the request has been send
1932 2ebf0428 Andreas Kohlbecker
 * @param string $method
1933
 *    The HTTP request method, either 'GET' or 'POST'
1934
 * @param string $post_data
1935
 *    The datastring send with a post request
1936 e2464cf8 Andreas Kohlbecker
 * @param $duration_fetch
1937
 *    The time in seconds it took to fetch the data from the web service
1938
 * @param $duration_parse
1939
 *    Time in seconds which was needed to parse the json response
1940
 * @param $datasize
1941
 *    Size of the data received from the server
1942
 * @param $status
1943
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1944
 * @return bool
1945
 *    TRUE if adding the debug information was successful
1946 6657531f Andreas Kohlbecker
 */
1947 2ebf0428 Andreas Kohlbecker
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1948 6657531f Andreas Kohlbecker
1949 e2464cf8 Andreas Kohlbecker
  static $initial_time = NULL;
1950
  if(!$initial_time) {
1951
    $initial_time = microtime(TRUE);
1952
  }
1953
  $time = microtime(TRUE) - $initial_time;
1954 6657531f Andreas Kohlbecker
1955
  // Decompose uri into path and query element.
1956
  $uri_parts = explode("?", $uri);
1957 98038f4c w.addink
  $query = array();
1958 6657531f Andreas Kohlbecker
  if (count($uri_parts) == 2) {
1959
    $path = $uri_parts[0];
1960
  }
1961
  else {
1962
    $path = $uri;
1963
  }
1964
1965 c1bcfc1b Andreas Kohlbecker
  if(strpos($uri, '?') > 0){
1966
    $json_uri = str_replace('?', '.json?', $uri);
1967
    $xml_uri = str_replace('?', '.xml?', $uri);
1968
  } else {
1969
    $json_uri = $uri . '.json';
1970
    $xml_uri = $json_uri . '.xml';
1971
  }
1972
1973 e2464cf8 Andreas Kohlbecker
  // data links to make data accecsible as json and xml
1974
  $data_links = '';
1975 6657531f Andreas Kohlbecker
  if (_is_cdm_ws_uri($path)) {
1976 2ebf0428 Andreas Kohlbecker
1977
    // see ./js/http-method-link.js
1978
1979
    if($method == 'GET'){
1980
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1981
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1982
      $data_links .= '<br/>';
1983
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1984
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1985
    } else {
1986
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1987
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1988
      $data_links .= '<br/>';
1989
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1990
    }
1991 6657531f Andreas Kohlbecker
  }
1992
  else {
1993 c1bcfc1b Andreas Kohlbecker
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1994 e2464cf8 Andreas Kohlbecker
  }
1995
1996
  //
1997
  $data = array(
1998
      'ws_uri' => $uri,
1999 2ebf0428 Andreas Kohlbecker
      'method' => $method,
2000
      'post_data' => $post_data,
2001 e2464cf8 Andreas Kohlbecker
      'time' => sprintf('%3.3f', $time),
2002
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2003
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2004
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2005
      'status' => $status,
2006
      'data_links' => $data_links
2007
  );
2008
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2009
    $_SESSION['cdm']['ws_debug'] = array();
2010 6657531f Andreas Kohlbecker
  }
2011 e2464cf8 Andreas Kohlbecker
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2012
2013
  // Mark this page as being uncacheable.
2014
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2015
  drupal_page_is_cacheable(FALSE);
2016
2017
  // Messages not set when DB connection fails.
2018
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2019 6657531f Andreas Kohlbecker
}
2020
2021 a4f964ee Andreas Kohlbecker
/**
2022
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2023
 * the visibility depends on whether
2024
 *  - the block is enabled
2025
 *  - the visibility restrictions in the block settings are satisfied
2026
 */
2027
function cdm_debug_block_visible() {
2028
  static $is_visible = null;
2029
2030
  if($is_visible === null){
2031
      $block = block_load('cdm_api', 'cdm_ws_debug');
2032 af932304 Andreas Kohlbecker
      $is_visible = isset($block->status) && $block->status == 1;
2033 a4f964ee Andreas Kohlbecker
      if($is_visible){
2034
        $blocks = array($block);
2035
        // Checks the page, user role, and user-specific visibilty settings.
2036
        block_block_list_alter($blocks);
2037
        $is_visible = count($blocks) > 0;
2038
      }
2039
  }
2040
  return $is_visible;
2041
}
2042
2043 6657531f Andreas Kohlbecker
/**
2044
 * @todo Please document this function.
2045
 * @see http://drupal.org/node/1354
2046
 */
2047 2ebf0428 Andreas Kohlbecker
function cdm_load_obj($response_body) {
2048
  $obj = json_decode($response_body);
2049 6657531f Andreas Kohlbecker
2050
  if (!(is_object($obj) || is_array($obj))) {
2051
    ob_start();
2052
    $obj_dump = ob_get_contents();
2053
    ob_clean();
2054
    return FALSE;
2055
  }
2056
2057
  return $obj;
2058
}
2059
2060
/**
2061 2fe78f3c Andreas Kohlbecker
 * Do a http request to a CDM RESTful web service.
2062 6657531f Andreas Kohlbecker
 *
2063
 * @param string $uri
2064
 *   The webservice url.
2065
 * @param string $method
2066
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2067
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2068 2ebf0428 Andreas Kohlbecker
 * @param $data: A string containing the request body, formatted as
2069
 *     'param=value&param=value&...'. Defaults to NULL.
2070 6657531f Andreas Kohlbecker
 *
2071 2fe78f3c Andreas Kohlbecker
 * @return object
2072
 *   The object as returned by drupal_http_request():
2073
 *   An object that can have one or more of the following components:
2074
 *   - request: A string containing the request body that was sent.
2075
 *   - code: An integer containing the response status code, or the error code
2076
 *     if an error occurred.
2077
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2078
 *   - status_message: The status message from the response, if a response was
2079
 *     received.
2080
 *   - redirect_code: If redirected, an integer containing the initial response
2081
 *     status code.
2082
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2083
 *     target.
2084
 *   - error: If an error occurred, the error message. Otherwise not set.
2085
 *   - headers: An array containing the response headers as name/value pairs.
2086
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2087
 *     easy access the array keys are returned in lower case.
2088
 *   - data: A string containing the response body that was received.
2089 6657531f Andreas Kohlbecker
 */
2090 2ebf0428 Andreas Kohlbecker
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2091 6657531f Andreas Kohlbecker
  static $acceptLanguage = NULL;
2092 0b606c0d Andreas Kohlbecker
  $header = array();
2093 af0cde1a Andreas Kohlbecker
  
2094
  if(!$acceptLanguage && module_exists('i18n')){
2095
    $acceptLanguage = i18n_language_content()->language;
2096
  }
2097 6657531f Andreas Kohlbecker
2098
  if (!$acceptLanguage) {
2099
    if (function_exists('apache_request_headers')) {
2100
      $headers = apache_request_headers();
2101
      if (isset($headers['Accept-Language'])) {
2102
        $acceptLanguage = $headers['Accept-Language'];
2103
      }
2104
    }
2105
  }
2106
2107
  if ($method != "GET" && $method != "POST") {
2108 2ebf0428 Andreas Kohlbecker
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2109 6657531f Andreas Kohlbecker
  }
2110
2111 0b606c0d Andreas Kohlbecker
  if (_is_cdm_ws_uri($uri)) {
2112 3db2866c Andreas Kohlbecker
    $header['Accept'] = 'application/json';
2113 6657531f Andreas Kohlbecker
    $header['Accept-Language'] = $acceptLanguage;
2114
    $header['Accept-Charset'] = 'UTF-8';
2115
  }
2116
2117 2ebf0428 Andreas Kohlbecker
  if($method == "POST") {
2118
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2119
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2120
  }
2121
2122 2dd59bb5 Andreas Kohlbecker
2123
  cdm_dd($uri);
2124 2fe78f3c Andreas Kohlbecker
  return drupal_http_request($uri, array(
2125
      'headers' => $header,
2126
      'method' => $method,
2127 2ebf0428 Andreas Kohlbecker
      'data' => $data,
2128 2fe78f3c Andreas Kohlbecker
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2129
      )
2130
   );
2131 6657531f Andreas Kohlbecker
}
2132
2133
/**
2134 37252893 Andreas Kohlbecker
 * Concatenates recursively the fields of all features contained in the given
2135
 * CDM FeatureTree root node.
2136
 *
2137
 * @param $rootNode
2138
 *     A CDM FeatureTree node
2139
 * @param
2140
 *     The character to be used as glue for concatenation, default is ', '
2141
 * @param $field_name
2142
 *     The field name of the CDM Features
2143 092744e1 Andreas Kohlbecker
 * @param $excludes
2144
 *     Allows defining a set of values to be excluded. This refers to the values
2145
 *     in the field denoted by the $field_name parameter
2146
 *
2147 6657531f Andreas Kohlbecker
 */
2148 092744e1 Andreas Kohlbecker
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2149 6657531f Andreas Kohlbecker
  $out = '';
2150
2151 37252893 Andreas Kohlbecker
  $pre_child_separator = $separator;
2152
  $post_child_separator = '';
2153
2154 fae36a2a Andreas Kohlbecker
  foreach ($root_node->childNodes as $feature_node) {
2155 6657531f Andreas Kohlbecker
    $out .= ($out ? $separator : '');
2156 092744e1 Andreas Kohlbecker
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2157
      $out .= $feature_node->feature->$field_name;
2158
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2159
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2160
        if (strlen($childlabels)) {
2161
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2162
        }
2163 6657531f Andreas Kohlbecker
      }
2164
    }
2165
  }
2166
  return $out;
2167
}
2168
2169
/**
2170
 * Create a one-dimensional form options array.
2171
 *
2172
 * Creates an array of all features in the feature tree of feature nodes,
2173
 * the node labels are indented by $node_char and $childIndent depending on the
2174
 * hierachy level.
2175
 *
2176
 * @param - $rootNode
2177
 * @param - $node_char
2178
 * @param - $childIndentStr
2179
 * @param - $childIndent
2180
 *   ONLY USED INTERNALLY!
2181
 *
2182
 * @return array
2183
 *   A one dimensional Drupal form options array.
2184
 */
2185
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2186
  $options = array();
2187 fae36a2a Andreas Kohlbecker
  foreach ($rootNode->childNodes as $featureNode) {
2188 6657531f Andreas Kohlbecker
    $indent_prefix = '';
2189
    if ($childIndent) {
2190
      $indent_prefix = $childIndent . $node_char . " ";
2191
    }
2192
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2193 fae36a2a Andreas Kohlbecker
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2194
      // Foreach ($featureNode->childNodes as $childNode){
2195 6657531f Andreas Kohlbecker
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2196
      $options = array_merge_recursive($options, $childList);
2197
      // }
2198
    }
2199
  }
2200
  return $options;
2201
}
2202
2203
/**
2204 72294996 Andreas Kohlbecker
 * Returns an array with all available FeatureTrees and the representations of the selected
2205
 * FeatureTree as a detail view.
2206
 *
2207 cdafd99f Alexander Oppermann
 * @param boolean $add_default_feature_free
2208 72294996 Andreas Kohlbecker
 * @return array
2209 cdafd99f Alexander Oppermann
 *  associative array with following keys:
2210
 *  -options: Returns an array with all available Feature Trees
2211
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2212 72294996 Andreas Kohlbecker
 *
2213 6657531f Andreas Kohlbecker
 */
2214 6188d24e Andreas Kohlbecker
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2215 3f485c6d Andreas Kohlbecker
2216
  $options = array();
2217
  $tree_representations = array();
2218 6657531f Andreas Kohlbecker
  $feature_trees = array();
2219
2220
  // Set tree that contains all features.
2221 6188d24e Andreas Kohlbecker
  if ($add_default_feature_free) {
2222 3f485c6d Andreas Kohlbecker
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2223
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2224
  }
2225
2226
  // Get feature trees from database.
2227 42f2e1e0 Andreas Kohlbecker
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2228 3f485c6d Andreas Kohlbecker
  if (is_array($persited_trees)) {
2229
    $feature_trees = array_merge($feature_trees, $persited_trees);
2230 6657531f Andreas Kohlbecker
  }
2231
2232 3f485c6d Andreas Kohlbecker
  foreach ($feature_trees as $featureTree) {
2233 6657531f Andreas Kohlbecker
2234 8c962983 Andreas Kohlbecker
    if(!is_object($featureTree)){
2235
      continue;
2236
    }
2237 3f485c6d Andreas Kohlbecker
    // Do not add the DEFAULT_FEATURETREE again,
2238
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2239 1717116c Andreas Kohlbecker
      $options[$featureTree->uuid] = $featureTree->titleCache;
2240 3f485c6d Andreas Kohlbecker
    }
2241
2242
    // Render the hierarchic tree structure
2243 fae36a2a Andreas Kohlbecker
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2244 3f485c6d Andreas Kohlbecker
2245
      // Render the hierarchic tree structure.
2246
      $treeDetails = '<div class="featuretree_structure">'
2247
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2248
        . '</div>';
2249
2250
      $form = array();
2251
      $form['featureTree-' .  $featureTree->uuid] = array(
2252
        '#type' => 'fieldset',
2253
        '#title' => 'Show details',
2254
        '#attributes' => array('class' => array('collapsible collapsed')),
2255
        // '#collapsible' => TRUE,
2256
        // '#collapsed' => TRUE,
2257
      );
2258
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2259
        '#markup' => $treeDetails,
2260
      );
2261
2262
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2263 6657531f Andreas Kohlbecker
    }
2264 8734e506 Alexander Oppermann
2265 3f485c6d Andreas Kohlbecker
  } // END loop over feature trees
2266 6657531f Andreas Kohlbecker
2267 3f485c6d Andreas Kohlbecker
  // return $options;
2268
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2269 6657531f Andreas Kohlbecker
}
2270
2271
/**
2272 de8b5b32 Andreas Kohlbecker
 * Provides the list of availbale classifications in form of an options array.
2273
 *
2274
 * The options array is suitable for drupal form API elements that allow multiple choices.
2275
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2276
 *
2277
 * The classifications are ordered alphabetically whereas the classification
2278
 * chosen as default will always appear on top of the array, followed by a
2279
 * blank line below.
2280
 *
2281 61b6ee11 Andreas Kohlbecker
 * @param bool $add_none_option
2282 1717116c Andreas Kohlbecker
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2283 61b6ee11 Andreas Kohlbecker
 *
2284 de8b5b32 Andreas Kohlbecker
 * @return array
2285
 *   classifications in an array as options for a form element that allows multiple choices.
2286 6657531f Andreas Kohlbecker
 */
2287 61b6ee11 Andreas Kohlbecker
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2288
2289 a488aeb6 Andreas Kohlbecker
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2290 de8b5b32 Andreas Kohlbecker
2291
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2292
  $default_classification_label = '';
2293
2294
  // add all classifications
2295 6188d24e Andreas Kohlbecker
  $taxonomic_tree_options = array();
2296 61b6ee11 Andreas Kohlbecker
  if ($add_none_option) {
2297
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2298
  }
2299 6657531f Andreas Kohlbecker
  if ($taxonTrees) {
2300
    foreach ($taxonTrees as $tree) {
2301 de8b5b32 Andreas Kohlbecker
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2302
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2303
      } else {
2304 61b6ee11 Andreas Kohlbecker
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2305 de8b5b32 Andreas Kohlbecker
        $default_classification_label = $tree->titleCache;
2306
      }
2307 6657531f Andreas Kohlbecker
    }
2308
  }
2309 61b6ee11 Andreas Kohlbecker
  // oder alphabetically the space
2310 de8b5b32 Andreas Kohlbecker
  asort($taxonomic_tree_options);
2311
2312 61b6ee11 Andreas Kohlbecker
  // now set the labels
2313
  //   for none
2314 f19f47fa Andreas Kohlbecker
  if ($add_none_option) {
2315 8ae3cfe3 Andreas Kohlbecker
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2316 61b6ee11 Andreas Kohlbecker
  }
2317
2318
  //   for default_classification
2319 805795b6 Andreas Kohlbecker
  if (is_uuid($default_classification_uuid)) {
2320 d88a1df7 Andreas Kohlbecker
    $taxonomic_tree_options[$default_classification_uuid] =
2321
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2322 6b1e5ae3 Andreas Kohlbecker
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2323 de8b5b32 Andreas Kohlbecker
  }
2324
2325 6188d24e Andreas Kohlbecker
  return $taxonomic_tree_options;
2326 6657531f Andreas Kohlbecker
}
2327
2328
/**
2329
 * @todo Please document this function.
2330
 * @see http://drupal.org/node/1354
2331
 */
2332
function cdm_api_secref_cache_prefetch(&$secUuids) {
2333
  // Comment @WA: global variables should start with a single underscore
2334
  // followed by the module and another underscore.
2335
  global $_cdm_api_secref_cache;
2336
  if (!is_array($_cdm_api_secref_cache)) {
2337
    $_cdm_api_secref_cache = array();
2338
  }
2339
  $uniqueUuids = array_unique($secUuids);
2340
  $i = 0;
2341
  $param = '';
2342
  while ($i++ < count($uniqueUuids)) {
2343
    $param .= $secUuids[$i] . ',';
2344
    if (strlen($param) + 37 > 2000) {
2345
      _cdm_api_secref_cache_add($param);
2346
      $param = '';
2347
    }
2348
  }
2349
  if ($param) {
2350
    _cdm_api_secref_cache_add($param);
2351
  }
2352
}
2353
2354
/**
2355
 * @todo Please document this function.
2356
 * @see http://drupal.org/node/1354
2357
 */
2358
function cdm_api_secref_cache_get($secUuid) {
2359
  global $_cdm_api_secref_cache;
2360
  if (!is_array($_cdm_api_secref_cache)) {
2361
    $_cdm_api_secref_cache = array();
2362
  }
2363
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2364
    _cdm_api_secref_cache_add($secUuid);
2365
  }
2366
  return $_cdm_api_secref_cache[$secUuid];
2367
}
2368
2369
/**
2370
 * @todo Please document this function.
2371
 * @see http://drupal.org/node/1354
2372
 */
2373
function cdm_api_secref_cache_clear() {
2374
  global $_cdm_api_secref_cache;
2375
  $_cdm_api_secref_cache = array();
2376
}
2377
2378 f26245c8 Andreas Kohlbecker
2379 6657531f Andreas Kohlbecker
/**
2380
 * Validates if the given string is a uuid.
2381
 *
2382
 * @param string $str
2383
 *   The string to validate.
2384
 *
2385
 * return bool
2386
 *   TRUE if the string is a UUID.
2387
 */
2388
function is_uuid($str) {
2389
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2390
}
2391
2392
/**
2393
 * Checks if the given $object is a valid cdm entity.
2394
 *
2395
 * An object is considered a cdm entity if it has a string field $object->class
2396
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2397 f19f47fa Andreas Kohlbecker
 * The function is null save.
2398 6657531f Andreas Kohlbecker
 *
2399
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2400
 *
2401
 * @param mixed $object
2402
 *   The object to validate
2403
 *
2404
 * @return bool
2405
 *   True if the object is a cdm entity.
2406
 */
2407
function is_cdm_entity($object) {
2408 f19f47fa Andreas Kohlbecker
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2409 6657531f Andreas Kohlbecker
}
2410
2411
/**
2412
 * @todo Please document this function.
2413
 * @see http://drupal.org/node/1354
2414
 */
2415
function _cdm_api_secref_cache_add($secUuidsStr) {
2416
  global $_cdm_api_secref_cache;
2417
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2418
  // Batch fetching not jet reimplemented thus:
2419
  /*
2420
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2421
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2422
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2423
  */
2424
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2425
}
2426
2427
/**
2428
 * Checks if the given uri starts with a cdm webservice url.
2429
 *
2430
 * Checks if the uri starts with the cdm webservice url stored in the
2431
 * Drupal variable 'cdm_webservice_url'.
2432
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2433
 *
2434
 * @param string $uri
2435
 *   The URI to test.
2436
 *
2437
 * @return bool
2438
 *   True if the uri starts with a cdm webservice url.
2439
 */
2440
function _is_cdm_ws_uri($uri) {
2441
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2442
}
2443
2444
/**
2445
 * @todo Please document this function.
2446
 * @see http://drupal.org/node/1354
2447
 */
2448
function queryString($elements) {
2449
  $query = '';
2450
  foreach ($elements as $key => $value) {
2451
    if (is_array($value)) {
2452
      foreach ($value as $v) {
2453
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2454
      }
2455
    }
2456
    else {
2457
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2458
    }
2459
  }
2460
  return $query;
2461
}
2462
2463
/**
2464
 * Implementation of the magic method __clone to allow deep cloning of objects
2465
 * and arrays.
2466
 */
2467
function __clone() {
2468
  foreach ($this as $name => $value) {
2469
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2470
      $this->$name = clone($this->$name);
2471
    }
2472
  }
2473
}
2474
2475 a783afbc Andreas Kohlbecker
/**
2476
 * Compares the given CDM Term instances by the  representationL10n.
2477
 *
2478
 * Can also be used with TermDTOs. To be used in usort()
2479
 *
2480
 * @see http://php.net/manual/en/function.usort.php
2481
 *
2482
 * @param $term1
2483
 *   The first CDM Term instance
2484
 * @param $term2
2485
 *   The second CDM Term instance
2486
 * @return int
2487
 *   The result of the comparison
2488
 */
2489
function compare_terms_by_representationL10n($term1, $term2) {
2490
2491
  if (!isset($term1->representation_L10n)) {
2492
    $term1->representationL10n = '';
2493
  }
2494
  if (!isset($term2->representation_L10n)) {
2495
    $term2->representationL10n = '';
2496
  }
2497
2498
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2499
}
2500
2501
2502 6657531f Andreas Kohlbecker
/**
2503
 * Make a 'deep copy' of an array.
2504
 *
2505
 * Make a complete deep copy of an array replacing
2506
 * references with deep copies until a certain depth is reached
2507
 * ($maxdepth) whereupon references are copied as-is...
2508
 *
2509
 * @see http://us3.php.net/manual/en/ref.array.php
2510
 *
2511
 * @param array $array
2512 cc3c9807 Andreas Kohlbecker
 * @param array $copy passed by reference
2513 6657531f Andreas Kohlbecker
 * @param int $maxdepth
2514
 * @param int $depth
2515
 */
2516
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2517
  if ($depth > $maxdepth) {
2518
    $copy = $array;
2519
    return;
2520
  }
2521
  if (!is_array($copy)) {
2522
    $copy = array();
2523
  }
2524
  foreach ($array as $k => &$v) {
2525
    if (is_array($v)) {
2526
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2527
    }
2528
    else {
2529
      $copy[$k] = $v;
2530
    }
2531
  }
2532
}
2533
2534
/**
2535 e2464cf8 Andreas Kohlbecker
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2536 6657531f Andreas Kohlbecker
 *
2537
 */
2538 e2464cf8 Andreas Kohlbecker
function _add_js_ws_debug() {
2539
2540 5ea8b301 Andreas Kohlbecker
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2541
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2542
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2543
    // use the developer versions of js libs
2544
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2545
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2546
  }
2547
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2548 e2464cf8 Andreas Kohlbecker
    array(
2549
      'type' => 'file',
2550
      'weight' => JS_LIBRARY,
2551
      'cache' => TRUE)
2552
    );
2553
2554 5ea8b301 Andreas Kohlbecker
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2555 e2464cf8 Andreas Kohlbecker
    array(
2556
      'type' => 'file',
2557
      'weight' => JS_LIBRARY,
2558
      'cache' => TRUE)
2559
    );
2560
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2561
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2562
2563
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2564
    array(
2565
      'type' => 'file',
2566
      'weight' => JS_LIBRARY,
2567
      'cache' => TRUE)
2568
    );
2569 2ebf0428 Andreas Kohlbecker
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2570
    array(
2571
    'type' => 'file',
2572
    'weight' => JS_LIBRARY,
2573
    'cache' => TRUE)
2574
    );
2575 6657531f Andreas Kohlbecker
2576
}
2577
2578
/**
2579
 * @todo Please document this function.
2580
 * @see http://drupal.org/node/1354
2581
 */
2582
function _no_classfication_uuid_message() {
2583
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2584
    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.');
2585
  }
2586
  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.');
2587
}
2588
2589
/**
2590
 * Implementation of hook flush_caches
2591
 *
2592
 * Add custom cache tables to the list of cache tables that
2593
 * will be cleared by the Clear button on the Performance page or whenever
2594
 * drupal_flush_all_caches is invoked.
2595
 *
2596
 * @author W.Addink <waddink@eti.uva.nl>
2597
 *
2598
 * @return array
2599
 *   An array with custom cache tables to include.
2600
 */
2601
function cdm_api_flush_caches() {
2602
  return array('cache_cdm_ws');
2603
}
2604 f26245c8 Andreas Kohlbecker
2605 2dd59bb5 Andreas Kohlbecker
/**
2606
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2607
 *
2608
 * @param $data
2609
 *   The variable to log to the drupal_debug.txt log file.
2610
 * @param $label
2611
 *   (optional) If set, a label to output before $data in the log file.
2612
 *
2613
 * @return
2614
 *   No return value if successful, FALSE if the log file could not be written
2615
 *   to.
2616
 *
2617
 * @see cdm_dataportal_init() where the log file is reset on each requests
2618
 * @see dd()
2619
 * @see http://drupal.org/node/314112
2620
 *
2621
 */
2622
function cdm_dd($data, $label = NULL) {
2623 43251923 Andreas Kohlbecker
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2624 2dd59bb5 Andreas Kohlbecker
    return dd($data, $label);
2625
  }
2626
}