Project

General

Profile

Download (102 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
 * info hook implementation for the CDM web service debug block
106
 *
107
 * Implements hook_block_info().
108
 *
109
 * @see \cdm_api_block_view()
110
 */
111
function cdm_api_block_info() {
112

    
113
  $block['cdm_ws_debug'] = array(
114
      "info" => t("CDM web service debug"),
115
      "cache" => DRUPAL_NO_CACHE
116
  );
117
  return $block;
118
}
119

    
120
/**
121
 * block_view hook implementation for the CDM web service debug block
122
 *
123
 * Implements hook_block_view().
124
 *
125
 * @see  cdm_api_block_info()
126
 */
127
function cdm_api_block_view($delta) {
128
  switch ($delta) {
129
    case 'cdm_ws_debug':
130

    
131
    $cdm_ws_url = cdm_webservice_url();
132

    
133
    $field_map = array(
134
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
135
        'time' => t('Time'),
136
        'fetch_seconds' => t('Fetching [s]'),
137
        'parse_seconds' => t('Parsing [s]'),
138
        'size_kb' => t('Size [kb]'),
139
        'status' => t('Status'),
140
        'data_links' =>  t('Links'),
141
    );
142

    
143

    
144
    if (!isset($_SESSION['cdm']['ws_debug'])) {
145
      $_SESSION['cdm']['ws_debug'] = array();
146
    }
147

    
148
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
149
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
150
    $rows = array();
151

    
152
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
153

    
154
      $data = unserialize($data);
155

    
156
      // stip of webservice base url
157
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
158
      if($data['method'] == 'POST'){
159
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
160
      }
161

    
162
      $cells = array();
163
      foreach ($field_map as $field => $label){
164
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
165
      }
166
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
167
    }
168
    // clear session again
169
    $_SESSION['cdm']['ws_debug'] = array();
170

    
171
    _add_js_ws_debug();
172

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

    
193
/**
194
 * Implements hook_cron().
195
 *
196
 * Expire outdated cache entries.
197
 */
198
function cdm_api_cron() {
199
  cache_clear_all(NULL, 'cache_cdm_ws');
200
}
201

    
202
/**
203
 * Lists the classifications a taxon belongs to
204
 *
205
 * @param CDM type Taxon $taxon
206
 *   the taxon
207
 *
208
 * @return array
209
 *   aray of CDM instances of Type Classification
210
 */
211
function get_classifications_for_taxon($taxon) {
212

    
213
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);
214
}
215

    
216
/**
217
 * Returns the chosen FeatureTree to be used as FeatureTree for the taxon profile.
218
 *
219
 * The FeatureTree returned is the term tree one that has been set in the
220
 * dataportal settings (layout->taxon:profile).
221
 * When the chosen FeatureTree is not found in the database,
222
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
223
 *
224
 * @return object
225
 *   A cdm TermTree object.
226
 */
227
function get_profile_feature_tree() {
228
  static $profile_featureTree;
229

    
230
  if($profile_featureTree == NULL) {
231
    $profile_featureTree = cdm_ws_get(
232
      CDM_WS_TERMTREE,
233
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
234
    );
235
    if (!$profile_featureTree) {
236
      $profile_featureTree = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
237
    }
238
  }
239

    
240
  return $profile_featureTree;
241
}
242

    
243
/**
244
 * Returns the chosen TermTree to be used as FeatureTree for SpecimenDescriptions.
245
 *
246
 * The TermTree returned is the one that has been set in the
247
 * dataportal settings (layout->taxon:specimen).
248
 * When the chosen TermTree is not found in the database,
249
 * the standard term tree (UUID_DEFAULT_TERMTREE) will be returned.
250
 *
251
 * @return object
252
 *   A cdm TermTree object.
253
 */
254
function cdm_get_occurrence_featureTree() {
255
  static $occurrence_featureTree;
256

    
257
  if($occurrence_featureTree == NULL) {
258
    $occurrence_featureTree = cdm_ws_get(
259
      CDM_WS_TERMTREE,
260
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
261
    );
262
    if (!$occurrence_featureTree) {
263
      $occurrence_featureTree = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
264
    }
265
  }
266
  return $occurrence_featureTree;
267
}
268

    
269
/**
270
 * Returns the FeatureTree for structured descriptions
271
 *
272
 * The FeatureTree returned is the one that has been set in the
273
 * dataportal settings (layout->taxon:profile).
274
 * When the chosen FeatureTree is not found in the database,
275
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
276
 *
277
 * @return mixed
278
 *   A cdm FeatureTree object.
279
 */
280
function get_structured_description_featureTree() {
281
  static $structured_description_featureTree;
282

    
283
  if($structured_description_featureTree == NULL) {
284
    $structured_description_featureTree = cdm_ws_get(
285
        CDM_WS_TERMTREE,
286
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
287
    );
288
    if (!$structured_description_featureTree) {
289
      $structured_description_featureTree = cdm_ws_get(
290
          CDM_WS_TERMTREE,
291
          UUID_DEFAULT_FEATURETREE
292
      );
293
    }
294
  }
295
  return $structured_description_featureTree;
296
}
297

    
298

    
299
/**
300
 * @todo Please document this function.
301
 * @see http://drupal.org/node/1354
302
 */
303
function set_last_taxon_page_tab($taxonPageTab) {
304
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
305
}
306

    
307
/**
308
 * @todo Please document this function.
309
 * @see http://drupal.org/node/1354
310
 */
311
function get_last_taxon_page_tab() {
312
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
313
    return $_SESSION['cdm']['taxon_page_tab'];
314
  }
315
  else {
316
    return FALSE;
317
  }
318
}
319

    
320
/**
321
 * NOTE: The cdm-library provides a very similar server side function. See
322
 * eu.etaxonomy.cdm.model.media.MediaUtils.filterAndOrderMediaRepresentations()
323
 *
324
 * @param object $media
325
 * @param array $mime_types
326
 *    an array of mimetypes in their order of preference. e.g:
327
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
328
 * @param int $width
329
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
330
 * @param int $height
331
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
332
 * @param bool $mime_types_filter_excludes
333
 *    Toggles the mode of the $mime_types filter to exclude when set to TRUE
334
 * @param bool $strict_size_limit
335
 *    Width an height parameters are treated as maximum values when this parameter is enabled.
336
 * @return array
337
 *   An array with preferred media representations or else an empty array.
338
 */
339
function cdm_preferred_media_representations($media, array $mime_types, $width = NULL, $height = NULL, $mime_types_filter_excludes = FALSE, $strict_size_limit = FALSE) {
340
    
341
    $matching_representations_by_rank = [];
342
    if (!isset($media->representations[0])) {
343
      return $matching_representations_by_rank;
344
    }
345

    
346
    foreach ($media->representations as &$representation) {
347
      // If the mimetype is not known, try inferring it.
348
      if (!$representation->mimeType) {
349
        if (isset($representation->parts[0])) {
350
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
351
        }
352
      }
353
      $mime_type_match = array_search($representation->mimeType, $mime_types) !== false;
354
      $match_per_mime_type_filter = $mime_types_filter_excludes ? !$mime_type_match : $mime_type_match;
355
      if ($match_per_mime_type_filter) {
356
        $expansion_delta_sum = 0;
357
        $valid_parts_cnt = 0;
358
        // Look for part with the best matching size.
359
        foreach ($representation->parts as $part) {
360
          if (empty($part->uri)) {
361
            // skip part if URI is missing
362
            continue;
363
          }
364
          if($strict_size_limit){
365
            if (isset($part->width) && isset($part->height) && $part->width <= $width && $part->height <= $height) {
366
              $valid_parts_cnt++;
367
            }
368
          } else {
369
            // calculate expansion delta
370
            $valid_parts_cnt++;
371
            $expansion_delta = PHP_INT_MAX; // biggest delta for unknown sizes
372

    
373
            // determine the optimal size
374
            if (isset($part->width) && isset($part->height)) {
375
              $expansion = $part->width * $part->height;
376
              if ($width != null && $height != null) {
377
                $optimalExpansion = $height * $width;
378
              } else {
379
                $optimalExpansion = PHP_INT_MAX;
380
              }
381
              // determine the difference
382
              $expansion_delta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
383
            }
384
            // sum up the expansionDeltas of all parts contained in the representation
385
            $expansion_delta_sum += $expansion_delta;
386
          }// end parts
387
        }
388
        if($valid_parts_cnt > 0){
389
          $expansion_delta_sum = $expansion_delta_sum / $valid_parts_cnt;
390
          $matching_representations_by_rank[$expansion_delta_sum] = $representation;
391
        }
392
      }
393
    }
394

    
395
    // Sort the array so that the smallest key value is the first in the array
396
    ksort($matching_representations_by_rank);
397
    return $matching_representations_by_rank;
398
}
399

    
400

    
401

    
402
/**
403
 * Infers the mime type of a file using the filename extension.
404
 *
405
 * The filename extension is used to infer the mime type.
406
 *
407
 * @param string $filepath
408
 *   The path to the respective file.
409
 *
410
 * @return string
411
 *   The mimetype for the file or FALSE if the according mime type could
412
 *   not be found.
413
 */
414
function infer_mime_type($filepath) {
415
  static $mimemap = NULL;
416
  if (!$mimemap) {
417
    $mimemap = array(
418
      'jpg' => 'image/jpeg',
419
      'jpeg' => 'image/jpeg',
420
      'png' => 'image/png',
421
      'gif' => 'image/gif',
422
      'giff' => 'image/gif',
423
      'tif' => 'image/tif',
424
      'tiff' => 'image/tif',
425
      'pdf' => 'application/pdf',
426
      'html' => 'text/html',
427
      'htm' => 'text/html',
428
    );
429
  }
430
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
431
  if (isset($mimemap[$extension])) {
432
    return $mimemap[$extension];
433
  }
434
  else {
435
    // FIXME remove this hack just return FALSE;
436
    return 'text/html';
437
  }
438
}
439

    
440
/**
441
 * Formats a mysql datatime as string
442
 *
443
 * @param $datetime
444
 * @param string $format
445
 *
446
 * @return
447
 *  the formatted string representation of the $datetime
448
 */
449
function format_datetime($datetime, $format = 'Y-m-d H:i:s O', $strip_zeros = true){
450

    
451
  return date($format, strtotime($datetime));
452
}
453

    
454
/**
455
 * Converts an ISO 8601 org.joda.time.Partial to a year.
456
 *
457
 * The function expects an ISO 8601 time representation of a
458
 * org.joda.time.Partial of the form yyyy-MM-dd.
459
 *
460
 * @param string $partial
461
 *   ISO 8601 time representation of a org.joda.time.Partial.
462
 *
463
 * @return string
464
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
465
 */
466
function partialToYear($partial) {
467
  if (is_string($partial)) {
468
    $year = drupal_substr($partial, 0, 4);
469
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
470
      return $year;
471
    }
472
  }
473
  return '';
474
}
475

    
476
/**
477
 * Converts an ISO 8601 org.joda.time.Partial to a month.
478
 *
479
 * This function expects an ISO 8601 time representation of a
480
 * org.joda.time.Partial of the form yyyy-MM-dd.
481
 * In case the month is unknown (= ???) NULL is returned.
482
 *
483
 * @param string $partial
484
 *   ISO 8601 time representation of a org.joda.time.Partial.
485
 *
486
 * @return string
487
 *   A month.
488
 */
489
function partialToMonth($partial) {
490
  if (is_string($partial)) {
491
    $month = drupal_substr($partial, 5, 2);
492
    if (preg_match("/[0-9][0-9]/", $month)) {
493
      return $month;
494
    }
495
  }
496
  return '';
497
}
498

    
499
/**
500
 * Converts an ISO 8601 org.joda.time.Partial to a day.
501
 *
502
 * This function expects an ISO 8601 time representation of a
503
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
504
 * In case the day is unknown (= ???) NULL is returned.
505
 *
506
 * @param string $partial
507
 *   ISO 8601 time representation of a org.joda.time.Partial.
508
 *
509
 * @return string
510
 *   A day.
511
 */
512
function partialToDay($partial) {
513
  if (is_string($partial)) {
514
    $day = drupal_substr($partial, 8, 2);
515
    if (preg_match("/[0-9][0-9]/", $day)) {
516
      return $day;
517
    }
518
  }
519
  return '';
520
}
521

    
522
/**
523
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
524
 *
525
 * This function expects an ISO 8601 time representations of a
526
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
527
 * four digit year, month and day with dashes:
528
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
529
 *
530
 * The partial may contain question marks eg: "1973-??-??",
531
 * these are turned in to '00' or are stripped depending of the $stripZeros
532
 * parameter.
533
 *
534
 * @param string $partial
535
 *   org.joda.time.Partial.
536
 * @param bool $stripZeros
537
 *   If set to TRUE the zero (00) month and days will be hidden:
538
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
539
 * @param string @format
540
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
541
 *    - "YYYY": Year only
542
 *    - "YYYY-MM-DD": this is the default
543
 *
544
 * @return string
545
 *   YYYY-MM-DD formatted year, month, day.
546
 */
547
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
548

    
549
  $y = NULL; $m = NULL; $d = NULL;
550

    
551
  if(strpos($format, 'YY') !== FALSE){
552
    $y = partialToYear($partial);
553
  }
554
  if(strpos($format, 'MM') !== FALSE){
555
    $m = partialToMonth($partial);
556
  }
557
  if(strpos($format, 'DD') !== FALSE){
558
    $d = partialToDay($partial);
559
  }
560

    
561
  $y = $y ? $y : '0000';
562
  $m = $m ? $m : '00';
563
  $d = $d ? $d : '00';
564

    
565
  $date = '';
566

    
567
  if ($y == '0000' && $stripZeros && $m == '00' && $d == '00') {
568
    return '';
569
  }
570
  else {
571
    $date = $y;
572
  }
573

    
574
  if ($m == '00' && $stripZeros && $d == '00') {
575
    return $date;
576
  }
577
  else {
578
    $date .= "-" . $m;
579
  }
580

    
581
  if ($d == '00' && $stripZeros) {
582
    return $date;
583
  }
584
  else {
585
    $date .= "-" . $d;
586
  }
587
  return $date;
588
}
589

    
590
/**
591
 * Converts a time period to a string.
592
 *
593
 * See also partialToDate($partial, $stripZeros).
594
 *
595
 * @param object $period
596
 *   An JodaTime org.joda.time.Period object.
597
 * @param bool $stripZeros
598
 *   If set to True, the zero (00) month and days will be hidden:
599
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
600
 * @param string @format
601
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
602
 *    - "YYYY": Year only
603
 *    - "YYYY-MM-DD": this is the default
604
 *
605
 * @return string
606
 *   Returns a date in the form of a string.
607
 */
608
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
609
  $dateString = '';
610
  if (is_string($period)){
611
        $dateString = $period;
612
  }else {
613
      if ($period->freeText) {
614
          $dateString = $period->freeText;
615
      }elseif(isset_not_empty($period->timePeriod)){
616
          $dateString = $period->timePeriod;
617
      }else {
618
          if ($period->start) {
619
              $dateString = partialToDate($period->start, $stripZeros, $format);
620
          }
621
          if ($period->end) {
622
              $end_str = partialToDate($period->end, $stripZeros, $format);
623
              $dateString .= ($dateString && $end_str ? ' ' . t('to') . ' ' : '') . $end_str;
624
          }
625

    
626
      }
627
  }
628

    
629
  return $dateString;
630
}
631

    
632
/**
633
 * returns the earliest date available in the $period in a normalized
634
 * form suitable for sorting, e.g.:
635
 *
636
 *  - 1956-00-00
637
 *  - 0000-00-00
638
 *  - 1957-03-00
639
 *
640
 * that is either the start date is returned if set otherwise the
641
 * end date
642
 *
643
 * @param  $period
644
 *    An JodaTime org.joda.time.Period object.
645
 * @return string normalized form of the date
646
 *   suitable for sorting
647
 */
648
function timePeriodAsOrderKey($period) {
649
  $dateString = '';
650
  if ($period->start) {
651
    $dateString = partialToDate($period->start, false);
652
  }
653
  if ($period->end) {
654
    $dateString .= partialToDate($period->end, false);
655
  }
656
  return $dateString;
657
}
658

    
659
/**
660
 * Composes a absolute CDM web service URI with parameters and querystring.
661
 *
662
 * @param string $uri_pattern
663
 *   String with place holders ($0, $1, ..) that should be replaced by the
664
 *   according element of the $pathParameters array.
665
 * @param array $pathParameters
666
 *   An array of path elements, or a single element.
667
 * @param string $query
668
 *   A query string to append to the URL.
669
 *
670
 * @return string
671
 *   A complete URL with parameters to a CDM webservice.
672
 */
673
function cdm_compose_ws_url($uri_pattern, $pathParameters = array(), $query = NULL) {
674
  if (empty($pathParameters)) {
675
    $pathParameters = array();
676
  }
677
  $path = cdm_compose_url($uri_pattern, $pathParameters, $query);
678
  $url = cdm_webservice_url() . $path;
679
  return $url;
680
}
681

    
682
/**
683
 * Wrapper to access the 'cdm_webservice_url' and to ensure that
684
 * the returned webservice url scheme conforms to the scheme of the
685
 * page request.
686
 *
687
 * @param string $default optional parameter to set the default, by default an empty string is returned
688
 */
689
function cdm_webservice_url($default = ''){
690
  static $conform_ws_url = null;
691
  if($conform_ws_url === null) {
692
    $ws_url = variable_get('cdm_webservice_url', $default);
693
    if($ws_url && $_SERVER['REQUEST_SCHEME'] == 'https' && parse_url($ws_url, PHP_URL_SCHEME) === 'http'){
694
      $conform_ws_url = preg_replace("/^http\:/", "https:", $ws_url);
695
      drupal_set_message('The <stong>CDM web service URL</stong> scheme should be set to <strong>HTTPS</strong> the '
696
        . l('CDM Data Portal settings', 'admin/config/cdm_dataportal/settings'), 'warning');
697
    } else {
698
      $conform_ws_url = $ws_url;
699
    }
700
  }
701
  return $conform_ws_url;
702
}
703

    
704
/**
705
 * Composes a relative Url with parameters and querystring.
706
 *
707
 * @param string $uri_pattern
708
 *   String with place holders ($0, $1, ..) that should be replaced by the
709
 *   according element of the $pathParameters array.
710
 * @param array $pathParameters
711
 *   An array of path elements, or a single element.
712
 * @param string $query
713
 *   A query string to append to the URL.
714
 *
715
 * @return string
716
 *   A relative URL with query parameters.
717
 */
718
function cdm_compose_url($uri_pattern, $pathParameters, $query = NULL) {
719

    
720
  // (1)
721
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
722
  // according element of the $pathParameters array.
723
  static $helperArray = [];
724
  if (isset($pathParameters) && !is_array($pathParameters)) {
725
    $helperArray[0] = $pathParameters;
726
    $pathParameters = $helperArray;
727
  }
728

    
729
  $i = 0;
730
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
731
    if (count($pathParameters) <= $i) {
732
      drupal_set_message('cdm_compose_url(): missing pathParameter ' . $i .' for ' . $uri_pattern, 'error');
733
      break;
734
    }
735
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
736
    ++$i;
737
  }
738

    
739
  // (2)
740
  // Append all remaining element of the $pathParameters array as path
741
  // elements.
742
  if (count($pathParameters) > $i) {
743
    // Strip trailing slashes.
744
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
745
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
746
    }
747
    while (count($pathParameters) > $i) {
748
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
749
      ++$i;
750
    }
751
  }
752

    
753
  // (3)
754
  // Append the query string supplied by $query.
755
  $uri_pattern = append_query_parameters($uri_pattern, $query);
756

    
757
  $path = $uri_pattern;
758
  return $path;
759
}
760

    
761
/**
762
 * @param string $uri
763
 *
764
 * @param $query_string
765
 *
766
 * @return string
767
 */
768
function append_query_parameters($uri, $query_string) {
769

    
770
  if (isset($query_string)) {
771
    $uri .= (strpos($uri, '?') !== FALSE ? '&' : '?') . $query_string;
772
  }
773

    
774
  return $uri;
775
}
776

    
777
/**
778
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
779
 *     together with a theme name to such a proxy function?
780
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
781
 *     Maybe we want to have two different proxy functions, one with theming and one without?
782
 *
783
 * @param string $uri
784
 *     A URI to a CDM Rest service from which to retrieve an object
785
 * @param string|null $hook
786
 *     (optional) The hook name to which the retrieved object should be passed.
787
 *     Hooks can either be a theme_hook() or compose_hook() implementation
788
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
789
 *     suitable for drupal_render()
790
 *
791
 * @todo Please document this function.
792
 * @see http://drupal.org/node/1354
793
 */
794
function proxy_content($uri, $hook = NULL) {
795

    
796
  $args = func_get_args();
797
  $do_gzip = function_exists('gzencode');
798
  $uriEncoded = array_shift($args);
799
  $uri = urldecode($uriEncoded);
800
  $hook = array_shift($args);
801
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
802

    
803
  $post_data = null;
804

    
805
  if ($request_method == "POST" || $request_method == "PUT") {
806
    // read response body via inputstream module
807
    $post_data = file_get_contents("php://input");
808
  }
809

    
810
  // Find and deserialize arrays.
811
  foreach ($args as &$arg) {
812
    // FIXME use regex to find serialized arrays.
813
    //       or should we accept json instead of php serializations?
814
    if (strpos($arg, "a:") === 0) {
815
      $arg = unserialize($arg);
816
    }
817
  }
818

    
819
  // In all these cases perform a simple get request.
820
  // TODO reconsider caching logic in this function.
821

    
822
  if (empty($hook)) {
823
    // simply return the webservice response
824
    // Print out JSON, the cache cannot be used since it contains objects.
825
    $http_response = cdm_http_request($uri, $request_method, $post_data);
826
    if (isset($http_response->headers)) {
827
      foreach ($http_response->headers as $hname => $hvalue) {
828
        drupal_add_http_header($hname, $hvalue);
829
      }
830
    }
831
    if (isset($http_response->data)) {
832
      print $http_response->data;
833
      flush();
834
    }
835
    exit(); // leave drupal here
836
  } else {
837
    // $hook has been supplied
838
    // handle $hook either as compose or theme hook
839
    // pass through theme or compose hook
840
    // compose hooks can be called without data, therefore
841
    // passing the $uri in this case is not always a requirement
842

    
843
    if($uri && $uri != 'NULL') {
844
    // do a security check since the $uri will be passed
845
    // as absolute URI to cdm_ws_get()
846
      if (!_is_cdm_ws_uri($uri)) {
847
        drupal_set_message(
848
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
849
          'error'
850
        );
851
        return '';
852
      }
853

    
854
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
855
    } else {
856
      $obj = NULL;
857
    }
858

    
859
    $response_data = NULL;
860

    
861
    if (function_exists('compose_' . $hook)){
862
      // call compose hook
863

    
864
      $elements =  call_user_func('compose_' . $hook, $obj);
865
      // pass the render array to drupal_render()
866
      $response_data = drupal_render($elements);
867
    } else {
868
      // call theme hook
869

    
870
      // TODO use theme registry to get the registered hook info and
871
      //    use these defaults
872
      switch($hook) {
873
        case 'cdm_taxontree':
874
          $variables = array(
875
            'tree' => $obj,
876
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
877
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
878
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
879
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
880
            );
881
          $response_data = theme($hook, $variables);
882
          break;
883

    
884
        case 'cdm_list_of_taxa':
885
            $variables = array(
886
              'records' => $obj,
887
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
888
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
889
            $response_data = theme($hook, $variables);
890
            break;
891

    
892
        default:
893
          drupal_set_message(t(
894
          'Theme !theme is not yet supported by the function !function.', array(
895
          '!theme' => $hook,
896
          '!function' => __FUNCTION__,
897
          )), 'error');
898
          break;
899
      } // END of theme hook switch
900
    } // END of tread as theme hook
901

    
902

    
903
    if($do_gzip){
904
      $response_data = gzencode($response_data, 2, FORCE_GZIP);
905
      drupal_add_http_header('Content-Encoding', 'gzip');
906
    }
907
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
908
    drupal_add_http_header('Content-Length', strlen($response_data));
909

    
910
    print $response_data;
911
  } // END of handle $hook either as compose ot theme hook
912

    
913
}
914

    
915
/**
916
 * @todo Please document this function.
917
 * @see http://drupal.org/node/1354
918
 */
919
function setvalue_session() {
920
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
921
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
922
    $var_keys = explode('][', $var_keys);
923
  }
924
  else {
925
    return;
926
  }
927
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
928

    
929
  // Prevent from malicous tags.
930
  $val = strip_tags($val);
931

    
932
  $session_var = &$_SESSION;
933
  //$i = 0;
934
  foreach ($var_keys as $key) {
935
    // $hasMoreKeys = ++$i < count($session);
936
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
937
      $session_var[$key] = array();
938
    }
939
    $session_var = &$session_var[$key];
940
  }
941
  $session_var = $val;
942
  if (isset($_REQUEST['destination'])) {
943
    drupal_goto($_REQUEST['destination']);
944
  }
945
}
946

    
947
/**
948
 * @todo Please document this function.
949
 * @see http://drupal.org/node/1354
950
 */
951
function uri_uriByProxy($uri, $theme = FALSE) {
952
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
953
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
954
}
955

    
956
/**
957
 * Composes the the absolute REST service URI to the annotations pager
958
 * for the given CDM entity.
959
 *
960
 * NOTE: Not all CDM Base types are yet supported.
961
 *
962
 * @param $cdm_entity
963
 *   The CDM entity to construct the annotations pager uri for
964
 */
965
function cdm_compose_annotations_uri($cdm_entity) {
966
    $cdm_entity_type = "";
967
    if (isset_not_empty($cdm_entity->class)){
968
        $cdm_entity_type = $cdm_entity->class;
969
    }elseif(isset_not_empty($cdm_entity->clazz)){
970
        $cdm_entity_type = $cdm_entity->clazz;
971
    }
972

    
973

    
974

    
975
  if($cdm_entity_type == 'DerivedUnitFacade'){
976
    // TODO with the below code we may miss annotations.
977
    //  Better implement a derivedUnitFacade/{uuid}/annotations service and use that instead
978
    if(isset($cdm_entity->fieldUnitEntityReference)){
979
      $cdm_entity_type = $cdm_entity->fieldUnitEntityReference->type;
980
      $cdm_entity_uuid = $cdm_entity->fieldUnitEntityReference->uuid;
981
    } elseif(isset($cdm_entity->baseUnitEntityReference)){
982
      $cdm_entity_type = $cdm_entity->baseUnitEntityReference->type;
983
      $cdm_entity_uuid = $cdm_entity->baseUnitEntityReference->uuid;
984
    }
985
  } elseif ($cdm_entity_type == 'TypedEntityReference'){
986
    $cdm_entity_type = $cdm_entity->type;
987
    $cdm_entity_uuid = $cdm_entity->uuid;
988
  } else {
989
    if (isset($cdm_entity->uuid)) {
990
      $cdm_entity_uuid = $cdm_entity->uuid;
991
    }
992
  }
993

    
994
  if(!isset($cdm_entity_uuid) || !isset($cdm_entity_type) || !$cdm_entity_type ){
995
    // silently give up
996
    return;
997
  }
998

    
999
  $ws_base_uri = cdm_ws_base_uri($cdm_entity_type);
1000

    
1001
  if($ws_base_uri === null){
1002
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdm_entity_type), E_USER_ERROR);
1003
  }
1004
  return cdm_compose_ws_url($ws_base_uri, array(
1005
    $cdm_entity_uuid,
1006
    'annotations',
1007
  ));
1008
}
1009

    
1010
/**
1011
 * Provides the base URI of the cdm REST service responsible for the passed simple name
1012
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
1013
 *
1014
 * @param $cdm_type_simple
1015
 *    simple name of a CDM java class
1016
 * @return null|string
1017
 */
1018
function cdm_ws_base_uri($cdm_type_simple)
1019
{
1020
  switch ($cdm_type_simple) {
1021
    case 'TaxonNode':
1022
    case 'TaxonNodeDto':
1023
      $ws_base_uri = CDM_WS_TAXONNODE;
1024
      break;
1025

    
1026
    case 'TaxonBase':
1027
    case 'Taxon':
1028
    case 'Synonym':
1029
      $ws_base_uri = CDM_WS_TAXON;
1030
      break;
1031

    
1032
    case 'TaxonName':
1033
      $ws_base_uri = CDM_WS_NAME;
1034
      break;
1035

    
1036
    case 'Media':
1037
      $ws_base_uri = CDM_WS_MEDIA;
1038
      break;
1039

    
1040
    case 'Reference':
1041
      $ws_base_uri = CDM_WS_REFERENCE;
1042
      break;
1043

    
1044
    case 'Registration':
1045
      $ws_base_uri = CDM_WS_REGISTRATION;
1046
      break;
1047

    
1048
    case 'FieldUnit':
1049
    case 'DerivedUnit':
1050
    case 'DnaSample':
1051
    case 'MediaSpecimen':
1052
    case 'DerivedUnitDTO':
1053
    case 'FieldUnitDTO':
1054
    case 'DNASampleDTO':
1055
      $ws_base_uri = CDM_WS_OCCURRENCE;
1056
      break;
1057

    
1058
    case 'Amplification':
1059
    case 'DerivationEvent':
1060
    case 'DeterminationEvent':
1061
    case 'GatheringEvent':
1062
    case 'MaterialOrMethodEvent':
1063
    case 'SingleRead':
1064
      $ws_base_uri = CDM_WS_EVENTBASE;
1065
      break;
1066

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

    
1080
    case 'Person':
1081
    case 'Team':
1082
    case 'AgentBase':
1083
      $ws_base_uri = CDM_WS_AGENT;
1084
      break;
1085

    
1086
    case 'PolytomousKey':
1087
    case 'MediaKey':
1088
    case 'MultiAccessKey':
1089
      $ws_base_uri = $cdm_type_simple;
1090
      $ws_base_uri[0] = strtolower($ws_base_uri[0]);
1091
      break;
1092

    
1093
    case 'TextualTypeDesignation':
1094
    case 'SpecimenTypeDesignation':
1095
    case 'NameTypeDesignation':
1096
    case 'TypeDesignationDTO':
1097
      $ws_base_uri = CDM_WS_TYPEDESIGNATION;
1098
      break;
1099
    default:
1100
      $ws_base_uri = null;
1101
      drupal_set_message(
1102
        t('cdm_ws_base_uri()  - cdm type name "@cdm_type_simple" unsupported',
1103
          array('@cdm_type_simple' => $cdm_type_simple )),
1104
        'error');
1105
  }
1106
  return $ws_base_uri;
1107
}
1108

    
1109
function cdm_type_has_tagged_text($cdm_type_name){
1110
  return array_search($cdm_type_name, ['TaxonName', 'Taxon', 'Synonym']) !== false;
1111
}
1112

    
1113
/**
1114
 * Enter description here...
1115
 *
1116
 * @param string $resource_uri
1117
 * @param int $page_size
1118
 *   The maximum number of entities returned per page.
1119
 *   The default page size as configured in the cdm server
1120
 *   will be used if set to NULL
1121
 *   to return all entities in a single page).
1122
 * @param int $page_index
1123
 *   The number of the page to be returned, the first page has the
1124
 *   page_index = 0
1125
 * @param array $query
1126
 *   A array holding the HTTP request query parameters for the request
1127
 * @param string $method
1128
 *   The HTTP method to use, valid values are "GET" or "POST"
1129
 * @param bool $absolute_uri
1130
 *   TRUE when the URL should be treated as absolute URL.
1131
 *
1132
 * @return object
1133
 *   A CDM Pager object
1134
 *
1135
 */
1136
function cdm_ws_page($resource_uri, $page_size, $page_index, array $query = array(), $method = 'GET', $absolute_uri = FALSE) {
1137

    
1138
  $query['pageIndex'] = $page_index;
1139
  $query['pageSize'] = $page_size;
1140

    
1141
  $pager = cdm_ws_get($resource_uri, NULL, queryString($query), $method, $absolute_uri);
1142
  if(is_array($pager)){
1143
    trigger_error("Expecting web service to return pager objects but received an array:<br/>" . $resource_uri . '?' . queryString($query) . '<br/>Wrapping response in pager to recover from error.', E_USER_WARNING);
1144
    $records = $pager;
1145
    $pager = new stdClass();
1146
    $pager->records = $records;
1147
    $pager->count = count($records);
1148
    $pager->pageSize = $pager->count;
1149
    $pager->nextIndex = null;
1150
  }
1151
  return $pager;
1152
}
1153

    
1154

    
1155
/**
1156
 * Sends a http GET request to the generic page method which allows for filtering entities by Restrictions.
1157
 *
1158
 * @param $cdm_entity_type
1159
 * @param $class_restriction
1160
 *   Optional param to narrow down polymorph types to a specific type.
1161
 * @param array $restrictions
1162
 *   An array of Restriction objects
1163
 * @param array $init_strategy
1164
 *   The init strategy to initialize the entity beans while being loaded from the
1165
 *   persistent storage by the cdm
1166
 * @param int $page_size
1167
 *   The maximum number of entities returned per page.
1168
 *   The default page size as configured in the cdm server
1169
 *   will be used if set to NULL
1170
 *   to return all entities in a single page).
1171
 * @param int $page_index
1172
 *   The number of the page to be returned, the first page has the
1173
 *   pageNumber = 0
1174
 *
1175
 * @return object
1176
 *   A CDM Pager object
1177
 */
1178
function cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy, $page_size, $page_index) {
1179

    
1180
  $restrictions_json = array(); // json_encode($restrictions);
1181
  foreach ($restrictions as $restr){
1182
    $restrictions_json[] = json_encode($restr);
1183
  }
1184
  $filter_parameters = [
1185
    'restriction' => $restrictions_json,
1186
    'initStrategy' => $init_strategy
1187
  ];
1188
  if($class_restriction){
1189
    $filter_parameters['class'] = $class_restriction;
1190
  }
1191

    
1192
  return cdm_ws_page(
1193
      'portal/' . cdm_ws_base_uri($cdm_entity_type),
1194
      $page_size,
1195
      $page_index,
1196
    $filter_parameters,
1197
    "GET"
1198
    );
1199
}
1200

    
1201
/**
1202
 * Fetches all entities returned by the the generic page method for the Restrictions applied as filter.
1203
 *
1204
 * @param $cdm_entity_type
1205
 * @param $class_restriction
1206
 *   Optional param to narrow down polymorph types to a specific type.
1207
 * @param array $restrictions
1208
 *   An array of Restriction objects
1209
 * @param array $init_strategy
1210
 *   The init strategy to initialize the entity beans while being loaded from the
1211
 *   persistent storage by the cdm
1212
 *
1213
 * @return array
1214
 *   A array of CDM entities
1215
 */
1216
function cdm_ws_fetch_all_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy){
1217
  $page_index = 0;
1218
  // using a bigger page size to avoid to many multiple requests
1219
  $page_size = 500;
1220
  $entities = array();
1221

    
1222
  while ($page_index !== FALSE && $page_index < 1){
1223
    $pager =  cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, $restrictions, $init_strategy, $page_size, $page_index);
1224
    if(isset($pager->records) && is_array($pager->records)) {
1225
      $entities = array_merge($entities, $pager->records);
1226
      if(!empty($pager->nextIndex)){
1227
        $page_index = $pager->nextIndex;
1228
      } else {
1229
        $page_index = FALSE;
1230
      }
1231
    } else {
1232
      $page_index = FALSE;
1233
    }
1234
  }
1235
  return $entities;
1236
}
1237

    
1238

    
1239
  /**
1240
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1241
 *
1242
 * @param string $resourceURI
1243
 * @param array $query
1244
 *   A array holding the HTTP request query parameters for the request
1245
 * @param string $method
1246
 *   The HTTP method to use, valid values are "GET" or "POST";
1247
 * @param bool $absoluteURI
1248
 *   TRUE when the URL should be treated as absolute URL.
1249
 *
1250
 * @return array
1251
 *     A list of CDM entitites
1252
 *
1253
 */
1254
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1255
  $page_index = 0;
1256
  // using a bigger page size to avoid too many multiple requests
1257
  $page_size = 500;
1258
  $entities = [];
1259

    
1260
  while (true){
1261
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1262
    if(isset($pager->records) && is_array($pager->records)) {
1263
      $entities = array_merge($entities, $pager->records);
1264
      if(is_numeric($pager->nextIndex) && $page_index < $pager->nextIndex){
1265
        $page_index = $pager->nextIndex;
1266
      } else {
1267
        break;
1268
      }
1269
    } else {
1270
      break;
1271
    }
1272
  }
1273
  return $entities;
1274
}
1275

    
1276
/*
1277
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1278
  $viewrank = _cdm_taxonomy_compose_viewrank();
1279
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1280
  ? '/' . $path : '') ;
1281
}
1282
*/
1283

    
1284
/**
1285
 * @todo Enter description here...
1286
 *
1287
 * @param string $taxon_uuid
1288
 *  The UUID of a cdm taxon instance
1289
 * @param string $ignore_rank_limit
1290
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1291
 *
1292
 * @return string
1293
 *   A cdm REST service URL path to a Classification
1294
 */
1295
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1296

    
1297
  $view_uuid = get_current_classification_uuid();
1298
  $rank_uuid = NULL;
1299
  if (!$ignore_rank_limit) {
1300
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1301
  }
1302

    
1303
  if (!empty($taxon_uuid)) {
1304
    return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1305
      $view_uuid,
1306
      $taxon_uuid,
1307
    ));
1308
  }
1309
  else {
1310
    if (is_uuid($rank_uuid)) {
1311
      return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1312
        $view_uuid,
1313
        $rank_uuid,
1314
      ));
1315
    }
1316
    else {
1317
      return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1318
        $view_uuid,
1319
      ));
1320
    }
1321
  }
1322
}
1323

    
1324
/**
1325
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1326
 *
1327
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1328
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1329
 *
1330
 * Operates in two modes depending on whether the parameter
1331
 * $taxon_uuid is set or NULL.
1332
 *
1333
 * A) $taxon_uuid = NULL:
1334
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1335
 *  2. otherwise return the default classification as defined by the admin via the settings
1336
 *
1337
 * b) $taxon_uuid is set:
1338
 *   return the classification to whcih the taxon belongs to.
1339
 *
1340
 * @param UUID $taxon_uuid
1341
 *   The UUID of a cdm taxon instance
1342
 */
1343
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1344

    
1345
    $response = NULL;
1346

    
1347
    // 1st try
1348
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1349

    
1350
    if ($response == NULL) {
1351
      // 2dn try by ignoring the rank limit
1352
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1353
    }
1354

    
1355
    if ($response == NULL) {
1356
      // 3rd try, last fallback:
1357
      //    return the default classification
1358
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1359
        // Delete the session value and try again with the default.
1360
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1361
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1362
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1363
      }
1364
      else {
1365
        // Check if taxonomictree_uuid is valid.
1366
        // expecting an array of taxonNodes,
1367
        // empty classifications are ok so no warning in this case!
1368
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1369
        if (!is_array($test)) {
1370
          // The default set by the admin seems to be invalid or is not even set.
1371
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1372
        } else if (count($test) == 0) {
1373
          // The default set by the admin seems to be invalid or is not even set.
1374
          drupal_set_message("The chosen classification is empty.", 'status');
1375
        }
1376
      }
1377
    }
1378

    
1379
  return $response;
1380
}
1381

    
1382
/**
1383
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1384
 * 
1385
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1386
 * variable is set.
1387
 *
1388
 * @param string $taxon_uuid
1389
 *
1390
 * @return array
1391
 *   An array of CDM TaxonNodeDTO objects
1392
 */
1393
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1394
  $view_uuid = get_current_classification_uuid();
1395
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1396

    
1397
  $response = NULL;
1398
  if (is_uuid($rank_uuid)) {
1399
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1400
      $view_uuid,
1401
      $taxon_uuid,
1402
      $rank_uuid,
1403
    ));
1404
  }
1405
  else {
1406
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1407
      $view_uuid,
1408
      $taxon_uuid,
1409
    ));
1410
  }
1411

    
1412
  if ($response == NULL) {
1413
    // Error handing.
1414
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1415
//      // Delete the session value and try again with the default.
1416
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1417
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1418
//    }
1419
//    else {
1420
      // Check if taxonomictree_uuid is valid.
1421
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1422
      if ($test == NULL) {
1423
        // The default set by the admin seems to be invalid or is not even set.
1424
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1425
      }
1426
//    }
1427
  }
1428

    
1429
  return $response;
1430
}
1431

    
1432

    
1433
// =============================Terms and Vocabularies ========================================= //
1434

    
1435
/**
1436
 * Returns the localized representation for the given term.
1437
 *
1438
 * @param Object $definedTermBase
1439
 * 	  of cdm type DefinedTermBase
1440
 * @return string
1441
 * 	  the localized representation_L10n of the term,
1442
 *    otherwise the titleCache as fall back,
1443
 *    otherwise the default_representation which defaults to an empty string
1444
 */
1445
function cdm_term_representation($definedTermBase, $default_representation = '') {
1446
  if ( isset($definedTermBase->representation_L10n) ) {
1447
    return $definedTermBase->representation_L10n;
1448
  } elseif ( isset($definedTermBase->titleCache)) {
1449
    return $definedTermBase->titleCache;
1450
  } elseif (isset($definedTermBase->label)){
1451
      return $definedTermBase->label;
1452
  }
1453

    
1454
  if (is_string($definedTermBase)){
1455
      return $definedTermBase;
1456
  }
1457
  return $default_representation;
1458
}
1459

    
1460
/**
1461
 * Returns the abbreviated localized representation for the given term.
1462
 *
1463
 * @param Object $definedTermBase
1464
 * 	  of cdm type DefinedTermBase
1465
 * @return string
1466
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1467
 *    if this representation is not available the function delegates the
1468
 *    call to cdm_term_representation()
1469
 */
1470
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1471
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1472
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1473
  } else {
1474
    cdm_term_representation($definedTermBase, $default_representation);
1475
  }
1476
}
1477

    
1478
/**
1479
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1480
 *
1481
 * The options array is suitable for drupal form API elements that allow multiple choices.
1482
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1483
 *
1484
 * @param array $terms
1485
 *   a list of CDM DefinedTermBase instances
1486
 *
1487
 * @param $term_label_callback
1488
 *   A callback function to override the term representations
1489
 *
1490
 * @param bool $empty_option
1491
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1492
 *
1493
 * @return array
1494
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1495

    
1496
 */
1497
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1498
  $options = array();
1499
  if(isset($terms) && is_array($terms)) {
1500
    foreach ($terms as $term) {
1501
      if ($term_label_callback && function_exists($term_label_callback)) {
1502
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1503
      } else {
1504
        //TODO use cdm_term_representation() here?
1505
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1506
      }
1507
    }
1508
  }
1509

    
1510
  if($empty_option !== FALSE){
1511
    array_unshift ($options, "");
1512
  }
1513

    
1514
  return $options;
1515
}
1516

    
1517
/**
1518
 * Creates and array of options for drupal select form elements.
1519
 *
1520
 * @param $vocabulary_uuid
1521
 *   The UUID of the CDM Term Vocabulary
1522
 * @param $term_label_callback
1523
 *   An optional call back function which can be used to modify the term label
1524
 * @param bool $empty_option
1525
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1526
 * @param array $include_filter
1527
 *   An associative array consisting of a field name an regular expression. All term matching
1528
 *   these filter are included. The value of the field is converted to a String by var_export()
1529
 *   so a boolean 'true' can be matched by '/true/'
1530
 * @param string $order_by
1531
 *   One of the order by constants defined in this file
1532
 * @return array
1533
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1534
 */
1535
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1536
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1537

    
1538
  static $vocabularyOptions = array();
1539

    
1540
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1541
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1542
      array(
1543
        'orderBy' => $order_by
1544
      )
1545
    );
1546

    
1547
    // apply the include filter
1548
    if($include_filter != null){
1549
      $included_terms = array();
1550

    
1551
      foreach ($terms as $term){
1552
        $include = true;
1553
        foreach ($include_filter as $field=>$regex){
1554
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1555
          if(!$include){
1556
            break;
1557
          }
1558
        }
1559
        if($include){
1560
          $included_terms[] = $term;
1561
        }
1562
      }
1563

    
1564
      $terms = $included_terms;
1565
    }
1566

    
1567
    // make options list
1568
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1569
  }
1570

    
1571
  $options = $vocabularyOptions[$vocabulary_uuid];
1572

    
1573
  return $options;
1574
}
1575

    
1576
/**
1577
 * Creates and array of defaults for drupal select form elements.
1578
 *
1579
 * @param $vocabulary_uuid
1580
 *   The UUID of the CDM Term Vocabulary
1581
 * @param $term_label_callback
1582
 *   An optional call back function which can be used to modify the term label
1583
 * @param bool $empty_option
1584
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1585
 * @param array $include_filter
1586
 *   An associative array consisting of a field name an regular expression. All term matching
1587
 *   these filter are included. The value of the field is converted to a String by var_export()
1588
 *   so a boolean 'true' can be matched by '/true/'
1589
 * @param string $order_by
1590
 *   One of the order by constants defined in this file
1591
 * @return array
1592
 *   the terms in an array (key: uuid => value: uuid) as defaults for a form element that allows multiple choices.
1593
 */
1594
function cdm_vocabulary_as_defaults($vocabulary_uuid, array $include_filter = null) {
1595

    
1596
  $options = cdm_vocabulary_as_option($vocabulary_uuid, null, null, $include_filter);
1597
  $defaults = array();
1598
  foreach ($options as $uuid => $value){
1599
    $defaults[$uuid] = $uuid;
1600
  }
1601

    
1602
  return $defaults;
1603
}
1604

    
1605
/**
1606
 * @param $term_type string one of
1607
 *  - Unknown
1608
 *  - Language
1609
 *  - NamedArea
1610
 *  - Rank
1611
 *  - Feature
1612
 *  - AnnotationType
1613
 *  - MarkerType
1614
 *  - ExtensionType
1615
 *  - DerivationEventType
1616
 *  - PresenceAbsenceTerm
1617
 *  - NomenclaturalStatusType
1618
 *  - NameRelationshipType
1619
 *  - HybridRelationshipType
1620
 *  - SynonymRelationshipType
1621
 *  - TaxonRelationshipType
1622
 *  - NameTypeDesignationStatus
1623
 *  - SpecimenTypeDesignationStatus
1624
 *  - InstitutionType
1625
 *  - NamedAreaType
1626
 *  - NamedAreaLevel
1627
 *  - RightsType
1628
 *  - MeasurementUnit
1629
 *  - StatisticalMeasure
1630
 *  - MaterialOrMethod
1631
 *  - Material
1632
 *  - Method
1633
 *  - Modifier
1634
 *  - Scope
1635
 *  - Stage
1636
 *  - KindOfUnit
1637
 *  - Sex
1638
 *  - ReferenceSystem
1639
 *  - State
1640
 *  - NaturalLanguageTerm
1641
 *  - TextFormat
1642
 *  - DeterminationModifier
1643
 *  - DnaMarker
1644
 *
1645
 * @param  $order_by
1646
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1647
 *  possible values:
1648
 *    - CDM_ORDER_BY_ID_ASC
1649
 *    - CDM_ORDER_BY_ID_DESC
1650
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1651
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1652
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1653
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1654
 * @param bool $empty_option
1655
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1656
 * @return array
1657
 *    the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1658
 */
1659
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1660
  $terms = cdm_ws_fetch_all(
1661
    CDM_WS_TERM,
1662
    array(
1663
      'class' => $term_type,
1664
      'orderBy' => $order_by
1665
    )
1666
  );
1667
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1668
}
1669

    
1670
/**
1671
 * @param array $none_option
1672
 *    Will add a filter option to search for NULL values
1673
 * @param $with_empty_option
1674
 *    Will add an empty option to the beginning. Choosing this option will disable the filtering.
1675
 * @return array
1676
 *   An array of options with uuids as key and the localized term representation as value
1677
 */
1678
function cdm_type_designation_status_filter_terms_as_options($none_option_label, $with_empty_option = false){
1679
  $filter_terms = cdm_ws_get(CDM_WS_TYPE_DESIGNATION_STATUS_FILTER_TERMS);
1680

    
1681
  $options = [];
1682

    
1683
  if(isset($filter_terms) && is_array($filter_terms)) {
1684
    foreach ($filter_terms as $filter_term) {
1685
      $options[join(',', $filter_term->uuids)] = $filter_term->label;
1686
    }
1687
  }
1688

    
1689
  if(is_string($none_option_label)){
1690
    $options = array_merge(array('NULL' => $none_option_label), $options);
1691
  }
1692

    
1693
  if($with_empty_option !== FALSE){
1694
    array_unshift ($options, "");
1695
  }
1696

    
1697
  return $options;
1698
}
1699

    
1700

    
1701

    
1702
/**
1703
 * Callback function which provides the localized representation of a cdm term.
1704
 *
1705
 * The representation is build by concatenating the abbreviated label with the label
1706
 * and thus is especially useful for relationship terms
1707
 * The localized representation provided by the cdm can be overwritten by
1708
 * providing a drupal translation.
1709
 *
1710
 */
1711
function _cdm_relationship_type_term_label_callback($term) {
1712
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1713
    return $term->representation_L10n_abbreviatedLabel . ' : '
1714
    . t('@term', array('@term' => $term->representation_L10n));
1715
  }
1716
else {
1717
    return t('@term', array('@term' => $term->representation_L10n));
1718
  }
1719
}
1720

    
1721
/**
1722
 * Callback function which provides the localized inverse representation of a cdm term.
1723
 *
1724
 * The representation is build by concatenating the abbreviated label with the label
1725
 * and thus is especially useful for relationship terms
1726
 * The localized representation provided by the cdm can be overwritten by
1727
 * providing a drupal translation.
1728
 *
1729
 */
1730
function _cdm_relationship_type_term_inverse_label_callback($term) {
1731
  if (isset($term->inverseRepresentation_L10n_abbreviatedLabel)) {
1732
    return $term->inverseRepresentation_L10n_abbreviatedLabel . ' : '
1733
      . t('@term', array('@term' => $term->inverseRepresentation_L10n));
1734
  }
1735
  else {
1736
    return t('@term', array('@term' => $term->inverseRepresentation_L10n));
1737
  }
1738
}
1739

    
1740
/**
1741
 * Returns the localized abbreviated label of the relationship term.
1742
 *
1743
 * In case the abbreviated label is not set the normal representation is returned.
1744
 *
1745
 * @param $term
1746
 * @param bool $is_inverse_relation
1747
 * @return string
1748
 *   The abbreviated label
1749
 */
1750
function cdm_relationship_type_term_abbreviated_label($term, $is_inverse_relation = false){
1751

    
1752
  if($is_inverse_relation) {
1753
    if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1754
      $abbr_label = $term->inverseResentation_L10n_abbreviatedLabel;
1755
    } else {
1756
      $abbr_label = $term->inverseRepresentation_L10n;
1757
    }
1758
  } else {
1759
    if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1760
      $abbr_label = $term->representation_L10n_abbreviatedLabel;
1761
    } else {
1762
      $abbr_label = $term->representation_L10n;
1763
    }
1764
  }
1765
  return $abbr_label;
1766
}
1767

    
1768
/**
1769
 * Returns the symbol of the relationship term.
1770
 *
1771
 * In case the symbol is not set the function falls back to use the abbreviated label or
1772
 * the normal representation..
1773
 *
1774
 * @param $term
1775
 * @param bool $is_inverse_relation
1776
 * @return string
1777
 *   The abbreviated label
1778
 */
1779
function cdm_relationship_type_term_symbol($term, $is_inverse_relation = false){
1780

    
1781
  if($is_inverse_relation) {
1782
    if (isset($term->inverseSymbol) && $term->inverseSymbol) {
1783
      $symbol = $term->inverseSymbol;
1784
    } else if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1785
      $symbol = $term->inverseResentation_L10n_abbreviatedLabel;
1786
    } else {
1787
      $symbol = $term->inverseRepresentation_L10n;
1788
    }
1789
  } else {
1790
    if (isset($term->symbol) && $term->symbol) {
1791
      $symbol = $term->symbol;
1792
    } else if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1793
      $symbol = $term->representation_L10n_abbreviatedLabel;
1794
    } else {
1795
      $symbol = $term->representation_L10n;
1796
    }
1797
  }
1798
  return $symbol;
1799
}
1800

    
1801
// ========================================================================================== //
1802
/**
1803
 * @todo Improve documentation of this function.
1804
 *
1805
 * eu.etaxonomy.cdm.model.description.
1806
 * CategoricalData
1807
 * CommonTaxonName
1808
 * Distribution
1809
 * IndividualsAssociation
1810
 * QuantitativeData
1811
 * TaxonInteraction
1812
 * TextData
1813
 */
1814
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1815
  static $types = array(
1816
    "CategoricalData",
1817
    "CommonTaxonName",
1818
    "Distribution",
1819
    "IndividualsAssociation",
1820
    "QuantitativeData",
1821
    "TaxonInteraction",
1822
    "TextData",
1823
  );
1824

    
1825
  static $options = NULL;
1826
  if ($options == NULL) {
1827
    $options = array();
1828
    if ($prependEmptyElement) {
1829
      $options[' '] = '';
1830
    }
1831
    foreach ($types as $type) {
1832
      // No internatianalization here since these are purely technical terms.
1833
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1834
    }
1835
  }
1836
  return $options;
1837
}
1838

    
1839

    
1840
/**
1841
 * Fetches all TaxonDescription descriptions elements which are associated to the
1842
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1843
 * feature tree.
1844
 * @param $feature_tree
1845
 *     The CDM FeatureTree to be used as template
1846
 * @param $taxon_uuid
1847
 *     The UUID of the taxon
1848
 * @param $excludes
1849
 *     UUIDs of features to be excluded
1850
 * @return object
1851
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1852
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1853
 *     witch will hold the according $descriptionElements.
1854
 */
1855
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1856

    
1857
  if (!$feature_tree) {
1858
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1859
      In order to see the species profiles of your taxa, please select a
1860
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1861
    return FALSE;
1862
  }
1863

    
1864
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1865
      array(
1866
      'taxon' => $taxon_uuid,
1867
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1868
      ),
1869
      'POST'
1870
  );
1871

    
1872
  // Combine all descriptions into one feature tree.
1873
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1874
  $feature_tree->root->childNodes = $merged_nodes;
1875

    
1876
  return $feature_tree;
1877
}
1878

    
1879
/**
1880
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdm_entity.
1881
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1882
 * be requested for the annotations.
1883
 *
1884
 * @param string $cdm_entity_or_dto
1885
 *   An annotatable cdm entity, or corresponding DTO, DTOs containig AnnotationDTOs
1886
 *     in an array field named 'annotations' is supported by this method.
1887
 * @param array $include_types
1888
 *   If an array of annotation type uuids is supplied by this parameter the
1889
 *   list of annotations is resticted to those which belong to this type.
1890
 *
1891
 * @return array
1892
 *   An array of Annotation objects or an empty array.
1893
 */
1894
function cdm_ws_fetch_annotations(&$cdm_entity_or_dto, $include_types = FALSE) {
1895

    
1896
  if(!isset($cdm_entity_or_dto->annotations)){
1897
    $annotation_url = cdm_compose_annotations_uri($cdm_entity_or_dto);
1898
    if ($annotation_url){
1899
        $cdm_entity_or_dto->annotations = cdm_ws_fetch_all($annotation_url, array(), 'GET', TRUE);
1900
    }
1901

    
1902
  }
1903

    
1904
  $annotations_or_dtos = array();
1905
  if (!isset($cdm_entity_or_dto->annotations)){
1906
      return $annotations_or_dtos;
1907
  }
1908

    
1909
  if (is_array($cdm_entity_or_dto->annotations)){
1910
      $annotation_or_dtos = $cdm_entity_or_dto->annotations;
1911
  }else{
1912
      $annotation_or_dtos = $cdm_entity_or_dto->annotations->items;
1913
  }
1914
  foreach ($annotation_or_dtos as $annotation_or_dto) {
1915
    if ($include_types) {
1916
      $is_dto = is_cdm_dto($annotation_or_dto);
1917
      if (($is_dto ? annotation_dto_has_type($annotation_or_dto, $include_types) : annotation_has_type($annotation_or_dto, $include_types))) {
1918
        $annotations_or_dtos[] = $annotation_or_dto;
1919
      }
1920
    }
1921
    else {
1922
      $annotations_or_dtos[] = $annotation_or_dto;
1923
    }
1924
  }
1925
  return $annotations_or_dtos;
1926
}
1927

    
1928
/**
1929
 * @param $annotation
1930
 * @param array $include_types
1931
 *
1932
 * @return bool
1933
 */
1934
function annotation_has_type($annotation, array $include_types) {
1935
  return (isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $include_types, TRUE))
1936
    || (!isset($annotation->annotationType) && in_array('NULL_VALUE', $include_types, TRUE));
1937
}
1938

    
1939
/**
1940
 * @param $annotation_dto
1941
 * @param array $include_types
1942
 *
1943
 * @return bool
1944
 */
1945
function annotation_dto_has_type($annotation_dto, array $include_types) {
1946
  return (isset($annotation_dto->annotationTypeUuid) && in_array($annotation_dto->annotationTypeUuid, $include_types, TRUE))
1947
    || ($annotation_dto->annotationTypeUuid === NULL && in_array('NULL_VALUE', $include_types, TRUE));
1948
}
1949

    
1950
/**
1951
 * Tests if the passed object is a DTO exposed by the cdm webservices.
1952
 * All these DTOs contain a field `class` with the Java class simple name
1953
 * as value. As all DTO classes are suffixed with "DTO" this method can test
1954
 * for this class name suffix.
1955
 *
1956
 * @param $cdm_dto
1957
 *  The potential cdm dto to test
1958
 *
1959
 * @return bool
1960
 *  True in case the $cdm_dto is a DTO
1961
 */
1962
function is_cdm_dto(&$cdm_dto) {
1963
  return isset_not_empty($cdm_dto->type) && isset_not_empty($cdm_dto->class) && (str_endsWith($cdm_dto->class , 'DTO') || str_endsWith($cdm_dto->class , 'Dto') );
1964
}
1965

    
1966
/**
1967
 * Provides the list of visible annotations for the $cdm_entity.
1968
 *
1969
 * @param $cdm_entity_or_dto
1970
 *     The annotatable CDM entity or corresponding DTO, DTOs containig AnnotationDTOs
1971
 *     in an array field named 'annotations' is supported by this method
1972
 *
1973
 * @return array of the annotations entities or DTOs which are visible according
1974
 *     to the settings as stored in ANNOTATION_TYPES_VISIBLE
1975
 */
1976
function cdm_fetch_visible_annotations($cdm_entity_or_dto){
1977

    
1978
  static $annotations_types_filter = null;
1979
  if(!$annotations_types_filter) {
1980
    $annotations_types_filter = unserialize(EXTENSION_TYPES_VISIBLE_DEFAULT);
1981
  }
1982
  return cdm_ws_fetch_annotations($cdm_entity_or_dto, variable_get(ANNOTATION_TYPES_VISIBLE, $annotations_types_filter));
1983
}
1984

    
1985
function cdm_load_tagged_full_title($taxon_name){
1986
  if(isset($taxon_name) && !isset($taxon_name->taggedFullTitle)){
1987
    $tagged_full_title = cdm_ws_get(CDM_WS_NAME, array($taxon_name->uuid, 'taggedFullTitle'));
1988
    if(is_array($tagged_full_title)){
1989
      $taxon_name->taggedFullTitle = $tagged_full_title;
1990

    
1991
    }
1992
  }
1993
}
1994

    
1995
/**
1996
 * Extends the $cdm_entity object by the field if it is not already existing.
1997
 *
1998
 * This function can only be used for fields with 1 to many relations.
1999
  *
2000
 * @param $cdm_base_type
2001
 * @param $field_name
2002
 * @param $cdm_entity
2003
 */
2004
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
2005
{
2006
  if (!isset($cdm_entity->$field_name)) {
2007
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
2008
    $cdm_entity->$field_name = $items;
2009
  }
2010
}
2011

    
2012

    
2013
/**
2014
 * Get a NomenclaturalReference string.
2015
 *
2016
 * Returns the NomenclaturalReference string with correctly placed
2017
 * microreference (= reference detail) e.g.
2018
 * in Phytotaxa 43: 1-48. 2012.
2019
 *
2020
 * @param string $referenceUuid
2021
 *   UUID of the reference.
2022
 * @param string $microreference
2023
 *   Reference detail.
2024
 *
2025
 * @return string
2026
 *   a NomenclaturalReference.
2027
 */
2028
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
2029

    
2030
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
2031
  if(is_array($microreference) || is_object($microreference)) {
2032
    return '';
2033
  }
2034

    
2035
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
2036
    $referenceUuid,
2037
  ), "microReference=" . urlencode($microreference));
2038

    
2039
  if ($obj) {
2040
    return $obj->String;
2041
  }
2042
  else {
2043
    return NULL;
2044
  }
2045
}
2046

    
2047
/**
2048
 * finds and returns the FeatureNode denoted by the given $feature_uuid
2049
 *
2050
 * @param $feature_tree_nodes
2051
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
2052
 * @param $feature_uuid
2053
 *    The UUID of the Feature
2054
 * @return object
2055
 *    the FeatureNode or null
2056
 */
2057
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
2058

    
2059
  // 1. scan this level
2060
  foreach ($feature_tree_nodes as $node){
2061
    if($node->term->uuid == $feature_uuid){
2062
      return $node;
2063
    }
2064
  }
2065

    
2066
  // 2. descend into childen
2067
  foreach ($feature_tree_nodes as $node){
2068
    if(is_array($node->childNodes)){
2069
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
2070
      if($node) {
2071
        return $node;
2072
      }
2073
    }
2074
  }
2075
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
2076
  return $null_var;
2077
}
2078

    
2079
/**
2080
 * finds and returns the FeatureNode denoted by the given $feature_uuid
2081
 *
2082
 * TODO: This needs to be adapted to the new DTO implementation
2083
 *
2084
 * @param $feature_tree_nodes
2085
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
2086
 * @param $feature_uuid
2087
 *    The UUID of the Feature
2088
 * @return object
2089
 *    the FeatureNode or null
2090
 */
2091
function &cdm_feature_tree_new_find_node($feature_tree_nodes, $feature_uuid){
2092

    
2093
    // 1. scan this level
2094
    foreach ($feature_tree_nodes as $node){
2095
        if($node->uuid == $feature_uuid){
2096
            return $node;
2097
        }
2098
    }
2099

    
2100
    // 2. descend into childen do we need this in the new implementation???
2101
    foreach ($feature_tree_nodes as $node){
2102
        if(is_array($node->childNodes)){
2103
            $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
2104
            if($node) {
2105
                return $node;
2106
            }
2107
        }
2108
    }
2109
    $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
2110
    return $null_var;
2111
}
2112

    
2113
/**
2114
 * finds and returns the FeatureNodes for distributions
2115
 *
2116
 * @param $feature_tree_nodes
2117
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
2118
 * @return object
2119
 *    the FeatureNode or null
2120
 */
2121
function &cdm_feature_tree_new_find_distributionNode($feature_tree_nodes){
2122

    
2123
    // 1. scan this level
2124
    $nodes = array();
2125
    foreach ($feature_tree_nodes as $node){
2126
        if(isset_not_empty($node->facts) && isset_not_empty($node->facts->items) && $node->facts->items[0]->clazz == 'DistributionInfoDto'){
2127
            $nodes[] = $node;
2128
        }
2129
    }
2130

    
2131
    // 2. descend into childen do we need this in the new implementation???
2132
    foreach ($feature_tree_nodes as $node){
2133
        if(isset($node->childNodes) && is_array($node->childNodes)){
2134
            $node = cdm_feature_tree_new_find_distributionNode($node->childNodes);
2135
            if($node) {
2136
                $nodes[] = $node;
2137
            }
2138
        }
2139
    }
2140

    
2141
    return $nodes;
2142
}
2143

    
2144

    
2145

    
2146
/**
2147
 * Merges the given featureNodes structure with the descriptionElements.
2148
 *
2149
 * This method is used in preparation for rendering the descriptionElements.
2150
 * The descriptionElements which belong to a specific feature node are appended
2151
 * to a feature node by creating a new field:
2152
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
2153
 * The descriptionElements will be cleared in advance in order to allow reusing the
2154
 * same feature tree without the risk of mixing sets of description elements.
2155
 *
2156
 * which originally is not existing in the cdm.
2157
 *
2158
 *
2159
 *
2160
 * @param array $featureNodes
2161
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
2162
 *    may have children.
2163
 * @param array $descriptionElements
2164
 *    A flat array of cdm DescriptionElements
2165
 * @return array
2166
 *    The $featureNodes structure enriched with the according $descriptionElements
2167
 */
2168
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
2169

    
2170
  foreach ($featureNodes as &$feature_node) {
2171
    // since the $featureNodes array is reused for each description
2172
    // it is necessary to clear the custom node fields in advance
2173
    if(isset($feature_node->descriptionElements)){
2174
      unset($feature_node->descriptionElements);
2175
    }
2176

    
2177
    // Append corresponding elements to an additional node field:
2178
    // $node->descriptionElements.
2179
    foreach ($descriptionElements as $element) {
2180
      if ($element->feature->uuid == $feature_node->term->uuid) {
2181
        if (!isset($feature_node->descriptionElements)) {
2182
          $feature_node->descriptionElements = array();
2183
        }
2184
        $feature_node->descriptionElements[] = $element;
2185
      }
2186
    }
2187

    
2188
    // Recurse into node children.
2189
    if (isset($feature_node->childNodes[0])) {
2190
      $mergedChildNodes = _mergeFeatureTreeDescriptions($feature_node->childNodes, $descriptionElements);
2191
      $feature_node->childNodes = $mergedChildNodes;
2192
    }
2193

    
2194
    if(!isset($feature_node->descriptionElements) && !isset($feature_node->childNodes[0])){
2195
      unset($feature_node);
2196
    }
2197

    
2198
  }
2199

    
2200
  return $featureNodes;
2201
}
2202

    
2203
/**
2204
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
2205
 *
2206
 * The response from the HTTP GET request is returned as object.
2207
 * The response objects coming from the webservice configured in the
2208
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
2209
 *  in a level 2 (L2) cache.
2210
 *
2211
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
2212
 * function, this cache persists only per each single page execution.
2213
 * Any object coming from the webservice is stored into it by default.
2214
 * In contrast to this default caching mechanism the L2 cache only is used if
2215
 * the 'cdm_webservice_cache' variable is set to TRUE,
2216
 * which can be set using the modules administrative settings section.
2217
 * Objects stored in this L2 cache are serialized and stored
2218
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
2219
 * objects that are stored in the database will persist as
2220
 * long as the drupal cache is not being cleared and are available across
2221
 * multiple script executions.
2222
 *
2223
 * @param string $uri
2224
 *   URL to the webservice.
2225
 * @param array $pathParameters
2226
 *   An array of path parameters.
2227
 * @param string $query_string
2228
 *   A query_string string to be appended to the URL.
2229
 * @param string $method
2230
 *   The HTTP method to use, valid values are "GET" or "POST";
2231
 * @param bool $absoluteURI
2232
 *   TRUE when the URL should be treated as absolute URL.
2233
 *
2234
 * @return object| array
2235
 *   The de-serialized webservice response object.
2236
 */
2237
function cdm_ws_get($uri, $pathParameters = array(), $query_string = NULL, $method = "GET", $absoluteURI = FALSE) {
2238

    
2239
  static $cacheL1 = array();
2240

    
2241
  $data = NULL;
2242
  // store query_string string in $data and clear the query_string, $data will be set as HTTP request body
2243
  if($method == 'POST'){
2244
    $data = $query_string;
2245
    $query_string = NULL;
2246
  }
2247

    
2248
  // Transform the given uri path or pattern into a proper webservice uri.
2249
  if (!$absoluteURI) {
2250
    $uri = cdm_compose_ws_url($uri, $pathParameters, $query_string);
2251
  } else {
2252
    if($query_string){
2253
      $uri = append_query_parameters($uri, $query_string);
2254
    }
2255
  }
2256
  cdm_ws_apply_classification_subtree_filter($uri);
2257

    
2258
  // read request parameter 'cacheL2_refresh'
2259
  // which allows refreshing the level 2 cache
2260
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
2261

    
2262
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
2263
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
2264

    
2265
  if($method == 'GET'){
2266
    $cache_key = $uri;
2267
  } else {
2268
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
2269
    // crc32 is faster but creates much shorter hashes
2270
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
2271
  }
2272

    
2273
  if (array_key_exists($cache_key, $cacheL1)) {
2274
    $cacheL1_obj = $cacheL1[$uri];
2275
  }
2276

    
2277
  $set_cacheL1 = FALSE;
2278
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
2279
    $set_cacheL1 = TRUE;
2280
  }
2281

    
2282
  // Only cache cdm webservice URIs.
2283
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
2284
  $cacheL2_entry = FALSE;
2285

    
2286
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
2287
    // Try to get object from cacheL2.
2288
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
2289
  }
2290

    
2291
  if (isset($cacheL1_obj)) {
2292
    //
2293
    // The object has been found in the L1 cache.
2294
    //
2295
    $obj = $cacheL1_obj;
2296
    if (cdm_debug_block_visible()) {
2297
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
2298
    }
2299
  }
2300
  elseif ($cacheL2_entry) {
2301
    //
2302
    // The object has been found in the L2 cache.
2303
    //
2304
    $duration_parse_start = microtime(TRUE);
2305
    $obj = unserialize($cacheL2_entry->data);
2306
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2307

    
2308
    if (cdm_debug_block_visible()) {
2309
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
2310
    }
2311
  }
2312
  else {
2313
    //
2314
    // Get the object from the webservice and cache it.
2315
    //
2316
    $duration_fetch_start = microtime(TRUE);
2317
    // Request data from webservice JSON or XML.
2318
    $response = cdm_http_request($uri, $method, $data);
2319
    $response_body = NULL;
2320
    if (isset($response->data)) {
2321
      $response_body = $response->data;
2322
    }
2323
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2324
    $duration_parse_start = microtime(TRUE);
2325

    
2326
    // Parse data and create object.
2327
    $obj = cdm_load_obj($response_body);
2328

    
2329
    if(isset($obj->servlet) && isset($obj->status) && is_numeric($obj->status)){
2330
      // this is json error message returned by jetty #8914
2331
      // wee need to replace it by null to avoid breaking existing assumptions in the code here
2332
      // this is also related to #2711
2333
      $obj = null;
2334
    }
2335

    
2336
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2337

    
2338
    if (cdm_debug_block_visible()) {
2339
      if ($obj || $response_body == "[]") {
2340
        $status = 'valid';
2341
      }
2342
      else {
2343
        $status = 'invalid';
2344
      }
2345
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2346
    }
2347
    if ($set_cacheL2) {
2348
      // Store the object in cache L2.
2349
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2350
      // flag serialized is set properly in the cache table.
2351
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2352
    }
2353
  }
2354
  if ($obj) {
2355
    // Store the object in cache L1.
2356
    if ($set_cacheL1) {
2357
      $cacheL1[$cache_key] = $obj;
2358
    }
2359
  }
2360
  return $obj;
2361
}
2362

    
2363
function cdm_ws_apply_classification_subtree_filter(&$uri){
2364

    
2365
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
2366
    "#/classification/[0-9a-f\-]{36}/childNodes#",
2367
    /* covered by above pattern:
2368
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2369
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2370
    */
2371
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
2372
    /* covered by above pattern:
2373
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2374
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2375
    */
2376
    '#/portal/classification/[0-9a-f\-]{36}/pathFrom/[0-9a-f\-]{36}#',
2377
    "#/portal/taxon/search#",
2378
    "#/portal/taxon/find#",
2379
    /* covered by above pattern:
2380
    "#/portal/taxon/findByDescriptionElementFullText#",
2381
    "#/portal/taxon/findByFullText#",
2382
    "#/portal/taxon/findByEverythingFullText#",
2383
    "#/portal/taxon/findByIdentifier#",
2384
    "#/portal/taxon/findByMarker#",
2385
    "#/portal/taxon/findByMarker#",
2386
    "#/portal/taxon/findByMarker#",
2387
    */
2388
    "#/portal/taxon/[0-9a-f\-]{36}#"
2389
    /* covered by above pattern:
2390
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
2391
    */
2392
  ));
2393

    
2394
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
2395
  if(is_uuid($sub_tree_filter_uuid_value)){
2396
    foreach($classification_subtree_filter_patterns as $preg_pattern){
2397
      if(preg_match($preg_pattern, $uri)){
2398
        // no need to take care for uri fragments with ws uris!
2399
        if(strpos( $uri, '?')){
2400
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
2401
        } else {
2402
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
2403
        }
2404
        break;
2405
      }
2406
    }
2407
  }
2408

    
2409
}
2410
/**
2411
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2412
 *
2413
 * The cdm_ws_debug block will display the debug information.
2414
 *
2415
 * @param $uri
2416
 *    The CDM REST URI to which the request has been send
2417
 * @param string $method
2418
 *    The HTTP request method, either 'GET' or 'POST'
2419
 * @param string $post_data
2420
 *    The datastring send with a post request
2421
 * @param $duration_fetch
2422
 *    The time in seconds it took to fetch the data from the web service
2423
 * @param $duration_parse
2424
 *    Time in seconds which was needed to parse the json response
2425
 * @param $datasize
2426
 *    Size of the data received from the server
2427
 * @param $status
2428
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2429
 * @return bool
2430
 *    TRUE if adding the debug information was successful
2431
 */
2432
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2433

    
2434
  static $initial_time = NULL;
2435
  if(!$initial_time) {
2436
    $initial_time = microtime(TRUE);
2437
  }
2438
  $time = microtime(TRUE) - $initial_time;
2439

    
2440
  // Decompose uri into path and query element.
2441
  $uri_parts = explode("?", $uri);
2442
  $query = array();
2443
  if (count($uri_parts) == 2) {
2444
    $path = $uri_parts[0];
2445
  }
2446
  else {
2447
    $path = $uri;
2448
  }
2449

    
2450
  if(strpos($uri, '?') > 0){
2451
    $json_uri = str_replace('?', '.json?', $uri);
2452
    $xml_uri = str_replace('?', '.xml?', $uri);
2453
  } else {
2454
    $json_uri = $uri . '.json';
2455
    $xml_uri = $json_uri . '.xml';
2456
  }
2457

    
2458
  // data links to make data accessible as json and xml
2459
  $data_links = '';
2460
  if (_is_cdm_ws_uri($path)) {
2461

    
2462
    // see ./js/http-method-link.js
2463

    
2464
    if($method == 'GET'){
2465
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2466
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2467
      $data_links .= '<br/>';
2468
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2469
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2470
    } else {
2471
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2472
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2473
      $data_links .= '<br/>';
2474
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2475
    }
2476
  }
2477
  else {
2478
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2479
  }
2480

    
2481
  //
2482
  $data = array(
2483
      'ws_uri' => $uri,
2484
      'method' => $method,
2485
      'post_data' => $post_data,
2486
      'time' => sprintf('%3.3f', $time),
2487
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2488
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2489
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2490
      'status' => $status,
2491
      'data_links' => $data_links
2492
  );
2493
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2494
    $_SESSION['cdm']['ws_debug'] = array();
2495
  }
2496
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2497

    
2498
  // Mark this page as being uncacheable.
2499
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2500
  drupal_page_is_cacheable(FALSE);
2501

    
2502
  // Messages not set when DB connection fails.
2503
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2504
}
2505

    
2506
/**
2507
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2508
 * the visibility depends on whether
2509
 *  - the block is enabled
2510
 *  - the visibility restrictions in the block settings are satisfied
2511
 */
2512
function cdm_debug_block_visible() {
2513
  static $is_visible = null;
2514

    
2515
  if($is_visible === null){
2516
      $block = block_load('cdm_api', 'cdm_ws_debug');
2517
      $is_visible = isset($block->status) && $block->status == 1;
2518
      if($is_visible){
2519
        $blocks = array($block);
2520
        // Checks the page, user role, and user-specific visibilty settings.
2521
        block_block_list_alter($blocks);
2522
        $is_visible = count($blocks) > 0;
2523
      }
2524
  }
2525
  return $is_visible;
2526
}
2527

    
2528
/**
2529
 * @todo Please document this function.
2530
 * @see http://drupal.org/node/1354
2531
 */
2532
function cdm_load_obj($response_body) {
2533
  $obj = json_decode($response_body);
2534

    
2535
  if (!(is_object($obj) || is_array($obj))) {
2536
    ob_start();
2537
    $obj_dump = ob_get_contents();
2538
    ob_clean();
2539
    return FALSE;
2540
  }
2541

    
2542
  return $obj;
2543
}
2544

    
2545
/**
2546
 * Do a http request to a CDM RESTful web service.
2547
 *
2548
 * @param string $uri
2549
 *   The webservice url.
2550
 * @param string $method
2551
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2552
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2553
 * @param $data: A string containing the request body, formatted as
2554
 *     'param=value&param=value&...'. Defaults to NULL.
2555
 *
2556
 * @return object
2557
 *   The object as returned by drupal_http_request():
2558
 *   An object that can have one or more of the following components:
2559
 *   - request: A string containing the request body that was sent.
2560
 *   - code: An integer containing the response status code, or the error code
2561
 *     if an error occurred.
2562
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2563
 *   - status_message: The status message from the response, if a response was
2564
 *     received.
2565
 *   - redirect_code: If redirected, an integer containing the initial response
2566
 *     status code.
2567
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2568
 *     target.
2569
 *   - error: If an error occurred, the error message. Otherwise not set.
2570
 *   - headers: An array containing the response headers as name/value pairs.
2571
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2572
 *     easy access the array keys are returned in lower case.
2573
 *   - data: A string containing the response body that was received.
2574
 */
2575
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2576
  static $acceptLanguage = NULL;
2577
  $header = array();
2578
  
2579
  if(!$acceptLanguage && module_exists('i18n')){
2580
    $acceptLanguage = i18n_language_content()->language;
2581
  }
2582

    
2583
  if (!$acceptLanguage) {
2584
    if (function_exists('apache_request_headers')) {
2585
      $headers = apache_request_headers();
2586
      if (isset($headers['Accept-Language'])) {
2587
        $acceptLanguage = $headers['Accept-Language'];
2588
      }
2589
    }
2590
  }
2591

    
2592
  if ($method != "GET" && $method != "POST") {
2593
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2594
  }
2595

    
2596
  if (_is_cdm_ws_uri($uri)) {
2597
    $header['Accept'] = 'application/json';
2598
    $header['Accept-Language'] = $acceptLanguage;
2599
    $header['Accept-Charset'] = 'UTF-8';
2600
  }
2601

    
2602
  if($method == "POST") {
2603
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2604
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2605
  }
2606

    
2607
  $context_resource = null;
2608
  if(!variable_get('cdm_webservice_url_ssl_verify', 1)){
2609
    $context_resource = stream_context_create(array('ssl' => array('verify_peer' => FALSE, 'verify_peer_name' => FALSE)));
2610
  }
2611
  cdm_dd($uri);
2612
  return drupal_http_request($uri, array(
2613
      'headers' => $header,
2614
      'method' => $method,
2615
      'data' => $data,
2616
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT,
2617
      'context' => $context_resource
2618
      )
2619
   );
2620
}
2621

    
2622
/**
2623
 * Concatenates recursively the fields of all features contained in the given
2624
 * CDM FeatureTree root node.
2625
 *
2626
 * @param $rootNode
2627
 *     A CDM FeatureTree node
2628
 * @param
2629
 *     The character to be used as glue for concatenation, default is ', '
2630
 * @param $field_name
2631
 *     The field name of the CDM Features
2632
 * @param $excludes
2633
 *     Allows defining a set of values to be excluded. This refers to the values
2634
 *     in the field denoted by the $field_name parameter
2635
 *
2636
 */
2637
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2638
  $out = '';
2639

    
2640
  $pre_child_separator = $separator;
2641
  $post_child_separator = '';
2642

    
2643
  foreach ($root_node->childNodes as $feature_node) {
2644
    $out .= ($out ? $separator : '');
2645
    if(!in_array($feature_node->term->$field_name, $excludes)) {
2646
      $out .= $feature_node->term->$field_name;
2647
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2648
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2649
        if (strlen($childlabels)) {
2650
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2651
        }
2652
      }
2653
    }
2654
  }
2655
  return $out;
2656
}
2657

    
2658
/**
2659
 * Create a one-dimensional form options array.
2660
 *
2661
 * Creates an array of all features in the feature tree of feature nodes,
2662
 * the node labels are indented by $node_char and $childIndent depending on the
2663
 * hierachy level.
2664
 *
2665
 * @param - $rootNode
2666
 * @param - $node_char
2667
 * @param - $childIndentStr
2668
 * @param - $childIndent
2669
 *   ONLY USED INTERNALLY!
2670
 *
2671
 * @return array
2672
 *   A one dimensional Drupal form options array.
2673
 */
2674
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2675
  $options = array();
2676
  foreach ($rootNode->childNodes as $featureNode) {
2677
    $indent_prefix = '';
2678
    if ($childIndent) {
2679
      $indent_prefix = $childIndent . $node_char . " ";
2680
    }
2681
    $options[$featureNode->term->uuid] = $indent_prefix . $featureNode->term->representation_L10n;
2682
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2683
      // Foreach ($featureNode->childNodes as $childNode){
2684
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2685
      $options = array_merge_recursive($options, $childList);
2686
      // }
2687
    }
2688
  }
2689
  return $options;
2690
}
2691

    
2692
/**
2693
 * Returns an array with all available FeatureTrees and the representations of the selected
2694
 * FeatureTree as a detail view.
2695
 *
2696
 * @param boolean $add_default_feature_free
2697
 * @param boolean $show_weight
2698
 *     Show the weight which will be applied to the according feature block
2699
 * @return array
2700
 *  associative array with following keys:
2701
 *  -options: Returns an array with all available Feature Trees
2702
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2703
 *
2704
 */
2705
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE, $show_weight = FALSE) {
2706

    
2707
  $options = array();
2708
  $tree_representations = array();
2709
  $feature_trees = array();
2710

    
2711
  // Set tree that contains all features.
2712
  if ($add_default_feature_free) {
2713
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2714
    $feature_trees[] = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
2715
  }
2716

    
2717
  // Get feature trees from database.
2718
  $persisted_trees = cdm_ws_fetch_all(CDM_WS_TERMTREES, array("termType" => "Feature"));
2719
  if (is_array($persisted_trees)) {
2720
    $feature_trees = array_merge($feature_trees, $persisted_trees);
2721
  }
2722

    
2723
  foreach ($feature_trees as $featureTree) {
2724

    
2725
    if(!is_object($featureTree)){
2726
      continue;
2727
    }
2728
    // Do not add the DEFAULT_FEATURETREE again,
2729
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2730
      $options[$featureTree->uuid] = $featureTree->representation_L10n;
2731
    }
2732

    
2733
    // Render the hierarchic tree structure
2734
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2735

    
2736
      // Render the hierarchic tree structure.
2737
      $treeDetails = '<div class="featuretree_structure">'
2738
        . render_feature_tree_hierarchy($featureTree->uuid, $show_weight)
2739
        . '</div>';
2740

    
2741
      $form = array();
2742
      $form['featureTree-' .  $featureTree->uuid] = array(
2743
        '#type' => 'fieldset',
2744
        '#title' => 'Show details',
2745
        '#attributes' => array('class' => array('collapsible collapsed')),
2746
        // '#collapsible' => TRUE,
2747
        // '#collapsed' => TRUE,
2748
      );
2749
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2750
        '#markup' => $treeDetails,
2751
      );
2752

    
2753
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2754
    }
2755

    
2756
  } // END loop over feature trees
2757

    
2758
  // return $options;
2759
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2760
}
2761
/*
2762
 **
2763
 * Returns an array with all available FeatureTrees and the representations of the selected
2764
 * FeatureTree as a detail view.
2765
 *
2766
 * @param boolean $add_default_feature_free
2767
 * @param boolean $show_weight
2768
 *     Show the weight which will be applied to the according feature block
2769
 * @return array
2770
 *  associative array with following keys:
2771
 *  -options: Returns an array with all available Feature Trees
2772
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2773
 *
2774
 */
2775
function cdm_get_statusTrees_as_options($add_default_feature_free = TRUE) {
2776

    
2777
    $options = array();
2778
    $tree_representations = array();
2779
    $status_trees = array();
2780

    
2781
    // Set tree that contains all features.
2782
    //if ($add_default_feature_free) {
2783
    //    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2784
    //    $feature_trees[] = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
2785
    //}
2786

    
2787
    // Get feature trees from database.
2788
    $persisted_trees = cdm_ws_fetch_all(CDM_WS_TERMTREES, array("termType" => "PresenceAbsenceTerm"));
2789
    if (is_array($persisted_trees)) {
2790
        $status_trees = array_merge($status_trees, $persisted_trees);
2791
    }
2792

    
2793

    
2794
    foreach ($status_trees as $status_tree) {
2795

    
2796
        if(!is_object($status_tree)){
2797
            continue;
2798
        }
2799
        //if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2800
        $options[$status_tree->uuid] = $status_tree->representation_L10n;
2801
        //}
2802
        // Render the hierarchic tree structure
2803
        if (is_array( $status_tree->root->childNodes) && count( $status_tree->root->childNodes) > 0) {
2804

    
2805
            // Render the hierarchic tree structure.
2806
            $treeDetails = '<div class="featuretree_structure">'
2807
                . render_feature_tree_hierarchy($status_tree->uuid, false)
2808
                . '</div>';
2809

    
2810
            $form = array();
2811
            $form['statusTree-' .  $status_tree->uuid] = array(
2812
                '#type' => 'fieldset',
2813
                '#title' => 'Show details',
2814
                '#attributes' => array('class' => array('collapsible collapsed')),
2815
                // '#collapsible' => TRUE,
2816
                // '#collapsed' => TRUE,
2817
            );
2818
            $form['statusTree-' .  $status_tree->uuid]['details'] = array(
2819
                '#markup' => $treeDetails,
2820
            );
2821

    
2822
            $tree_representations[$status_tree->uuid] = drupal_render($form);
2823
        }
2824

    
2825
    } // END loop over feature trees
2826

    
2827
    // return $options;
2828
    return array('options' => $options, 'treeRepresentations' => $tree_representations);
2829
}
2830

    
2831
/*
2832
 **
2833
 * Returns an array with all available FeatureTrees and the representations of the selected
2834
 * FeatureTree as a detail view.
2835
 *
2836
 * @param boolean $add_default_feature_free
2837
 * @param boolean $show_weight
2838
 *     Show the weight which will be applied to the according feature block
2839
 * @return array
2840
 *  associative array with following keys:
2841
 *  -options: Returns an array with all available Feature Trees
2842
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2843
 *
2844
 */
2845
function cdm_get_areaTrees_as_options($add_default_feature_free = TRUE) {
2846

    
2847
    $options = array();
2848
    $tree_representations = array();
2849
    $area_trees = array();
2850

    
2851
    // Set tree that contains all features.
2852
    //if ($add_default_feature_free) {
2853
    //    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2854
    //    $feature_trees[] = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
2855
    //}
2856

    
2857
    // Get feature trees from database.
2858
    $persisted_trees = cdm_ws_fetch_all(CDM_WS_TERMTREES, array("termType" => "NamedArea"));
2859
    if (is_array($persisted_trees)) {
2860
        $area_trees = array_merge($area_trees, $persisted_trees);
2861
    }
2862

    
2863

    
2864
    foreach ($area_trees as $areaTree) {
2865

    
2866
        if(!is_object($areaTree)){
2867
            continue;
2868
        }
2869
        //if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2870
            $options[$areaTree->uuid] = $areaTree->representation_L10n;
2871
        //}
2872
        // Render the hierarchic tree structure
2873
        if (is_array( $areaTree->root->childNodes) && count( $areaTree->root->childNodes) > 0) {
2874

    
2875
            // Render the hierarchic tree structure.
2876
            $treeDetails = '<div class="featuretree_structure">'
2877
                . render_feature_tree_hierarchy($areaTree->uuid, false)
2878
                . '</div>';
2879

    
2880
            $form = array();
2881
            $form['areaTree-' .  $areaTree->uuid] = array(
2882
                '#type' => 'fieldset',
2883
                '#title' => 'Show details',
2884
                '#attributes' => array('class' => array('collapsible collapsed')),
2885
                // '#collapsible' => TRUE,
2886
                // '#collapsed' => TRUE,
2887
            );
2888
            $form['areaTree-' .  $areaTree->uuid]['details'] = array(
2889
                '#markup' => $treeDetails,
2890
            );
2891

    
2892
            $tree_representations[$areaTree->uuid] = drupal_render($form);
2893
        }
2894

    
2895
    } // END loop over feature trees
2896

    
2897
    // return $options;
2898
    return array('options' => $options, 'treeRepresentations' => $tree_representations);
2899
}
2900

    
2901
/**
2902
 * Provides the list of available classifications in form of an options array.
2903
 *
2904
 * The options array is suitable for drupal form API elements that allow multiple choices.
2905
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2906
 *
2907
 * The classifications are ordered alphabetically whereas the classification
2908
 * chosen as default will always appear on top of the array, followed by a
2909
 * blank line below.
2910
 *
2911
 * @param bool $add_none_option
2912
 *   is true an additional 'none' option will be added if and only if there are
2913
 *   more than one options. Defaults to FALSE
2914
 *
2915
 * @param $include_uuids
2916
 *   The taxon tree uuids to be included, other taxon trees will be filtered out.
2917
 *   You may want to use here:
2918
 *   variable_get(CDM_TAXONTREE_INCLUDES, [])
2919
 *
2920
 *
2921
 * @return array
2922
 *   classifications in an array as options for a form element that allows multiple choices.
2923
 */
2924
function cdm_get_taxontrees_as_options($add_none_option = FALSE, $include_uuids = []) {
2925

    
2926
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2927

    
2928
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2929
  $default_classification_label = '';
2930

    
2931
  // add all classifications
2932
  $taxonomic_tree_options = array();
2933
  if ($add_none_option) {
2934
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2935
  }
2936
  if ($taxonTrees) {
2937
    foreach ($taxonTrees as $tree) {
2938
      if(is_array($include_uuids) && count($include_uuids) > 0 && array_search($tree->uuid, $include_uuids) === FALSE){
2939
        continue;
2940
      }
2941
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2942
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2943
      } else {
2944
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2945
        $default_classification_label = $tree->titleCache;
2946
      }
2947
    }
2948
  }
2949
  // oder alphabetically the space
2950
  asort($taxonomic_tree_options);
2951

    
2952
  // now set the labels for none
2953
  if ($add_none_option && count($taxonomic_tree_options) > 2) {
2954
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2955
  } else {
2956
    unset($taxonomic_tree_options['NONE']);
2957
  }
2958

    
2959
  //   for default_classification
2960
  if (is_uuid($default_classification_uuid)) {
2961
    $taxonomic_tree_options[$default_classification_uuid] =
2962
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2963
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2964
  }
2965

    
2966
  return $taxonomic_tree_options;
2967
}
2968

    
2969
/**
2970
 * @todo Please document this function.
2971
 * @see http://drupal.org/node/1354
2972
 */
2973
function cdm_api_secref_cache_prefetch(&$secUuids) {
2974
  // Comment @WA: global variables should start with a single underscore
2975
  // followed by the module and another underscore.
2976
  global $_cdm_api_secref_cache;
2977
  if (!is_array($_cdm_api_secref_cache)) {
2978
    $_cdm_api_secref_cache = array();
2979
  }
2980
  $uniqueUuids = array_unique($secUuids);
2981
  $i = 0;
2982
  $param = '';
2983
  while ($i++ < count($uniqueUuids)) {
2984
    $param .= $secUuids[$i] . ',';
2985
    if (strlen($param) + 37 > 2000) {
2986
      _cdm_api_secref_cache_add($param);
2987
      $param = '';
2988
    }
2989
  }
2990
  if ($param) {
2991
    _cdm_api_secref_cache_add($param);
2992
  }
2993
}
2994

    
2995
/**
2996
 * @todo Please document this function.
2997
 * @see http://drupal.org/node/1354
2998
 */
2999
function cdm_api_secref_cache_get($secUuid) {
3000
  global $_cdm_api_secref_cache;
3001
  if (!is_array($_cdm_api_secref_cache)) {
3002
    $_cdm_api_secref_cache = array();
3003
  }
3004
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
3005
    _cdm_api_secref_cache_add($secUuid);
3006
  }
3007
  return $_cdm_api_secref_cache[$secUuid];
3008
}
3009

    
3010
/**
3011
 * @todo Please document this function.
3012
 * @see http://drupal.org/node/1354
3013
 */
3014
function cdm_api_secref_cache_clear() {
3015
  global $_cdm_api_secref_cache;
3016
  $_cdm_api_secref_cache = array();
3017
}
3018

    
3019

    
3020
/**
3021
 * @todo Please document this function.
3022
 * @see http://drupal.org/node/1354
3023
 */
3024
function _cdm_api_secref_cache_add($secUuidsStr) {
3025
  global $_cdm_api_secref_cache;
3026
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
3027
  // Batch fetching not jet reimplemented thus:
3028
  /*
3029
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
3030
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
3031
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
3032
  */
3033
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
3034
}
3035

    
3036
/**
3037
 * Checks if the given uri starts with a cdm webservice url.
3038
 *
3039
 * Checks if the uri starts with the cdm webservice url stored in the
3040
 * Drupal variable 'cdm_webservice_url'.
3041
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
3042
 *
3043
 * @param string $uri
3044
 *   The URI to test.
3045
 *
3046
 * @return bool
3047
 *   True if the uri starts with a cdm webservice url.
3048
 */
3049
function _is_cdm_ws_uri($uri) {
3050
  return str_beginsWith($uri, cdm_webservice_url('#EMPTY#'));
3051
}
3052

    
3053
/**
3054
 * @todo Please document this function.
3055
 * @see http://drupal.org/node/1354
3056
 */
3057
function queryString($elements) {
3058
  $query = '';
3059
  foreach ($elements as $key => $value) {
3060
    if (is_array($value) && !empty($value)) {
3061
      foreach ($value as $v) {
3062
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
3063
      }
3064
    }
3065
    else {
3066
        //if (is_numeric($value) || !empty($value)){
3067
            $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
3068
        //}
3069

    
3070
    }
3071
  }
3072
  return $query;
3073
}
3074

    
3075
/**
3076
 * Compares the given CDM Term instances by the  representationL10n.
3077
 *
3078
 * Can also be used with TermDTOs. To be used in usort()
3079
 *
3080
 * @see http://php.net/manual/en/function.usort.php
3081
 *
3082
 * @param $term1
3083
 *   The first CDM Term instance
3084
 * @param $term2
3085
 *   The second CDM Term instance
3086
 * @return int
3087
 *   The result of the comparison
3088
 */
3089
function compare_terms_by_representationL10n($term1, $term2) {
3090

    
3091
  if (!isset($term1->representation_L10n)) {
3092
    $term1->representationL10n = '';
3093
  }
3094
  if (!isset($term2->representation_L10n)) {
3095
    $term2->representationL10n = '';
3096
  }
3097

    
3098
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
3099
}
3100

    
3101
function compare_terms_by_order_index($term1, $term2) {
3102

    
3103

    
3104
  if (!isset($term1->orderIndex)) {
3105
    $a = 0;
3106
  } else {
3107
    $a = $term1->orderIndex;
3108
  }
3109
  if (!isset($term2->orderIndex)) {
3110
    $b = 0;
3111
  } else {
3112
    $b = $term2->orderIndex;
3113
  }
3114

    
3115
  if ($a == $b) {
3116
    return 0;
3117
  }
3118
  return ($a < $b) ? -1 : 1;
3119

    
3120
}
3121

    
3122

    
3123
/**
3124
 * Make a 'deep copy' of an array.
3125
 *
3126
 * Make a complete deep copy of an array replacing
3127
 * references with deep copies until a certain depth is reached
3128
 * ($maxdepth) whereupon references are copied as-is...
3129
 *
3130
 * @see http://us3.php.net/manual/en/ref.array.php
3131
 *
3132
 * @param array $array
3133
 * @param array $copy passed by reference
3134
 * @param int $maxdepth
3135
 * @param int $depth
3136
 */
3137
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
3138
  if ($depth > $maxdepth) {
3139
    $copy = $array;
3140
    return;
3141
  }
3142
  if (!is_array($copy)) {
3143
    $copy = array();
3144
  }
3145
  foreach ($array as $k => &$v) {
3146
    if (is_array($v)) {
3147
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
3148
    }
3149
    else {
3150
      $copy[$k] = $v;
3151
    }
3152
  }
3153
}
3154

    
3155
/**
3156
 * Concatenated the uuids of the passed cdm entity with `,` as glue.
3157
 * The returned string is suitable for cdm webservices consuming UUIDList as
3158
 * parameter
3159
 *
3160
 * @param array $cdm_entities
3161
 *
3162
 * @return string
3163
 */
3164
function cdm_uuid_list_parameter_value(array $cdm_entities){
3165
  $uuids = [];
3166
  foreach ($cdm_entities as $entity){
3167
    if(isset($entity) && is_uuid($entity->uuid) ){
3168
      $uuids[] = $entity->uuid;
3169
    }
3170
  }
3171
  return  join(',', $uuids);
3172
}
3173

    
3174
/**
3175
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
3176
 *
3177
 */
3178
function _add_js_ws_debug() {
3179

    
3180
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
3181
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
3182
  if (variable_get('cdm_js_devel_mode', FALSE)) {
3183
    // use the developer versions of js libs
3184
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
3185
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
3186
  }
3187
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
3188
    array(
3189
      'type' => 'file',
3190
      'weight' => JS_LIBRARY,
3191
      'cache' => TRUE)
3192
    );
3193

    
3194
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
3195
    array(
3196
      'type' => 'file',
3197
      'weight' => JS_LIBRARY,
3198
      'cache' => TRUE)
3199
    );
3200
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
3201
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
3202

    
3203
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
3204
    array(
3205
      'type' => 'file',
3206
      'weight' => JS_LIBRARY,
3207
      'cache' => TRUE)
3208
    );
3209
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
3210
    array(
3211
    'type' => 'file',
3212
    'weight' => JS_LIBRARY,
3213
    'cache' => TRUE)
3214
    );
3215

    
3216
}
3217

    
3218
/**
3219
 * @todo Please document this function.
3220
 * @see http://drupal.org/node/1354
3221
 */
3222
function _no_classfication_uuid_message() {
3223
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
3224
    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.');
3225
  }
3226
  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.');
3227
}
3228

    
3229
/**
3230
 * Implementation of hook flush_caches
3231
 *
3232
 * Add custom cache tables to the list of cache tables that
3233
 * will be cleared by the Clear button on the Performance page or whenever
3234
 * drupal_flush_all_caches is invoked.
3235
 *
3236
 * @author W.Addink <waddink@eti.uva.nl>
3237
 *
3238
 * @return array
3239
 *   An array with custom cache tables to include.
3240
 */
3241
function cdm_api_flush_caches() {
3242
  return array('cache_cdm_ws');
3243
}
3244

    
3245
/**
3246
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
3247
 *
3248
 * @param $data
3249
 *   The variable to log to the drupal_debug.txt log file.
3250
 * @param $label
3251
 *   (optional) If set, a label to output before $data in the log file.
3252
 *
3253
 * @return
3254
 *   No return value if successful, FALSE if the log file could not be written
3255
 *   to.
3256
 *
3257
 * @see cdm_dataportal_init() where the log file is reset on each requests
3258
 * @see dd()
3259
 * @see http://drupal.org/node/314112
3260
 *
3261
 */
3262
function cdm_dd($data, $label = NULL) {
3263
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
3264
    return dd($data, $label);
3265
  }
3266
}
3267

    
(5-5/12)