Project

General

Profile

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

    
24
  module_load_include('php', 'cdm_api', 'xml2json');
25
  module_load_include('php', 'cdm_api', 'commons');
26
  module_load_include('php', 'cdm_api', 'uuids');
27
  module_load_include('php', 'cdm_api', 'enums');
28
  module_load_include('php', 'cdm_api', 'webservice_uris');
29
  module_load_include('php', 'cdm_api', 'cdm_node');
30
  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
 * Converts an ISO 8601 org.joda.time.Partial to a year.
425
 *
426
 * The function expects an ISO 8601 time representation of a
427
 * org.joda.time.Partial of the form yyyy-MM-dd.
428
 *
429
 * @param string $partial
430
 *   ISO 8601 time representation of a org.joda.time.Partial.
431
 *
432
 * @return string
433
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
434
 */
435
function partialToYear($partial) {
436
  if (is_string($partial)) {
437
    $year = substr($partial, 0, 4);
438
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
439
      return $year;
440
    }
441
  }
442
  return '';
443
}
444

    
445
/**
446
 * Converts an ISO 8601 org.joda.time.Partial to a month.
447
 *
448
 * This function expects an ISO 8601 time representation of a
449
 * org.joda.time.Partial of the form yyyy-MM-dd.
450
 * In case the month is unknown (= ???) NULL is returned.
451
 *
452
 * @param string $partial
453
 *   ISO 8601 time representation of a org.joda.time.Partial.
454
 *
455
 * @return string
456
 *   A month.
457
 */
458
function partialToMonth($partial) {
459
  if (is_string($partial)) {
460
    $month = substr($partial, 5, 2);
461
    if (preg_match("/[0-9][0-9]/", $month)) {
462
      return $month;
463
    }
464
  }
465
  return '';
466
}
467

    
468
/**
469
 * Converts an ISO 8601 org.joda.time.Partial to a day.
470
 *
471
 * This function expects an ISO 8601 time representation of a
472
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
473
 * In case the day is unknown (= ???) NULL is returned.
474
 *
475
 * @param string $partial
476
 *   ISO 8601 time representation of a org.joda.time.Partial.
477
 *
478
 * @return string
479
 *   A day.
480
 */
481
function partialToDay($partial) {
482
  if (is_string($partial)) {
483
    $day = substr($partial, 8, 2);
484
    if (preg_match("/[0-9][0-9]/", $day)) {
485
      return $day;
486
    }
487
  }
488
  return '';
489
}
490

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

    
518
  $y = NULL; $m = NULL; $d = NULL;
519

    
520
  if(strpos($format, 'YY') !== FALSE){
521
    $y = partialToYear($partial);
522
  }
523
  if(strpos($format, 'MM') !== FALSE){
524
    $m = partialToMonth($partial);
525
  }
526
  if(strpos($format, 'DD') !== FALSE){
527
    $d = partialToDay($partial);
528
  }
529

    
530
  $y = $y ? $y : '00';
531
  $m = $m ? $m : '00';
532
  $d = $d ? $d : '00';
533

    
534
  $date = '';
535

    
536
  if ($y == '00' && $stripZeros) {
537
    return '';
538
  }
539
  else {
540
    $date = $y;
541
  }
542

    
543
  if ($m == '00' && $stripZeros) {
544
    return $date;
545
  }
546
  else {
547
    $date .= "-" . $m;
548
  }
549

    
550
  if ($d == '00' && $stripZeros) {
551
    return $date;
552
  }
553
  else {
554
    $date .= "-" . $d;
555
  }
556
  return $date;
557
}
558

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

    
593
/**
594
 * returns the earliest date available in the $period in a normalized
595
 * form suitable for sorting, e.g.:
596
 *
597
 *  - 1956-00-00
598
 *  - 0000-00-00
599
 *  - 1957-03-00
600
 *
601
 * that is either the start date is returned if set otherwise the
602
 * end date
603
 *
604
 * @param  $period
605
 *    An JodaTime org.joda.time.Period object.
606
 * @return string normalized form of the date
607
 *   suitable for sorting
608
 */
609
function timePeriodAsOrderKey($period) {
610
  $dateString = '';
611
  if ($period->start) {
612
    $dateString = partialToDate($period->start, false);
613
  }
614
  if ($period->end) {
615
    $dateString .= partialToDate($period->end, false);
616
  }
617
  return $dateString;
618
}
619

    
620
/**
621
 * Composes a absolute CDM web service URI with parameters and querystring.
622
 *
623
 * @param string $uri_pattern
624
 *   String with place holders ($0, $1, ..) that should be replaced by the
625
 *   according element of the $pathParameters array.
626
 * @param array $pathParameters
627
 *   An array of path elements, or a single element.
628
 * @param string $query
629
 *   A query string to append to the URL.
630
 *
631
 * @return string
632
 *   A complete URL with parameters to a CDM webservice.
633
 */
634
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
635
  if (empty($pathParameters)) {
636
    $pathParameters = array();
637
  }
638

    
639
  // (1)
640
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
641
  // according element of the $pathParameters array.
642
  static $helperArray = array();
643
  if (isset($pathParameters) && !is_array($pathParameters)) {
644
    $helperArray[0] = $pathParameters;
645
    $pathParameters = $helperArray;
646
  }
647

    
648
  $i = 0;
649
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
650
    if (count($pathParameters) <= $i) {
651
        drupal_set_message(
652
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
653
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
654
          'error');
655
      break;
656
    }
657
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
658
    ++$i;
659
  }
660

    
661
  // (2)
662
  // Append all remaining element of the $pathParameters array as path
663
  // elements.
664
  if (count($pathParameters) > $i) {
665
    // Strip trailing slashes.
666
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
667
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
668
    }
669
    while (count($pathParameters) > $i) {
670
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
671
      ++$i;
672
    }
673
  }
674

    
675
  // (3)
676
  // Append the query string supplied by $query.
677
  if (isset($query)) {
678
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
679
  }
680

    
681
  $path = $uri_pattern;
682

    
683
  $uri = variable_get('cdm_webservice_url', '') . $path;
684
  return $uri;
685
}
686

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

    
706
  $args = func_get_args();
707
  $do_gzip = function_exists('gzencode');
708
  $uriEncoded = array_shift($args);
709
  $uri = urldecode($uriEncoded);
710
  $hook = array_shift($args);
711
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
712

    
713
  $post_data = null;
714

    
715
  if ($request_method == "POST" || $request_method == "PUT") {
716
    // read response body via inputstream module
717
    $post_data = file_get_contents("php://input");
718
  }
719

    
720
  // Find and deserialize arrays.
721
  foreach ($args as &$arg) {
722
    // FIXME use regex to find serialized arrays.
723
    //       or should we accept json instead of php serializations?
724
    if (strpos($arg, "a:") === 0) {
725
      $arg = unserialize($arg);
726
    }
727
  }
728

    
729
  // In all these cases perform a simple get request.
730
  // TODO reconsider caching logic in this function.
731

    
732
  if (empty($hook)) {
733
    // simply return the webservice response
734
    // Print out JSON, the cache cannot be used since it contains objects.
735
    $http_response = cdm_http_request($uri, $request_method, $post_data);
736
    if (isset($http_response->headers)) {
737
      foreach ($http_response->headers as $hname => $hvalue) {
738
        drupal_add_http_header($hname, $hvalue);
739
      }
740
    }
741
    if (isset($http_response->data)) {
742
      print $http_response->data;
743
      flush();
744
    }
745
    exit(); // leave drupal here
746
  } else {
747
    // $hook has been supplied
748
    // handle $hook either as compose ot theme hook
749
    // pass through theme or comose hook
750
    // compose hooks can be called without data, therefore
751
    // passing the $uri in this case is not always a requirement
752

    
753
    if($uri && $uri != 'NULL') {
754
    // do a security check since the $uri will be passed
755
    // as absolute URI to cdm_ws_get()
756
      if (!_is_cdm_ws_uri($uri)) {
757
        drupal_set_message(
758
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
759
          'error'
760
        );
761
        return '';
762
      }
763

    
764
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
765
    } else {
766
      $obj = NULL;
767
    }
768

    
769
    $reponse_data = NULL;
770

    
771
    if (function_exists('compose_' . $hook)){
772
      // call compose hook
773

    
774
      $elements =  call_user_func('compose_' . $hook, $obj);
775
      // pass the render array to drupal_render()
776
      $reponse_data = drupal_render($elements);
777
    } else {
778
      // call theme hook
779

    
780
      // TODO use theme registry to get the registered hook info and
781
      //    use these defaults
782
      switch($hook) {
783
        case 'cdm_taxontree':
784
          $variables = array(
785
            'tree' => $obj,
786
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
787
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
788
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
789
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
790
            );
791
          $reponse_data = theme($hook, $variables);
792
          break;
793

    
794
        case 'cdm_list_of_taxa':
795
            $variables = array(
796
              'records' => $obj,
797
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
798
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
799
            $reponse_data = theme($hook, $variables);
800
            break;
801

    
802
        case 'cdm_media_caption':
803
          $variables = array(
804
            'media' => $obj,
805
            // $args[0] is set in taxon_image_gallery_default in
806
            // cdm_dataportal.page.theme.
807
            'elements' => isset($args[0]) ? $args[0] : array(
808
            'title',
809
            'description',
810
            'artist',
811
            'location',
812
            'rights',
813
          ),
814
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
815
          );
816
          $reponse_data = theme($hook, $variables);
817
          break;
818

    
819
        default:
820
          drupal_set_message(t(
821
          'Theme !theme is not yet supported by the function !function.', array(
822
          '!theme' => $hook,
823
          '!function' => __FUNCTION__,
824
          )), 'error');
825
          break;
826
      } // END of theme hook switch
827
    } // END of tread as theme hook
828

    
829

    
830
    if($do_gzip){
831
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
832
      drupal_add_http_header('Content-Encoding', 'gzip');
833
    }
834
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
835
    drupal_add_http_header('Content-Length', strlen($reponse_data));
836

    
837
    print $reponse_data;
838
  } // END of handle $hook either as compose ot theme hook
839

    
840
}
841

    
842
/**
843
 * @todo Please document this function.
844
 * @see http://drupal.org/node/1354
845
 */
846
function setvalue_session() {
847
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
848
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
849
    $var_keys = explode('][', $var_keys);
850
  }
851
  else {
852
    return;
853
  }
854
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
855

    
856
  // Prevent from malicous tags.
857
  $val = strip_tags($val);
858

    
859
  $session_var = &$_SESSION;
860
  //$i = 0;
861
  foreach ($var_keys as $key) {
862
    // $hasMoreKeys = ++$i < count($session);
863
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
864
      $session_var[$key] = array();
865
    }
866
    $session_var = &$session_var[$key];
867
  }
868
  $session_var = $val;
869
  if (isset($_REQUEST['destination'])) {
870
    drupal_goto($_REQUEST['destination']);
871
  }
872
}
873

    
874
/**
875
 * @todo Please document this function.
876
 * @see http://drupal.org/node/1354
877
 */
878
function uri_uriByProxy($uri, $theme = FALSE) {
879
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
880
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
881
}
882

    
883
/**
884
 * Composes the the absolute REST service URI to the annotations pager
885
 * for the given CDM entity.
886
 *
887
 * NOTE: Not all CDM Base types are yet supported.
888
 *
889
 * @param $cdmBase
890
 *   The CDM entity to construct the annotations pager uri for
891
 */
892
function cdm_compose_annotations_uri($cdmBase) {
893

    
894
  if (!$cdmBase->uuid) {
895
    return;
896
  }
897

    
898
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
899

    
900
  if($ws_base_uri === null){
901
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
902
  }
903
  return cdm_compose_url($ws_base_uri, array(
904
    $cdmBase->uuid,
905
    'annotations',
906
  ));
907
}
908

    
909
/**
910
 * Provides the base URI of the cdm REST service responsible for the passed simple name
911
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
912
 *
913
 * @param $cdm_type_simple
914
 *    simple name of a CDM java class
915
 * @return null|string
916
 */
917
function cdm_ws_base_uri($cdm_type_simple)
918
{
919
  $ws_base_uri = NULL;
920
  switch ($cdm_type_simple) {
921
    case 'TaxonBase':
922
    case 'Taxon':
923
    case 'Synonym':
924
      $ws_base_uri = CDM_WS_TAXON;
925
      break;
926

    
927
    case 'TaxonName':
928
      $ws_base_uri = CDM_WS_NAME;
929
      break;
930

    
931
    case 'Media':
932
      $ws_base_uri = CDM_WS_MEDIA;
933
      break;
934

    
935
    case 'Reference':
936
      $ws_base_uri = CDM_WS_REFERENCE;
937
      break;
938

    
939
    case 'Distribution':
940
    case 'TextData':
941
    case 'TaxonInteraction':
942
    case 'QuantitativeData':
943
    case 'IndividualsAssociation':
944
    case 'CommonTaxonName':
945
    case 'CategoricalData':
946
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
947
      break;
948

    
949
    case 'PolytomousKey':
950
    case 'MediaKey':
951
    case 'MultiAccessKey':
952
      $ws_base_uri = $cdm_type_simple;
953
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
954
      break;
955

    
956
    default:
957
      $ws_base_uri = null;
958
  }
959
  return $ws_base_uri;
960
}
961

    
962
/**
963
 * Enter description here...
964
 *
965
 * @param string $resourceURI
966
 * @param int $pageSize
967
 *   The maximum number of entities returned per page.
968
 *   The default page size as configured in the cdm server
969
 *   will be used if set to NULL
970
 *   to return all entities in a single page).
971
 * @param int $pageNumber
972
 *   The number of the page to be returned, the first page has the
973
 *   pageNumber = 0
974
 * @param array $query
975
 *   A array holding the HTTP request query parameters for the request
976
 * @param string $method
977
 *   The HTTP method to use, valid values are "GET" or "POST"
978
 * @param bool $absoluteURI
979
 *   TRUE when the URL should be treated as absolute URL.
980
 *
981
 * @return the a CDM Pager object
982
 *
983
 */
984
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
985

    
986
  $query['pageNumber'] = $pageNumber;
987
  $query['pageSize'] = $pageSize;
988

    
989
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
990
}
991

    
992
/**
993
 * Fetches all entities from the given REST endpoint using the pager mechanism.
994
 *
995
 * @param string $resourceURI
996
 * @param array $query
997
 *   A array holding the HTTP request query parameters for the request
998
 * @param string $method
999
 *   The HTTP method to use, valid values are "GET" or "POST";
1000
 * @param bool $absoluteURI
1001
 *   TRUE when the URL should be treated as absolute URL.
1002
 *
1003
 * @return array
1004
 *     A list of CDM entitites
1005
 *
1006
 */
1007
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1008
  $page_index = 0;
1009
  // using a bigger page size to avoid to many multiple requests
1010
  $page_size = 500;
1011
  $entities = array();
1012

    
1013
  while ($page_index !== FALSE){
1014
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1015
    if(isset($pager->records) && is_array($pager->records)) {
1016
      $entities = array_merge($entities, $pager->records);
1017
      if(!empty($pager->nextIndex)){
1018
        $page_index = $pager->nextIndex;
1019
      } else {
1020
        $page_index = FALSE;
1021
      }
1022
    } else {
1023
      $page_index = FALSE;
1024
    }
1025
  }
1026
  return $entities;
1027
}
1028

    
1029
/*
1030
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1031
  $viewrank = _cdm_taxonomy_compose_viewrank();
1032
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1033
  ? '/' . $path : '') ;
1034
}
1035
*/
1036

    
1037
/**
1038
 * @todo Enter description here...
1039
 *
1040
 * @param string $taxon_uuid
1041
 *  The UUID of a cdm taxon instance
1042
 * @param string $ignore_rank_limit
1043
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1044
 *
1045
 * @return string
1046
 *   A cdm REST service URL path to a Classification
1047
 */
1048
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1049

    
1050
  $view_uuid = get_current_classification_uuid();
1051
  $rank_uuid = NULL;
1052
  if (!$ignore_rank_limit) {
1053
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1054
  }
1055

    
1056
  if (!empty($taxon_uuid)) {
1057
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1058
      $view_uuid,
1059
      $taxon_uuid,
1060
    ));
1061
  }
1062
  else {
1063
    if (is_uuid($rank_uuid)) {
1064
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1065
        $view_uuid,
1066
        $rank_uuid,
1067
      ));
1068
    }
1069
    else {
1070
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1071
        $view_uuid,
1072
      ));
1073
    }
1074
  }
1075
}
1076

    
1077
/**
1078
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1079
 *
1080
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1081
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1082
 *
1083
 * Operates in two modes depending on whether the parameter
1084
 * $taxon_uuid is set or NULL.
1085
 *
1086
 * A) $taxon_uuid = NULL:
1087
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1088
 *  2. otherwise return the default classification as defined by the admin via the settings
1089
 *
1090
 * b) $taxon_uuid is set:
1091
 *   return the classification to whcih the taxon belongs to.
1092
 *
1093
 * @param UUID $taxon_uuid
1094
 *   The UUID of a cdm taxon instance
1095
 */
1096
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1097

    
1098
    $response = NULL;
1099

    
1100
    // 1st try
1101
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1102

    
1103
    if ($response == NULL) {
1104
      // 2dn try by ignoring the rank limit
1105
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1106
    }
1107

    
1108
    if ($response == NULL) {
1109
      // 3rd try, last fallback:
1110
      //    return the default classification
1111
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1112
        // Delete the session value and try again with the default.
1113
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1114
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1115
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1116
      }
1117
      else {
1118
        // Check if taxonomictree_uuid is valid.
1119
        // expecting an array of taxonNodes,
1120
        // empty classifications are ok so no warning in this case!
1121
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1122
        if (!is_array($test)) {
1123
          // The default set by the admin seems to be invalid or is not even set.
1124
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1125
        }
1126
        if (count($test) == 0) {
1127
          // The default set by the admin seems to be invalid or is not even set.
1128
          drupal_set_message("The chosen classification is empty.", 'status');
1129
        }
1130
      }
1131
    }
1132

    
1133
  return $response;
1134
}
1135

    
1136
/**
1137
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1138
 * 
1139
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1140
 * variable is set.
1141
 *
1142
 * @param string $taxon_uuid
1143
 *
1144
 * @return array
1145
 *   An array of CDM TaxonNodeDTO objects
1146
 */
1147
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1148
  $view_uuid = get_current_classification_uuid();
1149
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1150

    
1151
  $response = NULL;
1152
  if (is_uuid($rank_uuid)) {
1153
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1154
      $view_uuid,
1155
      $taxon_uuid,
1156
      $rank_uuid,
1157
    ));
1158
  }
1159
  else {
1160
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1161
      $view_uuid,
1162
      $taxon_uuid,
1163
    ));
1164
  }
1165

    
1166
  if ($response == NULL) {
1167
    // Error handing.
1168
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1169
//      // Delete the session value and try again with the default.
1170
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1171
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1172
//    }
1173
//    else {
1174
      // Check if taxonomictree_uuid is valid.
1175
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1176
      if ($test == NULL) {
1177
        // The default set by the admin seems to be invalid or is not even set.
1178
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1179
      }
1180
//    }
1181
  }
1182

    
1183
  return $response;
1184
}
1185

    
1186

    
1187
// =============================Terms and Vocabularies ========================================= //
1188

    
1189
/**
1190
 * Returns the localized representation for the given term.
1191
 *
1192
 * @param Object $definedTermBase
1193
 * 	  of cdm type DefinedTermBase
1194
 * @return string
1195
 * 	  the localized representation_L10n of the term,
1196
 *    otherwise the titleCache as fall back,
1197
 *    otherwise the default_representation which defaults to an empty string
1198
 */
1199
function cdm_term_representation($definedTermBase, $default_representation = '') {
1200
  if ( isset($definedTermBase->representation_L10n) ) {
1201
    return $definedTermBase->representation_L10n;
1202
  } elseif ( isset($definedTermBase->titleCache)) {
1203
    return $definedTermBase->titleCache;
1204
  }
1205
  return $default_representation;
1206
}
1207

    
1208
/**
1209
 * Returns the abbreviated localized representation for the given term.
1210
 *
1211
 * @param Object $definedTermBase
1212
 * 	  of cdm type DefinedTermBase
1213
 * @return string
1214
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1215
 *    if this representation is not available the function delegates the
1216
 *    call to cdm_term_representation()
1217
 */
1218
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1219
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1220
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1221
  } else {
1222
    cdm_term_representation($definedTermBase, $default_representation);
1223
  }
1224
}
1225

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

    
1257
  if($empty_option !== FALSE){
1258
    array_unshift ($options, "");
1259
  }
1260

    
1261
  return $options;
1262
}
1263

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

    
1284
  static $vocabularyOptions = array();
1285

    
1286
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1287
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1288
      array(
1289
        'orderBy' => $order_by
1290
      )
1291
    );
1292

    
1293
    // apply the include filter
1294
    if($include_filter != null){
1295
      $included_terms = array();
1296

    
1297
      foreach ($terms as $term){
1298
        $include = true;
1299
        foreach ($include_filter as $field=>$regex){
1300
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1301
          if(!$include){
1302
            break;
1303
          }
1304
        }
1305
        if($include){
1306
          $included_terms[] = $term;
1307
        }
1308
      }
1309

    
1310
      $terms = $included_terms;
1311
    }
1312

    
1313
    // make options list
1314
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1315
  }
1316

    
1317
  $options = $vocabularyOptions[$vocabulary_uuid];
1318

    
1319
  return $options;
1320
}
1321

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

    
1387

    
1388
/**
1389
 * @todo Please document this function.
1390
 * @see http://drupal.org/node/1354
1391
 */
1392
function _cdm_relationship_type_term_label_callback($term) {
1393
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1394
    return $term->representation_L10n_abbreviatedLabel . ' : '
1395
    . t('@term', array('@term' => $term->representation_L10n));
1396
  }
1397
else {
1398
    return t('@term', array('@term' => $term->representation_L10n));
1399
  }
1400
}
1401

    
1402
// ========================================================================================== //
1403
/**
1404
 * @todo Improve documentation of this function.
1405
 *
1406
 * eu.etaxonomy.cdm.model.description.
1407
 * CategoricalData
1408
 * CommonTaxonName
1409
 * Distribution
1410
 * IndividualsAssociation
1411
 * QuantitativeData
1412
 * TaxonInteraction
1413
 * TextData
1414
 */
1415
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1416
  static $types = array(
1417
    "CategoricalData",
1418
    "CommonTaxonName",
1419
    "Distribution",
1420
    "IndividualsAssociation",
1421
    "QuantitativeData",
1422
    "TaxonInteraction",
1423
    "TextData",
1424
  );
1425

    
1426
  static $options = NULL;
1427
  if ($options == NULL) {
1428
    $options = array();
1429
    if ($prependEmptyElement) {
1430
      $options[' '] = '';
1431
    }
1432
    foreach ($types as $type) {
1433
      // No internatianalization here since these are purely technical terms.
1434
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1435
    }
1436
  }
1437
  return $options;
1438
}
1439

    
1440

    
1441
/**
1442
 * Fetches all TaxonDescription descriptions elements which are associated to the
1443
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1444
 * feature tree.
1445
 * @param $feature_tree
1446
 *     The CDM FeatureTree to be used as template
1447
 * @param $taxon_uuid
1448
 *     The UUID of the taxon
1449
 * @param $excludes
1450
 *     UUIDs of features to be excluded
1451
 * @return$feature_tree
1452
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1453
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1454
 *     witch will hold the according $descriptionElements.
1455
 */
1456
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1457

    
1458
  if (!$feature_tree) {
1459
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1460
      In order to see the species profiles of your taxa, please select a
1461
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1462
    return FALSE;
1463
  }
1464

    
1465
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1466
      array(
1467
      'taxon' => $taxon_uuid,
1468
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1469
      ),
1470
      'POST'
1471
  );
1472

    
1473
  // Combine all descriptions into one feature tree.
1474
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1475
  $feature_tree->root->childNodes = $merged_nodes;
1476

    
1477
  return $feature_tree;
1478
}
1479

    
1480
/**
1481
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1482
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1483
 * be requested for the annotations.
1484
 *
1485
 * @param string $cdmBase
1486
 *   An annotatable cdm entity.
1487
 * @param array $includeTypes
1488
 *   If an array of annotation type uuids is supplied by this parameter the
1489
 *   list of annotations is resticted to those which belong to this type.
1490
 *
1491
 * @return array
1492
 *   An array of Annotation objects or an empty array.
1493
 */
1494
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1495

    
1496
  if(!isset($cdmBase->annotations)){
1497
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1498
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1499
  }
1500

    
1501
  $annotations = array();
1502
  foreach ($cdmBase->annotations as $annotation) {
1503
    if ($includeTypes) {
1504
      if (
1505
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1506
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1507
      ) {
1508
        $annotations[] = $annotation;
1509
      }
1510
    }
1511
    else {
1512
      $annotations[] = $annotation;
1513
    }
1514
  }
1515
  return $annotations;
1516

    
1517
}
1518

    
1519
/**
1520
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1521
 *
1522
 * @param object $annotatable_entity
1523
 *   The CDM AnnotatableEntity to load annotations for
1524
 */
1525
function cdm_load_annotations(&$annotatable_entity) {
1526
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1527
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1528
    if (is_array($annotations)) {
1529
      $annotatable_entity->annotations = $annotations;
1530
    }
1531
  }
1532
}
1533

    
1534
/**
1535
 * Extends the $cdm_entity object by the field if it is not already existing.
1536
 *
1537
 * This function can only be used for fields with 1 to many relations.
1538
  *
1539
 * @param $cdm_base_type
1540
 * @param $field_name
1541
 * @param $cdm_entity
1542
 */
1543
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1544
{
1545
  if (!isset($cdm_entity->$field_name)) {
1546
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1547
    $cdm_entity->$field_name = $items;
1548
  }
1549
}
1550

    
1551

    
1552
/**
1553
 * Get a NomenclaturalReference string.
1554
 *
1555
 * Returns the NomenclaturalReference string with correctly placed
1556
 * microreference (= reference detail) e.g.
1557
 * in Phytotaxa 43: 1-48. 2012.
1558
 *
1559
 * @param string $referenceUuid
1560
 *   UUID of the reference.
1561
 * @param string $microreference
1562
 *   Reference detail.
1563
 *
1564
 * @return string
1565
 *   a NomenclaturalReference.
1566
 */
1567
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1568

    
1569
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1570
  if(is_array($microreference) || is_object($microreference)) {
1571
    return '';
1572
  }
1573

    
1574
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1575
    $referenceUuid,
1576
  ), "microReference=" . urlencode($microreference));
1577

    
1578
  if ($obj) {
1579
    return $obj->String;
1580
  }
1581
  else {
1582
    return NULL;
1583
  }
1584
}
1585

    
1586
/**
1587
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1588
 *
1589
 * @param $feature_tree_nodes
1590
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1591
 * @param $feature_uuid
1592
 *    The UUID of the Feature
1593
 * @return returns the FeatureNode or null
1594
 */
1595
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1596

    
1597
  // 1. scan this level
1598
  foreach ($feature_tree_nodes as $node){
1599
    if($node->feature->uuid == $feature_uuid){
1600
      return $node;
1601
    }
1602
  }
1603

    
1604
  // 2. descend into childen
1605
  foreach ($feature_tree_nodes as $node){
1606
    if(is_array($node->childNodes)){
1607
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1608
      if($node) {
1609
        return $node;
1610
      }
1611
    }
1612
  }
1613
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1614
  return $null_var;
1615
}
1616

    
1617
/**
1618
 * Merges the given featureNodes structure with the descriptionElements.
1619
 *
1620
 * This method is used in preparation for rendering the descriptionElements.
1621
 * The descriptionElements which belong to a specific feature node are appended
1622
 * to a the feature node by creating a new field:
1623
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1624
 * The descriptionElements will be cleared in advance in order to allow reusing the
1625
 * same feature tree without the risk of mixing sets of description elements.
1626
 *
1627
 * which originally is not existing in the cdm.
1628
 *
1629
 *
1630
 *
1631
 * @param array $featureNodes
1632
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1633
 *    may have children.
1634
 * @param array $descriptionElements
1635
 *    An flat array of cdm DescriptionElements
1636
 * @return array
1637
 *    The $featureNodes structure enriched with the according $descriptionElements
1638
 */
1639
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1640

    
1641
  foreach ($featureNodes as &$node) {
1642
    // since the $featureNodes array is reused for each description
1643
    // it is necessary to clear the custom node fields in advance
1644
    if(isset($node->descriptionElements)){
1645
      unset($node->descriptionElements);
1646
    }
1647

    
1648
    // Append corresponding elements to an additional node field:
1649
    // $node->descriptionElements.
1650
    foreach ($descriptionElements as $element) {
1651
      if ($element->feature->uuid == $node->feature->uuid) {
1652
        if (!isset($node->descriptionElements)) {
1653
          $node->descriptionElements = array();
1654
        }
1655
        $node->descriptionElements[] = $element;
1656
      }
1657
    }
1658

    
1659
    // Recurse into node children.
1660
    if (isset($node->childNodes[0])) {
1661
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1662
      $node->childNodes = $mergedChildNodes;
1663
    }
1664

    
1665
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1666
      unset($node);
1667
    }
1668

    
1669
  }
1670

    
1671
  return $featureNodes;
1672
}
1673

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

    
1710
  static $cacheL1 = array();
1711

    
1712
  $data = NULL;
1713
  // store query string in $data and clear the query, $data will be set as HTTP request body
1714
  if($method == 'POST'){
1715
    $data = $query;
1716
    $query = NULL;
1717
  }
1718

    
1719
  // Transform the given uri path or pattern into a proper webservice uri.
1720
  if (!$absoluteURI) {
1721
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1722
  }
1723
  cdm_ws_apply_classification_subtree_filter($uri);
1724

    
1725
  // read request parameter 'cacheL2_refresh'
1726
  // which allows refreshing the level 2 cache
1727
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1728

    
1729
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1730
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1731

    
1732
  if($method == 'GET'){
1733
    $cache_key = $uri;
1734
  } else {
1735
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1736
    // crc32 is faster but creates much shorter hashes
1737
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1738
  }
1739

    
1740
  if (array_key_exists($cache_key, $cacheL1)) {
1741
    $cacheL1_obj = $cacheL1[$uri];
1742
  }
1743

    
1744
  $set_cacheL1 = FALSE;
1745
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1746
    $set_cacheL1 = TRUE;
1747
  }
1748

    
1749
  // Only cache cdm webservice URIs.
1750
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1751
  $cacheL2_entry = FALSE;
1752

    
1753
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1754
    // Try to get object from cacheL2.
1755
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1756
  }
1757

    
1758
  if (isset($cacheL1_obj)) {
1759
    //
1760
    // The object has been found in the L1 cache.
1761
    //
1762
    $obj = $cacheL1_obj;
1763
    if (cdm_debug_block_visible()) {
1764
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1765
    }
1766
  }
1767
  elseif ($cacheL2_entry) {
1768
    //
1769
    // The object has been found in the L2 cache.
1770
    //
1771
    $duration_parse_start = microtime(TRUE);
1772
    $obj = unserialize($cacheL2_entry->data);
1773
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1774

    
1775
    if (cdm_debug_block_visible()) {
1776
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1777
    }
1778
  }
1779
  else {
1780
    //
1781
    // Get the object from the webservice and cache it.
1782
    //
1783
    $duration_fetch_start = microtime(TRUE);
1784
    // Request data from webservice JSON or XML.
1785
    $response = cdm_http_request($uri, $method, $data);
1786
    $response_body = NULL;
1787
    if (isset($response->data)) {
1788
      $response_body = $response->data;
1789
    }
1790
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1791
    $duration_parse_start = microtime(TRUE);
1792

    
1793
    // Parse data and create object.
1794
    $obj = cdm_load_obj($response_body);
1795

    
1796
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1797

    
1798
    if (cdm_debug_block_visible()) {
1799
      if ($obj || $response_body == "[]") {
1800
        $status = 'valid';
1801
      }
1802
      else {
1803
        $status = 'invalid';
1804
      }
1805
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1806
    }
1807
    if ($set_cacheL2) {
1808
      // Store the object in cache L2.
1809
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1810
      // flag serialized is set properly in the cache table.
1811
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1812
    }
1813
  }
1814
  if ($obj) {
1815
    // Store the object in cache L1.
1816
    if ($set_cacheL1) {
1817
      $cacheL1[$cache_key] = $obj;
1818
    }
1819
  }
1820
  return $obj;
1821
}
1822

    
1823
function cdm_ws_apply_classification_subtree_filter(&$uri){
1824

    
1825
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
1826
    "#/classification/[0-9a-f\-]{36}/childNodes#",
1827
    /* covered by above pattern:
1828
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
1829
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
1830
    */
1831
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
1832
    /* covered by above pattern:
1833
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
1834
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
1835
    */
1836
    "#/portal/taxon/search#",
1837
    "#/portal/taxon/find#",
1838
    /* covered by above pattern:
1839
    "#/portal/taxon/findByDescriptionElementFullText#",
1840
    "#/portal/taxon/findByFullText#",
1841
    "#/portal/taxon/findByEverythingFullText#",
1842
    "#/portal/taxon/findByIdentifier#",
1843
    "#/portal/taxon/findByMarker#",
1844
    "#/portal/taxon/findByMarker#",
1845
    "#/portal/taxon/findByMarker#",
1846
    */
1847
    "#/portal/taxon/[0-9a-f\-]{36}#"
1848
    /* covered by above pattern:
1849
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
1850
    */
1851
  ));
1852

    
1853
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
1854
  if(is_uuid($sub_tree_filter_uuid_value)){
1855
    foreach($classification_subtree_filter_patterns as $preg_pattern){
1856
      if(preg_match($preg_pattern, $uri)){
1857
        // no need to take care for uri fragments with ws uris!
1858
        if(strpos( $uri, '?')){
1859
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
1860
        } else {
1861
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
1862
        }
1863
        break;
1864
      }
1865
    }
1866
  }
1867

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2001
  return $obj;
2002
}
2003

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

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

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

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

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

    
2066

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

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

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

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

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

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

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

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

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

    
2176
  foreach ($feature_trees as $featureTree) {
2177

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

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

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

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

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

    
2209
  } // END loop over feature trees
2210

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

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

    
2233
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2234

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

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

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

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

    
2269
  return $taxonomic_tree_options;
2270
}
2271

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

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

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

    
2322

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

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

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

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

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

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

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

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

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

    
2447
function compare_terms_by_order_index($term1, $term2) {
2448

    
2449

    
2450
  if (!isset($term1->orderIndex)) {
2451
    $a = 0;
2452
  } else {
2453
    $a = $term1->orderIndex;
2454
  }
2455
  if (!isset($term2->orderIndex)) {
2456
    $b = 0;
2457
  } else {
2458
    $b = $term2->orderIndex;
2459
  }
2460

    
2461
  if ($a == $b) {
2462
    return 0;
2463
  }
2464
  return ($a < $b) ? -1 : 1;
2465

    
2466
}
2467

    
2468

    
2469
/**
2470
 * Make a 'deep copy' of an array.
2471
 *
2472
 * Make a complete deep copy of an array replacing
2473
 * references with deep copies until a certain depth is reached
2474
 * ($maxdepth) whereupon references are copied as-is...
2475
 *
2476
 * @see http://us3.php.net/manual/en/ref.array.php
2477
 *
2478
 * @param array $array
2479
 * @param array $copy passed by reference
2480
 * @param int $maxdepth
2481
 * @param int $depth
2482
 */
2483
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2484
  if ($depth > $maxdepth) {
2485
    $copy = $array;
2486
    return;
2487
  }
2488
  if (!is_array($copy)) {
2489
    $copy = array();
2490
  }
2491
  foreach ($array as $k => &$v) {
2492
    if (is_array($v)) {
2493
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2494
    }
2495
    else {
2496
      $copy[$k] = $v;
2497
    }
2498
  }
2499
}
2500

    
2501
/**
2502
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2503
 *
2504
 */
2505
function _add_js_ws_debug() {
2506

    
2507
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2508
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2509
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2510
    // use the developer versions of js libs
2511
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2512
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2513
  }
2514
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2515
    array(
2516
      'type' => 'file',
2517
      'weight' => JS_LIBRARY,
2518
      'cache' => TRUE)
2519
    );
2520

    
2521
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2522
    array(
2523
      'type' => 'file',
2524
      'weight' => JS_LIBRARY,
2525
      'cache' => TRUE)
2526
    );
2527
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2528
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2529

    
2530
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2531
    array(
2532
      'type' => 'file',
2533
      'weight' => JS_LIBRARY,
2534
      'cache' => TRUE)
2535
    );
2536
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2537
    array(
2538
    'type' => 'file',
2539
    'weight' => JS_LIBRARY,
2540
    'cache' => TRUE)
2541
    );
2542

    
2543
}
2544

    
2545
/**
2546
 * @todo Please document this function.
2547
 * @see http://drupal.org/node/1354
2548
 */
2549
function _no_classfication_uuid_message() {
2550
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2551
    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.');
2552
  }
2553
  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.');
2554
}
2555

    
2556
/**
2557
 * Implementation of hook flush_caches
2558
 *
2559
 * Add custom cache tables to the list of cache tables that
2560
 * will be cleared by the Clear button on the Performance page or whenever
2561
 * drupal_flush_all_caches is invoked.
2562
 *
2563
 * @author W.Addink <waddink@eti.uva.nl>
2564
 *
2565
 * @return array
2566
 *   An array with custom cache tables to include.
2567
 */
2568
function cdm_api_flush_caches() {
2569
  return array('cache_cdm_ws');
2570
}
2571

    
2572
/**
2573
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2574
 *
2575
 * @param $data
2576
 *   The variable to log to the drupal_debug.txt log file.
2577
 * @param $label
2578
 *   (optional) If set, a label to output before $data in the log file.
2579
 *
2580
 * @return
2581
 *   No return value if successful, FALSE if the log file could not be written
2582
 *   to.
2583
 *
2584
 * @see cdm_dataportal_init() where the log file is reset on each requests
2585
 * @see dd()
2586
 * @see http://drupal.org/node/314112
2587
 *
2588
 */
2589
function cdm_dd($data, $label = NULL) {
2590
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2591
    return dd($data, $label);
2592
  }
2593
}
2594

    
(5-5/12)