Project

General

Profile

Download (76.1 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
  /**
3
   * @file
4
   * Required or useful functions for using CDM Data Store Webservices.
5
   *
6
   * Naming conventions:
7
   * ----------------------
8
   * - All webservice access methods are prefixed with cdm_ws.
9
   *
10
   * @copyright
11
   *   (C) 2007-2012 EDIT
12
   *   European Distributed Institute of Taxonomy
13
   *   http://www.e-taxonomy.eu
14
   *
15
   *   The contents of this module are subject to the Mozilla
16
   *   Public License Version 1.1.
17
   * @see http://www.mozilla.org/MPL/MPL-1.1.html
18
   *
19
   * @author
20
   *   - Andreas Kohlbecker <a.kohlbecker@BGBM.org>
21
   *   - Wouter Addink <w.addink@eti.uva.nl> (migration from Drupal 5 to Drupal7)
22
   */
23

    
24
  module_load_include('php', 'cdm_api', 'xml2json');
25
  module_load_include('php', 'cdm_api', 'commons');
26
  module_load_include('php', 'cdm_api', 'uuids');
27
  module_load_include('php', 'cdm_api', 'enums');
28
  module_load_include('php', 'cdm_api', 'webservice_uris');
29
  module_load_include('php', 'cdm_api', 'cdm_node');
30

    
31
  /**
32
   * Timeout used to override the default of 30 seconds
33
   * in @see drupal_http_request()
34
   *
35
   * @var CDM_HTTP_REQUEST_TIMEOUT: A float representing the maximum number of seconds the function
36
   *     call may take
37
   */
38
  define('CDM_HTTP_REQUEST_TIMEOUT', 90.0);
39

    
40
  define('SORT_ORDER_ID', 'sort_by_order_id');
41

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

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

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

    
65
  return $items;
66
}
67

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

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

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

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

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

    
99

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

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

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

    
110
      $data = unserialize($data);
111

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

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

    
127
    _add_js_ws_debug();
128

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

    
140
    return $block;
141
  }
142
}
143

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

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

    
166
// ===================== Tagged Text functions ================== //
167

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

    
196

    
197
/**
198
 * Finds the text tagged with $tag_type in an array of taggedText instances.
199
 *
200
 * Note: This function is currently unused.
201
 *
202
 * @param array $taggedtxt
203
 *   Array with text items.
204
 * @param string $tag_type
205
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
206
 *   to return all texts.
207
 *
208
 * @return array
209
 *   An array with the texts mapped by $tag_type.
210
 */
211
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
212
  $tokens = array();
213
  if (!empty($taggedtxt)) {
214
    foreach ($taggedtxt as $tagtxt) {
215
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
216
        $tokens[] = $tagtxt->text;
217
      }
218
    }
219
  }
220
  return $tokens;
221
}
222

    
223
/**
224
 * Preprocess the taggedTitle arrays.
225
 *
226
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
227
 * into tag type "name"
228
 *
229
 * Step 2: Two taggedTexts which have the same type and which have
230
 * a separator between them are merged together.
231
 *
232
 * @param array $taggedTextList
233
 *    An array of TaggedText objects
234
 */
235
function normalize_tagged_text(&$taggedTextList) {
236

    
237
  if (is_array($taggedTextList)) {
238

    
239
    // First pass: rename.
240
    for ($i = 0; $i < count($taggedTextList); $i++) {
241

    
242
      if ($taggedTextList[$i]->type == "hybridSign") {
243
        $taggedTextList[$i]->type = "name";
244
      }
245
    }
246

    
247
    // Second pass: resolve separators.
248
    $taggedNameListNew = array();
249
    for ($i = 0; $i < count($taggedTextList); $i++) {
250

    
251
      // elements of the same type concatenated by a separator should be merged together
252
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
253
        $taggedName = clone $taggedTextList[$i];
254
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
255
        $taggedNameListNew[] = $taggedName;
256
        ++$i;
257
        ++$i;
258
        continue;
259
      }
260
      // no special handling
261
      $taggedNameListNew[] = $taggedTextList[$i];
262

    
263
    }
264
    $taggedTextList = $taggedNameListNew;
265
  }
266
}
267

    
268
function split_secref_from_tagged_text(&$tagged_text) {
269

    
270
  $extracted_tt = array();
271
  if (is_array($tagged_text)) {
272
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
273
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
274
        $extracted_tt[0] = $tagged_text[$i];
275
        $extracted_tt[1] = $tagged_text[$i + 1];
276
        unset($tagged_text[$i]);
277
        unset($tagged_text[$i + 1]);
278
        break;
279
      }
280
    }
281
  }
282
  return $extracted_tt;
283
}
284

    
285

    
286
function split_nomstatus_from_tagged_text(&$tagged_text) {
287

    
288
  $extracted_tt = array();
289
  if (is_array($tagged_text)) {
290
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
291
      if ($tagged_text[$i]->type == "nomStatus"){
292
        $extracted_tt[] = $tagged_text[$i];
293
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
294
          $extracted_tt[] = $tagged_text[$i + 1];
295
          unset($tagged_text[$i + 1]);
296
        }
297
        if ($tagged_text[$i - 1]->type == "separator"){
298
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
299
          unset($tagged_text[$i - 1]);
300
        }
301
        unset($tagged_text[$i]);
302
        break;
303
      }
304
    }
305
  }
306
  return $extracted_tt;
307
}
308

    
309
function find_tagged_text_elements($taggedTextList, $type){
310
  $matching_elements = array();
311
  if (is_array($taggedTextList)) {
312
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
313
      if($taggedTextList[$i]->type == $type){
314
        $matching_elements[] = $taggedTextList[$i];
315
      }
316
    }
317
  }
318
  return $matching_elements;
319
}
320

    
321
// ===================== END of Tagged Text functions ================== //
322

    
323
/**
324
 * Returns the currently classification tree in use.
325
 */
326
function get_current_classification_uuid() {
327
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
328
    return $_SESSION['cdm']['taxonomictree_uuid'];
329
  }
330
  else {
331
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
332
  }
333
}
334

    
335
/**
336
 * Lists the classifications a taxon belongs to
337
 *
338
 * @param CDM type Taxon $taxon
339
 *   the taxon
340
 *
341
 * @return array
342
 *   aray of CDM instances of Type Classification
343
 */
344
function get_classifications_for_taxon($taxon) {
345

    
346
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
347
}
348

    
349
/**
350
 * Returns the chosen FeatureTree for the taxon profile.
351
 *
352
 * The FeatureTree profile returned is the one that has been set in the
353
 * dataportal settings (layout->taxon:profile).
354
 * When the chosen FeatureTree is not found in the database,
355
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
356
 *
357
 * @return mixed
358
 *   A cdm FeatureTree object.
359
 */
360
function get_profile_feature_tree() {
361
  static $profile_featureTree;
362

    
363
  if($profile_featureTree == NULL) {
364
    $profile_featureTree = cdm_ws_get(
365
      CDM_WS_FEATURETREE,
366
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
367
    );
368
    if (!$profile_featureTree) {
369
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
370
    }
371
  }
372

    
373
  return $profile_featureTree;
374
}
375

    
376
/**
377
 * Returns the chosen FeatureTree for SpecimenDescriptions.
378
 *
379
 * The FeatureTree returned is the one that has been set in the
380
 * dataportal settings (layout->taxon:specimen).
381
 * When the chosen FeatureTree is not found in the database,
382
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
383
 *
384
 * @return mixed
385
 *   A cdm FeatureTree object.
386
 */
387
function cdm_get_occurrence_featureTree() {
388
  static $occurrence_featureTree;
389

    
390
  if($occurrence_featureTree == NULL) {
391
    $occurrence_featureTree = cdm_ws_get(
392
      CDM_WS_FEATURETREE,
393
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
394
    );
395
    if (!$occurrence_featureTree) {
396
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
397
    }
398
  }
399
  return $occurrence_featureTree;
400
}
401

    
402
/**
403
 * Returns the FeatureTree for structured descriptions
404
 *
405
 * The FeatureTree returned is the one that has been set in the
406
 * dataportal settings (layout->taxon:profile).
407
 * When the chosen FeatureTree is not found in the database,
408
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
409
 *
410
 * @return mixed
411
 *   A cdm FeatureTree object.
412
 */
413
function get_structured_description_featureTree() {
414
  static $structured_description_featureTree;
415

    
416
  if($structured_description_featureTree == NULL) {
417
    $structured_description_featureTree = cdm_ws_get(
418
        CDM_WS_FEATURETREE,
419
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
420
    );
421
    if (!$structured_description_featureTree) {
422
      $structured_description_featureTree = cdm_ws_get(
423
          CDM_WS_FEATURETREE,
424
          UUID_DEFAULT_FEATURETREE
425
      );
426
    }
427
  }
428
  return $structured_description_featureTree;
429
}
430

    
431
/**
432
 * @todo Please document this function.
433
 * @see http://drupal.org/node/1354
434
 */
435
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
436
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
437
}
438

    
439
/**
440
 * @todo Please document this function.
441
 * @see http://drupal.org/node/1354
442
 */
443
function reset_taxonomictree_uuid($taxonomictree_uuid) {
444
  unset($_SESSION['cdm']['taxonomictree_uuid']);
445
}
446

    
447
/**
448
 * @todo Please document this function.
449
 * @see http://drupal.org/node/1354
450
 */
451
function set_last_taxon_page_tab($taxonPageTab) {
452
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
453
}
454

    
455
/**
456
 * @todo Please document this function.
457
 * @see http://drupal.org/node/1354
458
 */
459
function get_last_taxon_page_tab() {
460
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
461
    return $_SESSION['cdm']['taxon_page_tab'];
462
  }
463
  else {
464
    return FALSE;
465
  }
466
}
467

    
468
/**
469
 * @todo Improve the documentation of this function.
470
 *
471
 * media Array [4]
472
 * representations Array [3]
473
 * mimeType image/jpeg
474
 * representationParts Array [1]
475
 * duration 0
476
 * heigth 0
477
 * size 0
478
 * uri
479
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
480
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
481
 * width 0
482
 * suffix jpg
483
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
484
 * title
485
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
486
 *
487
 * @param object $media
488
 * @param array $mimeTypes
489
 * @param int $width
490
 * @param int $height
491
 *
492
 * @return array
493
 *   An array with preferred media representations or else an empty array.
494
 */
495
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
496
  $prefRepr = array();
497
  if (!isset($media->representations[0])) {
498
    return $prefRepr;
499
  }
500

    
501
  while (count($mimeTypes) > 0) {
502
    // getRepresentationByMimeType
503
    $mimeType = array_shift($mimeTypes);
504

    
505
    foreach ($media->representations as &$representation) {
506
      // If the mimetype is not known, try inferring it.
507
      if (!$representation->mimeType) {
508
        if (isset($representation->parts[0])) {
509
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
510
        }
511
      }
512

    
513
      if ($representation->mimeType == $mimeType) {
514
        // Preferred mimetype found -> erase all remaining mimetypes
515
        // to end loop.
516
        $mimeTypes = array();
517
        $dwa = 0;
518
        $dw = 0;
519
        // Look for part with the best matching size.
520
        foreach ($representation->parts as $part) {
521
          if (isset($part->width) && isset($part->height)) {
522
            $dw = $part->width * $part->height - $height * $width;
523
          }
524
          if ($dw < 0) {
525
            $dw *= -1;
526
          }
527
          $dwa += $dw;
528
        }
529
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
530
        $prefRepr[$dwa . '_'] = $representation;
531
      }
532
    }
533
  }
534
  // Sort the array.
535
  krsort($prefRepr);
536
  return $prefRepr;
537
}
538

    
539
/**
540
 * Infers the mime type of a file using the filename extension.
541
 *
542
 * The filename extension is used to infer the mime type.
543
 *
544
 * @param string $filepath
545
 *   The path to the respective file.
546
 *
547
 * @return string
548
 *   The mimetype for the file or FALSE if the according mime type could
549
 *   not be found.
550
 */
551
function infer_mime_type($filepath) {
552
  static $mimemap = NULL;
553
  if (!$mimemap) {
554
    $mimemap = array(
555
      'jpg' => 'image/jpeg',
556
      'jpeg' => 'image/jpeg',
557
      'png' => 'image/png',
558
      'gif' => 'image/gif',
559
      'giff' => 'image/gif',
560
      'tif' => 'image/tif',
561
      'tiff' => 'image/tif',
562
      'pdf' => 'application/pdf',
563
      'html' => 'text/html',
564
      'htm' => 'text/html',
565
    );
566
  }
567
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
568
  if (isset($mimemap[$extension])) {
569
    return $mimemap[$extension];
570
  }
571
  else {
572
    // FIXME remove this hack just return FALSE;
573
    return 'text/html';
574
  }
575
}
576

    
577
/**
578
 * Converts an ISO 8601 org.joda.time.Partial to a year.
579
 *
580
 * The function expects an ISO 8601 time representation of a
581
 * org.joda.time.Partial of the form yyyy-MM-dd.
582
 *
583
 * @param string $partial
584
 *   ISO 8601 time representation of a org.joda.time.Partial.
585
 *
586
 * @return string
587
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
588
 */
589
function partialToYear($partial) {
590
  if (is_string($partial)) {
591
    $year = substr($partial, 0, 4);
592
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
593
      return $year;
594
    }
595
  }
596
  return;
597
}
598

    
599
/**
600
 * Converts an ISO 8601 org.joda.time.Partial to a month.
601
 *
602
 * This function expects an ISO 8601 time representation of a
603
 * org.joda.time.Partial of the form yyyy-MM-dd.
604
 * In case the month is unknown (= ???) NULL is returned.
605
 *
606
 * @param string $partial
607
 *   ISO 8601 time representation of a org.joda.time.Partial.
608
 *
609
 * @return string
610
 *   A month.
611
 */
612
function partialToMonth($partial) {
613
  if (is_string($partial)) {
614
    $month = substr($partial, 5, 2);
615
    if (preg_match("/[0-9][0-9]/", $month)) {
616
      return $month;
617
    }
618
  }
619
  return;
620
}
621

    
622
/**
623
 * Converts an ISO 8601 org.joda.time.Partial to a day.
624
 *
625
 * This function expects an ISO 8601 time representation of a
626
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
627
 * In case the day is unknown (= ???) NULL is returned.
628
 *
629
 * @param string $partial
630
 *   ISO 8601 time representation of a org.joda.time.Partial.
631
 *
632
 * @return string
633
 *   A day.
634
 */
635
function partialToDay($partial) {
636
  if (is_string($partial)) {
637
    $day = substr($partial, 8, 2);
638
    if (preg_match("/[0-9][0-9]/", $day)) {
639
      return $day;
640
    }
641
  }
642
  return;
643
}
644

    
645
/**
646
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
647
 *
648
 * This function expects an ISO 8601 time representations of a
649
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
650
 * four digit year, month and day with dashes:
651
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
652
 *
653
 * The partial may contain question marks eg: "1973-??-??",
654
 * these are turned in to '00' or are stripped depending of the $stripZeros
655
 * parameter.
656
 *
657
 * @param string $partial
658
 *   org.joda.time.Partial.
659
 * @param bool $stripZeros
660
 *   If set to TRUE the zero (00) month and days will be hidden:
661
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
662
 * @param string @format
663
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
664
 *    - "YYYY": Year only
665
 *    - "YYYY-MM-DD": this is the default
666
 *
667
 * @return string
668
 *   YYYY-MM-DD formatted year, month, day.
669
 */
670
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
671

    
672
  $y = NULL; $m = NULL; $d = NULL;
673

    
674
  if(strpos($format, 'YY') !== FALSE){
675
    $y = partialToYear($partial);
676
  }
677
  if(strpos($format, 'MM') !== FALSE){
678
    $m = partialToMonth($partial);
679
  }
680
  if(strpos($format, 'DD') !== FALSE){
681
    $d = partialToDay($partial);
682
  }
683

    
684
  $y = $y ? $y : '00';
685
  $m = $m ? $m : '00';
686
  $d = $d ? $d : '00';
687

    
688
  $date = '';
689

    
690
  if ($y == '00' && $stripZeros) {
691
    return;
692
  }
693
  else {
694
    $date = $y;
695
  }
696

    
697
  if ($m == '00' && $stripZeros) {
698
    return $date;
699
  }
700
  else {
701
    $date .= "-" . $m;
702
  }
703

    
704
  if ($d == '00' && $stripZeros) {
705
    return $date;
706
  }
707
  else {
708
    $date .= "-" . $d;
709
  }
710
  return $date;
711
}
712

    
713
/**
714
 * Converts a time period to a string.
715
 *
716
 * See also partialToDate($partial, $stripZeros).
717
 *
718
 * @param object $period
719
 *   An JodaTime org.joda.time.Period object.
720
 * @param bool $stripZeros
721
 *   If set to True, the zero (00) month and days will be hidden:
722
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
723
 * @param string @format
724
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
725
 *    - "YYYY": Year only
726
 *    - "YYYY-MM-DD": this is the default
727
 *
728
 * @return string
729
 *   Returns a date in the form of a string.
730
 */
731
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
732
  $dateString = '';
733
  if ($period->start) {
734
    $dateString = partialToDate($period->start, $stripZeros, $format);
735
  }
736
  if ($period->end) {
737
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
738
  }
739
  return $dateString;
740
}
741

    
742
/**
743
 * returns the earliest date available in the $period in a normalized
744
 * form suitable for sorting, e.g.:
745
 *
746
 *  - 1956-00-00
747
 *  - 0000-00-00
748
 *  - 1957-03-00
749
 *
750
 * that is either the start date is returned if set otherwise the
751
 * end date
752
 *
753
 * @param  $period
754
 *    An JodaTime org.joda.time.Period object.
755
 * @return string normalized form of the date
756
 *   suitable for sorting
757
 */
758
function timePeriodAsOrderKey($period) {
759
  $dateString = '';
760
  if ($period->start) {
761
    $dateString = partialToDate($period->start, false);
762
  }
763
  if ($period->end) {
764
    $dateString .= partialToDate($period->end, false);
765
  }
766
  return $dateString;
767
}
768

    
769
/**
770
 * Composes a absolute CDM web service URI with parameters and querystring.
771
 *
772
 * @param string $uri_pattern
773
 *   String with place holders ($0, $1, ..) that should be replaced by the
774
 *   according element of the $pathParameters array.
775
 * @param array $pathParameters
776
 *   An array of path elements, or a single element.
777
 * @param string $query
778
 *   A query string to append to the URL.
779
 *
780
 * @return string
781
 *   A complete URL with parameters to a CDM webservice.
782
 */
783
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
784
  if (empty($pathParameters)) {
785
    $pathParameters = array();
786
  }
787

    
788
  // (1)
789
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
790
  // according element of the $pathParameters array.
791
  static $helperArray = array();
792
  if (isset($pathParameters) && !is_array($pathParameters)) {
793
    $helperArray[0] = $pathParameters;
794
    $pathParameters = $helperArray;
795
  }
796

    
797
  $i = 0;
798
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
799
    if (count($pathParameters) <= $i) {
800
        drupal_set_message(t('cdm_compose_url(): missing pathParameter ' . $i .  ' for ' . $uri_pattern), 'error');
801
      break;
802
    }
803
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
804
    ++$i;
805
  }
806

    
807
  // (2)
808
  // Append all remaining element of the $pathParameters array as path
809
  // elements.
810
  if (count($pathParameters) > $i) {
811
    // Strip trailing slashes.
812
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
813
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
814
    }
815
    while (count($pathParameters) > $i) {
816
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
817
      ++$i;
818
    }
819
  }
820

    
821
  // (3)
822
  // Append the query string supplied by $query.
823
  if (isset($query)) {
824
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
825
  }
826

    
827
  $path = $uri_pattern;
828

    
829
  $uri = variable_get('cdm_webservice_url', '') . $path;
830
  return $uri;
831
}
832

    
833
/**
834
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
835
 *     together with a theme name to such a proxy function?
836
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
837
 *     Maybe we want to have two different proxy functions, one with theming and one without?
838
 *
839
 * @param string $uri
840
 *     A URI to a CDM Rest service from which to retrieve an object
841
 * @param string|null $hook
842
 *     (optional) The hook name to which the retrieved object should be passed.
843
 *     Hooks can either be a theme_hook() or compose_hook() implementation
844
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
845
 *     suitable for drupal_render()
846
 *
847
 * @todo Please document this function.
848
 * @see http://drupal.org/node/1354
849
 */
850
function proxy_content($uri, $hook = NULL) {
851

    
852
  $args = func_get_args();
853
  $do_gzip = function_exists('gzencode');
854
  $uriEncoded = array_shift($args);
855
  $uri = urldecode($uriEncoded);
856
  $hook = array_shift($args);
857
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
858

    
859
  $post_data = null;
860

    
861
  if ($request_method == "POST" || $request_method == "PUT") {
862
    // read response body via inputstream module
863
    $post_data = file_get_contents("php://input");
864
  }
865

    
866
  // Find and deserialize arrays.
867
  foreach ($args as &$arg) {
868
    // FIXME use regex to find serialized arrays.
869
    //       or should we accept json instead of php serializations?
870
    if (strpos($arg, "a:") === 0) {
871
      $arg = unserialize($arg);
872
    }
873
  }
874

    
875
  // In all these cases perform a simple get request.
876
  // TODO reconsider caching logic in this function.
877

    
878
  if (empty($hook)) {
879
    // simply return the webservice response
880
    // Print out JSON, the cache cannot be used since it contains objects.
881
    $http_response = cdm_http_request($uri, $request_method, $post_data);
882
    if (isset($http_response->headers)) {
883
      foreach ($http_response->headers as $hname => $hvalue) {
884
        drupal_add_http_header($hname, $hvalue);
885
      }
886
    }
887
    if (isset($http_response->data)) {
888
      print $http_response->data;
889
      flush();
890
    }
891
    exit(); // leave drupal here
892
  } else {
893
    // $hook has been supplied
894
    // handle $hook either as compose ot theme hook
895
    // pass through theme or comose hook
896

    
897
    // do a security check since the $uri will be passed
898
    // as absolute URI to cdm_ws_get()
899
    if( !_is_cdm_ws_uri($uri)) {
900
      drupal_set_message(
901
      'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
902
      'error'
903
          );
904
          return '';
905
    }
906

    
907
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
908

    
909
    $reponse_data = NULL;
910

    
911
    if (function_exists('compose_' . $hook)){
912
      // call compose hook
913

    
914
      $elements =  call_user_func('compose_' . $hook, $obj);
915
      // pass the render array to drupal_render()
916
      $reponse_data = drupal_render($elements);
917
    } else {
918
      // call theme hook
919

    
920
      // TODO use theme registry to get the registered hook info and
921
      //    use these defaults
922
      switch($hook) {
923
        case 'cdm_taxontree':
924
          $variables = array(
925
            'tree' => $obj,
926
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
927
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
928
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
929
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
930
            );
931
          $reponse_data = theme($hook, $variables);
932
          break;
933

    
934
        case 'cdm_list_of_taxa':
935
            $variables = array(
936
              'records' => $obj,
937
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
938
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
939
            $reponse_data = theme($hook, $variables);
940
            break;
941

    
942
        case 'cdm_media_caption':
943
          $variables = array(
944
          'media' => $obj,
945
          // $args[0] is set in taxon_image_gallery_default in
946
          // cdm_dataportal.page.theme.
947
          'elements' => isset($args[0]) ? $args[0] : array(
948
          'title',
949
          'description',
950
          'artist',
951
          'location',
952
          'rights',
953
          ),
954
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
955
          );
956
          $reponse_data = theme($hook, $variables);
957
          break;
958

    
959
        default:
960
          drupal_set_message(t(
961
          'Theme !theme is not yet supported by the function !function.', array(
962
          '!theme' => $hook,
963
          '!function' => __FUNCTION__,
964
          )), 'error');
965
          break;
966
      } // END of theme hook switch
967
    } // END of tread as theme hook
968

    
969

    
970
    if($do_gzip){
971
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
972
      drupal_add_http_header('Content-Encoding', 'gzip');
973
    }
974
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
975
    drupal_add_http_header('Content-Length', strlen($reponse_data));
976

    
977
    print $reponse_data;
978
  } // END of handle $hook either as compose ot theme hook
979

    
980
}
981

    
982
/**
983
 * @todo Please document this function.
984
 * @see http://drupal.org/node/1354
985
 */
986
function setvalue_session() {
987
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
988
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
989
    $keys = explode('][', $keys);
990
  }
991
  else {
992
    return;
993
  }
994
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
995

    
996
  // Prevent from malicous tags.
997
  $val = strip_tags($val);
998

    
999
  $var = &$_SESSION;
1000
  $i = 0;
1001
  foreach ($keys as $key) {
1002
    $hasMoreKeys = ++$i < count($var);
1003
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
1004
      $var[$key] = array();
1005
    }
1006
    $var = &$var[$key];
1007
  }
1008
  $var = $val;
1009
  if (isset($_REQUEST['destination'])) {
1010
    drupal_goto($_REQUEST['destination']);
1011
  }
1012
}
1013

    
1014
/**
1015
 * @todo Please document this function.
1016
 * @see http://drupal.org/node/1354
1017
 */
1018
function uri_uriByProxy($uri, $theme = FALSE) {
1019
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1020
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1021
}
1022

    
1023
/**
1024
 * Composes the the absolute REST service URI to the annotations pager
1025
 * for the given CDM entity.
1026
 *
1027
 * NOTE: Not all CDM Base types are yet supported.
1028
 *
1029
 * @param $cdmBase
1030
 *   The CDM entity to construct the annotations pager uri for
1031
 */
1032
function cdm_compose_annotations_uri($cdmBase) {
1033
  if (!$cdmBase->uuid) {
1034
    return;
1035
  }
1036

    
1037
  $ws_base_uri = NULL;
1038
  switch ($cdmBase->class) {
1039
    case 'TaxonBase':
1040
    case 'Taxon':
1041
    case 'Synonym':
1042
      $ws_base_uri = CDM_WS_TAXON;
1043
      break;
1044

    
1045
    case 'TaxonNameBase':
1046
    case 'NonViralName':
1047
    case 'BacterialName':
1048
    case 'BotanicalName':
1049
    case 'CultivarPlantName':
1050
    case 'ZoologicalName':
1051
    case 'ViralName':
1052
      $ws_base_uri = CDM_WS_NAME;
1053
      break;
1054

    
1055
    case 'Media':
1056
      $ws_base_uri = CDM_WS_MEDIA;
1057
      break;
1058

    
1059
    case 'Reference':
1060
      $ws_base_uri = CDM_WS_REFERENCE;
1061
      break;
1062

    
1063
    case 'Distribution':
1064
    case 'TextData':
1065
    case 'TaxonInteraction':
1066
    case 'QuantitativeData':
1067
    case 'IndividualsAssociation':
1068
    case 'Distribution':
1069
    case 'CommonTaxonName':
1070
    case 'CategoricalData':
1071
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1072
      break;
1073

    
1074
    case 'PolytomousKey':
1075
    case 'MediaKey':
1076
    case 'MultiAccessKey':
1077
      $ws_base_uri = $cdmBase->class;
1078
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1079
      break;
1080

    
1081
    default:
1082
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1083
      return;
1084
  }
1085
  return cdm_compose_url($ws_base_uri, array(
1086
    $cdmBase->uuid,
1087
    'annotations',
1088
  ));
1089
}
1090

    
1091
/**
1092
 * Enter description here...
1093
 *
1094
 * @param string $resourceURI
1095
 * @param int $pageSize
1096
 *   The maximum number of entities returned per page.
1097
 *   The default page size as configured in the cdm server
1098
 *   will be used if set to NULL
1099
 *   to return all entities in a single page).
1100
 * @param int $pageNumber
1101
 *   The number of the page to be returned, the first page has the
1102
 *   pageNumber = 0
1103
 * @param array $query
1104
 *   A array holding the HTTP request query parameters for the request
1105
 * @param string $method
1106
 *   The HTTP method to use, valid values are "GET" or "POST"
1107
 * @param bool $absoluteURI
1108
 *   TRUE when the URL should be treated as absolute URL.
1109
 *
1110
 * @return the a CDM Pager object
1111
 *
1112
 */
1113
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1114

    
1115
  $query['pageNumber'] = $pageNumber;
1116
  $query['pageSize'] = $pageSize;
1117

    
1118
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1119
}
1120

    
1121
/**
1122
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1123
 *
1124
 * @param string $resourceURI
1125
 * @param array $query
1126
 *   A array holding the HTTP request query parameters for the request
1127
 * @param string $method
1128
 *   The HTTP method to use, valid values are "GET" or "POST";
1129
 * @param bool $absoluteURI
1130
 *   TRUE when the URL should be treated as absolute URL.
1131
 *
1132
 * @return array
1133
 *     A list of CDM entitites
1134
 *
1135
 */
1136
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1137
  $page_index = 0;
1138
  // using a bigger page size to avoid to many multiple requests
1139
  $page_size = 500;
1140
  $entities = array();
1141

    
1142
  while ($page_index !== FALSE){
1143
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1144
    if(isset($pager->records) && is_array($pager->records)) {
1145
      $entities = $pager->records;
1146
      if(!empty($pager->nextIndex)){
1147
        $page_index = $pager->nextIndex;
1148
      } else {
1149
        $page_index = FALSE;
1150
      }
1151
    } else {
1152
      $page_index = FALSE;
1153
    }
1154
  }
1155
  return $entities;
1156
}
1157

    
1158
/*
1159
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1160
  $viewrank = _cdm_taxonomy_compose_viewrank();
1161
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1162
  ? '/' . $path : '') ;
1163
}
1164
*/
1165

    
1166
/**
1167
 * @todo Enter description here...
1168
 *
1169
 * @param string $taxon_uuid
1170
 *  The UUID of a cdm taxon instance
1171
 * @param string $ignore_rank_limit
1172
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1173
 *
1174
 * @return A cdm REST service URL path to a Classification
1175
 */
1176
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1177

    
1178
  $view_uuid = get_current_classification_uuid();
1179
  $rank_uuid = NULL;
1180
  if (!$ignore_rank_limit) {
1181
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1182
  }
1183

    
1184
  if (!empty($taxon_uuid)) {
1185
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1186
      $view_uuid,
1187
      $taxon_uuid,
1188
    ));
1189
  }
1190
  else {
1191
    if (!empty($rank_uuid)) {
1192
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1193
        $view_uuid,
1194
        $rank_uuid,
1195
      ));
1196
    }
1197
    else {
1198
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1199
        $view_uuid,
1200
      ));
1201
    }
1202
  }
1203
}
1204

    
1205
/**
1206
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1207
 *
1208
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1209
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1210
 *
1211
 * Operates in two modes depending on whether the parameter
1212
 * $taxon_uuid is set or NULL.
1213
 *
1214
 * A) $taxon_uuid = NULL:
1215
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1216
 *  2. otherwise return the default classification as defined by the admin via the settings
1217
 *
1218
 * b) $taxon_uuid is set:
1219
 *   return the classification to whcih the taxon belongs to.
1220
 *
1221
 * @param UUID $taxon_uuid
1222
 *   The UUID of a cdm taxon instance
1223
 */
1224
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1225

    
1226
    $response = NULL;
1227

    
1228
    // 1st try
1229
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1230

    
1231
    if ($response == NULL) {
1232
      // 2dn try by ignoring the rank limit
1233
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1234
    }
1235

    
1236
    if ($response == NULL) {
1237
      // 3rd try, last fallback:
1238
      //    return the default classification
1239
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1240
        // Delete the session value and try again with the default.
1241
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1242
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1243
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1244
      }
1245
      else {
1246
        // Check if taxonomictree_uuid is valid.
1247
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1248
        if ($test == NULL) {
1249
          // The default set by the admin seems to be invalid or is not even set.
1250
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1251
        }
1252
      }
1253
    }
1254

    
1255
  return $response;
1256
}
1257

    
1258
/**
1259
 * @todo Enter description here...
1260
 *
1261
 * @param string $taxon_uuid
1262
 *
1263
 * @return unknown
1264
 */
1265
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1266
  $view_uuid = get_current_classification_uuid();
1267
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1268

    
1269
  $response = NULL;
1270
  if ($rank_uuid) {
1271
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1272
      $view_uuid,
1273
      $taxon_uuid,
1274
      $rank_uuid,
1275
    ));
1276
  }
1277
  else {
1278
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1279
      $view_uuid,
1280
      $taxon_uuid,
1281
    ));
1282
  }
1283

    
1284
  if ($response == NULL) {
1285
    // Error handing.
1286
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1287
      // Delete the session value and try again with the default.
1288
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1289
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1290
    }
1291
    else {
1292
      // Check if taxonomictree_uuid is valid.
1293
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1294
      if ($test == NULL) {
1295
        // The default set by the admin seems to be invalid or is not even set.
1296
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1297
      }
1298
    }
1299
  }
1300

    
1301
  return $response;
1302
}
1303

    
1304

    
1305
// =============================Terms and Vocabularies ========================================= //
1306

    
1307
/**
1308
 * Returns the localized representation for the given term.
1309
 *
1310
 * @param Object $definedTermBase
1311
 * 	  of cdm type DefinedTermBase
1312
 * @return string
1313
 * 	  the localized representation_L10n of the term,
1314
 *    otherwise the titleCache as fall back,
1315
 *    otherwise the default_representation which defaults to an empty string
1316
 */
1317
function cdm_term_representation($definedTermBase, $default_representation = '') {
1318
  if ( isset($definedTermBase->representation_L10n) ) {
1319
    return $definedTermBase->representation_L10n;
1320
  } elseif ( isset($definedTermBase->titleCache)) {
1321
    return $definedTermBase->titleCache;
1322
  }
1323
  return $default_representation;
1324
}
1325

    
1326
/**
1327
 * Returns the abbreviated localized representation for the given term.
1328
 *
1329
 * @param Object $definedTermBase
1330
 * 	  of cdm type DefinedTermBase
1331
 * @return string
1332
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1333
 *    if this representation is not available the function delegates the
1334
 *    call to cdm_term_representation()
1335
 */
1336
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1337
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1338
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1339
  } else {
1340
    cdm_term_representation($definedTermBase, $default_representation);
1341
  }
1342
}
1343

    
1344
/**
1345
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1346
 *
1347
 * The options array is suitable for drupal form API elements that allow multiple choices.
1348
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1349
 *
1350
 * @param array $terms
1351
 *   a list of CDM DefinedTermBase instances
1352
 *
1353
 * @param $sort_by
1354
 *  Optionally sort option SORT_ORDER_ID (default: sorts after the cdm order index ),
1355
 *  to sort alphabetically: SORT_ASC, SORT_DESC
1356
 *
1357
 * @param $term_label_callback
1358
 *   A callback function to override the term representations
1359
 *
1360
 * @return array
1361
 *   the terms in an array as options for a form element that allows multiple choices.
1362
 */
1363
function cdm_terms_as_options($terms, $sort_by = SORT_ORDER_ID, $term_label_callback = NULL){
1364
  $options = array();
1365
  if(isset($terms) && is_array($terms)){
1366
    foreach ($terms as $term){
1367
      if ($term_label_callback && function_exists($term_label_callback)) {
1368
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1369
      } else {
1370
        //TODO use cdm_term_representation() here?
1371
        $options[$term->uuid] = t($term->representation_L10n);
1372
      }
1373
    }
1374
  }
1375
  switch($sort_by){
1376
    case SORT_ORDER_ID: array_reverse($options);
1377
      break;
1378
    default: array_multisort($options, SORT_ASC);
1379
  }
1380

    
1381
  return $options;
1382
}
1383

    
1384
/**
1385
 * @todo Please document this function.
1386
 * @see http://drupal.org/node/1354
1387
 */
1388
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL, $default_option = FALSE, $sort_by = SORT_ORDER_ID) {
1389
  static $vocabularyOptions = array();
1390

    
1391
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1392
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1393
    $vocabularyOptions[$vocabularyUuid] = cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1394
  }
1395

    
1396
  $options = $vocabularyOptions[$vocabularyUuid];
1397
  if($default_option !== FALSE){
1398
    array_unshift ($options, "");
1399
  }
1400
  return $options;
1401
}
1402

    
1403
/**
1404
 * @param $term_type one of
1405
 *  - Unknown
1406
 *  - Language
1407
 *  - NamedArea
1408
 *  - Rank
1409
 *  - Feature
1410
 *  - AnnotationType
1411
 *  - MarkerType
1412
 *  - ExtensionType
1413
 *  - DerivationEventType
1414
 *  - PresenceAbsenceTerm
1415
 *  - NomenclaturalStatusType
1416
 *  - NameRelationshipType
1417
 *  - HybridRelationshipType
1418
 *  - SynonymRelationshipType
1419
 *  - TaxonRelationshipType
1420
 *  - NameTypeDesignationStatus
1421
 *  - SpecimenTypeDesignationStatus
1422
 *  - InstitutionType
1423
 *  - NamedAreaType
1424
 *  - NamedAreaLevel
1425
 *  - RightsType
1426
 *  - MeasurementUnit
1427
 *  - StatisticalMeasure
1428
 *  - MaterialOrMethod
1429
 *  - Material
1430
 *  - Method
1431
 *  - Modifier
1432
 *  - Scope
1433
 *  - Stage
1434
 *  - KindOfUnit
1435
 *  - Sex
1436
 *  - ReferenceSystem
1437
 *  - State
1438
 *  - NaturalLanguageTerm
1439
 *  - TextFormat
1440
 *  - DeterminationModifier
1441
 *  - DnaMarker
1442
 */
1443
function cdm_terms_by_type_as_option($term_type, $sort_by = SORT_ORDER_ID, $term_label_callback = NULL){
1444
  $terms = cdm_ws_fetch_all(CDM_WS_TERM, array('class' => $term_type));
1445
  return cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1446
}
1447

    
1448
/**
1449
 * @todo Please document this function.
1450
 * @see http://drupal.org/node/1354
1451
 */
1452
function cdm_rankVocabulary_as_option() {
1453
  $options = cdm_Vocabulary_as_option(UUID_RANK, NULL, "");
1454
  return $options;
1455
}
1456

    
1457
/**
1458
 * @todo Please document this function.
1459
 * @see http://drupal.org/node/1354
1460
 */
1461
function _cdm_relationship_type_term_label_callback($term) {
1462
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1463
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1464
  }
1465
else {
1466
    return t($term->representation_L10n);
1467
  }
1468
}
1469

    
1470
// ========================================================================================== //
1471
/**
1472
 * @todo Improve documentation of this function.
1473
 *
1474
 * eu.etaxonomy.cdm.model.description.
1475
 * CategoricalData
1476
 * CommonTaxonName
1477
 * Distribution
1478
 * IndividualsAssociation
1479
 * QuantitativeData
1480
 * TaxonInteraction
1481
 * TextData
1482
 */
1483
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1484
  static $types = array(
1485
    "CategoricalData",
1486
    "CommonTaxonName",
1487
    "Distribution",
1488
    "IndividualsAssociation",
1489
    "QuantitativeData",
1490
    "TaxonInteraction",
1491
    "TextData",
1492
  );
1493

    
1494
  static $options = NULL;
1495
  if ($options == NULL) {
1496
    $options = array();
1497
    if ($prependEmptyElement) {
1498
      $options[' '] = '';
1499
    }
1500
    foreach ($types as $type) {
1501
      // No internatianalization here since these are purely technical terms.
1502
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1503
    }
1504
  }
1505
  return $options;
1506
}
1507

    
1508

    
1509
/**
1510
 * Fetches all TaxonDescription descriptions elements which are associated to the
1511
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1512
 * feature tree.
1513
 * @param $feature_tree
1514
 *     The CDM FeatureTree to be used as template
1515
 * @param $taxon_uuid
1516
 *     The UUID of the taxon
1517
 * @param $excludes
1518
 *     UUIDs of features to be excluded
1519
 * @return$feature_tree
1520
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1521
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1522
 *     witch will hold the according $descriptionElements.
1523
 */
1524
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1525

    
1526
  if (!$feature_tree) {
1527
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1528
      In order to see the species profiles of your taxa, please select a
1529
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1530
    return FALSE;
1531
  }
1532

    
1533
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1534
      array(
1535
      'taxon' => $taxon_uuid,
1536
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1537
      ),
1538
      'POST'
1539
  );
1540

    
1541
  // Combine all descriptions into one feature tree.
1542
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1543
  $feature_tree->root->childNodes = $merged_nodes;
1544

    
1545
  return $feature_tree;
1546
}
1547

    
1548
/**
1549
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1550
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1551
 * be requested for the annotations.
1552
 *
1553
 * @param string $cdmBase
1554
 *   An annotatable cdm entity.
1555
 * @param array $includeTypes
1556
 *   If an array of annotation type uuids is supplied by this parameter the
1557
 *   list of annotations is resticted to those which belong to this type.
1558
 *
1559
 * @return array
1560
 *   An array of Annotation objects or an empty array.
1561
 */
1562
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1563

    
1564
  if(!isset($cdmBase->annotations)){
1565
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1566
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1567
  }
1568

    
1569
  $annotations = array();
1570
  foreach ($cdmBase->annotations as $annotation) {
1571
    if ($includeTypes) {
1572
      if (
1573
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1574
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1575
      ) {
1576
        $annotations[] = $annotation;
1577
      }
1578
    }
1579
    else {
1580
      $annotations[] = $annotation;
1581
    }
1582
  }
1583
  return $annotations;
1584

    
1585
}
1586

    
1587
/**
1588
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1589
 *
1590
 * @param object $annotatable_entity
1591
 *   The CDM AnnotatableEntity to load annotations for
1592
 */
1593
function cdm_load_annotations(&$annotatable_entity) {
1594
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1595
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1596
    if (is_array($annotations)) {
1597
      $annotatable_entity->annotations = $annotations;
1598
    }
1599
  }
1600
}
1601

    
1602
/**
1603
 * Get a NomenclaturalReference string.
1604
 *
1605
 * Returns the NomenclaturalReference string with correctly placed
1606
 * microreference (= reference detail) e.g.
1607
 * in Phytotaxa 43: 1-48. 2012.
1608
 *
1609
 * @param string $referenceUuid
1610
 *   UUID of the reference.
1611
 * @param string $microreference
1612
 *   Reference detail.
1613
 *
1614
 * @return string
1615
 *   a NomenclaturalReference.
1616
 */
1617
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1618
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1619
    $referenceUuid,
1620
  ), "microReference=" . urlencode($microreference));
1621

    
1622
  if ($obj) {
1623
    return $obj->String;
1624
  }
1625
  else {
1626
    return NULL;
1627
  }
1628
}
1629

    
1630
/**
1631
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1632
 *
1633
 * @param $feature_tree_nodes
1634
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1635
 * @param $feature_uuid
1636
 *    The UUID of the Feature
1637
 * @return returns the FeatureNode or null
1638
 */
1639
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1640

    
1641
  // 1. scan this level
1642
  foreach ($feature_tree_nodes as $node){
1643
    if($node->feature->uuid == $feature_uuid){
1644
      return $node;
1645
    }
1646
  }
1647

    
1648
  // 2. descend into childen
1649
  foreach ($feature_tree_nodes as $node){
1650
    if(is_array($node->childNodes)){
1651
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1652
      if($node) {
1653
        return $node;
1654
      }
1655
    }
1656
  }
1657
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1658
  return $null_var;
1659
}
1660

    
1661
/**
1662
 * Merges the given featureNodes structure with the descriptionElements.
1663
 *
1664
 * This method is used in preparation for rendering the descriptionElements.
1665
 * The descriptionElements which belong to a specific feature node are appended
1666
 * to a the feature node by creating a new field:
1667
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1668
 * The descriptionElements will be cleared in advance in order to allow reusing the
1669
 * same feature tree without the risk of mixing sets of description elements.
1670
 *
1671
 * which originally is not existing in the cdm.
1672
 *
1673
 *
1674
 *
1675
 * @param array $featureNodes
1676
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1677
 *    may have children.
1678
 * @param array $descriptionElements
1679
 *    An flat array of cdm DescriptionElements
1680
 * @return array
1681
 *    The $featureNodes structure enriched with the according $descriptionElements
1682
 */
1683
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1684

    
1685
  foreach ($featureNodes as &$node) {
1686
    // since the $featureNodes array is reused for each description
1687
    // it is necessary to clear the custom node fields in advance
1688
    if(isset($node->descriptionElements)){
1689
      unset($node->descriptionElements);
1690
    }
1691

    
1692
    // Append corresponding elements to an additional node field:
1693
    // $node->descriptionElements.
1694
    foreach ($descriptionElements as $element) {
1695
      if ($element->feature->uuid == $node->feature->uuid) {
1696
        if (!isset($node->descriptionElements)) {
1697
          $node->descriptionElements = array();
1698
        }
1699
        $node->descriptionElements[] = $element;
1700
      }
1701
    }
1702

    
1703
    // Recurse into node children.
1704
    if (isset($node->childNodes[0])) {
1705
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1706
      $node->childNodes = $mergedChildNodes;
1707
    }
1708

    
1709
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1710
      unset($node);
1711
    }
1712

    
1713
  }
1714

    
1715
  return $featureNodes;
1716
}
1717

    
1718
/**
1719
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1720
 *
1721
 * The response from the HTTP GET request is returned as object.
1722
 * The response objects coming from the webservice configured in the
1723
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1724
 *  in a level 2 (L2) cache.
1725
 *
1726
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1727
 * function, this cache persists only per each single page execution.
1728
 * Any object coming from the webservice is stored into it by default.
1729
 * In contrast to this default caching mechanism the L2 cache only is used if
1730
 * the 'cdm_webservice_cache' variable is set to TRUE,
1731
 * which can be set using the modules administrative settings section.
1732
 * Objects stored in this L2 cache are serialized and stored
1733
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1734
 * objects that are stored in the database will persist as
1735
 * long as the drupal cache is not being cleared and are available across
1736
 * multiple script executions.
1737
 *
1738
 * @param string $uri
1739
 *   URL to the webservice.
1740
 * @param array $pathParameters
1741
 *   An array of path parameters.
1742
 * @param string $query
1743
 *   A query string to be appended to the URL.
1744
 * @param string $method
1745
 *   The HTTP method to use, valid values are "GET" or "POST";
1746
 * @param bool $absoluteURI
1747
 *   TRUE when the URL should be treated as absolute URL.
1748
 *
1749
 * @return object| array
1750
 *   The de-serialized webservice response object.
1751
 */
1752
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1753

    
1754
  static $cacheL1 = array();
1755

    
1756
  $data = NULL;
1757
  // store query string in $data and clear the query, $data will be set as HTTP request body
1758
  if($method == 'POST'){
1759
    $data = $query;
1760
    $query = NULL;
1761
  }
1762

    
1763
  // Transform the given uri path or pattern into a proper webservice uri.
1764
  if (!$absoluteURI) {
1765
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1766
  }
1767

    
1768
  // read request parameter 'cacheL2_refresh'
1769
  // which allows refreshing the level 2 cache
1770
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1771

    
1772
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1773
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1774

    
1775
  if($method == 'GET'){
1776
    $cache_key = $uri;
1777
  } else {
1778
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1779
    // crc32 is faster but creates much shorter hashes
1780
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1781
  }
1782

    
1783
  if (array_key_exists($cache_key, $cacheL1)) {
1784
    $cacheL1_obj = $cacheL1[$uri];
1785
  }
1786

    
1787
  $set_cacheL1 = FALSE;
1788
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1789
    $set_cacheL1 = TRUE;
1790
  }
1791

    
1792
  // Only cache cdm webservice URIs.
1793
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1794
  $cacheL2_entry = FALSE;
1795

    
1796
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1797
    // Try to get object from cacheL2.
1798
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1799
  }
1800

    
1801
  if (isset($cacheL1_obj)) {
1802
    //
1803
    // The object has been found in the L1 cache.
1804
    //
1805
    $obj = $cacheL1_obj;
1806
    if (cdm_debug_block_visible()) {
1807
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1808
    }
1809
  }
1810
  elseif ($cacheL2_entry) {
1811
    //
1812
    // The object has been found in the L2 cache.
1813
    //
1814
    $duration_parse_start = microtime(TRUE);
1815
    $obj = unserialize($cacheL2_entry->data);
1816
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1817

    
1818
    if (cdm_debug_block_visible()) {
1819
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1820
    }
1821
  }
1822
  else {
1823
    //
1824
    // Get the object from the webservice and cache it.
1825
    //
1826
    $duration_fetch_start = microtime(TRUE);
1827
    // Request data from webservice JSON or XML.
1828
    $response = cdm_http_request($uri, $method, $data);
1829
    $response_body = NULL;
1830
    if (isset($response->data)) {
1831
      $response_body = $response->data;
1832
    }
1833
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1834
    $duration_parse_start = microtime(TRUE);
1835

    
1836
    // Parse data and create object.
1837
    $obj = cdm_load_obj($response_body);
1838

    
1839
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1840

    
1841
    if (cdm_debug_block_visible()) {
1842
      if ($obj || $response_body == "[]") {
1843
        $status = 'valid';
1844
      }
1845
      else {
1846
        $status = 'invalid';
1847
      }
1848
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1849
    }
1850
    if ($set_cacheL2) {
1851
      // Store the object in cache L2.
1852
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1853
      // flag serialized is set properly in the cache table.
1854
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1855
    }
1856
  }
1857
  if ($obj) {
1858
    // Store the object in cache L1.
1859
    if ($set_cacheL1) {
1860
      $cacheL1[$cache_key] = $obj;
1861
    }
1862
  }
1863
  return $obj;
1864
}
1865

    
1866
/**
1867
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1868
 *
1869
 * The cdm_ws_debug block will display the debug information.
1870
 *
1871
 * @param $uri
1872
 *    The CDM REST URI to which the request has been send
1873
 * @param string $method
1874
 *    The HTTP request method, either 'GET' or 'POST'
1875
 * @param string $post_data
1876
 *    The datastring send with a post request
1877
 * @param $duration_fetch
1878
 *    The time in seconds it took to fetch the data from the web service
1879
 * @param $duration_parse
1880
 *    Time in seconds which was needed to parse the json response
1881
 * @param $datasize
1882
 *    Size of the data received from the server
1883
 * @param $status
1884
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1885
 * @return bool
1886
 *    TRUE if adding the debug information was successful
1887
 */
1888
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1889

    
1890
  static $initial_time = NULL;
1891
  if(!$initial_time) {
1892
    $initial_time = microtime(TRUE);
1893
  }
1894
  $time = microtime(TRUE) - $initial_time;
1895

    
1896
  // Decompose uri into path and query element.
1897
  $uri_parts = explode("?", $uri);
1898
  $query = array();
1899
  if (count($uri_parts) == 2) {
1900
    $path = $uri_parts[0];
1901
  }
1902
  else {
1903
    $path = $uri;
1904
  }
1905

    
1906
  if(strpos($uri, '?') > 0){
1907
    $json_uri = str_replace('?', '.json?', $uri);
1908
    $xml_uri = str_replace('?', '.xml?', $uri);
1909
  } else {
1910
    $json_uri = $uri . '.json';
1911
    $xml_uri = $json_uri . '.xml';
1912
  }
1913

    
1914
  // data links to make data accecsible as json and xml
1915
  $data_links = '';
1916
  if (_is_cdm_ws_uri($path)) {
1917

    
1918
    // see ./js/http-method-link.js
1919

    
1920
    if($method == 'GET'){
1921
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1922
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1923
      $data_links .= '<br/>';
1924
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1925
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1926
    } else {
1927
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1928
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1929
      $data_links .= '<br/>';
1930
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1931
    }
1932
  }
1933
  else {
1934
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1935
  }
1936

    
1937
  //
1938
  $data = array(
1939
      'ws_uri' => $uri,
1940
      'method' => $method,
1941
      'post_data' => $post_data,
1942
      'time' => sprintf('%3.3f', $time),
1943
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1944
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1945
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1946
      'status' => $status,
1947
      'data_links' => $data_links
1948
  );
1949
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1950
    $_SESSION['cdm']['ws_debug'] = array();
1951
  }
1952
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1953

    
1954
  // Mark this page as being uncacheable.
1955
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1956
  drupal_page_is_cacheable(FALSE);
1957

    
1958
  // Messages not set when DB connection fails.
1959
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1960
}
1961

    
1962
/**
1963
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1964
 * the visibility depends on whether
1965
 *  - the block is enabled
1966
 *  - the visibility restrictions in the block settings are satisfied
1967
 */
1968
function cdm_debug_block_visible() {
1969
  static $is_visible = null;
1970

    
1971
  if($is_visible === null){
1972
      $block = block_load('cdm_api', 'cdm_ws_debug');
1973
      $is_visible = isset($block->status) && $block->status == 1;
1974
      if($is_visible){
1975
        $blocks = array($block);
1976
        // Checks the page, user role, and user-specific visibilty settings.
1977
        block_block_list_alter($blocks);
1978
        $is_visible = count($blocks) > 0;
1979
      }
1980
  }
1981
  return $is_visible;
1982
}
1983

    
1984
/**
1985
 * @todo Please document this function.
1986
 * @see http://drupal.org/node/1354
1987
 */
1988
function cdm_load_obj($response_body) {
1989
  $obj = json_decode($response_body);
1990

    
1991
  if (!(is_object($obj) || is_array($obj))) {
1992
    ob_start();
1993
    $obj_dump = ob_get_contents();
1994
    ob_clean();
1995
    return FALSE;
1996
  }
1997

    
1998
  return $obj;
1999
}
2000

    
2001
/**
2002
 * Do a http request to a CDM RESTful web service.
2003
 *
2004
 * @param string $uri
2005
 *   The webservice url.
2006
 * @param string $method
2007
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2008
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2009
 * @param $data: A string containing the request body, formatted as
2010
 *     'param=value&param=value&...'. Defaults to NULL.
2011
 *
2012
 * @return object
2013
 *   The object as returned by drupal_http_request():
2014
 *   An object that can have one or more of the following components:
2015
 *   - request: A string containing the request body that was sent.
2016
 *   - code: An integer containing the response status code, or the error code
2017
 *     if an error occurred.
2018
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2019
 *   - status_message: The status message from the response, if a response was
2020
 *     received.
2021
 *   - redirect_code: If redirected, an integer containing the initial response
2022
 *     status code.
2023
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2024
 *     target.
2025
 *   - error: If an error occurred, the error message. Otherwise not set.
2026
 *   - headers: An array containing the response headers as name/value pairs.
2027
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2028
 *     easy access the array keys are returned in lower case.
2029
 *   - data: A string containing the response body that was received.
2030
 */
2031
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2032
  static $acceptLanguage = NULL;
2033
  $header = array();
2034
  
2035
  if(!$acceptLanguage && module_exists('i18n')){
2036
    $acceptLanguage = i18n_language_content()->language;
2037
  }
2038

    
2039
  if (!$acceptLanguage) {
2040
    if (function_exists('apache_request_headers')) {
2041
      $headers = apache_request_headers();
2042
      if (isset($headers['Accept-Language'])) {
2043
        $acceptLanguage = $headers['Accept-Language'];
2044
      }
2045
    }
2046
  }
2047

    
2048
  if ($method != "GET" && $method != "POST") {
2049
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2050
  }
2051

    
2052
  if (_is_cdm_ws_uri($uri)) {
2053
    $header['Accept'] = 'application/json';
2054
    $header['Accept-Language'] = $acceptLanguage;
2055
    $header['Accept-Charset'] = 'UTF-8';
2056
  }
2057

    
2058
  if($method == "POST") {
2059
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2060
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2061
  }
2062

    
2063

    
2064
  cdm_dd($uri);
2065
  return drupal_http_request($uri, array(
2066
      'headers' => $header,
2067
      'method' => $method,
2068
      'data' => $data,
2069
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2070
      )
2071
   );
2072
}
2073

    
2074
/**
2075
 * Concatenates recursively the fields of all features contained in the given
2076
 * CDM FeatureTree root node.
2077
 *
2078
 * @param $rootNode
2079
 *     A CDM FeatureTree node
2080
 * @param
2081
 *     The character to be used as glue for concatenation, default is ', '
2082
 * @param $field_name
2083
 *     The field name of the CDM Features
2084
 * @param $excludes
2085
 *     Allows defining a set of values to be excluded. This refers to the values
2086
 *     in the field denoted by the $field_name parameter
2087
 *
2088
 */
2089
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2090
  $out = '';
2091

    
2092
  $pre_child_separator = $separator;
2093
  $post_child_separator = '';
2094

    
2095
  foreach ($root_node->childNodes as $feature_node) {
2096
    $out .= ($out ? $separator : '');
2097
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2098
      $out .= $feature_node->feature->$field_name;
2099
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2100
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2101
        if (strlen($childlabels)) {
2102
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2103
        }
2104
      }
2105
    }
2106
  }
2107
  return $out;
2108
}
2109

    
2110
/**
2111
 * Create a one-dimensional form options array.
2112
 *
2113
 * Creates an array of all features in the feature tree of feature nodes,
2114
 * the node labels are indented by $node_char and $childIndent depending on the
2115
 * hierachy level.
2116
 *
2117
 * @param - $rootNode
2118
 * @param - $node_char
2119
 * @param - $childIndentStr
2120
 * @param - $childIndent
2121
 *   ONLY USED INTERNALLY!
2122
 *
2123
 * @return array
2124
 *   A one dimensional Drupal form options array.
2125
 */
2126
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2127
  $options = array();
2128
  foreach ($rootNode->childNodes as $featureNode) {
2129
    $indent_prefix = '';
2130
    if ($childIndent) {
2131
      $indent_prefix = $childIndent . $node_char . " ";
2132
    }
2133
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2134
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2135
      // Foreach ($featureNode->childNodes as $childNode){
2136
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2137
      $options = array_merge_recursive($options, $childList);
2138
      // }
2139
    }
2140
  }
2141
  return $options;
2142
}
2143

    
2144
/**
2145
 * Returns an array with all available FeatureTrees and the representations of the selected
2146
 * FeatureTree as a detail view.
2147
 *
2148
 * @param boolean $add_default_feature_free
2149
 * @return array
2150
 *  associative array with following keys:
2151
 *  -options: Returns an array with all available Feature Trees
2152
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2153
 *
2154
 */
2155
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2156

    
2157
  $options = array();
2158
  $tree_representations = array();
2159
  $feature_trees = array();
2160

    
2161
  // Set tree that contains all features.
2162
  if ($add_default_feature_free) {
2163
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2164
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2165
  }
2166

    
2167
  // Get feature trees from database.
2168
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2169
  if (is_array($persited_trees)) {
2170
    $feature_trees = array_merge($feature_trees, $persited_trees);
2171
  }
2172

    
2173
  foreach ($feature_trees as $featureTree) {
2174

    
2175
    if(!is_object($featureTree)){
2176
      continue;
2177
    }
2178
    // Do not add the DEFAULT_FEATURETREE again,
2179
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2180
      $options[$featureTree->uuid] = $featureTree->titleCache;
2181
    }
2182

    
2183
    // Render the hierarchic tree structure
2184
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2185

    
2186
      // Render the hierarchic tree structure.
2187
      $treeDetails = '<div class="featuretree_structure">'
2188
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2189
        . '</div>';
2190

    
2191
      $form = array();
2192
      $form['featureTree-' .  $featureTree->uuid] = array(
2193
        '#type' => 'fieldset',
2194
        '#title' => 'Show details',
2195
        '#attributes' => array('class' => array('collapsible collapsed')),
2196
        // '#collapsible' => TRUE,
2197
        // '#collapsed' => TRUE,
2198
      );
2199
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2200
        '#markup' => $treeDetails,
2201
      );
2202

    
2203
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2204
    }
2205

    
2206
  } // END loop over feature trees
2207

    
2208
  // return $options;
2209
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2210
}
2211

    
2212
/**
2213
 * Provides the list of availbale classifications in form of an options array.
2214
 *
2215
 * The options array is suitable for drupal form API elements that allow multiple choices.
2216
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2217
 *
2218
 * The classifications are ordered alphabetically whereas the classification
2219
 * chosen as default will always appear on top of the array, followed by a
2220
 * blank line below.
2221
 *
2222
 * @param bool $add_none_option
2223
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2224
 *
2225
 * @return array
2226
 *   classifications in an array as options for a form element that allows multiple choices.
2227
 */
2228
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2229

    
2230
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2231

    
2232
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2233
  $default_classification_label = '';
2234

    
2235
  // add all classifications
2236
  $taxonomic_tree_options = array();
2237
  if ($add_none_option) {
2238
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2239
  }
2240
  if ($taxonTrees) {
2241
    foreach ($taxonTrees as $tree) {
2242
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2243
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2244
      } else {
2245
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2246
        $default_classification_label = $tree->titleCache;
2247
      }
2248
    }
2249
  }
2250
  // oder alphabetically the space
2251
  asort($taxonomic_tree_options);
2252

    
2253
  // now set the labels
2254
  //   for none
2255
  if ($add_none_option) {
2256
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2257
  }
2258

    
2259
  //   for default_classification
2260
  if (is_uuid($default_classification_uuid)) {
2261
    $taxonomic_tree_options[$default_classification_uuid] =
2262
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2263
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2264
  }
2265

    
2266
  return $taxonomic_tree_options;
2267
}
2268

    
2269
/**
2270
 * @todo Please document this function.
2271
 * @see http://drupal.org/node/1354
2272
 */
2273
function cdm_api_secref_cache_prefetch(&$secUuids) {
2274
  // Comment @WA: global variables should start with a single underscore
2275
  // followed by the module and another underscore.
2276
  global $_cdm_api_secref_cache;
2277
  if (!is_array($_cdm_api_secref_cache)) {
2278
    $_cdm_api_secref_cache = array();
2279
  }
2280
  $uniqueUuids = array_unique($secUuids);
2281
  $i = 0;
2282
  $param = '';
2283
  while ($i++ < count($uniqueUuids)) {
2284
    $param .= $secUuids[$i] . ',';
2285
    if (strlen($param) + 37 > 2000) {
2286
      _cdm_api_secref_cache_add($param);
2287
      $param = '';
2288
    }
2289
  }
2290
  if ($param) {
2291
    _cdm_api_secref_cache_add($param);
2292
  }
2293
}
2294

    
2295
/**
2296
 * @todo Please document this function.
2297
 * @see http://drupal.org/node/1354
2298
 */
2299
function cdm_api_secref_cache_get($secUuid) {
2300
  global $_cdm_api_secref_cache;
2301
  if (!is_array($_cdm_api_secref_cache)) {
2302
    $_cdm_api_secref_cache = array();
2303
  }
2304
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2305
    _cdm_api_secref_cache_add($secUuid);
2306
  }
2307
  return $_cdm_api_secref_cache[$secUuid];
2308
}
2309

    
2310
/**
2311
 * @todo Please document this function.
2312
 * @see http://drupal.org/node/1354
2313
 */
2314
function cdm_api_secref_cache_clear() {
2315
  global $_cdm_api_secref_cache;
2316
  $_cdm_api_secref_cache = array();
2317
}
2318

    
2319

    
2320
/**
2321
 * Validates if the given string is a uuid.
2322
 *
2323
 * @param string $str
2324
 *   The string to validate.
2325
 *
2326
 * return bool
2327
 *   TRUE if the string is a UUID.
2328
 */
2329
function is_uuid($str) {
2330
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2331
}
2332

    
2333
/**
2334
 * Checks if the given $object is a valid cdm entity.
2335
 *
2336
 * An object is considered a cdm entity if it has a string field $object->class
2337
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2338
 * The function is null save.
2339
 *
2340
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2341
 *
2342
 * @param mixed $object
2343
 *   The object to validate
2344
 *
2345
 * @return bool
2346
 *   True if the object is a cdm entity.
2347
 */
2348
function is_cdm_entity($object) {
2349
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2350
}
2351

    
2352
/**
2353
 * @todo Please document this function.
2354
 * @see http://drupal.org/node/1354
2355
 */
2356
function _cdm_api_secref_cache_add($secUuidsStr) {
2357
  global $_cdm_api_secref_cache;
2358
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2359
  // Batch fetching not jet reimplemented thus:
2360
  /*
2361
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2362
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2363
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2364
  */
2365
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2366
}
2367

    
2368
/**
2369
 * Checks if the given uri starts with a cdm webservice url.
2370
 *
2371
 * Checks if the uri starts with the cdm webservice url stored in the
2372
 * Drupal variable 'cdm_webservice_url'.
2373
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2374
 *
2375
 * @param string $uri
2376
 *   The URI to test.
2377
 *
2378
 * @return bool
2379
 *   True if the uri starts with a cdm webservice url.
2380
 */
2381
function _is_cdm_ws_uri($uri) {
2382
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2383
}
2384

    
2385
/**
2386
 * @todo Please document this function.
2387
 * @see http://drupal.org/node/1354
2388
 */
2389
function queryString($elements) {
2390
  $query = '';
2391
  foreach ($elements as $key => $value) {
2392
    if (is_array($value)) {
2393
      foreach ($value as $v) {
2394
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2395
      }
2396
    }
2397
    else {
2398
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2399
    }
2400
  }
2401
  return $query;
2402
}
2403

    
2404
/**
2405
 * Implementation of the magic method __clone to allow deep cloning of objects
2406
 * and arrays.
2407
 */
2408
function __clone() {
2409
  foreach ($this as $name => $value) {
2410
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2411
      $this->$name = clone($this->$name);
2412
    }
2413
  }
2414
}
2415

    
2416
/**
2417
 * Compares the given CDM Term instances by the  representationL10n.
2418
 *
2419
 * Can also be used with TermDTOs. To be used in usort()
2420
 *
2421
 * @see http://php.net/manual/en/function.usort.php
2422
 *
2423
 * @param $term1
2424
 *   The first CDM Term instance
2425
 * @param $term2
2426
 *   The second CDM Term instance
2427
 * @return int
2428
 *   The result of the comparison
2429
 */
2430
function compare_terms_by_representationL10n($term1, $term2) {
2431

    
2432
  if (!isset($term1->representation_L10n)) {
2433
    $term1->representationL10n = '';
2434
  }
2435
  if (!isset($term2->representation_L10n)) {
2436
    $term2->representationL10n = '';
2437
  }
2438

    
2439
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2440
}
2441

    
2442

    
2443
/**
2444
 * Make a 'deep copy' of an array.
2445
 *
2446
 * Make a complete deep copy of an array replacing
2447
 * references with deep copies until a certain depth is reached
2448
 * ($maxdepth) whereupon references are copied as-is...
2449
 *
2450
 * @see http://us3.php.net/manual/en/ref.array.php
2451
 *
2452
 * @param array $array
2453
 * @param array $copy passed by reference
2454
 * @param int $maxdepth
2455
 * @param int $depth
2456
 */
2457
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2458
  if ($depth > $maxdepth) {
2459
    $copy = $array;
2460
    return;
2461
  }
2462
  if (!is_array($copy)) {
2463
    $copy = array();
2464
  }
2465
  foreach ($array as $k => &$v) {
2466
    if (is_array($v)) {
2467
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2468
    }
2469
    else {
2470
      $copy[$k] = $v;
2471
    }
2472
  }
2473
}
2474

    
2475
/**
2476
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2477
 *
2478
 */
2479
function _add_js_ws_debug() {
2480

    
2481
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2482
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2483
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2484
    // use the developer versions of js libs
2485
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2486
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2487
  }
2488
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2489
    array(
2490
      'type' => 'file',
2491
      'weight' => JS_LIBRARY,
2492
      'cache' => TRUE)
2493
    );
2494

    
2495
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2496
    array(
2497
      'type' => 'file',
2498
      'weight' => JS_LIBRARY,
2499
      'cache' => TRUE)
2500
    );
2501
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2502
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2503

    
2504
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2505
    array(
2506
      'type' => 'file',
2507
      'weight' => JS_LIBRARY,
2508
      'cache' => TRUE)
2509
    );
2510
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2511
    array(
2512
    'type' => 'file',
2513
    'weight' => JS_LIBRARY,
2514
    'cache' => TRUE)
2515
    );
2516

    
2517
}
2518

    
2519
/**
2520
 * @todo Please document this function.
2521
 * @see http://drupal.org/node/1354
2522
 */
2523
function _no_classfication_uuid_message() {
2524
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2525
    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.');
2526
  }
2527
  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.');
2528
}
2529

    
2530
/**
2531
 * Implementation of hook flush_caches
2532
 *
2533
 * Add custom cache tables to the list of cache tables that
2534
 * will be cleared by the Clear button on the Performance page or whenever
2535
 * drupal_flush_all_caches is invoked.
2536
 *
2537
 * @author W.Addink <waddink@eti.uva.nl>
2538
 *
2539
 * @return array
2540
 *   An array with custom cache tables to include.
2541
 */
2542
function cdm_api_flush_caches() {
2543
  return array('cache_cdm_ws');
2544
}
2545

    
2546
/**
2547
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2548
 *
2549
 * @param $data
2550
 *   The variable to log to the drupal_debug.txt log file.
2551
 * @param $label
2552
 *   (optional) If set, a label to output before $data in the log file.
2553
 *
2554
 * @return
2555
 *   No return value if successful, FALSE if the log file could not be written
2556
 *   to.
2557
 *
2558
 * @see cdm_dataportal_init() where the log file is reset on each requests
2559
 * @see dd()
2560
 * @see http://drupal.org/node/314112
2561
 *
2562
 */
2563
function cdm_dd($data, $label = NULL) {
2564
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2565
    return dd($data, $label);
2566
  }
2567
}
2568

    
(5-5/11)