Project

General

Profile

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

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

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

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

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

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

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

    
65
  return $items;
66
}
67

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

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

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

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

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

    
99

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

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

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

    
110
      $data = unserialize($data);
111

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

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

    
127
    _add_js_ws_debug();
128

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

    
140
    return $block;
141
  }
142
}
143

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

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

    
166
// ===================== 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
  $request_params = '';
789
  $path_params = '';
790

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

    
800
  $i = 0;
801
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
802
    if (count($pathParameters) <= $i) {
803
      if (module_exists("user") && user_access('administer')) {
804
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
805
      }
806
      break;
807
    }
808
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
809
    ++$i;
810
  }
811

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

    
826
  // (3)
827
  // Append the query string supplied by $query.
828
  if (isset($query)) {
829
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
830
  }
831

    
832
  $path = $uri_pattern;
833

    
834
  $uri = variable_get('cdm_webservice_url', '') . $path;
835
  return $uri;
836
}
837

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

    
857
  $args = func_get_args();
858
  $do_gzip = function_exists('gzencode');
859
  $uriEncoded = array_shift($args);
860
  $uri = urldecode($uriEncoded);
861
  $hook = array_shift($args);
862
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
863

    
864
  $post_data = null;
865

    
866
  if ($request_method == "POST" || $request_method == "PUT") {
867
    // read response body via inputstream module
868
    $post_data = file_get_contents("php://input");
869
  }
870

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

    
880
  // In all these cases perform a simple get request.
881
  // TODO reconsider caching logic in this function.
882

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

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

    
912
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
913

    
914
    $reponse_data = NULL;
915

    
916
    if (function_exists('compose_' . $hook)){
917
      // call compose hook
918

    
919
      $elements =  call_user_func('compose_' . $hook, $obj);
920
      // pass the render array to drupal_render()
921
      $reponse_data = drupal_render($elements);
922
    } else {
923
      // call theme hook
924

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

    
939
        case 'cdm_list_of_taxa':
940
            $variables = array(
941
              'records' => $obj,
942
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
943
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
944
            $reponse_data = theme($hook, $variables);
945
            break;
946

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

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

    
974

    
975
    if($do_gzip){
976
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
977
      drupal_add_http_header('Content-Encoding', 'gzip');
978
    }
979
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
980
    drupal_add_http_header('Content-Length', strlen($reponse_data));
981

    
982
    print $reponse_data;
983
  } // END of handle $hook either as compose ot theme hook
984

    
985
}
986

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

    
1001
  // Prevent from malicous tags.
1002
  $val = strip_tags($val);
1003

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

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

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

    
1042
  $ws_base_uri = NULL;
1043
  switch ($cdmBase->class) {
1044
    case 'TaxonBase':
1045
    case 'Taxon':
1046
    case 'Synonym':
1047
      $ws_base_uri = CDM_WS_TAXON;
1048
      break;
1049

    
1050
    case 'TaxonNameBase':
1051
    case 'NonViralName':
1052
    case 'BacterialName':
1053
    case 'BotanicalName':
1054
    case 'CultivarPlantName':
1055
    case 'ZoologicalName':
1056
    case 'ViralName':
1057
      $ws_base_uri = CDM_WS_NAME;
1058
      break;
1059

    
1060
    case 'Media':
1061
      $ws_base_uri = CDM_WS_MEDIA;
1062
      break;
1063

    
1064
    case 'Reference':
1065
      $ws_base_uri = CDM_WS_REFERENCE;
1066
      break;
1067

    
1068
    case 'Distribution':
1069
    case 'TextData':
1070
    case 'TaxonInteraction':
1071
    case 'QuantitativeData':
1072
    case 'IndividualsAssociation':
1073
    case 'Distribution':
1074
    case 'CommonTaxonName':
1075
    case 'CategoricalData':
1076
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1077
      break;
1078

    
1079
    case 'PolytomousKey':
1080
    case 'MediaKey':
1081
    case 'MultiAccessKey':
1082
      $ws_base_uri = $cdmBase->class;
1083
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1084
      break;
1085

    
1086
    default:
1087
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1088
      return;
1089
  }
1090
  return cdm_compose_url($ws_base_uri, array(
1091
    $cdmBase->uuid,
1092
    'annotations',
1093
  ));
1094
}
1095

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

    
1120
  $query['pageNumber'] = $pageNumber;
1121
  $query['pageSize'] = $pageSize;
1122

    
1123
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1124
}
1125

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

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

    
1163
/*
1164
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1165
  $viewrank = _cdm_taxonomy_compose_viewrank();
1166
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1167
  ? '/' . $path : '') ;
1168
}
1169
*/
1170

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

    
1183
  $view_uuid = get_current_classification_uuid();
1184
  $rank_uuid = NULL;
1185
  if (!$ignore_rank_limit) {
1186
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1187
  }
1188

    
1189
  if (!empty($taxon_uuid)) {
1190
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1191
      $view_uuid,
1192
      $taxon_uuid,
1193
    ));
1194
  }
1195
  else {
1196
    if (!empty($rank_uuid)) {
1197
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1198
        $view_uuid,
1199
        $rank_uuid,
1200
      ));
1201
    }
1202
    else {
1203
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1204
        $view_uuid,
1205
      ));
1206
    }
1207
  }
1208
}
1209

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

    
1231
    $response = NULL;
1232

    
1233
    // 1st try
1234
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1235

    
1236
    if ($response == NULL) {
1237
      // 2dn try by ignoring the rank limit
1238
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1239
    }
1240

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

    
1260
  return $response;
1261
}
1262

    
1263
/**
1264
 * @todo Enter description here...
1265
 *
1266
 * @param string $taxon_uuid
1267
 *
1268
 * @return unknown
1269
 */
1270
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1271
  $view_uuid = get_current_classification_uuid();
1272
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1273

    
1274
  $response = NULL;
1275
  if ($rank_uuid) {
1276
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1277
      $view_uuid,
1278
      $taxon_uuid,
1279
      $rank_uuid,
1280
    ));
1281
  }
1282
  else {
1283
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1284
      $view_uuid,
1285
      $taxon_uuid,
1286
    ));
1287
  }
1288

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

    
1306
  return $response;
1307
}
1308

    
1309

    
1310
// =============================Terms and Vocabularies ========================================= //
1311

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

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

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

    
1386
  return $options;
1387
}
1388

    
1389
/**
1390
 * @todo Please document this function.
1391
 * @see http://drupal.org/node/1354
1392
 */
1393
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL, $default_option = FALSE, $sort_by = SORT_ORDER_ID) {
1394
  static $vocabularyOptions = array();
1395

    
1396
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1397
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabularyUuid . '/terms');
1398
    $vocabularyOptions[$vocabularyUuid] = cdm_terms_as_options($terms, $sort_by, $term_label_callback);
1399
  }
1400

    
1401
  $options = $vocabularyOptions[$vocabularyUuid];
1402
  if($default_option !== FALSE){
1403
    array_unshift ($options, "");
1404
  }
1405
  return $options;
1406
}
1407

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

    
1453
/**
1454
 * @todo Please document this function.
1455
 * @see http://drupal.org/node/1354
1456
 */
1457
function cdm_rankVocabulary_as_option() {
1458
  $options = cdm_Vocabulary_as_option(UUID_RANK, NULL, "");
1459
  return $options;
1460
}
1461

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

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

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

    
1513

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

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

    
1538
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1539
      array(
1540
      'taxon' => $taxon_uuid,
1541
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1542
      ),
1543
      'POST'
1544
  );
1545

    
1546
  // Combine all descriptions into one feature tree.
1547
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1548
  $feature_tree->root->childNodes = $merged_nodes;
1549

    
1550
  return $feature_tree;
1551
}
1552

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

    
1569
  if(!isset($cdmBase->annotations)){
1570
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1571
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1572
  }
1573

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

    
1590
}
1591

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

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

    
1627
  if ($obj) {
1628
    return $obj->String;
1629
  }
1630
  else {
1631
    return NULL;
1632
  }
1633
}
1634

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

    
1646
  // 1. scan this level
1647
  foreach ($feature_tree_nodes as $node){
1648
    if($node->feature->uuid == $feature_uuid){
1649
      return $node;
1650
    }
1651
  }
1652

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

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

    
1690
  foreach ($featureNodes as &$node) {
1691
    // since the $featureNodes array is reused for each description
1692
    // it is necessary to clear the custom node fields in advance
1693
    if(isset($node->descriptionElements)){
1694
      unset($node->descriptionElements);
1695
    }
1696

    
1697
    // Append corresponding elements to an additional node field:
1698
    // $node->descriptionElements.
1699
    foreach ($descriptionElements as $element) {
1700
      if ($element->feature->uuid == $node->feature->uuid) {
1701
        if (!isset($node->descriptionElements)) {
1702
          $node->descriptionElements = array();
1703
        }
1704
        $node->descriptionElements[] = $element;
1705
      }
1706
    }
1707

    
1708
    // Recurse into node children.
1709
    if (isset($node->childNodes[0])) {
1710
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1711
      $node->childNodes = $mergedChildNodes;
1712
    }
1713

    
1714
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1715
      unset($node);
1716
    }
1717

    
1718
  }
1719

    
1720
  return $featureNodes;
1721
}
1722

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

    
1759
  static $cacheL1 = array();
1760

    
1761
  $data = NULL;
1762
  // store query string in $data and clear the query, $data will be set as HTTP request body
1763
  if($method == 'POST'){
1764
    $data = $query;
1765
    $query = NULL;
1766
  }
1767

    
1768
  // Transform the given uri path or pattern into a proper webservice uri.
1769
  if (!$absoluteURI) {
1770
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1771
  }
1772

    
1773
  // read request parameter 'cacheL2_refresh'
1774
  // which allows refreshig the level 2 cache
1775
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1776

    
1777
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1778
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1779

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

    
1788
  if (array_key_exists($cache_key, $cacheL1)) {
1789
    $cacheL1_obj = $cacheL1[$uri];
1790
  }
1791

    
1792
  $set_cacheL1 = FALSE;
1793
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1794
    $set_cacheL1 = TRUE;
1795
  }
1796

    
1797
  // Only cache cdm webservice URIs.
1798
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1799
  $cacheL2_entry = FALSE;
1800

    
1801
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1802
    // Try to get object from cacheL2.
1803
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1804
  }
1805

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

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

    
1841
    // Parse data and create object.
1842
    $obj = cdm_load_obj($response_body);
1843

    
1844
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1845

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

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

    
1895
  static $initial_time = NULL;
1896
  if(!$initial_time) {
1897
    $initial_time = microtime(TRUE);
1898
  }
1899
  $time = microtime(TRUE) - $initial_time;
1900

    
1901
  // Decompose uri into path and query element.
1902
  $uri_parts = explode("?", $uri);
1903
  $query = array();
1904
  if (count($uri_parts) == 2) {
1905
    $path = $uri_parts[0];
1906
  }
1907
  else {
1908
    $path = $uri;
1909
  }
1910

    
1911
  if(strpos($uri, '?') > 0){
1912
    $json_uri = str_replace('?', '.json?', $uri);
1913
    $xml_uri = str_replace('?', '.xml?', $uri);
1914
  } else {
1915
    $json_uri = $uri . '.json';
1916
    $xml_uri = $json_uri . '.xml';
1917
  }
1918

    
1919
  // data links to make data accecsible as json and xml
1920
  $data_links = '';
1921
  if (_is_cdm_ws_uri($path)) {
1922

    
1923
    // see ./js/http-method-link.js
1924

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

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

    
1959
  // Mark this page as being uncacheable.
1960
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1961
  drupal_page_is_cacheable(FALSE);
1962

    
1963
  // Messages not set when DB connection fails.
1964
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1965
}
1966

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

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

    
1989
/**
1990
 * @todo Please document this function.
1991
 * @see http://drupal.org/node/1354
1992
 */
1993
function cdm_load_obj($response_body) {
1994
  $obj = json_decode($response_body);
1995

    
1996
  if (!(is_object($obj) || is_array($obj))) {
1997
    ob_start();
1998
    $obj_dump = ob_get_contents();
1999
    ob_clean();
2000
    return FALSE;
2001
  }
2002

    
2003
  return $obj;
2004
}
2005

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

    
2040
  if (!$acceptLanguage) {
2041
    if (function_exists('apache_request_headers')) {
2042
      $headers = apache_request_headers();
2043
      if (isset($headers['Accept-Language'])) {
2044
        $acceptLanguage = $headers['Accept-Language'];
2045
      }
2046
    }
2047
    if (!$acceptLanguage) {
2048
      // DEFAULT TODO make configurable.
2049
      $acceptLanguage = "en";
2050
    }
2051
  }
2052

    
2053
  if ($method != "GET" && $method != "POST") {
2054
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2055
  }
2056

    
2057
  if (_is_cdm_ws_uri($uri)) {
2058
    $header['Accept'] = 'application/json';
2059
    $header['Accept-Language'] = $acceptLanguage;
2060
    $header['Accept-Charset'] = 'UTF-8';
2061
  }
2062

    
2063
  if($method == "POST") {
2064
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2065
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2066
  }
2067

    
2068

    
2069
  cdm_dd($uri);
2070
  return drupal_http_request($uri, array(
2071
      'headers' => $header,
2072
      'method' => $method,
2073
      'data' => $data,
2074
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2075
      )
2076
   );
2077
}
2078

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

    
2097
  $pre_child_separator = $separator;
2098
  $post_child_separator = '';
2099

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

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

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

    
2162
  $options = array();
2163
  $tree_representations = array();
2164
  $feature_trees = array();
2165

    
2166
  // Set tree that contains all features.
2167
  if ($add_default_feature_free) {
2168
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2169
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2170
  }
2171

    
2172
  // Get feature trees from database.
2173
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2174
  if (is_array($persited_trees)) {
2175
    $feature_trees = array_merge($feature_trees, $persited_trees);
2176
  }
2177

    
2178
  foreach ($feature_trees as $featureTree) {
2179

    
2180
    if(!is_object($featureTree)){
2181
      continue;
2182
    }
2183
    // Do not add the DEFAULT_FEATURETREE again,
2184
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2185
      $options[$featureTree->uuid] = $featureTree->titleCache;
2186
    }
2187

    
2188
    // Render the hierarchic tree structure
2189
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2190

    
2191
      // Render the hierarchic tree structure.
2192
      $treeDetails = '<div class="featuretree_structure">'
2193
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2194
        . '</div>';
2195

    
2196
      $form = array();
2197
      $form['featureTree-' .  $featureTree->uuid] = array(
2198
        '#type' => 'fieldset',
2199
        '#title' => 'Show details',
2200
        '#attributes' => array('class' => array('collapsible collapsed')),
2201
        // '#collapsible' => TRUE,
2202
        // '#collapsed' => TRUE,
2203
      );
2204
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2205
        '#markup' => $treeDetails,
2206
      );
2207

    
2208
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2209
    }
2210

    
2211
  } // END loop over feature trees
2212

    
2213
  // return $options;
2214
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2215
}
2216

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

    
2235
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2236

    
2237
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2238
  $default_classification_label = '';
2239

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

    
2258
  // now set the labels
2259
  //   for none
2260
  if ($add_none_option) {
2261
    $taxonomic_tree_options['NONE'] = '-- ' . t('ALL (incl. w/o classification)') . ' --';
2262
  }
2263

    
2264
  //   for default_classification
2265
  if (is_uuid($default_classification_uuid)) {
2266
    $taxonomic_tree_options[$default_classification_uuid] =
2267
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2268
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2269
  }
2270

    
2271
  return $taxonomic_tree_options;
2272
}
2273

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

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

    
2315
/**
2316
 * @todo Please document this function.
2317
 * @see http://drupal.org/node/1354
2318
 */
2319
function cdm_api_secref_cache_clear() {
2320
  global $_cdm_api_secref_cache;
2321
  $_cdm_api_secref_cache = array();
2322
}
2323

    
2324

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

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

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

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

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

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

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

    
2437
  if (!isset($term1->representation_L10n)) {
2438
    $term1->representationL10n = '';
2439
  }
2440
  if (!isset($term2->representation_L10n)) {
2441
    $term2->representationL10n = '';
2442
  }
2443

    
2444
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2445
}
2446

    
2447

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

    
2480
/**
2481
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2482
 *
2483
 */
2484
function _add_js_ws_debug() {
2485

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

    
2500
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2501
    array(
2502
      'type' => 'file',
2503
      'weight' => JS_LIBRARY,
2504
      'cache' => TRUE)
2505
    );
2506
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2507
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2508

    
2509
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2510
    array(
2511
      'type' => 'file',
2512
      'weight' => JS_LIBRARY,
2513
      'cache' => TRUE)
2514
    );
2515
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2516
    array(
2517
    'type' => 'file',
2518
    'weight' => JS_LIBRARY,
2519
    'cache' => TRUE)
2520
    );
2521

    
2522
}
2523

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

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

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

    
(5-5/11)