Project

General

Profile

Download (78.5 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
  module_load_include('inc', 'cdm_api', 'tagged_text');
31

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

    
41

    
42

    
43
/**
44
 * orderBy webservice query parameter value
45
 */
46
define('CDM_ORDER_BY_ID_ASC', 'BY_ID_ASC');
47

    
48
/**
49
 * orderBy webservice query parameter value
50
 */
51
define('CDM_ORDER_BY_ID_DESC', 'BY_ID_DESC');
52
/**
53
 * orderBy webservice query parameter value
54
 */
55
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'BY_TITLE_CACHE_ASC');
56
/**
57
 * orderBy webservice query parameter value
58
 */
59
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'BY_TITLE_CACHE_DESC');
60
/**
61
 * orderBy webservice query parameter value
62
 */
63
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_ASC', 'BY_NOMENCLATURAL_ORDER_ASC');
64
/**
65
 * orderBy webservice query parameter value
66
 */
67
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_DESC', 'BY_NOMENCLATURAL_ORDER_DESC');
68
/**
69
 * orderBy webservice query parameter value
70
 */
71
define('CDM_ORDER_BY_ORDER_INDEX_ASC', 'BY_ORDER_INDEX_ASC');
72
/**
73
 * orderBy webservice query parameter value
74
 */
75
define('CDM_ORDER_BY_ORDER_INDEX_DESC', 'BY_ORDER_INDEX_DESC');
76

    
77

    
78
/**
79
 * Implements hook_menu().
80
 */
81
function cdm_api_menu() {
82
  $items = array();
83

    
84
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
85
  $items['cdm_api/proxy'] = array(
86
    'page callback' => 'proxy_content',
87
    'access arguments' => array(
88
      'access cdm content',
89
    ),
90
    'type' => MENU_CALLBACK,
91
  );
92

    
93
  $items['cdm_api/setvalue/session'] = array(
94
    'page callback' => 'setvalue_session',
95
    'access arguments' => array(
96
      'access cdm content',
97
    ),
98
    'type' => MENU_CALLBACK,
99
  );
100

    
101
  return $items;
102
}
103

    
104
/**
105
 * Implements hook_block_info().
106
 */
107
function cdm_api_block_info() {
108

    
109
  $block['cdm_ws_debug'] = array(
110
      "info" => t("CDM web service debug"),
111
      "cache" => DRUPAL_NO_CACHE
112
  );
113
  return $block;
114
}
115

    
116
/**
117
 * Implements hook_block_view().
118
 */
119
function cdm_api_block_view($delta) {
120
  switch ($delta) {
121
    case 'cdm_ws_debug':
122

    
123
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
124

    
125
    $field_map = array(
126
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
127
        'time' => t('Time'),
128
        'fetch_seconds' => t('Fetching [s]'),
129
        'parse_seconds' => t('Parsing [s]'),
130
        'size_kb' => t('Size [kb]'),
131
        'status' => t('Status'),
132
        'data_links' =>  t('Links'),
133
    );
134

    
135

    
136
    if (!isset($_SESSION['cdm']['ws_debug'])) {
137
      $_SESSION['cdm']['ws_debug'] = array();
138
    }
139

    
140
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
141
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
142
    $rows = array();
143

    
144
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
145

    
146
      $data = unserialize($data);
147

    
148
      // stip of webservice base url
149
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
150
      if($data['method'] == 'POST'){
151
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
152
      }
153

    
154
      $cells = array();
155
      foreach ($field_map as $field => $label){
156
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
157
      }
158
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
159
    }
160
    // clear session again
161
    $_SESSION['cdm']['ws_debug'] = array();
162

    
163
    _add_js_ws_debug();
164

    
165
    $block['subject'] = ''; // no subject, title in content for having a defined element id
166
    // otherwise it would depend on the theme
167
    $block['content'] = array(
168
      '#markup' => '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
169
        // cannot use theme_table() since table footer is not jet supported in D7
170
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
171
        . $header
172
        . '<tbody>' . join('', $rows) . '</tbody>'
173
        . $footer
174
        . '</table></div>',
175
      '#attached' => array(
176
        'css' => array(
177
          drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_ws_debug.css'
178
        )
179
      )
180
    );
181
    return $block;
182
  }
183
}
184

    
185
/**
186
 * Implements hook_cron().
187
 *
188
 * Expire outdated cache entries.
189
 */
190
function cdm_api_cron() {
191
  cache_clear_all(NULL, 'cache_cdm_ws');
192
}
193

    
194
/**
195
 * Lists the classifications a taxon belongs to
196
 *
197
 * @param CDM type Taxon $taxon
198
 *   the taxon
199
 *
200
 * @return array
201
 *   aray of CDM instances of Type Classification
202
 */
203
function get_classifications_for_taxon($taxon) {
204

    
205
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
206
}
207

    
208
/**
209
 * Returns the chosen FeatureTree for the taxon profile.
210
 *
211
 * The FeatureTree profile returned is the one that has been set in the
212
 * dataportal settings (layout->taxon:profile).
213
 * When the chosen FeatureTree is not found in the database,
214
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
215
 *
216
 * @return mixed
217
 *   A cdm FeatureTree object.
218
 */
219
function get_profile_feature_tree() {
220
  static $profile_featureTree;
221

    
222
  if($profile_featureTree == NULL) {
223
    $profile_featureTree = cdm_ws_get(
224
      CDM_WS_FEATURETREE,
225
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
226
    );
227
    if (!$profile_featureTree) {
228
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
229
    }
230
  }
231

    
232
  return $profile_featureTree;
233
}
234

    
235
/**
236
 * Returns the chosen FeatureTree for SpecimenDescriptions.
237
 *
238
 * The FeatureTree returned is the one that has been set in the
239
 * dataportal settings (layout->taxon:specimen).
240
 * When the chosen FeatureTree is not found in the database,
241
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
242
 *
243
 * @return mixed
244
 *   A cdm FeatureTree object.
245
 */
246
function cdm_get_occurrence_featureTree() {
247
  static $occurrence_featureTree;
248

    
249
  if($occurrence_featureTree == NULL) {
250
    $occurrence_featureTree = cdm_ws_get(
251
      CDM_WS_FEATURETREE,
252
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
253
    );
254
    if (!$occurrence_featureTree) {
255
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
256
    }
257
  }
258
  return $occurrence_featureTree;
259
}
260

    
261
/**
262
 * Returns the FeatureTree for structured descriptions
263
 *
264
 * The FeatureTree returned is the one that has been set in the
265
 * dataportal settings (layout->taxon:profile).
266
 * When the chosen FeatureTree is not found in the database,
267
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
268
 *
269
 * @return mixed
270
 *   A cdm FeatureTree object.
271
 */
272
function get_structured_description_featureTree() {
273
  static $structured_description_featureTree;
274

    
275
  if($structured_description_featureTree == NULL) {
276
    $structured_description_featureTree = cdm_ws_get(
277
        CDM_WS_FEATURETREE,
278
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
279
    );
280
    if (!$structured_description_featureTree) {
281
      $structured_description_featureTree = cdm_ws_get(
282
          CDM_WS_FEATURETREE,
283
          UUID_DEFAULT_FEATURETREE
284
      );
285
    }
286
  }
287
  return $structured_description_featureTree;
288
}
289

    
290

    
291
/**
292
 * @todo Please document this function.
293
 * @see http://drupal.org/node/1354
294
 */
295
function set_last_taxon_page_tab($taxonPageTab) {
296
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
297
}
298

    
299
/**
300
 * @todo Please document this function.
301
 * @see http://drupal.org/node/1354
302
 */
303
function get_last_taxon_page_tab() {
304
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
305
    return $_SESSION['cdm']['taxon_page_tab'];
306
  }
307
  else {
308
    return FALSE;
309
  }
310
}
311

    
312
/**
313
 *
314
 * @param object $media
315
 * @param array $mimeTypes
316
 *    an array of mimetypes in their order of preference. e.g:
317
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
318
 * @param int $width
319
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
320
 * @param int $height
321
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
322
 *
323
 * @return array
324
 *   An array with preferred media representations or else an empty array.
325
 */
326
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
327
  $prefRepr = array();
328
  if (!isset($media->representations[0])) {
329
    return $prefRepr;
330
  }
331

    
332
  while (count($mimeTypes) > 0) {
333
    // getRepresentationByMimeType
334
    $mimeType = array_shift($mimeTypes);
335

    
336
    foreach ($media->representations as &$representation) {
337
      // If the mimetype is not known, try inferring it.
338
      if (!$representation->mimeType) {
339
        if (isset($representation->parts[0])) {
340
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
341
        }
342
      }
343

    
344
      if ($representation->mimeType == $mimeType) {
345
        // Preferred mimetype found -> erase all remaining mimetypes
346
        // to end loop.
347
        $mimeTypes = array();
348
        $expansionDeltaSum = 0;
349
        $valid_parts_cnt = 0;
350
        // Look for part with the best matching size.
351
        foreach ($representation->parts as $part) {
352
          if (empty($part->uri)) {
353
            // skip part if URI is missing
354
            continue;
355
          }
356
          $valid_parts_cnt++;
357
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
358

    
359
          // determine the optimal size
360
          if (isset($part->width) && isset($part->height)) {
361
            $expansion = $part->width * $part->height;
362
            if ($width != null && $height != null) {
363
              $optimalExpansion = $height * $width;
364
            } else {
365
              $optimalExpansion = PHP_INT_MAX;
366
            }
367
            // determine the difference
368
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
369
          }
370
          // sum up the expansionDeltas of all parts contained in the representation
371
          $expansionDeltaSum += $expansionDelta;
372
        }
373
        if($valid_parts_cnt > 0){
374
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
375
          $prefRepr[$expansionDeltaSum] = $representation;
376
        }
377
      }
378
    }
379
  }
380
  // Sort the array so that the smallest key value is the first in the array
381
  ksort($prefRepr);
382
  return $prefRepr;
383
}
384

    
385
/**
386
 * Infers the mime type of a file using the filename extension.
387
 *
388
 * The filename extension is used to infer the mime type.
389
 *
390
 * @param string $filepath
391
 *   The path to the respective file.
392
 *
393
 * @return string
394
 *   The mimetype for the file or FALSE if the according mime type could
395
 *   not be found.
396
 */
397
function infer_mime_type($filepath) {
398
  static $mimemap = NULL;
399
  if (!$mimemap) {
400
    $mimemap = array(
401
      'jpg' => 'image/jpeg',
402
      'jpeg' => 'image/jpeg',
403
      'png' => 'image/png',
404
      'gif' => 'image/gif',
405
      'giff' => 'image/gif',
406
      'tif' => 'image/tif',
407
      'tiff' => 'image/tif',
408
      'pdf' => 'application/pdf',
409
      'html' => 'text/html',
410
      'htm' => 'text/html',
411
    );
412
  }
413
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
414
  if (isset($mimemap[$extension])) {
415
    return $mimemap[$extension];
416
  }
417
  else {
418
    // FIXME remove this hack just return FALSE;
419
    return 'text/html';
420
  }
421
}
422

    
423
/**
424
 * Formats a mysql datatime as string
425
 *
426
 * @param $datetime
427
 * @param string $format
428
 *
429
 * @return
430
 *  the formatted string representation of the $datetime
431
 */
432
function format_datetime($datetime, $format = 'Y-m-d H:i:s'){
433
  return date($format, strtotime($datetime));
434
}
435

    
436
/**
437
 * Converts an ISO 8601 org.joda.time.Partial to a year.
438
 *
439
 * The function expects an ISO 8601 time representation of a
440
 * org.joda.time.Partial of the form yyyy-MM-dd.
441
 *
442
 * @param string $partial
443
 *   ISO 8601 time representation of a org.joda.time.Partial.
444
 *
445
 * @return string
446
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
447
 */
448
function partialToYear($partial) {
449
  if (is_string($partial)) {
450
    $year = substr($partial, 0, 4);
451
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
452
      return $year;
453
    }
454
  }
455
  return '';
456
}
457

    
458
/**
459
 * Converts an ISO 8601 org.joda.time.Partial to a month.
460
 *
461
 * This function expects an ISO 8601 time representation of a
462
 * org.joda.time.Partial of the form yyyy-MM-dd.
463
 * In case the month is unknown (= ???) NULL is returned.
464
 *
465
 * @param string $partial
466
 *   ISO 8601 time representation of a org.joda.time.Partial.
467
 *
468
 * @return string
469
 *   A month.
470
 */
471
function partialToMonth($partial) {
472
  if (is_string($partial)) {
473
    $month = substr($partial, 5, 2);
474
    if (preg_match("/[0-9][0-9]/", $month)) {
475
      return $month;
476
    }
477
  }
478
  return '';
479
}
480

    
481
/**
482
 * Converts an ISO 8601 org.joda.time.Partial to a day.
483
 *
484
 * This function expects an ISO 8601 time representation of a
485
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
486
 * In case the day is unknown (= ???) NULL is returned.
487
 *
488
 * @param string $partial
489
 *   ISO 8601 time representation of a org.joda.time.Partial.
490
 *
491
 * @return string
492
 *   A day.
493
 */
494
function partialToDay($partial) {
495
  if (is_string($partial)) {
496
    $day = substr($partial, 8, 2);
497
    if (preg_match("/[0-9][0-9]/", $day)) {
498
      return $day;
499
    }
500
  }
501
  return '';
502
}
503

    
504
/**
505
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
506
 *
507
 * This function expects an ISO 8601 time representations of a
508
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
509
 * four digit year, month and day with dashes:
510
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
511
 *
512
 * The partial may contain question marks eg: "1973-??-??",
513
 * these are turned in to '00' or are stripped depending of the $stripZeros
514
 * parameter.
515
 *
516
 * @param string $partial
517
 *   org.joda.time.Partial.
518
 * @param bool $stripZeros
519
 *   If set to TRUE the zero (00) month and days will be hidden:
520
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
521
 * @param string @format
522
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
523
 *    - "YYYY": Year only
524
 *    - "YYYY-MM-DD": this is the default
525
 *
526
 * @return string
527
 *   YYYY-MM-DD formatted year, month, day.
528
 */
529
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
530

    
531
  $y = NULL; $m = NULL; $d = NULL;
532

    
533
  if(strpos($format, 'YY') !== FALSE){
534
    $y = partialToYear($partial);
535
  }
536
  if(strpos($format, 'MM') !== FALSE){
537
    $m = partialToMonth($partial);
538
  }
539
  if(strpos($format, 'DD') !== FALSE){
540
    $d = partialToDay($partial);
541
  }
542

    
543
  $y = $y ? $y : '00';
544
  $m = $m ? $m : '00';
545
  $d = $d ? $d : '00';
546

    
547
  $date = '';
548

    
549
  if ($y == '00' && $stripZeros) {
550
    return '';
551
  }
552
  else {
553
    $date = $y;
554
  }
555

    
556
  if ($m == '00' && $stripZeros) {
557
    return $date;
558
  }
559
  else {
560
    $date .= "-" . $m;
561
  }
562

    
563
  if ($d == '00' && $stripZeros) {
564
    return $date;
565
  }
566
  else {
567
    $date .= "-" . $d;
568
  }
569
  return $date;
570
}
571

    
572
/**
573
 * Converts a time period to a string.
574
 *
575
 * See also partialToDate($partial, $stripZeros).
576
 *
577
 * @param object $period
578
 *   An JodaTime org.joda.time.Period object.
579
 * @param bool $stripZeros
580
 *   If set to True, the zero (00) month and days will be hidden:
581
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
582
 * @param string @format
583
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
584
 *    - "YYYY": Year only
585
 *    - "YYYY-MM-DD": this is the default
586
 *
587
 * @return string
588
 *   Returns a date in the form of a string.
589
 */
590
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
591
  $dateString = '';
592
  if($period->freeText){
593
    $dateString = $period->freeText;
594
  } else {
595
    if ($period->start) {
596
      $dateString = partialToDate($period->start, $stripZeros, $format);
597
    }
598
    if ($period->end) {
599
      $end_str = partialToDate($period->end, $stripZeros, $format);
600
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
601
    }
602
  }
603
  return $dateString;
604
}
605

    
606
/**
607
 * returns the earliest date available in the $period in a normalized
608
 * form suitable for sorting, e.g.:
609
 *
610
 *  - 1956-00-00
611
 *  - 0000-00-00
612
 *  - 1957-03-00
613
 *
614
 * that is either the start date is returned if set otherwise the
615
 * end date
616
 *
617
 * @param  $period
618
 *    An JodaTime org.joda.time.Period object.
619
 * @return string normalized form of the date
620
 *   suitable for sorting
621
 */
622
function timePeriodAsOrderKey($period) {
623
  $dateString = '';
624
  if ($period->start) {
625
    $dateString = partialToDate($period->start, false);
626
  }
627
  if ($period->end) {
628
    $dateString .= partialToDate($period->end, false);
629
  }
630
  return $dateString;
631
}
632

    
633
/**
634
 * Composes a absolute CDM web service URI with parameters and querystring.
635
 *
636
 * @param string $uri_pattern
637
 *   String with place holders ($0, $1, ..) that should be replaced by the
638
 *   according element of the $pathParameters array.
639
 * @param array $pathParameters
640
 *   An array of path elements, or a single element.
641
 * @param string $query
642
 *   A query string to append to the URL.
643
 *
644
 * @return string
645
 *   A complete URL with parameters to a CDM webservice.
646
 */
647
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
648
  if (empty($pathParameters)) {
649
    $pathParameters = array();
650
  }
651

    
652
  // (1)
653
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
654
  // according element of the $pathParameters array.
655
  static $helperArray = array();
656
  if (isset($pathParameters) && !is_array($pathParameters)) {
657
    $helperArray[0] = $pathParameters;
658
    $pathParameters = $helperArray;
659
  }
660

    
661
  $i = 0;
662
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
663
    if (count($pathParameters) <= $i) {
664
        drupal_set_message(
665
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
666
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
667
          'error');
668
      break;
669
    }
670
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
671
    ++$i;
672
  }
673

    
674
  // (2)
675
  // Append all remaining element of the $pathParameters array as path
676
  // elements.
677
  if (count($pathParameters) > $i) {
678
    // Strip trailing slashes.
679
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
680
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
681
    }
682
    while (count($pathParameters) > $i) {
683
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
684
      ++$i;
685
    }
686
  }
687

    
688
  // (3)
689
  // Append the query string supplied by $query.
690
  if (isset($query)) {
691
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
692
  }
693

    
694
  $path = $uri_pattern;
695

    
696
  $uri = variable_get('cdm_webservice_url', '') . $path;
697
  return $uri;
698
}
699

    
700
/**
701
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
702
 *     together with a theme name to such a proxy function?
703
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
704
 *     Maybe we want to have two different proxy functions, one with theming and one without?
705
 *
706
 * @param string $uri
707
 *     A URI to a CDM Rest service from which to retrieve an object
708
 * @param string|null $hook
709
 *     (optional) The hook name to which the retrieved object should be passed.
710
 *     Hooks can either be a theme_hook() or compose_hook() implementation
711
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
712
 *     suitable for drupal_render()
713
 *
714
 * @todo Please document this function.
715
 * @see http://drupal.org/node/1354
716
 */
717
function proxy_content($uri, $hook = NULL) {
718

    
719
  $args = func_get_args();
720
  $do_gzip = function_exists('gzencode');
721
  $uriEncoded = array_shift($args);
722
  $uri = urldecode($uriEncoded);
723
  $hook = array_shift($args);
724
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
725

    
726
  $post_data = null;
727

    
728
  if ($request_method == "POST" || $request_method == "PUT") {
729
    // read response body via inputstream module
730
    $post_data = file_get_contents("php://input");
731
  }
732

    
733
  // Find and deserialize arrays.
734
  foreach ($args as &$arg) {
735
    // FIXME use regex to find serialized arrays.
736
    //       or should we accept json instead of php serializations?
737
    if (strpos($arg, "a:") === 0) {
738
      $arg = unserialize($arg);
739
    }
740
  }
741

    
742
  // In all these cases perform a simple get request.
743
  // TODO reconsider caching logic in this function.
744

    
745
  if (empty($hook)) {
746
    // simply return the webservice response
747
    // Print out JSON, the cache cannot be used since it contains objects.
748
    $http_response = cdm_http_request($uri, $request_method, $post_data);
749
    if (isset($http_response->headers)) {
750
      foreach ($http_response->headers as $hname => $hvalue) {
751
        drupal_add_http_header($hname, $hvalue);
752
      }
753
    }
754
    if (isset($http_response->data)) {
755
      print $http_response->data;
756
      flush();
757
    }
758
    exit(); // leave drupal here
759
  } else {
760
    // $hook has been supplied
761
    // handle $hook either as compose ot theme hook
762
    // pass through theme or comose hook
763
    // compose hooks can be called without data, therefore
764
    // passing the $uri in this case is not always a requirement
765

    
766
    if($uri && $uri != 'NULL') {
767
    // do a security check since the $uri will be passed
768
    // as absolute URI to cdm_ws_get()
769
      if (!_is_cdm_ws_uri($uri)) {
770
        drupal_set_message(
771
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
772
          'error'
773
        );
774
        return '';
775
      }
776

    
777
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
778
    } else {
779
      $obj = NULL;
780
    }
781

    
782
    $reponse_data = NULL;
783

    
784
    if (function_exists('compose_' . $hook)){
785
      // call compose hook
786

    
787
      $elements =  call_user_func('compose_' . $hook, $obj);
788
      // pass the render array to drupal_render()
789
      $reponse_data = drupal_render($elements);
790
    } else {
791
      // call theme hook
792

    
793
      // TODO use theme registry to get the registered hook info and
794
      //    use these defaults
795
      switch($hook) {
796
        case 'cdm_taxontree':
797
          $variables = array(
798
            'tree' => $obj,
799
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
800
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
801
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
802
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
803
            );
804
          $reponse_data = theme($hook, $variables);
805
          break;
806

    
807
        case 'cdm_list_of_taxa':
808
            $variables = array(
809
              'records' => $obj,
810
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
811
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
812
            $reponse_data = theme($hook, $variables);
813
            break;
814

    
815
        case 'cdm_media_caption':
816
          $variables = array(
817
            'media' => $obj,
818
            // $args[0] is set in taxon_image_gallery_default in
819
            // cdm_dataportal.page.theme.
820
            'elements' => isset($args[0]) ? $args[0] : array(
821
            'title',
822
            'description',
823
            'artist',
824
            'location',
825
            'rights',
826
          ),
827
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
828
          );
829
          $reponse_data = theme($hook, $variables);
830
          break;
831

    
832
        default:
833
          drupal_set_message(t(
834
          'Theme !theme is not yet supported by the function !function.', array(
835
          '!theme' => $hook,
836
          '!function' => __FUNCTION__,
837
          )), 'error');
838
          break;
839
      } // END of theme hook switch
840
    } // END of tread as theme hook
841

    
842

    
843
    if($do_gzip){
844
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
845
      drupal_add_http_header('Content-Encoding', 'gzip');
846
    }
847
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
848
    drupal_add_http_header('Content-Length', strlen($reponse_data));
849

    
850
    print $reponse_data;
851
  } // END of handle $hook either as compose ot theme hook
852

    
853
}
854

    
855
/**
856
 * @todo Please document this function.
857
 * @see http://drupal.org/node/1354
858
 */
859
function setvalue_session() {
860
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
861
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
862
    $var_keys = explode('][', $var_keys);
863
  }
864
  else {
865
    return;
866
  }
867
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
868

    
869
  // Prevent from malicous tags.
870
  $val = strip_tags($val);
871

    
872
  $session_var = &$_SESSION;
873
  //$i = 0;
874
  foreach ($var_keys as $key) {
875
    // $hasMoreKeys = ++$i < count($session);
876
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
877
      $session_var[$key] = array();
878
    }
879
    $session_var = &$session_var[$key];
880
  }
881
  $session_var = $val;
882
  if (isset($_REQUEST['destination'])) {
883
    drupal_goto($_REQUEST['destination']);
884
  }
885
}
886

    
887
/**
888
 * @todo Please document this function.
889
 * @see http://drupal.org/node/1354
890
 */
891
function uri_uriByProxy($uri, $theme = FALSE) {
892
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
893
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
894
}
895

    
896
/**
897
 * Composes the the absolute REST service URI to the annotations pager
898
 * for the given CDM entity.
899
 *
900
 * NOTE: Not all CDM Base types are yet supported.
901
 *
902
 * @param $cdmBase
903
 *   The CDM entity to construct the annotations pager uri for
904
 */
905
function cdm_compose_annotations_uri($cdmBase) {
906

    
907
  if (!$cdmBase->uuid) {
908
    return;
909
  }
910

    
911
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
912

    
913
  if($ws_base_uri === null){
914
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
915
  }
916
  return cdm_compose_url($ws_base_uri, array(
917
    $cdmBase->uuid,
918
    'annotations',
919
  ));
920
}
921

    
922
/**
923
 * Provides the base URI of the cdm REST service responsible for the passed simple name
924
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
925
 *
926
 * @param $cdm_type_simple
927
 *    simple name of a CDM java class
928
 * @return null|string
929
 */
930
function cdm_ws_base_uri($cdm_type_simple)
931
{
932
  $ws_base_uri = NULL;
933
  switch ($cdm_type_simple) {
934
    case 'TaxonBase':
935
    case 'Taxon':
936
    case 'Synonym':
937
      $ws_base_uri = CDM_WS_TAXON;
938
      break;
939

    
940
    case 'TaxonName':
941
      $ws_base_uri = CDM_WS_NAME;
942
      break;
943

    
944
    case 'Media':
945
      $ws_base_uri = CDM_WS_MEDIA;
946
      break;
947

    
948
    case 'Reference':
949
      $ws_base_uri = CDM_WS_REFERENCE;
950
      break;
951

    
952
    case 'Distribution':
953
    case 'TextData':
954
    case 'TaxonInteraction':
955
    case 'QuantitativeData':
956
    case 'IndividualsAssociation':
957
    case 'CommonTaxonName':
958
    case 'CategoricalData':
959
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
960
      break;
961

    
962
    case 'PolytomousKey':
963
    case 'MediaKey':
964
    case 'MultiAccessKey':
965
      $ws_base_uri = $cdm_type_simple;
966
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
967
      break;
968

    
969
    default:
970
      $ws_base_uri = null;
971
  }
972
  return $ws_base_uri;
973
}
974

    
975
/**
976
 * Enter description here...
977
 *
978
 * @param string $resourceURI
979
 * @param int $pageSize
980
 *   The maximum number of entities returned per page.
981
 *   The default page size as configured in the cdm server
982
 *   will be used if set to NULL
983
 *   to return all entities in a single page).
984
 * @param int $pageNumber
985
 *   The number of the page to be returned, the first page has the
986
 *   pageNumber = 0
987
 * @param array $query
988
 *   A array holding the HTTP request query parameters for the request
989
 * @param string $method
990
 *   The HTTP method to use, valid values are "GET" or "POST"
991
 * @param bool $absoluteURI
992
 *   TRUE when the URL should be treated as absolute URL.
993
 *
994
 * @return the a CDM Pager object
995
 *
996
 */
997
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
998

    
999
  $query['pageNumber'] = $pageNumber;
1000
  $query['pageSize'] = $pageSize;
1001

    
1002
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1003
}
1004

    
1005
/**
1006
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1007
 *
1008
 * @param string $resourceURI
1009
 * @param array $query
1010
 *   A array holding the HTTP request query parameters for the request
1011
 * @param string $method
1012
 *   The HTTP method to use, valid values are "GET" or "POST";
1013
 * @param bool $absoluteURI
1014
 *   TRUE when the URL should be treated as absolute URL.
1015
 *
1016
 * @return array
1017
 *     A list of CDM entitites
1018
 *
1019
 */
1020
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1021
  $page_index = 0;
1022
  // using a bigger page size to avoid to many multiple requests
1023
  $page_size = 500;
1024
  $entities = array();
1025

    
1026
  while ($page_index !== FALSE){
1027
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1028
    if(isset($pager->records) && is_array($pager->records)) {
1029
      $entities = array_merge($entities, $pager->records);
1030
      if(!empty($pager->nextIndex)){
1031
        $page_index = $pager->nextIndex;
1032
      } else {
1033
        $page_index = FALSE;
1034
      }
1035
    } else {
1036
      $page_index = FALSE;
1037
    }
1038
  }
1039
  return $entities;
1040
}
1041

    
1042
/*
1043
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1044
  $viewrank = _cdm_taxonomy_compose_viewrank();
1045
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1046
  ? '/' . $path : '') ;
1047
}
1048
*/
1049

    
1050
/**
1051
 * @todo Enter description here...
1052
 *
1053
 * @param string $taxon_uuid
1054
 *  The UUID of a cdm taxon instance
1055
 * @param string $ignore_rank_limit
1056
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1057
 *
1058
 * @return string
1059
 *   A cdm REST service URL path to a Classification
1060
 */
1061
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1062

    
1063
  $view_uuid = get_current_classification_uuid();
1064
  $rank_uuid = NULL;
1065
  if (!$ignore_rank_limit) {
1066
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1067
  }
1068

    
1069
  if (!empty($taxon_uuid)) {
1070
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1071
      $view_uuid,
1072
      $taxon_uuid,
1073
    ));
1074
  }
1075
  else {
1076
    if (is_uuid($rank_uuid)) {
1077
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1078
        $view_uuid,
1079
        $rank_uuid,
1080
      ));
1081
    }
1082
    else {
1083
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1084
        $view_uuid,
1085
      ));
1086
    }
1087
  }
1088
}
1089

    
1090
/**
1091
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1092
 *
1093
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1094
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1095
 *
1096
 * Operates in two modes depending on whether the parameter
1097
 * $taxon_uuid is set or NULL.
1098
 *
1099
 * A) $taxon_uuid = NULL:
1100
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1101
 *  2. otherwise return the default classification as defined by the admin via the settings
1102
 *
1103
 * b) $taxon_uuid is set:
1104
 *   return the classification to whcih the taxon belongs to.
1105
 *
1106
 * @param UUID $taxon_uuid
1107
 *   The UUID of a cdm taxon instance
1108
 */
1109
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1110

    
1111
    $response = NULL;
1112

    
1113
    // 1st try
1114
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1115

    
1116
    if ($response == NULL) {
1117
      // 2dn try by ignoring the rank limit
1118
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1119
    }
1120

    
1121
    if ($response == NULL) {
1122
      // 3rd try, last fallback:
1123
      //    return the default classification
1124
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1125
        // Delete the session value and try again with the default.
1126
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1127
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1128
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1129
      }
1130
      else {
1131
        // Check if taxonomictree_uuid is valid.
1132
        // expecting an array of taxonNodes,
1133
        // empty classifications are ok so no warning in this case!
1134
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1135
        if (!is_array($test)) {
1136
          // The default set by the admin seems to be invalid or is not even set.
1137
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1138
        }
1139
        if (count($test) == 0) {
1140
          // The default set by the admin seems to be invalid or is not even set.
1141
          drupal_set_message("The chosen classification is empty.", 'status');
1142
        }
1143
      }
1144
    }
1145

    
1146
  return $response;
1147
}
1148

    
1149
/**
1150
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1151
 * 
1152
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1153
 * variable is set.
1154
 *
1155
 * @param string $taxon_uuid
1156
 *
1157
 * @return array
1158
 *   An array of CDM TaxonNodeDTO objects
1159
 */
1160
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1161
  $view_uuid = get_current_classification_uuid();
1162
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1163

    
1164
  $response = NULL;
1165
  if (is_uuid($rank_uuid)) {
1166
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1167
      $view_uuid,
1168
      $taxon_uuid,
1169
      $rank_uuid,
1170
    ));
1171
  }
1172
  else {
1173
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1174
      $view_uuid,
1175
      $taxon_uuid,
1176
    ));
1177
  }
1178

    
1179
  if ($response == NULL) {
1180
    // Error handing.
1181
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1182
//      // Delete the session value and try again with the default.
1183
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1184
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1185
//    }
1186
//    else {
1187
      // Check if taxonomictree_uuid is valid.
1188
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1189
      if ($test == NULL) {
1190
        // The default set by the admin seems to be invalid or is not even set.
1191
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1192
      }
1193
//    }
1194
  }
1195

    
1196
  return $response;
1197
}
1198

    
1199

    
1200
// =============================Terms and Vocabularies ========================================= //
1201

    
1202
/**
1203
 * Returns the localized representation for the given term.
1204
 *
1205
 * @param Object $definedTermBase
1206
 * 	  of cdm type DefinedTermBase
1207
 * @return string
1208
 * 	  the localized representation_L10n of the term,
1209
 *    otherwise the titleCache as fall back,
1210
 *    otherwise the default_representation which defaults to an empty string
1211
 */
1212
function cdm_term_representation($definedTermBase, $default_representation = '') {
1213
  if ( isset($definedTermBase->representation_L10n) ) {
1214
    return $definedTermBase->representation_L10n;
1215
  } elseif ( isset($definedTermBase->titleCache)) {
1216
    return $definedTermBase->titleCache;
1217
  }
1218
  return $default_representation;
1219
}
1220

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

    
1239
/**
1240
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1241
 *
1242
 * The options array is suitable for drupal form API elements that allow multiple choices.
1243
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1244
 *
1245
 * @param array $terms
1246
 *   a list of CDM DefinedTermBase instances
1247
 *
1248
 * @param $term_label_callback
1249
 *   A callback function to override the term representations
1250
 *
1251
 * @param bool $empty_option
1252
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1253
 *
1254
 * @return array
1255
 *   the terms in an array as options for a form element that allows multiple choices.
1256
 */
1257
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1258
  $options = array();
1259
  if(isset($terms) && is_array($terms)) {
1260
    foreach ($terms as $term) {
1261
      if ($term_label_callback && function_exists($term_label_callback)) {
1262
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1263
      } else {
1264
        //TODO use cdm_term_representation() here?
1265
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1266
      }
1267
    }
1268
  }
1269

    
1270
  if($empty_option !== FALSE){
1271
    array_unshift ($options, "");
1272
  }
1273

    
1274
  return $options;
1275
}
1276

    
1277
/**
1278
 * Creates and array of options for drupal select form elements.
1279
 *
1280
 * @param $vocabulary_uuid
1281
 *   The UUID of the CDM Term Vocabulary
1282
 * @param $term_label_callback
1283
 *   An optional call back function which can be used to modify the term label
1284
 * @param bool $empty_option
1285
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1286
 * @param array $include_filter
1287
 *   An associative array consisting of a field name an regular expression. All term matching
1288
 *   these filter are included. The value of the field is converted to a String by var_export()
1289
 *   so a boolean 'true' can be matched by '/true/'
1290
 * @param string $order_by
1291
 *   One of the order by constants defined in this file
1292
 * @return mixed
1293
 */
1294
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1295
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1296

    
1297
  static $vocabularyOptions = array();
1298

    
1299
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1300
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1301
      array(
1302
        'orderBy' => $order_by
1303
      )
1304
    );
1305

    
1306
    // apply the include filter
1307
    if($include_filter != null){
1308
      $included_terms = array();
1309

    
1310
      foreach ($terms as $term){
1311
        $include = true;
1312
        foreach ($include_filter as $field=>$regex){
1313
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1314
          if(!$include){
1315
            break;
1316
          }
1317
        }
1318
        if($include){
1319
          $included_terms[] = $term;
1320
        }
1321
      }
1322

    
1323
      $terms = $included_terms;
1324
    }
1325

    
1326
    // make options list
1327
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1328
  }
1329

    
1330
  $options = $vocabularyOptions[$vocabulary_uuid];
1331

    
1332
  return $options;
1333
}
1334

    
1335
/**
1336
 * @param $term_type string one of
1337
 *  - Unknown
1338
 *  - Language
1339
 *  - NamedArea
1340
 *  - Rank
1341
 *  - Feature
1342
 *  - AnnotationType
1343
 *  - MarkerType
1344
 *  - ExtensionType
1345
 *  - DerivationEventType
1346
 *  - PresenceAbsenceTerm
1347
 *  - NomenclaturalStatusType
1348
 *  - NameRelationshipType
1349
 *  - HybridRelationshipType
1350
 *  - SynonymRelationshipType
1351
 *  - TaxonRelationshipType
1352
 *  - NameTypeDesignationStatus
1353
 *  - SpecimenTypeDesignationStatus
1354
 *  - InstitutionType
1355
 *  - NamedAreaType
1356
 *  - NamedAreaLevel
1357
 *  - RightsType
1358
 *  - MeasurementUnit
1359
 *  - StatisticalMeasure
1360
 *  - MaterialOrMethod
1361
 *  - Material
1362
 *  - Method
1363
 *  - Modifier
1364
 *  - Scope
1365
 *  - Stage
1366
 *  - KindOfUnit
1367
 *  - Sex
1368
 *  - ReferenceSystem
1369
 *  - State
1370
 *  - NaturalLanguageTerm
1371
 *  - TextFormat
1372
 *  - DeterminationModifier
1373
 *  - DnaMarker
1374
 *
1375
 * @param  $order_by
1376
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1377
 *  possible values:
1378
 *    - CDM_ORDER_BY_ID_ASC
1379
 *    - CDM_ORDER_BY_ID_DESC
1380
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1381
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1382
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1383
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1384
 * @param bool $empty_option
1385
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1386
 * @return array
1387
 *    the terms in an array as options for a form element that allows multiple choices.
1388
 */
1389
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1390
  $terms = cdm_ws_fetch_all(
1391
    CDM_WS_TERM,
1392
    array(
1393
      'class' => $term_type,
1394
      'orderBy' => $order_by
1395
    )
1396
  );
1397
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1398
}
1399

    
1400

    
1401
/**
1402
 * @todo Please document this function.
1403
 * @see http://drupal.org/node/1354
1404
 */
1405
function _cdm_relationship_type_term_label_callback($term) {
1406
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1407
    return $term->representation_L10n_abbreviatedLabel . ' : '
1408
    . t('@term', array('@term' => $term->representation_L10n));
1409
  }
1410
else {
1411
    return t('@term', array('@term' => $term->representation_L10n));
1412
  }
1413
}
1414

    
1415
// ========================================================================================== //
1416
/**
1417
 * @todo Improve documentation of this function.
1418
 *
1419
 * eu.etaxonomy.cdm.model.description.
1420
 * CategoricalData
1421
 * CommonTaxonName
1422
 * Distribution
1423
 * IndividualsAssociation
1424
 * QuantitativeData
1425
 * TaxonInteraction
1426
 * TextData
1427
 */
1428
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1429
  static $types = array(
1430
    "CategoricalData",
1431
    "CommonTaxonName",
1432
    "Distribution",
1433
    "IndividualsAssociation",
1434
    "QuantitativeData",
1435
    "TaxonInteraction",
1436
    "TextData",
1437
  );
1438

    
1439
  static $options = NULL;
1440
  if ($options == NULL) {
1441
    $options = array();
1442
    if ($prependEmptyElement) {
1443
      $options[' '] = '';
1444
    }
1445
    foreach ($types as $type) {
1446
      // No internatianalization here since these are purely technical terms.
1447
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1448
    }
1449
  }
1450
  return $options;
1451
}
1452

    
1453

    
1454
/**
1455
 * Fetches all TaxonDescription descriptions elements which are associated to the
1456
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1457
 * feature tree.
1458
 * @param $feature_tree
1459
 *     The CDM FeatureTree to be used as template
1460
 * @param $taxon_uuid
1461
 *     The UUID of the taxon
1462
 * @param $excludes
1463
 *     UUIDs of features to be excluded
1464
 * @return$feature_tree
1465
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1466
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1467
 *     witch will hold the according $descriptionElements.
1468
 */
1469
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1470

    
1471
  if (!$feature_tree) {
1472
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1473
      In order to see the species profiles of your taxa, please select a
1474
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1475
    return FALSE;
1476
  }
1477

    
1478
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1479
      array(
1480
      'taxon' => $taxon_uuid,
1481
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1482
      ),
1483
      'POST'
1484
  );
1485

    
1486
  // Combine all descriptions into one feature tree.
1487
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1488
  $feature_tree->root->childNodes = $merged_nodes;
1489

    
1490
  return $feature_tree;
1491
}
1492

    
1493
/**
1494
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1495
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1496
 * be requested for the annotations.
1497
 *
1498
 * @param string $cdmBase
1499
 *   An annotatable cdm entity.
1500
 * @param array $includeTypes
1501
 *   If an array of annotation type uuids is supplied by this parameter the
1502
 *   list of annotations is resticted to those which belong to this type.
1503
 *
1504
 * @return array
1505
 *   An array of Annotation objects or an empty array.
1506
 */
1507
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1508

    
1509
  if(!isset($cdmBase->annotations)){
1510
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1511
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1512
  }
1513

    
1514
  $annotations = array();
1515
  foreach ($cdmBase->annotations as $annotation) {
1516
    if ($includeTypes) {
1517
      if (
1518
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1519
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1520
      ) {
1521
        $annotations[] = $annotation;
1522
      }
1523
    }
1524
    else {
1525
      $annotations[] = $annotation;
1526
    }
1527
  }
1528
  return $annotations;
1529

    
1530
}
1531

    
1532
/**
1533
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1534
 *
1535
 * @param object $annotatable_entity
1536
 *   The CDM AnnotatableEntity to load annotations for
1537
 */
1538
function cdm_load_annotations(&$annotatable_entity) {
1539
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1540
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1541
    if (is_array($annotations)) {
1542
      $annotatable_entity->annotations = $annotations;
1543
    }
1544
  }
1545
}
1546

    
1547
/**
1548
 * Extends the $cdm_entity object by the field if it is not already existing.
1549
 *
1550
 * This function can only be used for fields with 1 to many relations.
1551
  *
1552
 * @param $cdm_base_type
1553
 * @param $field_name
1554
 * @param $cdm_entity
1555
 */
1556
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1557
{
1558
  if (!isset($cdm_entity->$field_name)) {
1559
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1560
    $cdm_entity->$field_name = $items;
1561
  }
1562
}
1563

    
1564

    
1565
/**
1566
 * Get a NomenclaturalReference string.
1567
 *
1568
 * Returns the NomenclaturalReference string with correctly placed
1569
 * microreference (= reference detail) e.g.
1570
 * in Phytotaxa 43: 1-48. 2012.
1571
 *
1572
 * @param string $referenceUuid
1573
 *   UUID of the reference.
1574
 * @param string $microreference
1575
 *   Reference detail.
1576
 *
1577
 * @return string
1578
 *   a NomenclaturalReference.
1579
 */
1580
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1581

    
1582
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1583
  if(is_array($microreference) || is_object($microreference)) {
1584
    return '';
1585
  }
1586

    
1587
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1588
    $referenceUuid,
1589
  ), "microReference=" . urlencode($microreference));
1590

    
1591
  if ($obj) {
1592
    return $obj->String;
1593
  }
1594
  else {
1595
    return NULL;
1596
  }
1597
}
1598

    
1599
/**
1600
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1601
 *
1602
 * @param $feature_tree_nodes
1603
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1604
 * @param $feature_uuid
1605
 *    The UUID of the Feature
1606
 * @return returns the FeatureNode or null
1607
 */
1608
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1609

    
1610
  // 1. scan this level
1611
  foreach ($feature_tree_nodes as $node){
1612
    if($node->feature->uuid == $feature_uuid){
1613
      return $node;
1614
    }
1615
  }
1616

    
1617
  // 2. descend into childen
1618
  foreach ($feature_tree_nodes as $node){
1619
    if(is_array($node->childNodes)){
1620
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1621
      if($node) {
1622
        return $node;
1623
      }
1624
    }
1625
  }
1626
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1627
  return $null_var;
1628
}
1629

    
1630
/**
1631
 * Merges the given featureNodes structure with the descriptionElements.
1632
 *
1633
 * This method is used in preparation for rendering the descriptionElements.
1634
 * The descriptionElements which belong to a specific feature node are appended
1635
 * to a the feature node by creating a new field:
1636
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1637
 * The descriptionElements will be cleared in advance in order to allow reusing the
1638
 * same feature tree without the risk of mixing sets of description elements.
1639
 *
1640
 * which originally is not existing in the cdm.
1641
 *
1642
 *
1643
 *
1644
 * @param array $featureNodes
1645
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1646
 *    may have children.
1647
 * @param array $descriptionElements
1648
 *    An flat array of cdm DescriptionElements
1649
 * @return array
1650
 *    The $featureNodes structure enriched with the according $descriptionElements
1651
 */
1652
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1653

    
1654
  foreach ($featureNodes as &$node) {
1655
    // since the $featureNodes array is reused for each description
1656
    // it is necessary to clear the custom node fields in advance
1657
    if(isset($node->descriptionElements)){
1658
      unset($node->descriptionElements);
1659
    }
1660

    
1661
    // Append corresponding elements to an additional node field:
1662
    // $node->descriptionElements.
1663
    foreach ($descriptionElements as $element) {
1664
      if ($element->feature->uuid == $node->feature->uuid) {
1665
        if (!isset($node->descriptionElements)) {
1666
          $node->descriptionElements = array();
1667
        }
1668
        $node->descriptionElements[] = $element;
1669
      }
1670
    }
1671

    
1672
    // Recurse into node children.
1673
    if (isset($node->childNodes[0])) {
1674
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1675
      $node->childNodes = $mergedChildNodes;
1676
    }
1677

    
1678
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1679
      unset($node);
1680
    }
1681

    
1682
  }
1683

    
1684
  return $featureNodes;
1685
}
1686

    
1687
/**
1688
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1689
 *
1690
 * The response from the HTTP GET request is returned as object.
1691
 * The response objects coming from the webservice configured in the
1692
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1693
 *  in a level 2 (L2) cache.
1694
 *
1695
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1696
 * function, this cache persists only per each single page execution.
1697
 * Any object coming from the webservice is stored into it by default.
1698
 * In contrast to this default caching mechanism the L2 cache only is used if
1699
 * the 'cdm_webservice_cache' variable is set to TRUE,
1700
 * which can be set using the modules administrative settings section.
1701
 * Objects stored in this L2 cache are serialized and stored
1702
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1703
 * objects that are stored in the database will persist as
1704
 * long as the drupal cache is not being cleared and are available across
1705
 * multiple script executions.
1706
 *
1707
 * @param string $uri
1708
 *   URL to the webservice.
1709
 * @param array $pathParameters
1710
 *   An array of path parameters.
1711
 * @param string $query
1712
 *   A query string to be appended to the URL.
1713
 * @param string $method
1714
 *   The HTTP method to use, valid values are "GET" or "POST";
1715
 * @param bool $absoluteURI
1716
 *   TRUE when the URL should be treated as absolute URL.
1717
 *
1718
 * @return object| array
1719
 *   The de-serialized webservice response object.
1720
 */
1721
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1722

    
1723
  static $cacheL1 = array();
1724

    
1725
  $data = NULL;
1726
  // store query string in $data and clear the query, $data will be set as HTTP request body
1727
  if($method == 'POST'){
1728
    $data = $query;
1729
    $query = NULL;
1730
  }
1731

    
1732
  // Transform the given uri path or pattern into a proper webservice uri.
1733
  if (!$absoluteURI) {
1734
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1735
  }
1736
  cdm_ws_apply_classification_subtree_filter($uri);
1737

    
1738
  // read request parameter 'cacheL2_refresh'
1739
  // which allows refreshing the level 2 cache
1740
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1741

    
1742
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1743
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1744

    
1745
  if($method == 'GET'){
1746
    $cache_key = $uri;
1747
  } else {
1748
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1749
    // crc32 is faster but creates much shorter hashes
1750
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1751
  }
1752

    
1753
  if (array_key_exists($cache_key, $cacheL1)) {
1754
    $cacheL1_obj = $cacheL1[$uri];
1755
  }
1756

    
1757
  $set_cacheL1 = FALSE;
1758
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1759
    $set_cacheL1 = TRUE;
1760
  }
1761

    
1762
  // Only cache cdm webservice URIs.
1763
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1764
  $cacheL2_entry = FALSE;
1765

    
1766
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1767
    // Try to get object from cacheL2.
1768
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1769
  }
1770

    
1771
  if (isset($cacheL1_obj)) {
1772
    //
1773
    // The object has been found in the L1 cache.
1774
    //
1775
    $obj = $cacheL1_obj;
1776
    if (cdm_debug_block_visible()) {
1777
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1778
    }
1779
  }
1780
  elseif ($cacheL2_entry) {
1781
    //
1782
    // The object has been found in the L2 cache.
1783
    //
1784
    $duration_parse_start = microtime(TRUE);
1785
    $obj = unserialize($cacheL2_entry->data);
1786
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1787

    
1788
    if (cdm_debug_block_visible()) {
1789
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1790
    }
1791
  }
1792
  else {
1793
    //
1794
    // Get the object from the webservice and cache it.
1795
    //
1796
    $duration_fetch_start = microtime(TRUE);
1797
    // Request data from webservice JSON or XML.
1798
    $response = cdm_http_request($uri, $method, $data);
1799
    $response_body = NULL;
1800
    if (isset($response->data)) {
1801
      $response_body = $response->data;
1802
    }
1803
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1804
    $duration_parse_start = microtime(TRUE);
1805

    
1806
    // Parse data and create object.
1807
    $obj = cdm_load_obj($response_body);
1808

    
1809
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1810

    
1811
    if (cdm_debug_block_visible()) {
1812
      if ($obj || $response_body == "[]") {
1813
        $status = 'valid';
1814
      }
1815
      else {
1816
        $status = 'invalid';
1817
      }
1818
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1819
    }
1820
    if ($set_cacheL2) {
1821
      // Store the object in cache L2.
1822
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1823
      // flag serialized is set properly in the cache table.
1824
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1825
    }
1826
  }
1827
  if ($obj) {
1828
    // Store the object in cache L1.
1829
    if ($set_cacheL1) {
1830
      $cacheL1[$cache_key] = $obj;
1831
    }
1832
  }
1833
  return $obj;
1834
}
1835

    
1836
function cdm_ws_apply_classification_subtree_filter(&$uri){
1837

    
1838
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
1839
    "#/classification/[0-9a-f\-]{36}/childNodes#",
1840
    /* covered by above pattern:
1841
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
1842
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
1843
    */
1844
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
1845
    /* covered by above pattern:
1846
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
1847
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
1848
    */
1849
    '#/portal/classification/[0-9a-f\-]{36}/pathFrom/[0-9a-f\-]{36}#',
1850
    "#/portal/taxon/search#",
1851
    "#/portal/taxon/find#",
1852
    /* covered by above pattern:
1853
    "#/portal/taxon/findByDescriptionElementFullText#",
1854
    "#/portal/taxon/findByFullText#",
1855
    "#/portal/taxon/findByEverythingFullText#",
1856
    "#/portal/taxon/findByIdentifier#",
1857
    "#/portal/taxon/findByMarker#",
1858
    "#/portal/taxon/findByMarker#",
1859
    "#/portal/taxon/findByMarker#",
1860
    */
1861
    "#/portal/taxon/[0-9a-f\-]{36}#"
1862
    /* covered by above pattern:
1863
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
1864
    */
1865
  ));
1866

    
1867
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
1868
  if(is_uuid($sub_tree_filter_uuid_value)){
1869
    foreach($classification_subtree_filter_patterns as $preg_pattern){
1870
      if(preg_match($preg_pattern, $uri)){
1871
        // no need to take care for uri fragments with ws uris!
1872
        if(strpos( $uri, '?')){
1873
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
1874
        } else {
1875
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
1876
        }
1877
        break;
1878
      }
1879
    }
1880
  }
1881

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

    
1907
  static $initial_time = NULL;
1908
  if(!$initial_time) {
1909
    $initial_time = microtime(TRUE);
1910
  }
1911
  $time = microtime(TRUE) - $initial_time;
1912

    
1913
  // Decompose uri into path and query element.
1914
  $uri_parts = explode("?", $uri);
1915
  $query = array();
1916
  if (count($uri_parts) == 2) {
1917
    $path = $uri_parts[0];
1918
  }
1919
  else {
1920
    $path = $uri;
1921
  }
1922

    
1923
  if(strpos($uri, '?') > 0){
1924
    $json_uri = str_replace('?', '.json?', $uri);
1925
    $xml_uri = str_replace('?', '.xml?', $uri);
1926
  } else {
1927
    $json_uri = $uri . '.json';
1928
    $xml_uri = $json_uri . '.xml';
1929
  }
1930

    
1931
  // data links to make data accecsible as json and xml
1932
  $data_links = '';
1933
  if (_is_cdm_ws_uri($path)) {
1934

    
1935
    // see ./js/http-method-link.js
1936

    
1937
    if($method == 'GET'){
1938
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1939
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1940
      $data_links .= '<br/>';
1941
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1942
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1943
    } else {
1944
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1945
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1946
      $data_links .= '<br/>';
1947
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1948
    }
1949
  }
1950
  else {
1951
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1952
  }
1953

    
1954
  //
1955
  $data = array(
1956
      'ws_uri' => $uri,
1957
      'method' => $method,
1958
      'post_data' => $post_data,
1959
      'time' => sprintf('%3.3f', $time),
1960
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1961
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1962
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1963
      'status' => $status,
1964
      'data_links' => $data_links
1965
  );
1966
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1967
    $_SESSION['cdm']['ws_debug'] = array();
1968
  }
1969
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1970

    
1971
  // Mark this page as being uncacheable.
1972
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1973
  drupal_page_is_cacheable(FALSE);
1974

    
1975
  // Messages not set when DB connection fails.
1976
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1977
}
1978

    
1979
/**
1980
 * helper function to dtermine if the cdm_debug_block should be displayed or not
1981
 * the visibility depends on whether
1982
 *  - the block is enabled
1983
 *  - the visibility restrictions in the block settings are satisfied
1984
 */
1985
function cdm_debug_block_visible() {
1986
  static $is_visible = null;
1987

    
1988
  if($is_visible === null){
1989
      $block = block_load('cdm_api', 'cdm_ws_debug');
1990
      $is_visible = isset($block->status) && $block->status == 1;
1991
      if($is_visible){
1992
        $blocks = array($block);
1993
        // Checks the page, user role, and user-specific visibilty settings.
1994
        block_block_list_alter($blocks);
1995
        $is_visible = count($blocks) > 0;
1996
      }
1997
  }
1998
  return $is_visible;
1999
}
2000

    
2001
/**
2002
 * @todo Please document this function.
2003
 * @see http://drupal.org/node/1354
2004
 */
2005
function cdm_load_obj($response_body) {
2006
  $obj = json_decode($response_body);
2007

    
2008
  if (!(is_object($obj) || is_array($obj))) {
2009
    ob_start();
2010
    $obj_dump = ob_get_contents();
2011
    ob_clean();
2012
    return FALSE;
2013
  }
2014

    
2015
  return $obj;
2016
}
2017

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

    
2056
  if (!$acceptLanguage) {
2057
    if (function_exists('apache_request_headers')) {
2058
      $headers = apache_request_headers();
2059
      if (isset($headers['Accept-Language'])) {
2060
        $acceptLanguage = $headers['Accept-Language'];
2061
      }
2062
    }
2063
  }
2064

    
2065
  if ($method != "GET" && $method != "POST") {
2066
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2067
  }
2068

    
2069
  if (_is_cdm_ws_uri($uri)) {
2070
    $header['Accept'] = 'application/json';
2071
    $header['Accept-Language'] = $acceptLanguage;
2072
    $header['Accept-Charset'] = 'UTF-8';
2073
  }
2074

    
2075
  if($method == "POST") {
2076
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2077
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2078
  }
2079

    
2080

    
2081
  cdm_dd($uri);
2082
  return drupal_http_request($uri, array(
2083
      'headers' => $header,
2084
      'method' => $method,
2085
      'data' => $data,
2086
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2087
      )
2088
   );
2089
}
2090

    
2091
/**
2092
 * Concatenates recursively the fields of all features contained in the given
2093
 * CDM FeatureTree root node.
2094
 *
2095
 * @param $rootNode
2096
 *     A CDM FeatureTree node
2097
 * @param
2098
 *     The character to be used as glue for concatenation, default is ', '
2099
 * @param $field_name
2100
 *     The field name of the CDM Features
2101
 * @param $excludes
2102
 *     Allows defining a set of values to be excluded. This refers to the values
2103
 *     in the field denoted by the $field_name parameter
2104
 *
2105
 */
2106
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2107
  $out = '';
2108

    
2109
  $pre_child_separator = $separator;
2110
  $post_child_separator = '';
2111

    
2112
  foreach ($root_node->childNodes as $feature_node) {
2113
    $out .= ($out ? $separator : '');
2114
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2115
      $out .= $feature_node->feature->$field_name;
2116
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2117
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2118
        if (strlen($childlabels)) {
2119
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2120
        }
2121
      }
2122
    }
2123
  }
2124
  return $out;
2125
}
2126

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

    
2161
/**
2162
 * Returns an array with all available FeatureTrees and the representations of the selected
2163
 * FeatureTree as a detail view.
2164
 *
2165
 * @param boolean $add_default_feature_free
2166
 * @return array
2167
 *  associative array with following keys:
2168
 *  -options: Returns an array with all available Feature Trees
2169
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2170
 *
2171
 */
2172
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2173

    
2174
  $options = array();
2175
  $tree_representations = array();
2176
  $feature_trees = array();
2177

    
2178
  // Set tree that contains all features.
2179
  if ($add_default_feature_free) {
2180
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2181
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2182
  }
2183

    
2184
  // Get feature trees from database.
2185
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2186
  if (is_array($persited_trees)) {
2187
    $feature_trees = array_merge($feature_trees, $persited_trees);
2188
  }
2189

    
2190
  foreach ($feature_trees as $featureTree) {
2191

    
2192
    if(!is_object($featureTree)){
2193
      continue;
2194
    }
2195
    // Do not add the DEFAULT_FEATURETREE again,
2196
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2197
      $options[$featureTree->uuid] = $featureTree->titleCache;
2198
    }
2199

    
2200
    // Render the hierarchic tree structure
2201
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2202

    
2203
      // Render the hierarchic tree structure.
2204
      $treeDetails = '<div class="featuretree_structure">'
2205
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2206
        . '</div>';
2207

    
2208
      $form = array();
2209
      $form['featureTree-' .  $featureTree->uuid] = array(
2210
        '#type' => 'fieldset',
2211
        '#title' => 'Show details',
2212
        '#attributes' => array('class' => array('collapsible collapsed')),
2213
        // '#collapsible' => TRUE,
2214
        // '#collapsed' => TRUE,
2215
      );
2216
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2217
        '#markup' => $treeDetails,
2218
      );
2219

    
2220
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2221
    }
2222

    
2223
  } // END loop over feature trees
2224

    
2225
  // return $options;
2226
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2227
}
2228

    
2229
/**
2230
 * Provides the list of available classifications in form of an options array.
2231
 *
2232
 * The options array is suitable for drupal form API elements that allow multiple choices.
2233
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2234
 *
2235
 * The classifications are ordered alphabetically whereas the classification
2236
 * chosen as default will always appear on top of the array, followed by a
2237
 * blank line below.
2238
 *
2239
 * @param bool $add_none_option
2240
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2241
 *
2242
 * @return array
2243
 *   classifications in an array as options for a form element that allows multiple choices.
2244
 */
2245
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2246

    
2247
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2248

    
2249
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2250
  $default_classification_label = '';
2251

    
2252
  // add all classifications
2253
  $taxonomic_tree_options = array();
2254
  if ($add_none_option) {
2255
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2256
  }
2257
  if ($taxonTrees) {
2258
    foreach ($taxonTrees as $tree) {
2259
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2260
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2261
      } else {
2262
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2263
        $default_classification_label = $tree->titleCache;
2264
      }
2265
    }
2266
  }
2267
  // oder alphabetically the space
2268
  asort($taxonomic_tree_options);
2269

    
2270
  // now set the labels
2271
  //   for none
2272
  if ($add_none_option) {
2273
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2274
  }
2275

    
2276
  //   for default_classification
2277
  if (is_uuid($default_classification_uuid)) {
2278
    $taxonomic_tree_options[$default_classification_uuid] =
2279
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2280
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2281
  }
2282

    
2283
  return $taxonomic_tree_options;
2284
}
2285

    
2286
/**
2287
 * @todo Please document this function.
2288
 * @see http://drupal.org/node/1354
2289
 */
2290
function cdm_api_secref_cache_prefetch(&$secUuids) {
2291
  // Comment @WA: global variables should start with a single underscore
2292
  // followed by the module and another underscore.
2293
  global $_cdm_api_secref_cache;
2294
  if (!is_array($_cdm_api_secref_cache)) {
2295
    $_cdm_api_secref_cache = array();
2296
  }
2297
  $uniqueUuids = array_unique($secUuids);
2298
  $i = 0;
2299
  $param = '';
2300
  while ($i++ < count($uniqueUuids)) {
2301
    $param .= $secUuids[$i] . ',';
2302
    if (strlen($param) + 37 > 2000) {
2303
      _cdm_api_secref_cache_add($param);
2304
      $param = '';
2305
    }
2306
  }
2307
  if ($param) {
2308
    _cdm_api_secref_cache_add($param);
2309
  }
2310
}
2311

    
2312
/**
2313
 * @todo Please document this function.
2314
 * @see http://drupal.org/node/1354
2315
 */
2316
function cdm_api_secref_cache_get($secUuid) {
2317
  global $_cdm_api_secref_cache;
2318
  if (!is_array($_cdm_api_secref_cache)) {
2319
    $_cdm_api_secref_cache = array();
2320
  }
2321
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2322
    _cdm_api_secref_cache_add($secUuid);
2323
  }
2324
  return $_cdm_api_secref_cache[$secUuid];
2325
}
2326

    
2327
/**
2328
 * @todo Please document this function.
2329
 * @see http://drupal.org/node/1354
2330
 */
2331
function cdm_api_secref_cache_clear() {
2332
  global $_cdm_api_secref_cache;
2333
  $_cdm_api_secref_cache = array();
2334
}
2335

    
2336

    
2337
/**
2338
 * Validates if the given string is a uuid.
2339
 *
2340
 * @param string $str
2341
 *   The string to validate.
2342
 *
2343
 * return bool
2344
 *   TRUE if the string is a UUID.
2345
 */
2346
function is_uuid($str) {
2347
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2348
}
2349

    
2350
/**
2351
 * Checks if the given $object is a valid cdm entity.
2352
 *
2353
 * An object is considered a cdm entity if it has a string field $object->class
2354
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2355
 * The function is null save.
2356
 *
2357
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2358
 *
2359
 * @param mixed $object
2360
 *   The object to validate
2361
 *
2362
 * @return bool
2363
 *   True if the object is a cdm entity.
2364
 */
2365
function is_cdm_entity($object) {
2366
  return
2367
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2368
    && is_string($object->uuid) && is_uuid($object->uuid);
2369
}
2370

    
2371
/**
2372
 * @todo Please document this function.
2373
 * @see http://drupal.org/node/1354
2374
 */
2375
function _cdm_api_secref_cache_add($secUuidsStr) {
2376
  global $_cdm_api_secref_cache;
2377
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2378
  // Batch fetching not jet reimplemented thus:
2379
  /*
2380
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2381
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2382
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2383
  */
2384
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2385
}
2386

    
2387
/**
2388
 * Checks if the given uri starts with a cdm webservice url.
2389
 *
2390
 * Checks if the uri starts with the cdm webservice url stored in the
2391
 * Drupal variable 'cdm_webservice_url'.
2392
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2393
 *
2394
 * @param string $uri
2395
 *   The URI to test.
2396
 *
2397
 * @return bool
2398
 *   True if the uri starts with a cdm webservice url.
2399
 */
2400
function _is_cdm_ws_uri($uri) {
2401
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2402
}
2403

    
2404
/**
2405
 * @todo Please document this function.
2406
 * @see http://drupal.org/node/1354
2407
 */
2408
function queryString($elements) {
2409
  $query = '';
2410
  foreach ($elements as $key => $value) {
2411
    if (is_array($value)) {
2412
      foreach ($value as $v) {
2413
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2414
      }
2415
    }
2416
    else {
2417
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2418
    }
2419
  }
2420
  return $query;
2421
}
2422

    
2423
/**
2424
 * Implementation of the magic method __clone to allow deep cloning of objects
2425
 * and arrays.
2426
 */
2427
function __clone() {
2428
  foreach ($this as $name => $value) {
2429
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2430
      $this->$name = clone($this->$name);
2431
    }
2432
  }
2433
}
2434

    
2435
/**
2436
 * Compares the given CDM Term instances by the  representationL10n.
2437
 *
2438
 * Can also be used with TermDTOs. To be used in usort()
2439
 *
2440
 * @see http://php.net/manual/en/function.usort.php
2441
 *
2442
 * @param $term1
2443
 *   The first CDM Term instance
2444
 * @param $term2
2445
 *   The second CDM Term instance
2446
 * @return int
2447
 *   The result of the comparison
2448
 */
2449
function compare_terms_by_representationL10n($term1, $term2) {
2450

    
2451
  if (!isset($term1->representation_L10n)) {
2452
    $term1->representationL10n = '';
2453
  }
2454
  if (!isset($term2->representation_L10n)) {
2455
    $term2->representationL10n = '';
2456
  }
2457

    
2458
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2459
}
2460

    
2461
function compare_terms_by_order_index($term1, $term2) {
2462

    
2463

    
2464
  if (!isset($term1->orderIndex)) {
2465
    $a = 0;
2466
  } else {
2467
    $a = $term1->orderIndex;
2468
  }
2469
  if (!isset($term2->orderIndex)) {
2470
    $b = 0;
2471
  } else {
2472
    $b = $term2->orderIndex;
2473
  }
2474

    
2475
  if ($a == $b) {
2476
    return 0;
2477
  }
2478
  return ($a < $b) ? -1 : 1;
2479

    
2480
}
2481

    
2482

    
2483
/**
2484
 * Make a 'deep copy' of an array.
2485
 *
2486
 * Make a complete deep copy of an array replacing
2487
 * references with deep copies until a certain depth is reached
2488
 * ($maxdepth) whereupon references are copied as-is...
2489
 *
2490
 * @see http://us3.php.net/manual/en/ref.array.php
2491
 *
2492
 * @param array $array
2493
 * @param array $copy passed by reference
2494
 * @param int $maxdepth
2495
 * @param int $depth
2496
 */
2497
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2498
  if ($depth > $maxdepth) {
2499
    $copy = $array;
2500
    return;
2501
  }
2502
  if (!is_array($copy)) {
2503
    $copy = array();
2504
  }
2505
  foreach ($array as $k => &$v) {
2506
    if (is_array($v)) {
2507
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2508
    }
2509
    else {
2510
      $copy[$k] = $v;
2511
    }
2512
  }
2513
}
2514

    
2515
/**
2516
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2517
 *
2518
 */
2519
function _add_js_ws_debug() {
2520

    
2521
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2522
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2523
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2524
    // use the developer versions of js libs
2525
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2526
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2527
  }
2528
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2529
    array(
2530
      'type' => 'file',
2531
      'weight' => JS_LIBRARY,
2532
      'cache' => TRUE)
2533
    );
2534

    
2535
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2536
    array(
2537
      'type' => 'file',
2538
      'weight' => JS_LIBRARY,
2539
      'cache' => TRUE)
2540
    );
2541
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2542
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2543

    
2544
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2545
    array(
2546
      'type' => 'file',
2547
      'weight' => JS_LIBRARY,
2548
      'cache' => TRUE)
2549
    );
2550
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2551
    array(
2552
    'type' => 'file',
2553
    'weight' => JS_LIBRARY,
2554
    'cache' => TRUE)
2555
    );
2556

    
2557
}
2558

    
2559
/**
2560
 * @todo Please document this function.
2561
 * @see http://drupal.org/node/1354
2562
 */
2563
function _no_classfication_uuid_message() {
2564
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2565
    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.');
2566
  }
2567
  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.');
2568
}
2569

    
2570
/**
2571
 * Implementation of hook flush_caches
2572
 *
2573
 * Add custom cache tables to the list of cache tables that
2574
 * will be cleared by the Clear button on the Performance page or whenever
2575
 * drupal_flush_all_caches is invoked.
2576
 *
2577
 * @author W.Addink <waddink@eti.uva.nl>
2578
 *
2579
 * @return array
2580
 *   An array with custom cache tables to include.
2581
 */
2582
function cdm_api_flush_caches() {
2583
  return array('cache_cdm_ws');
2584
}
2585

    
2586
/**
2587
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2588
 *
2589
 * @param $data
2590
 *   The variable to log to the drupal_debug.txt log file.
2591
 * @param $label
2592
 *   (optional) If set, a label to output before $data in the log file.
2593
 *
2594
 * @return
2595
 *   No return value if successful, FALSE if the log file could not be written
2596
 *   to.
2597
 *
2598
 * @see cdm_dataportal_init() where the log file is reset on each requests
2599
 * @see dd()
2600
 * @see http://drupal.org/node/314112
2601
 *
2602
 */
2603
function cdm_dd($data, $label = NULL) {
2604
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2605
    return dd($data, $label);
2606
  }
2607
}
2608

    
(5-5/12)