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

    
221

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

    
236
  if (is_array($taggedTextList)) {
237

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

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

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

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

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

    
267
function split_secref_from_tagged_text(&$tagged_text) {
268

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

    
284

    
285
function split_nomstatus_from_tagged_text(&$tagged_text) {
286

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

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

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

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

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

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

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

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

    
372
  return $profile_featureTree;
373
}
374

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
687
  $date = '';
688

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

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

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

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

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

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

    
787
  $request_params = '';
788
  $path_params = '';
789

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

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

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

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

    
831
  $path = $uri_pattern;
832

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

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

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

    
863
  $post_data = null;
864

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

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

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

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

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

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

    
913
    $reponse_data = NULL;
914

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

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

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

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

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

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

    
973

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

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

    
984
}
985

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1230
    $response = NULL;
1231

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

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

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

    
1259
  return $response;
1260
}
1261

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

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

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

    
1305
  return $response;
1306
}
1307

    
1308

    
1309
// =============================Terms and Vocabularies ========================================= //
1310

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

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

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

    
1385
  return $options;
1386
}
1387

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

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

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

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

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

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

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

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

    
1512

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

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

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

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

    
1549
  return $feature_tree;
1550
}
1551

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

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

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

    
1589
}
1590

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

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

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

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

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

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

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

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

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

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

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

    
1717
  }
1718

    
1719
  return $featureNodes;
1720
}
1721

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

    
1758
  static $cacheL1 = array();
1759

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2002
  return $obj;
2003
}
2004

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

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

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

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

    
2067

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

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

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

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

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

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

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

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

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

    
2177
  foreach ($feature_trees as $featureTree) {
2178

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

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

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

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

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

    
2210
  } // END loop over feature trees
2211

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

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

    
2234
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2235

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

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

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

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

    
2270
  return $taxonomic_tree_options;
2271
}
2272

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

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

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

    
2323

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

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

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

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

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

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

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

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

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

    
2446

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

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

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

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

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

    
2521
}
2522

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

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

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

    
(5-5/11)