Project

General

Profile

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

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

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

    
41

    
42

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

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

    
77

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

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

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

    
101
  return $items;
102
}
103

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

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

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

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

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

    
135

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

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

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

    
146
      $data = unserialize($data);
147

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

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

    
163
    _add_js_ws_debug();
164

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

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

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

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

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

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

    
232
  return $profile_featureTree;
233
}
234

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

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

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

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

    
290

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
547
  $date = '';
548

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

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

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

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

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

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

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

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

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

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

    
694
  $path = $uri_pattern;
695

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

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

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

    
726
  $post_data = null;
727

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

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

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

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

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

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

    
782
    $reponse_data = NULL;
783

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

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

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

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

    
815
        case 'cdm_media_caption':
816
          $variables = $arg;
817
          $variables['media'] = $obj;
818

    
819
          $reponse_data = theme($hook, $variables);
820
          break;
821

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

    
832

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

    
840
    print $reponse_data;
841
  } // END of handle $hook either as compose ot theme hook
842

    
843
}
844

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

    
859
  // Prevent from malicous tags.
860
  $val = strip_tags($val);
861

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

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

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

    
897
  if (!$cdmBase->uuid) {
898
    return;
899
  }
900

    
901
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
902

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

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

    
930
    case 'TaxonName':
931
      $ws_base_uri = CDM_WS_NAME;
932
      break;
933

    
934
    case 'Media':
935
      $ws_base_uri = CDM_WS_MEDIA;
936
      break;
937

    
938
    case 'Reference':
939
      $ws_base_uri = CDM_WS_REFERENCE;
940
      break;
941

    
942
    case 'Distribution':
943
    case 'TextData':
944
    case 'TaxonInteraction':
945
    case 'QuantitativeData':
946
    case 'IndividualsAssociation':
947
    case 'CommonTaxonName':
948
    case 'CategoricalData':
949
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
950
      break;
951

    
952
    case 'PolytomousKey':
953
    case 'MediaKey':
954
    case 'MultiAccessKey':
955
      $ws_base_uri = $cdm_type_simple;
956
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
957
      break;
958

    
959
    default:
960
      $ws_base_uri = null;
961
  }
962
  return $ws_base_uri;
963
}
964

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

    
990
  $query['pageNumber'] = $pageNumber;
991
  $query['pageSize'] = $pageSize;
992

    
993
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
994
}
995

    
996

    
997
/**
998
 * Sends a http GET request to the generic page method which allows for filtering entities by Restrictions.
999
 *
1000
 * @param $cdm_entity_type
1001
 * @param array $restrictions
1002
 *   An array of Restriction objects
1003
 * @param array $init_strategy
1004
 *   The init strategy to initialize the entity beans while being loaded from the
1005
 *   persistent storage by the cdm
1006
 * @param int $page_size
1007
 *   The maximum number of entities returned per page.
1008
 *   The default page size as configured in the cdm server
1009
 *   will be used if set to NULL
1010
 *   to return all entities in a single page).
1011
 * @param int $page_index
1012
 *   The number of the page to be returned, the first page has the
1013
 *   pageNumber = 0
1014
 *
1015
 * @return object
1016
 *   A CDM Pager object
1017
 *
1018
 */
1019
function cdm_ws_page_by_restriction($cdm_entity_type, array $restrictions, array $init_strategy, $page_size, $page_index) {
1020

    
1021
  $restrictions_json = array(); // json_encode($restrictions);
1022
  foreach ($restrictions as $restr){
1023
    $restrictions_json[] = json_encode($restr);
1024
  }
1025
  return cdm_ws_page(
1026
      'portal/' . cdm_ws_base_uri($cdm_entity_type),
1027
      $page_size,
1028
      $page_index,
1029
      array(
1030
        'restriction' => $restrictions_json,
1031
        'initStrategy' => $init_strategy
1032
      ),
1033
      "GET"
1034
    );
1035
}
1036

    
1037
/**
1038
 * Fetches all entities returned by the the generic page method for the Restrictions applied as filter.
1039
 *
1040
 * @param $cdm_entity_type
1041
 * @param array $restrictions
1042
 *   An array of Restriction objects
1043
 * @param array $init_strategy
1044
 *   The init strategy to initialize the entity beans while being loaded from the
1045
 *   persistent storage by the cdm
1046
 * @param int $page_size
1047
 *   The maximum number of entities returned per page.
1048
 *   The default page size as configured in the cdm server
1049
 *   will be used if set to NULL
1050
 *   to return all entities in a single page).
1051
 * @param int $page_index
1052
 *   The number of the page to be returned, the first page has the
1053
 *   pageNumber = 0
1054
 *
1055
 * @return array
1056
 *   A array of CDM entities
1057
 *
1058
 */
1059
function cdm_ws_fetch_all_by_restriction($cdm_entity_type, array $restrictions, array $init_strategy){
1060
  $page_index = 0;
1061
  // using a bigger page size to avoid to many multiple requests
1062
  $page_size = 500;
1063
  $entities = array();
1064

    
1065
  while ($page_index !== FALSE && $page_index < 1){
1066
    $pager =  cdm_ws_page_by_restriction($cdm_entity_type, $restrictions, $init_strategy, $page_size, $page_index);
1067
    if(isset($pager->records) && is_array($pager->records)) {
1068
      $entities = array_merge($entities, $pager->records);
1069
      if(!empty($pager->nextIndex)){
1070
        $page_index = $pager->nextIndex;
1071
      } else {
1072
        $page_index = FALSE;
1073
      }
1074
    } else {
1075
      $page_index = FALSE;
1076
    }
1077
  }
1078
  return $entities;
1079
}
1080

    
1081

    
1082
  /**
1083
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1084
 *
1085
 * @param string $resourceURI
1086
 * @param array $query
1087
 *   A array holding the HTTP request query parameters for the request
1088
 * @param string $method
1089
 *   The HTTP method to use, valid values are "GET" or "POST";
1090
 * @param bool $absoluteURI
1091
 *   TRUE when the URL should be treated as absolute URL.
1092
 *
1093
 * @return array
1094
 *     A list of CDM entitites
1095
 *
1096
 */
1097
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1098
  $page_index = 0;
1099
  // using a bigger page size to avoid to many multiple requests
1100
  $page_size = 500;
1101
  $entities = array();
1102

    
1103
  while ($page_index !== FALSE){
1104
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1105
    if(isset($pager->records) && is_array($pager->records)) {
1106
      $entities = array_merge($entities, $pager->records);
1107
      if(!empty($pager->nextIndex)){
1108
        $page_index = $pager->nextIndex;
1109
      } else {
1110
        $page_index = FALSE;
1111
      }
1112
    } else {
1113
      $page_index = FALSE;
1114
    }
1115
  }
1116
  return $entities;
1117
}
1118

    
1119
/*
1120
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1121
  $viewrank = _cdm_taxonomy_compose_viewrank();
1122
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1123
  ? '/' . $path : '') ;
1124
}
1125
*/
1126

    
1127
/**
1128
 * @todo Enter description here...
1129
 *
1130
 * @param string $taxon_uuid
1131
 *  The UUID of a cdm taxon instance
1132
 * @param string $ignore_rank_limit
1133
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1134
 *
1135
 * @return string
1136
 *   A cdm REST service URL path to a Classification
1137
 */
1138
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1139

    
1140
  $view_uuid = get_current_classification_uuid();
1141
  $rank_uuid = NULL;
1142
  if (!$ignore_rank_limit) {
1143
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1144
  }
1145

    
1146
  if (!empty($taxon_uuid)) {
1147
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1148
      $view_uuid,
1149
      $taxon_uuid,
1150
    ));
1151
  }
1152
  else {
1153
    if (is_uuid($rank_uuid)) {
1154
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1155
        $view_uuid,
1156
        $rank_uuid,
1157
      ));
1158
    }
1159
    else {
1160
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1161
        $view_uuid,
1162
      ));
1163
    }
1164
  }
1165
}
1166

    
1167
/**
1168
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1169
 *
1170
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1171
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1172
 *
1173
 * Operates in two modes depending on whether the parameter
1174
 * $taxon_uuid is set or NULL.
1175
 *
1176
 * A) $taxon_uuid = NULL:
1177
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1178
 *  2. otherwise return the default classification as defined by the admin via the settings
1179
 *
1180
 * b) $taxon_uuid is set:
1181
 *   return the classification to whcih the taxon belongs to.
1182
 *
1183
 * @param UUID $taxon_uuid
1184
 *   The UUID of a cdm taxon instance
1185
 */
1186
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1187

    
1188
    $response = NULL;
1189

    
1190
    // 1st try
1191
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1192

    
1193
    if ($response == NULL) {
1194
      // 2dn try by ignoring the rank limit
1195
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1196
    }
1197

    
1198
    if ($response == NULL) {
1199
      // 3rd try, last fallback:
1200
      //    return the default classification
1201
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1202
        // Delete the session value and try again with the default.
1203
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1204
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1205
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1206
      }
1207
      else {
1208
        // Check if taxonomictree_uuid is valid.
1209
        // expecting an array of taxonNodes,
1210
        // empty classifications are ok so no warning in this case!
1211
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1212
        if (!is_array($test)) {
1213
          // The default set by the admin seems to be invalid or is not even set.
1214
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1215
        }
1216
        if (count($test) == 0) {
1217
          // The default set by the admin seems to be invalid or is not even set.
1218
          drupal_set_message("The chosen classification is empty.", 'status');
1219
        }
1220
      }
1221
    }
1222

    
1223
  return $response;
1224
}
1225

    
1226
/**
1227
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1228
 * 
1229
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1230
 * variable is set.
1231
 *
1232
 * @param string $taxon_uuid
1233
 *
1234
 * @return array
1235
 *   An array of CDM TaxonNodeDTO objects
1236
 */
1237
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1238
  $view_uuid = get_current_classification_uuid();
1239
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1240

    
1241
  $response = NULL;
1242
  if (is_uuid($rank_uuid)) {
1243
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1244
      $view_uuid,
1245
      $taxon_uuid,
1246
      $rank_uuid,
1247
    ));
1248
  }
1249
  else {
1250
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1251
      $view_uuid,
1252
      $taxon_uuid,
1253
    ));
1254
  }
1255

    
1256
  if ($response == NULL) {
1257
    // Error handing.
1258
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1259
//      // Delete the session value and try again with the default.
1260
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1261
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1262
//    }
1263
//    else {
1264
      // Check if taxonomictree_uuid is valid.
1265
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1266
      if ($test == NULL) {
1267
        // The default set by the admin seems to be invalid or is not even set.
1268
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1269
      }
1270
//    }
1271
  }
1272

    
1273
  return $response;
1274
}
1275

    
1276

    
1277
// =============================Terms and Vocabularies ========================================= //
1278

    
1279
/**
1280
 * Returns the localized representation for the given term.
1281
 *
1282
 * @param Object $definedTermBase
1283
 * 	  of cdm type DefinedTermBase
1284
 * @return string
1285
 * 	  the localized representation_L10n of the term,
1286
 *    otherwise the titleCache as fall back,
1287
 *    otherwise the default_representation which defaults to an empty string
1288
 */
1289
function cdm_term_representation($definedTermBase, $default_representation = '') {
1290
  if ( isset($definedTermBase->representation_L10n) ) {
1291
    return $definedTermBase->representation_L10n;
1292
  } elseif ( isset($definedTermBase->titleCache)) {
1293
    return $definedTermBase->titleCache;
1294
  }
1295
  return $default_representation;
1296
}
1297

    
1298
/**
1299
 * Returns the abbreviated localized representation for the given term.
1300
 *
1301
 * @param Object $definedTermBase
1302
 * 	  of cdm type DefinedTermBase
1303
 * @return string
1304
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1305
 *    if this representation is not available the function delegates the
1306
 *    call to cdm_term_representation()
1307
 */
1308
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1309
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1310
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1311
  } else {
1312
    cdm_term_representation($definedTermBase, $default_representation);
1313
  }
1314
}
1315

    
1316
/**
1317
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1318
 *
1319
 * The options array is suitable for drupal form API elements that allow multiple choices.
1320
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1321
 *
1322
 * @param array $terms
1323
 *   a list of CDM DefinedTermBase instances
1324
 *
1325
 * @param $term_label_callback
1326
 *   A callback function to override the term representations
1327
 *
1328
 * @param bool $empty_option
1329
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1330
 *
1331
 * @return array
1332
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1333

    
1334
 */
1335
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1336
  $options = array();
1337
  if(isset($terms) && is_array($terms)) {
1338
    foreach ($terms as $term) {
1339
      if ($term_label_callback && function_exists($term_label_callback)) {
1340
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1341
      } else {
1342
        //TODO use cdm_term_representation() here?
1343
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1344
      }
1345
    }
1346
  }
1347

    
1348
  if($empty_option !== FALSE){
1349
    array_unshift ($options, "");
1350
  }
1351

    
1352
  return $options;
1353
}
1354

    
1355
/**
1356
 * Creates and array of options for drupal select form elements.
1357
 *
1358
 * @param $vocabulary_uuid
1359
 *   The UUID of the CDM Term Vocabulary
1360
 * @param $term_label_callback
1361
 *   An optional call back function which can be used to modify the term label
1362
 * @param bool $empty_option
1363
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1364
 * @param array $include_filter
1365
 *   An associative array consisting of a field name an regular expression. All term matching
1366
 *   these filter are included. The value of the field is converted to a String by var_export()
1367
 *   so a boolean 'true' can be matched by '/true/'
1368
 * @param string $order_by
1369
 *   One of the order by constants defined in this file
1370
 * @return array
1371
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1372
 */
1373
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1374
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1375

    
1376
  static $vocabularyOptions = array();
1377

    
1378
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1379
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1380
      array(
1381
        'orderBy' => $order_by
1382
      )
1383
    );
1384

    
1385
    // apply the include filter
1386
    if($include_filter != null){
1387
      $included_terms = array();
1388

    
1389
      foreach ($terms as $term){
1390
        $include = true;
1391
        foreach ($include_filter as $field=>$regex){
1392
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1393
          if(!$include){
1394
            break;
1395
          }
1396
        }
1397
        if($include){
1398
          $included_terms[] = $term;
1399
        }
1400
      }
1401

    
1402
      $terms = $included_terms;
1403
    }
1404

    
1405
    // make options list
1406
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1407
  }
1408

    
1409
  $options = $vocabularyOptions[$vocabulary_uuid];
1410

    
1411
  return $options;
1412
}
1413

    
1414
/**
1415
 * @param $term_type string one of
1416
 *  - Unknown
1417
 *  - Language
1418
 *  - NamedArea
1419
 *  - Rank
1420
 *  - Feature
1421
 *  - AnnotationType
1422
 *  - MarkerType
1423
 *  - ExtensionType
1424
 *  - DerivationEventType
1425
 *  - PresenceAbsenceTerm
1426
 *  - NomenclaturalStatusType
1427
 *  - NameRelationshipType
1428
 *  - HybridRelationshipType
1429
 *  - SynonymRelationshipType
1430
 *  - TaxonRelationshipType
1431
 *  - NameTypeDesignationStatus
1432
 *  - SpecimenTypeDesignationStatus
1433
 *  - InstitutionType
1434
 *  - NamedAreaType
1435
 *  - NamedAreaLevel
1436
 *  - RightsType
1437
 *  - MeasurementUnit
1438
 *  - StatisticalMeasure
1439
 *  - MaterialOrMethod
1440
 *  - Material
1441
 *  - Method
1442
 *  - Modifier
1443
 *  - Scope
1444
 *  - Stage
1445
 *  - KindOfUnit
1446
 *  - Sex
1447
 *  - ReferenceSystem
1448
 *  - State
1449
 *  - NaturalLanguageTerm
1450
 *  - TextFormat
1451
 *  - DeterminationModifier
1452
 *  - DnaMarker
1453
 *
1454
 * @param  $order_by
1455
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1456
 *  possible values:
1457
 *    - CDM_ORDER_BY_ID_ASC
1458
 *    - CDM_ORDER_BY_ID_DESC
1459
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1460
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1461
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1462
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1463
 * @param bool $empty_option
1464
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1465
 * @return array
1466
 *    the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1467
 */
1468
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1469
  $terms = cdm_ws_fetch_all(
1470
    CDM_WS_TERM,
1471
    array(
1472
      'class' => $term_type,
1473
      'orderBy' => $order_by
1474
    )
1475
  );
1476
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1477
}
1478

    
1479
/**
1480
 * @param array $none_option
1481
 *    Will add a filter option to search for NULL values
1482
 * @param $with_empty_option
1483
 *    Will add an empty option to the beginning. Choosing this option will disable the filtering.
1484
 * @return array
1485
 *   An array of options with uuids as key and the localized term representation as value
1486
 */
1487
function cdm_type_designation_status_filter_terms_as_options($none_option_label, $with_empty_option = false){
1488
  $filter_terms = cdm_ws_get(CDM_WS_TYPE_DESIGNATION_STATUS_FILTER_TERMS);
1489

    
1490
  if(isset($filter_terms) && is_array($filter_terms)) {
1491
    foreach ($filter_terms as $filter_term) {
1492
      $options[join(',', $filter_term->uuids)] = $filter_term->label;
1493
    }
1494
  }
1495

    
1496
  if(is_string($none_option_label)){
1497
    $options = array_merge(array('NULL' => $none_option_label), $options);
1498
  }
1499

    
1500
  if($with_empty_option !== FALSE){
1501
    array_unshift ($options, "");
1502
  }
1503

    
1504

    
1505
  return $options;
1506
}
1507

    
1508

    
1509

    
1510
/**
1511
 * Callback function which provides the localized representation of a cdm term.
1512
 *
1513
 * The representation is build by concatenating the abbreviated label with the label
1514
 * and thus is especially useful for relationship terms
1515
 * The localized representation provided by the cdm can be overwritten by
1516
 * providing a drupal translation.
1517
 *
1518
 */
1519
function _cdm_relationship_type_term_label_callback($term) {
1520
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1521
    return $term->representation_L10n_abbreviatedLabel . ' : '
1522
    . t('@term', array('@term' => $term->representation_L10n));
1523
  }
1524
else {
1525
    return t('@term', array('@term' => $term->representation_L10n));
1526
  }
1527
}
1528

    
1529
/**
1530
 * Callback function which provides the localized inverse representation of a cdm term.
1531
 *
1532
 * The representation is build by concatenating the abbreviated label with the label
1533
 * and thus is especially useful for relationship terms
1534
 * The localized representation provided by the cdm can be overwritten by
1535
 * providing a drupal translation.
1536
 *
1537
 */
1538
function _cdm_relationship_type_term_inverse_label_callback($term) {
1539
  if (isset($term->inverseRepresentation_L10n_abbreviatedLabel)) {
1540
    return $term->inverseRepresentation_L10n_abbreviatedLabel . ' : '
1541
      . t('@term', array('@term' => $term->inverseRepresentation_L10n));
1542
  }
1543
  else {
1544
    return t('@term', array('@term' => $term->inverseRepresentation_L10n));
1545
  }
1546
}
1547

    
1548
/**
1549
 * Returns the localized abbreviated label of the relationship term.
1550
 *
1551
 * In case the abbreviated label is not set the normal representation is returned.
1552
 *
1553
 * @param $term
1554
 * @param bool $is_inverse_relation
1555
 * @return string
1556
 *   The abbreviated label
1557
 */
1558
function cdm_relationship_type_term_abbreviated_label($term, $is_inverse_relation = false){
1559

    
1560
  if($is_inverse_relation) {
1561
    if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1562
      $abbr_label = $term->inverseResentation_L10n_abbreviatedLabel;
1563
    } else {
1564
      $abbr_label = $term->inverseRepresentation_L10n;
1565
    }
1566
  } else {
1567
    if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1568
      $abbr_label = $term->representation_L10n_abbreviatedLabel;
1569
    } else {
1570
      $abbr_label = $term->representation_L10n;
1571
    }
1572
  }
1573
  return $abbr_label;
1574
}
1575

    
1576
/**
1577
 * Returns the symbol of the relationship term.
1578
 *
1579
 * In case the symbol is not set the function falls back to use the abbreviated label or
1580
 * the normal representation..
1581
 *
1582
 * @param $term
1583
 * @param bool $is_inverse_relation
1584
 * @return string
1585
 *   The abbreviated label
1586
 */
1587
function cdm_relationship_type_term_symbol($term, $is_inverse_relation = false){
1588

    
1589
  if($is_inverse_relation) {
1590
    if (isset($term->inverseSymbol) && $term->inverseSymbol) {
1591
      $symbol = $term->inverseSymbol;
1592
    } else if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1593
      $symbol = $term->inverseResentation_L10n_abbreviatedLabel;
1594
    } else {
1595
      $symbol = $term->inverseRepresentation_L10n;
1596
    }
1597
  } else {
1598
    if (isset($term->symbol) && $term->symbol) {
1599
      $symbol = $term->symbol;
1600
    } else if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1601
      $symbol = $term->representation_L10n_abbreviatedLabel;
1602
    } else {
1603
      $symbol = $term->representation_L10n;
1604
    }
1605
  }
1606
  return $symbol;
1607
}
1608

    
1609
// ========================================================================================== //
1610
/**
1611
 * @todo Improve documentation of this function.
1612
 *
1613
 * eu.etaxonomy.cdm.model.description.
1614
 * CategoricalData
1615
 * CommonTaxonName
1616
 * Distribution
1617
 * IndividualsAssociation
1618
 * QuantitativeData
1619
 * TaxonInteraction
1620
 * TextData
1621
 */
1622
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1623
  static $types = array(
1624
    "CategoricalData",
1625
    "CommonTaxonName",
1626
    "Distribution",
1627
    "IndividualsAssociation",
1628
    "QuantitativeData",
1629
    "TaxonInteraction",
1630
    "TextData",
1631
  );
1632

    
1633
  static $options = NULL;
1634
  if ($options == NULL) {
1635
    $options = array();
1636
    if ($prependEmptyElement) {
1637
      $options[' '] = '';
1638
    }
1639
    foreach ($types as $type) {
1640
      // No internatianalization here since these are purely technical terms.
1641
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1642
    }
1643
  }
1644
  return $options;
1645
}
1646

    
1647

    
1648
/**
1649
 * Fetches all TaxonDescription descriptions elements which are associated to the
1650
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1651
 * feature tree.
1652
 * @param $feature_tree
1653
 *     The CDM FeatureTree to be used as template
1654
 * @param $taxon_uuid
1655
 *     The UUID of the taxon
1656
 * @param $excludes
1657
 *     UUIDs of features to be excluded
1658
 * @return$feature_tree
1659
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1660
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1661
 *     witch will hold the according $descriptionElements.
1662
 */
1663
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1664

    
1665
  if (!$feature_tree) {
1666
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1667
      In order to see the species profiles of your taxa, please select a
1668
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1669
    return FALSE;
1670
  }
1671

    
1672
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1673
      array(
1674
      'taxon' => $taxon_uuid,
1675
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1676
      ),
1677
      'POST'
1678
  );
1679

    
1680
  // Combine all descriptions into one feature tree.
1681
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1682
  $feature_tree->root->childNodes = $merged_nodes;
1683

    
1684
  return $feature_tree;
1685
}
1686

    
1687
/**
1688
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1689
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1690
 * be requested for the annotations.
1691
 *
1692
 * @param string $cdmBase
1693
 *   An annotatable cdm entity.
1694
 * @param array $includeTypes
1695
 *   If an array of annotation type uuids is supplied by this parameter the
1696
 *   list of annotations is resticted to those which belong to this type.
1697
 *
1698
 * @return array
1699
 *   An array of Annotation objects or an empty array.
1700
 */
1701
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1702

    
1703
  if(!isset($cdmBase->annotations)){
1704
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1705
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1706
  }
1707

    
1708
  $annotations = array();
1709
  foreach ($cdmBase->annotations as $annotation) {
1710
    if ($includeTypes) {
1711
      if (
1712
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1713
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1714
      ) {
1715
        $annotations[] = $annotation;
1716
      }
1717
    }
1718
    else {
1719
      $annotations[] = $annotation;
1720
    }
1721
  }
1722
  return $annotations;
1723

    
1724
}
1725

    
1726
/**
1727
 * Provides the list of visible annotations for the $cdmBase.
1728
 *
1729
 * @param $cdmBase
1730
 *     The annotatable CDM entity
1731
 *
1732
 * @return array of the annotations which are visible according to the settings as stored in ANNOTATION_TYPES_VISIBLE
1733
 */
1734
function cdm_fetch_visible_annotations($cdmBase){
1735

    
1736
  static $annotations_types_filter = null;
1737
  if(!$annotations_types_filter) {
1738
    $annotations_types_filter = unserialize(ANNOTATIONS_TYPES_AS_FOOTNOTES_DEFAULT);
1739
  }
1740
  return cdm_ws_getAnnotationsFor($cdmBase, variable_get(ANNOTATION_TYPES_VISIBLE, $annotations_types_filter));
1741
}
1742

    
1743
/**
1744
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1745
 *
1746
 * NOTE: The annotations are not filtered by the ANNOTATION_TYPES_VISIBLE settings since this method is meant to act
1747
 * like the annotations have been fetched in the ORM-framework in the service.
1748
 *
1749
 * @param object $annotatable_entity
1750
 *   The CDM AnnotatableEntity to load annotations for
1751
 */
1752
function cdm_load_annotations(&$annotatable_entity) {
1753
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1754
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1755
    if (is_array($annotations)) {
1756
      $annotatable_entity->annotations = $annotations;
1757
    }
1758
  }
1759
}
1760

    
1761
function cdm_load_tagged_full_title($taxon_name){
1762
  if(isset($taxon_name) && !isset($taxon_name->taggedFullTitle)){
1763
    $tagged_full_title = cdm_ws_get(CDM_WS_NAME, array($taxon_name->uuid, 'taggedFullTitle'));
1764
    if(is_array($tagged_full_title)){
1765
      $taxon_name->taggedFullTitle = $tagged_full_title;
1766

    
1767
    }
1768
  }
1769
}
1770

    
1771
/**
1772
 * Extends the $cdm_entity object by the field if it is not already existing.
1773
 *
1774
 * This function can only be used for fields with 1 to many relations.
1775
  *
1776
 * @param $cdm_base_type
1777
 * @param $field_name
1778
 * @param $cdm_entity
1779
 */
1780
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1781
{
1782
  if (!isset($cdm_entity->$field_name)) {
1783
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1784
    $cdm_entity->$field_name = $items;
1785
  }
1786
}
1787

    
1788

    
1789
/**
1790
 * Get a NomenclaturalReference string.
1791
 *
1792
 * Returns the NomenclaturalReference string with correctly placed
1793
 * microreference (= reference detail) e.g.
1794
 * in Phytotaxa 43: 1-48. 2012.
1795
 *
1796
 * @param string $referenceUuid
1797
 *   UUID of the reference.
1798
 * @param string $microreference
1799
 *   Reference detail.
1800
 *
1801
 * @return string
1802
 *   a NomenclaturalReference.
1803
 */
1804
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1805

    
1806
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1807
  if(is_array($microreference) || is_object($microreference)) {
1808
    return '';
1809
  }
1810

    
1811
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1812
    $referenceUuid,
1813
  ), "microReference=" . urlencode($microreference));
1814

    
1815
  if ($obj) {
1816
    return $obj->String;
1817
  }
1818
  else {
1819
    return NULL;
1820
  }
1821
}
1822

    
1823
/**
1824
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1825
 *
1826
 * @param $feature_tree_nodes
1827
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1828
 * @param $feature_uuid
1829
 *    The UUID of the Feature
1830
 * @return returns the FeatureNode or null
1831
 */
1832
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1833

    
1834
  // 1. scan this level
1835
  foreach ($feature_tree_nodes as $node){
1836
    if($node->term->uuid == $feature_uuid){
1837
      return $node;
1838
    }
1839
  }
1840

    
1841
  // 2. descend into childen
1842
  foreach ($feature_tree_nodes as $node){
1843
    if(is_array($node->childNodes)){
1844
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1845
      if($node) {
1846
        return $node;
1847
      }
1848
    }
1849
  }
1850
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1851
  return $null_var;
1852
}
1853

    
1854
/**
1855
 * Merges the given featureNodes structure with the descriptionElements.
1856
 *
1857
 * This method is used in preparation for rendering the descriptionElements.
1858
 * The descriptionElements which belong to a specific feature node are appended
1859
 * to a the feature node by creating a new field:
1860
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1861
 * The descriptionElements will be cleared in advance in order to allow reusing the
1862
 * same feature tree without the risk of mixing sets of description elements.
1863
 *
1864
 * which originally is not existing in the cdm.
1865
 *
1866
 *
1867
 *
1868
 * @param array $featureNodes
1869
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1870
 *    may have children.
1871
 * @param array $descriptionElements
1872
 *    An flat array of cdm DescriptionElements
1873
 * @return array
1874
 *    The $featureNodes structure enriched with the according $descriptionElements
1875
 */
1876
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1877

    
1878
  foreach ($featureNodes as &$feature_node) {
1879
    // since the $featureNodes array is reused for each description
1880
    // it is necessary to clear the custom node fields in advance
1881
    if(isset($feature_node->descriptionElements)){
1882
      unset($feature_node->descriptionElements);
1883
    }
1884

    
1885
    // Append corresponding elements to an additional node field:
1886
    // $node->descriptionElements.
1887
    foreach ($descriptionElements as $element) {
1888
      if ($element->feature->uuid == $feature_node->term->uuid) {
1889
        if (!isset($feature_node->descriptionElements)) {
1890
          $feature_node->descriptionElements = array();
1891
        }
1892
        $feature_node->descriptionElements[] = $element;
1893
      }
1894
    }
1895

    
1896
    // Recurse into node children.
1897
    if (isset($feature_node->childNodes[0])) {
1898
      $mergedChildNodes = _mergeFeatureTreeDescriptions($feature_node->childNodes, $descriptionElements);
1899
      $feature_node->childNodes = $mergedChildNodes;
1900
    }
1901

    
1902
    if(!isset($feature_node->descriptionElements) && !isset($feature_node->childNodes[0])){
1903
      unset($feature_node);
1904
    }
1905

    
1906
  }
1907

    
1908
  return $featureNodes;
1909
}
1910

    
1911
/**
1912
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1913
 *
1914
 * The response from the HTTP GET request is returned as object.
1915
 * The response objects coming from the webservice configured in the
1916
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1917
 *  in a level 2 (L2) cache.
1918
 *
1919
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1920
 * function, this cache persists only per each single page execution.
1921
 * Any object coming from the webservice is stored into it by default.
1922
 * In contrast to this default caching mechanism the L2 cache only is used if
1923
 * the 'cdm_webservice_cache' variable is set to TRUE,
1924
 * which can be set using the modules administrative settings section.
1925
 * Objects stored in this L2 cache are serialized and stored
1926
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1927
 * objects that are stored in the database will persist as
1928
 * long as the drupal cache is not being cleared and are available across
1929
 * multiple script executions.
1930
 *
1931
 * @param string $uri
1932
 *   URL to the webservice.
1933
 * @param array $pathParameters
1934
 *   An array of path parameters.
1935
 * @param string $query
1936
 *   A query string to be appended to the URL.
1937
 * @param string $method
1938
 *   The HTTP method to use, valid values are "GET" or "POST";
1939
 * @param bool $absoluteURI
1940
 *   TRUE when the URL should be treated as absolute URL.
1941
 *
1942
 * @return object| array
1943
 *   The de-serialized webservice response object.
1944
 */
1945
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1946

    
1947
  static $cacheL1 = array();
1948

    
1949
  $data = NULL;
1950
  // store query string in $data and clear the query, $data will be set as HTTP request body
1951
  if($method == 'POST'){
1952
    $data = $query;
1953
    $query = NULL;
1954
  }
1955

    
1956
  // Transform the given uri path or pattern into a proper webservice uri.
1957
  if (!$absoluteURI) {
1958
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1959
  }
1960
  cdm_ws_apply_classification_subtree_filter($uri);
1961

    
1962
  // read request parameter 'cacheL2_refresh'
1963
  // which allows refreshing the level 2 cache
1964
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1965

    
1966
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1967
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1968

    
1969
  if($method == 'GET'){
1970
    $cache_key = $uri;
1971
  } else {
1972
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1973
    // crc32 is faster but creates much shorter hashes
1974
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1975
  }
1976

    
1977
  if (array_key_exists($cache_key, $cacheL1)) {
1978
    $cacheL1_obj = $cacheL1[$uri];
1979
  }
1980

    
1981
  $set_cacheL1 = FALSE;
1982
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1983
    $set_cacheL1 = TRUE;
1984
  }
1985

    
1986
  // Only cache cdm webservice URIs.
1987
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1988
  $cacheL2_entry = FALSE;
1989

    
1990
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1991
    // Try to get object from cacheL2.
1992
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1993
  }
1994

    
1995
  if (isset($cacheL1_obj)) {
1996
    //
1997
    // The object has been found in the L1 cache.
1998
    //
1999
    $obj = $cacheL1_obj;
2000
    if (cdm_debug_block_visible()) {
2001
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
2002
    }
2003
  }
2004
  elseif ($cacheL2_entry) {
2005
    //
2006
    // The object has been found in the L2 cache.
2007
    //
2008
    $duration_parse_start = microtime(TRUE);
2009
    $obj = unserialize($cacheL2_entry->data);
2010
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2011

    
2012
    if (cdm_debug_block_visible()) {
2013
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
2014
    }
2015
  }
2016
  else {
2017
    //
2018
    // Get the object from the webservice and cache it.
2019
    //
2020
    $duration_fetch_start = microtime(TRUE);
2021
    // Request data from webservice JSON or XML.
2022
    $response = cdm_http_request($uri, $method, $data);
2023
    $response_body = NULL;
2024
    if (isset($response->data)) {
2025
      $response_body = $response->data;
2026
    }
2027
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2028
    $duration_parse_start = microtime(TRUE);
2029

    
2030
    // Parse data and create object.
2031
    $obj = cdm_load_obj($response_body);
2032

    
2033
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2034

    
2035
    if (cdm_debug_block_visible()) {
2036
      if ($obj || $response_body == "[]") {
2037
        $status = 'valid';
2038
      }
2039
      else {
2040
        $status = 'invalid';
2041
      }
2042
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2043
    }
2044
    if ($set_cacheL2) {
2045
      // Store the object in cache L2.
2046
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2047
      // flag serialized is set properly in the cache table.
2048
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2049
    }
2050
  }
2051
  if ($obj) {
2052
    // Store the object in cache L1.
2053
    if ($set_cacheL1) {
2054
      $cacheL1[$cache_key] = $obj;
2055
    }
2056
  }
2057
  return $obj;
2058
}
2059

    
2060
function cdm_ws_apply_classification_subtree_filter(&$uri){
2061

    
2062
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
2063
    "#/classification/[0-9a-f\-]{36}/childNodes#",
2064
    /* covered by above pattern:
2065
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2066
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2067
    */
2068
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
2069
    /* covered by above pattern:
2070
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2071
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2072
    */
2073
    '#/portal/classification/[0-9a-f\-]{36}/pathFrom/[0-9a-f\-]{36}#',
2074
    "#/portal/taxon/search#",
2075
    "#/portal/taxon/find#",
2076
    /* covered by above pattern:
2077
    "#/portal/taxon/findByDescriptionElementFullText#",
2078
    "#/portal/taxon/findByFullText#",
2079
    "#/portal/taxon/findByEverythingFullText#",
2080
    "#/portal/taxon/findByIdentifier#",
2081
    "#/portal/taxon/findByMarker#",
2082
    "#/portal/taxon/findByMarker#",
2083
    "#/portal/taxon/findByMarker#",
2084
    */
2085
    "#/portal/taxon/[0-9a-f\-]{36}#"
2086
    /* covered by above pattern:
2087
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
2088
    */
2089
  ));
2090

    
2091
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
2092
  if(is_uuid($sub_tree_filter_uuid_value)){
2093
    foreach($classification_subtree_filter_patterns as $preg_pattern){
2094
      if(preg_match($preg_pattern, $uri)){
2095
        // no need to take care for uri fragments with ws uris!
2096
        if(strpos( $uri, '?')){
2097
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
2098
        } else {
2099
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
2100
        }
2101
        break;
2102
      }
2103
    }
2104
  }
2105

    
2106
}
2107
/**
2108
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2109
 *
2110
 * The cdm_ws_debug block will display the debug information.
2111
 *
2112
 * @param $uri
2113
 *    The CDM REST URI to which the request has been send
2114
 * @param string $method
2115
 *    The HTTP request method, either 'GET' or 'POST'
2116
 * @param string $post_data
2117
 *    The datastring send with a post request
2118
 * @param $duration_fetch
2119
 *    The time in seconds it took to fetch the data from the web service
2120
 * @param $duration_parse
2121
 *    Time in seconds which was needed to parse the json response
2122
 * @param $datasize
2123
 *    Size of the data received from the server
2124
 * @param $status
2125
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2126
 * @return bool
2127
 *    TRUE if adding the debug information was successful
2128
 */
2129
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2130

    
2131
  static $initial_time = NULL;
2132
  if(!$initial_time) {
2133
    $initial_time = microtime(TRUE);
2134
  }
2135
  $time = microtime(TRUE) - $initial_time;
2136

    
2137
  // Decompose uri into path and query element.
2138
  $uri_parts = explode("?", $uri);
2139
  $query = array();
2140
  if (count($uri_parts) == 2) {
2141
    $path = $uri_parts[0];
2142
  }
2143
  else {
2144
    $path = $uri;
2145
  }
2146

    
2147
  if(strpos($uri, '?') > 0){
2148
    $json_uri = str_replace('?', '.json?', $uri);
2149
    $xml_uri = str_replace('?', '.xml?', $uri);
2150
  } else {
2151
    $json_uri = $uri . '.json';
2152
    $xml_uri = $json_uri . '.xml';
2153
  }
2154

    
2155
  // data links to make data accecsible as json and xml
2156
  $data_links = '';
2157
  if (_is_cdm_ws_uri($path)) {
2158

    
2159
    // see ./js/http-method-link.js
2160

    
2161
    if($method == 'GET'){
2162
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2163
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2164
      $data_links .= '<br/>';
2165
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2166
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2167
    } else {
2168
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2169
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2170
      $data_links .= '<br/>';
2171
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2172
    }
2173
  }
2174
  else {
2175
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2176
  }
2177

    
2178
  //
2179
  $data = array(
2180
      'ws_uri' => $uri,
2181
      'method' => $method,
2182
      'post_data' => $post_data,
2183
      'time' => sprintf('%3.3f', $time),
2184
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2185
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2186
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2187
      'status' => $status,
2188
      'data_links' => $data_links
2189
  );
2190
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2191
    $_SESSION['cdm']['ws_debug'] = array();
2192
  }
2193
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2194

    
2195
  // Mark this page as being uncacheable.
2196
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2197
  drupal_page_is_cacheable(FALSE);
2198

    
2199
  // Messages not set when DB connection fails.
2200
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2201
}
2202

    
2203
/**
2204
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2205
 * the visibility depends on whether
2206
 *  - the block is enabled
2207
 *  - the visibility restrictions in the block settings are satisfied
2208
 */
2209
function cdm_debug_block_visible() {
2210
  static $is_visible = null;
2211

    
2212
  if($is_visible === null){
2213
      $block = block_load('cdm_api', 'cdm_ws_debug');
2214
      $is_visible = isset($block->status) && $block->status == 1;
2215
      if($is_visible){
2216
        $blocks = array($block);
2217
        // Checks the page, user role, and user-specific visibilty settings.
2218
        block_block_list_alter($blocks);
2219
        $is_visible = count($blocks) > 0;
2220
      }
2221
  }
2222
  return $is_visible;
2223
}
2224

    
2225
/**
2226
 * @todo Please document this function.
2227
 * @see http://drupal.org/node/1354
2228
 */
2229
function cdm_load_obj($response_body) {
2230
  $obj = json_decode($response_body);
2231

    
2232
  if (!(is_object($obj) || is_array($obj))) {
2233
    ob_start();
2234
    $obj_dump = ob_get_contents();
2235
    ob_clean();
2236
    return FALSE;
2237
  }
2238

    
2239
  return $obj;
2240
}
2241

    
2242
/**
2243
 * Do a http request to a CDM RESTful web service.
2244
 *
2245
 * @param string $uri
2246
 *   The webservice url.
2247
 * @param string $method
2248
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2249
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2250
 * @param $data: A string containing the request body, formatted as
2251
 *     'param=value&param=value&...'. Defaults to NULL.
2252
 *
2253
 * @return object
2254
 *   The object as returned by drupal_http_request():
2255
 *   An object that can have one or more of the following components:
2256
 *   - request: A string containing the request body that was sent.
2257
 *   - code: An integer containing the response status code, or the error code
2258
 *     if an error occurred.
2259
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2260
 *   - status_message: The status message from the response, if a response was
2261
 *     received.
2262
 *   - redirect_code: If redirected, an integer containing the initial response
2263
 *     status code.
2264
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2265
 *     target.
2266
 *   - error: If an error occurred, the error message. Otherwise not set.
2267
 *   - headers: An array containing the response headers as name/value pairs.
2268
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2269
 *     easy access the array keys are returned in lower case.
2270
 *   - data: A string containing the response body that was received.
2271
 */
2272
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2273
  static $acceptLanguage = NULL;
2274
  $header = array();
2275
  
2276
  if(!$acceptLanguage && module_exists('i18n')){
2277
    $acceptLanguage = i18n_language_content()->language;
2278
  }
2279

    
2280
  if (!$acceptLanguage) {
2281
    if (function_exists('apache_request_headers')) {
2282
      $headers = apache_request_headers();
2283
      if (isset($headers['Accept-Language'])) {
2284
        $acceptLanguage = $headers['Accept-Language'];
2285
      }
2286
    }
2287
  }
2288

    
2289
  if ($method != "GET" && $method != "POST") {
2290
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2291
  }
2292

    
2293
  if (_is_cdm_ws_uri($uri)) {
2294
    $header['Accept'] = 'application/json';
2295
    $header['Accept-Language'] = $acceptLanguage;
2296
    $header['Accept-Charset'] = 'UTF-8';
2297
  }
2298

    
2299
  if($method == "POST") {
2300
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2301
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2302
  }
2303

    
2304

    
2305
  cdm_dd($uri);
2306
  return drupal_http_request($uri, array(
2307
      'headers' => $header,
2308
      'method' => $method,
2309
      'data' => $data,
2310
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2311
      )
2312
   );
2313
}
2314

    
2315
/**
2316
 * Concatenates recursively the fields of all features contained in the given
2317
 * CDM FeatureTree root node.
2318
 *
2319
 * @param $rootNode
2320
 *     A CDM FeatureTree node
2321
 * @param
2322
 *     The character to be used as glue for concatenation, default is ', '
2323
 * @param $field_name
2324
 *     The field name of the CDM Features
2325
 * @param $excludes
2326
 *     Allows defining a set of values to be excluded. This refers to the values
2327
 *     in the field denoted by the $field_name parameter
2328
 *
2329
 */
2330
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2331
  $out = '';
2332

    
2333
  $pre_child_separator = $separator;
2334
  $post_child_separator = '';
2335

    
2336
  foreach ($root_node->childNodes as $feature_node) {
2337
    $out .= ($out ? $separator : '');
2338
    if(!in_array($feature_node->term->$field_name, $excludes)) {
2339
      $out .= $feature_node->term->$field_name;
2340
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2341
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2342
        if (strlen($childlabels)) {
2343
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2344
        }
2345
      }
2346
    }
2347
  }
2348
  return $out;
2349
}
2350

    
2351
/**
2352
 * Create a one-dimensional form options array.
2353
 *
2354
 * Creates an array of all features in the feature tree of feature nodes,
2355
 * the node labels are indented by $node_char and $childIndent depending on the
2356
 * hierachy level.
2357
 *
2358
 * @param - $rootNode
2359
 * @param - $node_char
2360
 * @param - $childIndentStr
2361
 * @param - $childIndent
2362
 *   ONLY USED INTERNALLY!
2363
 *
2364
 * @return array
2365
 *   A one dimensional Drupal form options array.
2366
 */
2367
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2368
  $options = array();
2369
  foreach ($rootNode->childNodes as $featureNode) {
2370
    $indent_prefix = '';
2371
    if ($childIndent) {
2372
      $indent_prefix = $childIndent . $node_char . " ";
2373
    }
2374
    $options[$featureNode->term->uuid] = $indent_prefix . $featureNode->term->representation_L10n;
2375
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2376
      // Foreach ($featureNode->childNodes as $childNode){
2377
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2378
      $options = array_merge_recursive($options, $childList);
2379
      // }
2380
    }
2381
  }
2382
  return $options;
2383
}
2384

    
2385
/**
2386
 * Returns an array with all available FeatureTrees and the representations of the selected
2387
 * FeatureTree as a detail view.
2388
 *
2389
 * @param boolean $add_default_feature_free
2390
 * @return array
2391
 *  associative array with following keys:
2392
 *  -options: Returns an array with all available Feature Trees
2393
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2394
 *
2395
 */
2396
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2397

    
2398
  $options = array();
2399
  $tree_representations = array();
2400
  $feature_trees = array();
2401

    
2402
  // Set tree that contains all features.
2403
  if ($add_default_feature_free) {
2404
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2405
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2406
  }
2407

    
2408
  // Get feature trees from database.
2409
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2410
  if (is_array($persited_trees)) {
2411
    $feature_trees = array_merge($feature_trees, $persited_trees);
2412
  }
2413

    
2414
  foreach ($feature_trees as $featureTree) {
2415

    
2416
    if(!is_object($featureTree)){
2417
      continue;
2418
    }
2419
    // Do not add the DEFAULT_FEATURETREE again,
2420
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2421
      $options[$featureTree->uuid] = $featureTree->titleCache;
2422
    }
2423

    
2424
    // Render the hierarchic tree structure
2425
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2426

    
2427
      // Render the hierarchic tree structure.
2428
      $treeDetails = '<div class="featuretree_structure">'
2429
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2430
        . '</div>';
2431

    
2432
      $form = array();
2433
      $form['featureTree-' .  $featureTree->uuid] = array(
2434
        '#type' => 'fieldset',
2435
        '#title' => 'Show details',
2436
        '#attributes' => array('class' => array('collapsible collapsed')),
2437
        // '#collapsible' => TRUE,
2438
        // '#collapsed' => TRUE,
2439
      );
2440
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2441
        '#markup' => $treeDetails,
2442
      );
2443

    
2444
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2445
    }
2446

    
2447
  } // END loop over feature trees
2448

    
2449
  // return $options;
2450
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2451
}
2452

    
2453
/**
2454
 * Provides the list of available classifications in form of an options array.
2455
 *
2456
 * The options array is suitable for drupal form API elements that allow multiple choices.
2457
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2458
 *
2459
 * The classifications are ordered alphabetically whereas the classification
2460
 * chosen as default will always appear on top of the array, followed by a
2461
 * blank line below.
2462
 *
2463
 * @param bool $add_none_option
2464
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2465
 *
2466
 * @return array
2467
 *   classifications in an array as options for a form element that allows multiple choices.
2468
 */
2469
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2470

    
2471
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2472

    
2473
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2474
  $default_classification_label = '';
2475

    
2476
  // add all classifications
2477
  $taxonomic_tree_options = array();
2478
  if ($add_none_option) {
2479
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2480
  }
2481
  if ($taxonTrees) {
2482
    foreach ($taxonTrees as $tree) {
2483
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2484
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2485
      } else {
2486
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2487
        $default_classification_label = $tree->titleCache;
2488
      }
2489
    }
2490
  }
2491
  // oder alphabetically the space
2492
  asort($taxonomic_tree_options);
2493

    
2494
  // now set the labels
2495
  //   for none
2496
  if ($add_none_option) {
2497
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2498
  }
2499

    
2500
  //   for default_classification
2501
  if (is_uuid($default_classification_uuid)) {
2502
    $taxonomic_tree_options[$default_classification_uuid] =
2503
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2504
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2505
  }
2506

    
2507
  return $taxonomic_tree_options;
2508
}
2509

    
2510
/**
2511
 * @todo Please document this function.
2512
 * @see http://drupal.org/node/1354
2513
 */
2514
function cdm_api_secref_cache_prefetch(&$secUuids) {
2515
  // Comment @WA: global variables should start with a single underscore
2516
  // followed by the module and another underscore.
2517
  global $_cdm_api_secref_cache;
2518
  if (!is_array($_cdm_api_secref_cache)) {
2519
    $_cdm_api_secref_cache = array();
2520
  }
2521
  $uniqueUuids = array_unique($secUuids);
2522
  $i = 0;
2523
  $param = '';
2524
  while ($i++ < count($uniqueUuids)) {
2525
    $param .= $secUuids[$i] . ',';
2526
    if (strlen($param) + 37 > 2000) {
2527
      _cdm_api_secref_cache_add($param);
2528
      $param = '';
2529
    }
2530
  }
2531
  if ($param) {
2532
    _cdm_api_secref_cache_add($param);
2533
  }
2534
}
2535

    
2536
/**
2537
 * @todo Please document this function.
2538
 * @see http://drupal.org/node/1354
2539
 */
2540
function cdm_api_secref_cache_get($secUuid) {
2541
  global $_cdm_api_secref_cache;
2542
  if (!is_array($_cdm_api_secref_cache)) {
2543
    $_cdm_api_secref_cache = array();
2544
  }
2545
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2546
    _cdm_api_secref_cache_add($secUuid);
2547
  }
2548
  return $_cdm_api_secref_cache[$secUuid];
2549
}
2550

    
2551
/**
2552
 * @todo Please document this function.
2553
 * @see http://drupal.org/node/1354
2554
 */
2555
function cdm_api_secref_cache_clear() {
2556
  global $_cdm_api_secref_cache;
2557
  $_cdm_api_secref_cache = array();
2558
}
2559

    
2560

    
2561
/**
2562
 * Validates if the given string is a uuid.
2563
 *
2564
 * @param string $str
2565
 *   The string to validate.
2566
 *
2567
 * return bool
2568
 *   TRUE if the string is a UUID.
2569
 */
2570
function is_uuid($str) {
2571
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2572
}
2573

    
2574
/**
2575
 * Checks if the given $object is a valid cdm entity.
2576
 *
2577
 * An object is considered a cdm entity if it has a string field $object->class
2578
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2579
 * The function is null save.
2580
 *
2581
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2582
 *
2583
 * @param mixed $object
2584
 *   The object to validate
2585
 *
2586
 * @return bool
2587
 *   True if the object is a cdm entity.
2588
 */
2589
function is_cdm_entity($object) {
2590
  return
2591
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2592
    && is_string($object->uuid) && is_uuid($object->uuid);
2593
}
2594

    
2595
/**
2596
 * @todo Please document this function.
2597
 * @see http://drupal.org/node/1354
2598
 */
2599
function _cdm_api_secref_cache_add($secUuidsStr) {
2600
  global $_cdm_api_secref_cache;
2601
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2602
  // Batch fetching not jet reimplemented thus:
2603
  /*
2604
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2605
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2606
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2607
  */
2608
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2609
}
2610

    
2611
/**
2612
 * Checks if the given uri starts with a cdm webservice url.
2613
 *
2614
 * Checks if the uri starts with the cdm webservice url stored in the
2615
 * Drupal variable 'cdm_webservice_url'.
2616
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2617
 *
2618
 * @param string $uri
2619
 *   The URI to test.
2620
 *
2621
 * @return bool
2622
 *   True if the uri starts with a cdm webservice url.
2623
 */
2624
function _is_cdm_ws_uri($uri) {
2625
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2626
}
2627

    
2628
/**
2629
 * @todo Please document this function.
2630
 * @see http://drupal.org/node/1354
2631
 */
2632
function queryString($elements) {
2633
  $query = '';
2634
  foreach ($elements as $key => $value) {
2635
    if (is_array($value)) {
2636
      foreach ($value as $v) {
2637
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2638
      }
2639
    }
2640
    else {
2641
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2642
    }
2643
  }
2644
  return $query;
2645
}
2646

    
2647
/**
2648
 * Implementation of the magic method __clone to allow deep cloning of objects
2649
 * and arrays.
2650
 */
2651
function __clone() {
2652
  foreach ($this as $name => $value) {
2653
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2654
      $this->$name = clone($this->$name);
2655
    }
2656
  }
2657
}
2658

    
2659
/**
2660
 * Compares the given CDM Term instances by the  representationL10n.
2661
 *
2662
 * Can also be used with TermDTOs. To be used in usort()
2663
 *
2664
 * @see http://php.net/manual/en/function.usort.php
2665
 *
2666
 * @param $term1
2667
 *   The first CDM Term instance
2668
 * @param $term2
2669
 *   The second CDM Term instance
2670
 * @return int
2671
 *   The result of the comparison
2672
 */
2673
function compare_terms_by_representationL10n($term1, $term2) {
2674

    
2675
  if (!isset($term1->representation_L10n)) {
2676
    $term1->representationL10n = '';
2677
  }
2678
  if (!isset($term2->representation_L10n)) {
2679
    $term2->representationL10n = '';
2680
  }
2681

    
2682
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2683
}
2684

    
2685
function compare_terms_by_order_index($term1, $term2) {
2686

    
2687

    
2688
  if (!isset($term1->orderIndex)) {
2689
    $a = 0;
2690
  } else {
2691
    $a = $term1->orderIndex;
2692
  }
2693
  if (!isset($term2->orderIndex)) {
2694
    $b = 0;
2695
  } else {
2696
    $b = $term2->orderIndex;
2697
  }
2698

    
2699
  if ($a == $b) {
2700
    return 0;
2701
  }
2702
  return ($a < $b) ? -1 : 1;
2703

    
2704
}
2705

    
2706

    
2707
/**
2708
 * Make a 'deep copy' of an array.
2709
 *
2710
 * Make a complete deep copy of an array replacing
2711
 * references with deep copies until a certain depth is reached
2712
 * ($maxdepth) whereupon references are copied as-is...
2713
 *
2714
 * @see http://us3.php.net/manual/en/ref.array.php
2715
 *
2716
 * @param array $array
2717
 * @param array $copy passed by reference
2718
 * @param int $maxdepth
2719
 * @param int $depth
2720
 */
2721
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2722
  if ($depth > $maxdepth) {
2723
    $copy = $array;
2724
    return;
2725
  }
2726
  if (!is_array($copy)) {
2727
    $copy = array();
2728
  }
2729
  foreach ($array as $k => &$v) {
2730
    if (is_array($v)) {
2731
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2732
    }
2733
    else {
2734
      $copy[$k] = $v;
2735
    }
2736
  }
2737
}
2738

    
2739
/**
2740
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2741
 *
2742
 */
2743
function _add_js_ws_debug() {
2744

    
2745
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2746
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2747
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2748
    // use the developer versions of js libs
2749
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2750
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2751
  }
2752
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2753
    array(
2754
      'type' => 'file',
2755
      'weight' => JS_LIBRARY,
2756
      'cache' => TRUE)
2757
    );
2758

    
2759
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2760
    array(
2761
      'type' => 'file',
2762
      'weight' => JS_LIBRARY,
2763
      'cache' => TRUE)
2764
    );
2765
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2766
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2767

    
2768
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2769
    array(
2770
      'type' => 'file',
2771
      'weight' => JS_LIBRARY,
2772
      'cache' => TRUE)
2773
    );
2774
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2775
    array(
2776
    'type' => 'file',
2777
    'weight' => JS_LIBRARY,
2778
    'cache' => TRUE)
2779
    );
2780

    
2781
}
2782

    
2783
/**
2784
 * @todo Please document this function.
2785
 * @see http://drupal.org/node/1354
2786
 */
2787
function _no_classfication_uuid_message() {
2788
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2789
    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.');
2790
  }
2791
  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.');
2792
}
2793

    
2794
/**
2795
 * Implementation of hook flush_caches
2796
 *
2797
 * Add custom cache tables to the list of cache tables that
2798
 * will be cleared by the Clear button on the Performance page or whenever
2799
 * drupal_flush_all_caches is invoked.
2800
 *
2801
 * @author W.Addink <waddink@eti.uva.nl>
2802
 *
2803
 * @return array
2804
 *   An array with custom cache tables to include.
2805
 */
2806
function cdm_api_flush_caches() {
2807
  return array('cache_cdm_ws');
2808
}
2809

    
2810
/**
2811
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2812
 *
2813
 * @param $data
2814
 *   The variable to log to the drupal_debug.txt log file.
2815
 * @param $label
2816
 *   (optional) If set, a label to output before $data in the log file.
2817
 *
2818
 * @return
2819
 *   No return value if successful, FALSE if the log file could not be written
2820
 *   to.
2821
 *
2822
 * @see cdm_dataportal_init() where the log file is reset on each requests
2823
 * @see dd()
2824
 * @see http://drupal.org/node/314112
2825
 *
2826
 */
2827
function cdm_dd($data, $label = NULL) {
2828
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2829
    return dd($data, $label);
2830
  }
2831
}
2832

    
(5-5/12)