Project

General

Profile

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

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

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

    
41

    
42

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

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

    
77

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

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

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

    
101
  return $items;
102
}
103

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

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

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

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

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

    
135

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

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

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

    
146
      $data = unserialize($data);
147

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

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

    
163
    _add_js_ws_debug();
164

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

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

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

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

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

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

    
232
  return $profile_featureTree;
233
}
234

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

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

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

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

    
290

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

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

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

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

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

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

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

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

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

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

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

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

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

    
533
  $y = NULL; $m = NULL; $d = NULL;
534

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

    
545
  $y = $y ? $y : '0000';
546
  $m = $m ? $m : '00';
547
  $d = $d ? $d : '00';
548

    
549
  $date = '';
550

    
551
  if ($y == '0000' && $stripZeros && $m == '00' && $d == '00') {
552
    return '';
553
  }
554
  else {
555
    $date = $y;
556
  }
557

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

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

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

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

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

    
655
  $uri = variable_get('cdm_webservice_url', '') . $path;
656
  return $uri;
657
}
658

    
659
/**
660
 * Composes a relative Url 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 relative URL with query parameters.
672
 */
673
function cdm_compose_url($uri_pattern, $pathParameters, $query = NULL) {
674

    
675
  // (1)
676
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
677
  // according element of the $pathParameters array.
678
  static $helperArray = [];
679
  if (isset($pathParameters) && !is_array($pathParameters)) {
680
    $helperArray[0] = $pathParameters;
681
    $pathParameters = $helperArray;
682
  }
683

    
684
  $i = 0;
685
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
686
    if (count($pathParameters) <= $i) {
687
      drupal_set_message('cdm_compose_url(): missing pathParameter ' . $i .' for ' . $uri_pattern, 'error');
688
      break;
689
    }
690
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
691
    ++$i;
692
  }
693

    
694
  // (2)
695
  // Append all remaining element of the $pathParameters array as path
696
  // elements.
697
  if (count($pathParameters) > $i) {
698
    // Strip trailing slashes.
699
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
700
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
701
    }
702
    while (count($pathParameters) > $i) {
703
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
704
      ++$i;
705
    }
706
  }
707

    
708
  // (3)
709
  // Append the query string supplied by $query.
710
  $uri_pattern = append_query_parameters($uri_pattern, $query);
711

    
712
  $path = $uri_pattern;
713
  return $path;
714
}
715

    
716
/**
717
 * @param string $uri
718
 *
719
 * @param $query_string
720
 *
721
 * @return string
722
 */
723
function append_query_parameters($uri, $query_string) {
724

    
725
  if (isset($query_string)) {
726
    $uri .= (strpos($uri, '?') !== FALSE ? '&' : '?') . $query_string;
727
  }
728

    
729
  return $uri;
730
}
731

    
732
/**
733
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
734
 *     together with a theme name to such a proxy function?
735
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
736
 *     Maybe we want to have two different proxy functions, one with theming and one without?
737
 *
738
 * @param string $uri
739
 *     A URI to a CDM Rest service from which to retrieve an object
740
 * @param string|null $hook
741
 *     (optional) The hook name to which the retrieved object should be passed.
742
 *     Hooks can either be a theme_hook() or compose_hook() implementation
743
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
744
 *     suitable for drupal_render()
745
 *
746
 * @todo Please document this function.
747
 * @see http://drupal.org/node/1354
748
 */
749
function proxy_content($uri, $hook = NULL) {
750

    
751
  $args = func_get_args();
752
  $do_gzip = function_exists('gzencode');
753
  $uriEncoded = array_shift($args);
754
  $uri = urldecode($uriEncoded);
755
  $hook = array_shift($args);
756
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
757

    
758
  $post_data = null;
759

    
760
  if ($request_method == "POST" || $request_method == "PUT") {
761
    // read response body via inputstream module
762
    $post_data = file_get_contents("php://input");
763
  }
764

    
765
  // Find and deserialize arrays.
766
  foreach ($args as &$arg) {
767
    // FIXME use regex to find serialized arrays.
768
    //       or should we accept json instead of php serializations?
769
    if (strpos($arg, "a:") === 0) {
770
      $arg = unserialize($arg);
771
    }
772
  }
773

    
774
  // In all these cases perform a simple get request.
775
  // TODO reconsider caching logic in this function.
776

    
777
  if (empty($hook)) {
778
    // simply return the webservice response
779
    // Print out JSON, the cache cannot be used since it contains objects.
780
    $http_response = cdm_http_request($uri, $request_method, $post_data);
781
    if (isset($http_response->headers)) {
782
      foreach ($http_response->headers as $hname => $hvalue) {
783
        drupal_add_http_header($hname, $hvalue);
784
      }
785
    }
786
    if (isset($http_response->data)) {
787
      print $http_response->data;
788
      flush();
789
    }
790
    exit(); // leave drupal here
791
  } else {
792
    // $hook has been supplied
793
    // handle $hook either as compose or theme hook
794
    // pass through theme or compose hook
795
    // compose hooks can be called without data, therefore
796
    // passing the $uri in this case is not always a requirement
797

    
798
    if($uri && $uri != 'NULL') {
799
    // do a security check since the $uri will be passed
800
    // as absolute URI to cdm_ws_get()
801
      if (!_is_cdm_ws_uri($uri)) {
802
        drupal_set_message(
803
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
804
          'error'
805
        );
806
        return '';
807
      }
808

    
809
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
810
    } else {
811
      $obj = NULL;
812
    }
813

    
814
    $reponse_data = NULL;
815

    
816
    if (function_exists('compose_' . $hook)){
817
      // call compose hook
818

    
819
      $elements =  call_user_func('compose_' . $hook, $obj);
820
      // pass the render array to drupal_render()
821
      $reponse_data = drupal_render($elements);
822
    } else {
823
      // call theme hook
824

    
825
      // TODO use theme registry to get the registered hook info and
826
      //    use these defaults
827
      switch($hook) {
828
        case 'cdm_taxontree':
829
          $variables = array(
830
            'tree' => $obj,
831
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
832
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
833
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
834
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
835
            );
836
          $reponse_data = theme($hook, $variables);
837
          break;
838

    
839
        case 'cdm_list_of_taxa':
840
            $variables = array(
841
              'records' => $obj,
842
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
843
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
844
            $reponse_data = theme($hook, $variables);
845
            break;
846

    
847
        case 'cdm_media_caption':
848
          $variables = $arg;
849
          $variables['media'] = $obj;
850

    
851
          $reponse_data = theme($hook, $variables);
852
          break;
853

    
854
        default:
855
          drupal_set_message(t(
856
          'Theme !theme is not yet supported by the function !function.', array(
857
          '!theme' => $hook,
858
          '!function' => __FUNCTION__,
859
          )), 'error');
860
          break;
861
      } // END of theme hook switch
862
    } // END of tread as theme hook
863

    
864

    
865
    if($do_gzip){
866
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
867
      drupal_add_http_header('Content-Encoding', 'gzip');
868
    }
869
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
870
    drupal_add_http_header('Content-Length', strlen($reponse_data));
871

    
872
    print $reponse_data;
873
  } // END of handle $hook either as compose ot theme hook
874

    
875
}
876

    
877
/**
878
 * @todo Please document this function.
879
 * @see http://drupal.org/node/1354
880
 */
881
function setvalue_session() {
882
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
883
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
884
    $var_keys = explode('][', $var_keys);
885
  }
886
  else {
887
    return;
888
  }
889
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
890

    
891
  // Prevent from malicous tags.
892
  $val = strip_tags($val);
893

    
894
  $session_var = &$_SESSION;
895
  //$i = 0;
896
  foreach ($var_keys as $key) {
897
    // $hasMoreKeys = ++$i < count($session);
898
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
899
      $session_var[$key] = array();
900
    }
901
    $session_var = &$session_var[$key];
902
  }
903
  $session_var = $val;
904
  if (isset($_REQUEST['destination'])) {
905
    drupal_goto($_REQUEST['destination']);
906
  }
907
}
908

    
909
/**
910
 * @todo Please document this function.
911
 * @see http://drupal.org/node/1354
912
 */
913
function uri_uriByProxy($uri, $theme = FALSE) {
914
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
915
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
916
}
917

    
918
/**
919
 * Composes the the absolute REST service URI to the annotations pager
920
 * for the given CDM entity.
921
 *
922
 * NOTE: Not all CDM Base types are yet supported.
923
 *
924
 * @param $cdm_entity
925
 *   The CDM entity to construct the annotations pager uri for
926
 */
927
function cdm_compose_annotations_uri($cdm_entity) {
928

    
929
  $cdm_entity_type = $cdm_entity->class;
930

    
931
  if($cdm_entity_type == 'DerivedUnitFacade'){
932
    // TODO with the below code we may miss annotations.
933
    //  Better implement a derivedUnitFacade/{uuid}/annotations service and use that instead
934
    if(isset($cdm_entity->fieldUnitEntityReference)){
935
      $cdm_entity_type = $cdm_entity->fieldUnitEntityReference->type;
936
      $cdm_entity_uuid = $cdm_entity->fieldUnitEntityReference->uuid;
937
    } elseif(isset($cdm_entity->baseUnitEntityReference)){
938
      $cdm_entity_type = $cdm_entity->baseUnitEntityReference->type;
939
      $cdm_entity_uuid = $cdm_entity->baseUnitEntityReference->uuid;
940
    }
941
  } elseif ($cdm_entity_type == 'TypedEntityReference'){
942
    $cdm_entity_type = $cdm_entity->type;
943
    $cdm_entity_uuid = $cdm_entity->uuid;
944
  } else {
945
    if (isset($cdm_entity->uuid)) {
946
      $cdm_entity_uuid = $cdm_entity->uuid;
947
    }
948
  }
949

    
950
  if(!isset($cdm_entity_uuid) || !isset($cdm_entity_type) || !$cdm_entity_type ){
951
    // silently give up
952
    return;
953
  }
954

    
955
  $ws_base_uri = cdm_ws_base_uri($cdm_entity_type);
956

    
957
  if($ws_base_uri === null){
958
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdm_entity_type), E_USER_ERROR);
959
  }
960
  return cdm_compose_ws_url($ws_base_uri, array(
961
    $cdm_entity_uuid,
962
    'annotations',
963
  ));
964
}
965

    
966
/**
967
 * Provides the base URI of the cdm REST service responsible for the passed simple name
968
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
969
 *
970
 * @param $cdm_type_simple
971
 *    simple name of a CDM java class
972
 * @return null|string
973
 */
974
function cdm_ws_base_uri($cdm_type_simple)
975
{
976
  $ws_base_uri = NULL;
977
  switch ($cdm_type_simple) {
978

    
979
    case 'TaxonNode':
980
    case 'TaxonNodeDto':
981
      $ws_base_uri = CDM_WS_TAXONNODE;
982
    case 'TaxonBase':
983
    case 'Taxon':
984
    case 'Synonym':
985
      $ws_base_uri = CDM_WS_TAXON;
986
      break;
987

    
988
    case 'TaxonName':
989
      $ws_base_uri = CDM_WS_NAME;
990
      break;
991

    
992
    case 'Media':
993
      $ws_base_uri = CDM_WS_MEDIA;
994
      break;
995

    
996
    case 'Reference':
997
      $ws_base_uri = CDM_WS_REFERENCE;
998
      break;
999

    
1000
    case 'Registration':
1001
      $ws_base_uri = CDM_WS_REFERENCE;
1002
      break;
1003

    
1004
    case 'FieldUnit':
1005
    case 'DerivedUnit':
1006
    case 'DnaSample':
1007
    case 'MediaSpecimen':
1008
    case 'DerivedUnitDTO':
1009
    case 'FieldUnitDTO':
1010
    case 'DNASampleDTO':
1011
      $ws_base_uri = CDM_WS_OCCURRENCE;
1012
      break;
1013

    
1014
    case 'Amplification':
1015
    case 'DerivationEvent':
1016
    case 'DeterminationEvent':
1017
    case 'GatheringEvent':
1018
    case 'MaterialOrMethodEvent':
1019
    case 'SingleRead':
1020
      $ws_base_uri = CDM_WS_EVENTBASE;
1021
      break;
1022

    
1023
    case 'Distribution':
1024
    case 'TextData':
1025
    case 'TaxonInteraction':
1026
    case 'QuantitativeData':
1027
    case 'IndividualsAssociation':
1028
    case 'CommonTaxonName':
1029
    case 'CategoricalData':
1030
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1031
      break;
1032

    
1033
    case 'Person':
1034
    case 'Team':
1035
    case 'AgentBase':
1036
      $ws_base_uri = CDM_WS_AGENT;
1037
      break;
1038

    
1039
    case 'PolytomousKey':
1040
    case 'MediaKey':
1041
    case 'MultiAccessKey':
1042
      $ws_base_uri = $cdm_type_simple;
1043
      $ws_base_uri[0] = strtolower($ws_base_uri[0]);
1044
      break;
1045

    
1046
    case 'TextualTypeDesignation':
1047
    case 'SpecimenTypeDesignation':
1048
    case 'NameTypeDesignation':
1049
    case 'TypeDesignationDTO':
1050
      $ws_base_uri = CDM_WS_TYPEDESIGNATION;
1051
      break;
1052
    default:
1053
      $ws_base_uri = null;
1054
      drupal_set_message(
1055
        t('cdm_ws_base_uri()  - cdm type name "@cdm_type_simple" unsupported',
1056
          array('@cdm_type_simple' => $cdm_type_simple )),
1057
        'error');
1058
  }
1059
  return $ws_base_uri;
1060
}
1061

    
1062
/**
1063
 * Enter description here...
1064
 *
1065
 * @param string $resource_uri
1066
 * @param int $page_size
1067
 *   The maximum number of entities returned per page.
1068
 *   The default page size as configured in the cdm server
1069
 *   will be used if set to NULL
1070
 *   to return all entities in a single page).
1071
 * @param int $page_index
1072
 *   The number of the page to be returned, the first page has the
1073
 *   page_index = 0
1074
 * @param array $query
1075
 *   A array holding the HTTP request query parameters for the request
1076
 * @param string $method
1077
 *   The HTTP method to use, valid values are "GET" or "POST"
1078
 * @param bool $absolute_uri
1079
 *   TRUE when the URL should be treated as absolute URL.
1080
 *
1081
 * @return object
1082
 *   A CDM Pager object
1083
 *
1084
 */
1085
function cdm_ws_page($resource_uri, $page_size, $page_index, array $query = array(), $method = 'GET', $absolute_uri = FALSE) {
1086

    
1087
  $query['pageIndex'] = $page_index;
1088
  $query['pageSize'] = $page_size;
1089

    
1090
  $pager = cdm_ws_get($resource_uri, NULL, queryString($query), $method, $absolute_uri);
1091
  if(is_array($pager)){
1092
    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);
1093
    $records = $pager;
1094
    $pager = new stdClass();
1095
    $pager->records = $records;
1096
    $pager->count = count($records);
1097
    $pager->pageSize = $pager->count;
1098
    $pager->nextIndex = null;
1099
  }
1100
  return $pager;
1101
}
1102

    
1103

    
1104
/**
1105
 * Sends a http GET request to the generic page method which allows for filtering entities by Restrictions.
1106
 *
1107
 * @param $cdm_entity_type
1108
 * @param $class_restriction
1109
 *   Optional param to narrow down polymorph types to a specific type.
1110
 * @param array $restrictions
1111
 *   An array of Restriction objects
1112
 * @param array $init_strategy
1113
 *   The init strategy to initialize the entity beans while being loaded from the
1114
 *   persistent storage by the cdm
1115
 * @param int $page_size
1116
 *   The maximum number of entities returned per page.
1117
 *   The default page size as configured in the cdm server
1118
 *   will be used if set to NULL
1119
 *   to return all entities in a single page).
1120
 * @param int $page_index
1121
 *   The number of the page to be returned, the first page has the
1122
 *   pageNumber = 0
1123
 *
1124
 * @return object
1125
 *   A CDM Pager object
1126
 */
1127
function cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy, $page_size, $page_index) {
1128

    
1129
  $restrictions_json = array(); // json_encode($restrictions);
1130
  foreach ($restrictions as $restr){
1131
    $restrictions_json[] = json_encode($restr);
1132
  }
1133
  $filter_parameters = [
1134
    'restriction' => $restrictions_json,
1135
    'initStrategy' => $init_strategy
1136
  ];
1137
  if($class_restriction){
1138
    $filter_parameters['class'] = $class_restriction;
1139
  }
1140

    
1141
  return cdm_ws_page(
1142
      'portal/' . cdm_ws_base_uri($cdm_entity_type),
1143
      $page_size,
1144
      $page_index,
1145
    $filter_parameters,
1146
    "GET"
1147
    );
1148
}
1149

    
1150
/**
1151
 * Fetches all entities returned by the the generic page method for the Restrictions applied as filter.
1152
 *
1153
 * @param $cdm_entity_type
1154
 * @param $class_restriction
1155
 *   Optional param to narrow down polymorph types to a specific type.
1156
 * @param array $restrictions
1157
 *   An array of Restriction objects
1158
 * @param array $init_strategy
1159
 *   The init strategy to initialize the entity beans while being loaded from the
1160
 *   persistent storage by the cdm
1161
 *
1162
 * @return array
1163
 *   A array of CDM entities
1164
 */
1165
function cdm_ws_fetch_all_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy){
1166
  $page_index = 0;
1167
  // using a bigger page size to avoid to many multiple requests
1168
  $page_size = 500;
1169
  $entities = array();
1170

    
1171
  while ($page_index !== FALSE && $page_index < 1){
1172
    $pager =  cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, $restrictions, $init_strategy, $page_size, $page_index);
1173
    if(isset($pager->records) && is_array($pager->records)) {
1174
      $entities = array_merge($entities, $pager->records);
1175
      if(!empty($pager->nextIndex)){
1176
        $page_index = $pager->nextIndex;
1177
      } else {
1178
        $page_index = FALSE;
1179
      }
1180
    } else {
1181
      $page_index = FALSE;
1182
    }
1183
  }
1184
  return $entities;
1185
}
1186

    
1187

    
1188
  /**
1189
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1190
 *
1191
 * @param string $resourceURI
1192
 * @param array $query
1193
 *   A array holding the HTTP request query parameters for the request
1194
 * @param string $method
1195
 *   The HTTP method to use, valid values are "GET" or "POST";
1196
 * @param bool $absoluteURI
1197
 *   TRUE when the URL should be treated as absolute URL.
1198
 *
1199
 * @return array
1200
 *     A list of CDM entitites
1201
 *
1202
 */
1203
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1204
  $page_index = 0;
1205
  // using a bigger page size to avoid too many multiple requests
1206
  $page_size = 500;
1207
  $entities = [];
1208

    
1209
  while (true){
1210
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1211
    if(isset($pager->records) && is_array($pager->records)) {
1212
      $entities = array_merge($entities, $pager->records);
1213
      if(is_numeric($pager->nextIndex) && $page_index < $pager->nextIndex){
1214
        $page_index = $pager->nextIndex;
1215
      } else {
1216
        break;
1217
      }
1218
    } else {
1219
      break;
1220
    }
1221
  }
1222
  return $entities;
1223
}
1224

    
1225
/*
1226
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1227
  $viewrank = _cdm_taxonomy_compose_viewrank();
1228
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1229
  ? '/' . $path : '') ;
1230
}
1231
*/
1232

    
1233
/**
1234
 * @todo Enter description here...
1235
 *
1236
 * @param string $taxon_uuid
1237
 *  The UUID of a cdm taxon instance
1238
 * @param string $ignore_rank_limit
1239
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1240
 *
1241
 * @return string
1242
 *   A cdm REST service URL path to a Classification
1243
 */
1244
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1245

    
1246
  $view_uuid = get_current_classification_uuid();
1247
  $rank_uuid = NULL;
1248
  if (!$ignore_rank_limit) {
1249
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1250
  }
1251

    
1252
  if (!empty($taxon_uuid)) {
1253
    return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1254
      $view_uuid,
1255
      $taxon_uuid,
1256
    ));
1257
  }
1258
  else {
1259
    if (is_uuid($rank_uuid)) {
1260
      return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1261
        $view_uuid,
1262
        $rank_uuid,
1263
      ));
1264
    }
1265
    else {
1266
      return cdm_compose_ws_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1267
        $view_uuid,
1268
      ));
1269
    }
1270
  }
1271
}
1272

    
1273
/**
1274
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1275
 *
1276
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1277
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1278
 *
1279
 * Operates in two modes depending on whether the parameter
1280
 * $taxon_uuid is set or NULL.
1281
 *
1282
 * A) $taxon_uuid = NULL:
1283
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1284
 *  2. otherwise return the default classification as defined by the admin via the settings
1285
 *
1286
 * b) $taxon_uuid is set:
1287
 *   return the classification to whcih the taxon belongs to.
1288
 *
1289
 * @param UUID $taxon_uuid
1290
 *   The UUID of a cdm taxon instance
1291
 */
1292
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1293

    
1294
    $response = NULL;
1295

    
1296
    // 1st try
1297
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1298

    
1299
    if ($response == NULL) {
1300
      // 2dn try by ignoring the rank limit
1301
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1302
    }
1303

    
1304
    if ($response == NULL) {
1305
      // 3rd try, last fallback:
1306
      //    return the default classification
1307
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1308
        // Delete the session value and try again with the default.
1309
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1310
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1311
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1312
      }
1313
      else {
1314
        // Check if taxonomictree_uuid is valid.
1315
        // expecting an array of taxonNodes,
1316
        // empty classifications are ok so no warning in this case!
1317
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1318
        if (!is_array($test)) {
1319
          // The default set by the admin seems to be invalid or is not even set.
1320
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1321
        } else if (count($test) == 0) {
1322
          // The default set by the admin seems to be invalid or is not even set.
1323
          drupal_set_message("The chosen classification is empty.", 'status');
1324
        }
1325
      }
1326
    }
1327

    
1328
  return $response;
1329
}
1330

    
1331
/**
1332
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1333
 * 
1334
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1335
 * variable is set.
1336
 *
1337
 * @param string $taxon_uuid
1338
 *
1339
 * @return array
1340
 *   An array of CDM TaxonNodeDTO objects
1341
 */
1342
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1343
  $view_uuid = get_current_classification_uuid();
1344
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1345

    
1346
  $response = NULL;
1347
  if (is_uuid($rank_uuid)) {
1348
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1349
      $view_uuid,
1350
      $taxon_uuid,
1351
      $rank_uuid,
1352
    ));
1353
  }
1354
  else {
1355
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1356
      $view_uuid,
1357
      $taxon_uuid,
1358
    ));
1359
  }
1360

    
1361
  if ($response == NULL) {
1362
    // Error handing.
1363
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1364
//      // Delete the session value and try again with the default.
1365
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1366
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1367
//    }
1368
//    else {
1369
      // Check if taxonomictree_uuid is valid.
1370
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1371
      if ($test == NULL) {
1372
        // The default set by the admin seems to be invalid or is not even set.
1373
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1374
      }
1375
//    }
1376
  }
1377

    
1378
  return $response;
1379
}
1380

    
1381

    
1382
// =============================Terms and Vocabularies ========================================= //
1383

    
1384
/**
1385
 * Returns the localized representation for the given term.
1386
 *
1387
 * @param Object $definedTermBase
1388
 * 	  of cdm type DefinedTermBase
1389
 * @return string
1390
 * 	  the localized representation_L10n of the term,
1391
 *    otherwise the titleCache as fall back,
1392
 *    otherwise the default_representation which defaults to an empty string
1393
 */
1394
function cdm_term_representation($definedTermBase, $default_representation = '') {
1395
  if ( isset($definedTermBase->representation_L10n) ) {
1396
    return $definedTermBase->representation_L10n;
1397
  } elseif ( isset($definedTermBase->titleCache)) {
1398
    return $definedTermBase->titleCache;
1399
  }
1400
  return $default_representation;
1401
}
1402

    
1403
/**
1404
 * Returns the abbreviated localized representation for the given term.
1405
 *
1406
 * @param Object $definedTermBase
1407
 * 	  of cdm type DefinedTermBase
1408
 * @return string
1409
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1410
 *    if this representation is not available the function delegates the
1411
 *    call to cdm_term_representation()
1412
 */
1413
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1414
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1415
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1416
  } else {
1417
    cdm_term_representation($definedTermBase, $default_representation);
1418
  }
1419
}
1420

    
1421
/**
1422
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1423
 *
1424
 * The options array is suitable for drupal form API elements that allow multiple choices.
1425
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1426
 *
1427
 * @param array $terms
1428
 *   a list of CDM DefinedTermBase instances
1429
 *
1430
 * @param $term_label_callback
1431
 *   A callback function to override the term representations
1432
 *
1433
 * @param bool $empty_option
1434
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1435
 *
1436
 * @return array
1437
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1438

    
1439
 */
1440
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1441
  $options = array();
1442
  if(isset($terms) && is_array($terms)) {
1443
    foreach ($terms as $term) {
1444
      if ($term_label_callback && function_exists($term_label_callback)) {
1445
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1446
      } else {
1447
        //TODO use cdm_term_representation() here?
1448
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1449
      }
1450
    }
1451
  }
1452

    
1453
  if($empty_option !== FALSE){
1454
    array_unshift ($options, "");
1455
  }
1456

    
1457
  return $options;
1458
}
1459

    
1460
/**
1461
 * Creates and array of options for drupal select form elements.
1462
 *
1463
 * @param $vocabulary_uuid
1464
 *   The UUID of the CDM Term Vocabulary
1465
 * @param $term_label_callback
1466
 *   An optional call back function which can be used to modify the term label
1467
 * @param bool $empty_option
1468
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1469
 * @param array $include_filter
1470
 *   An associative array consisting of a field name an regular expression. All term matching
1471
 *   these filter are included. The value of the field is converted to a String by var_export()
1472
 *   so a boolean 'true' can be matched by '/true/'
1473
 * @param string $order_by
1474
 *   One of the order by constants defined in this file
1475
 * @return array
1476
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1477
 */
1478
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1479
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1480

    
1481
  static $vocabularyOptions = array();
1482

    
1483
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1484
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1485
      array(
1486
        'orderBy' => $order_by
1487
      )
1488
    );
1489

    
1490
    // apply the include filter
1491
    if($include_filter != null){
1492
      $included_terms = array();
1493

    
1494
      foreach ($terms as $term){
1495
        $include = true;
1496
        foreach ($include_filter as $field=>$regex){
1497
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1498
          if(!$include){
1499
            break;
1500
          }
1501
        }
1502
        if($include){
1503
          $included_terms[] = $term;
1504
        }
1505
      }
1506

    
1507
      $terms = $included_terms;
1508
    }
1509

    
1510
    // make options list
1511
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1512
  }
1513

    
1514
  $options = $vocabularyOptions[$vocabulary_uuid];
1515

    
1516
  return $options;
1517
}
1518

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

    
1539
  $options = cdm_vocabulary_as_option($vocabulary_uuid, null, null, $include_filter);
1540
  $defaults = array();
1541
  foreach ($options as $uuid => $value){
1542
    $defaults[$uuid] = $uuid;
1543
  }
1544

    
1545
  return $defaults;
1546
}
1547

    
1548
/**
1549
 * @param $term_type string one of
1550
 *  - Unknown
1551
 *  - Language
1552
 *  - NamedArea
1553
 *  - Rank
1554
 *  - Feature
1555
 *  - AnnotationType
1556
 *  - MarkerType
1557
 *  - ExtensionType
1558
 *  - DerivationEventType
1559
 *  - PresenceAbsenceTerm
1560
 *  - NomenclaturalStatusType
1561
 *  - NameRelationshipType
1562
 *  - HybridRelationshipType
1563
 *  - SynonymRelationshipType
1564
 *  - TaxonRelationshipType
1565
 *  - NameTypeDesignationStatus
1566
 *  - SpecimenTypeDesignationStatus
1567
 *  - InstitutionType
1568
 *  - NamedAreaType
1569
 *  - NamedAreaLevel
1570
 *  - RightsType
1571
 *  - MeasurementUnit
1572
 *  - StatisticalMeasure
1573
 *  - MaterialOrMethod
1574
 *  - Material
1575
 *  - Method
1576
 *  - Modifier
1577
 *  - Scope
1578
 *  - Stage
1579
 *  - KindOfUnit
1580
 *  - Sex
1581
 *  - ReferenceSystem
1582
 *  - State
1583
 *  - NaturalLanguageTerm
1584
 *  - TextFormat
1585
 *  - DeterminationModifier
1586
 *  - DnaMarker
1587
 *
1588
 * @param  $order_by
1589
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1590
 *  possible values:
1591
 *    - CDM_ORDER_BY_ID_ASC
1592
 *    - CDM_ORDER_BY_ID_DESC
1593
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1594
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1595
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1596
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1597
 * @param bool $empty_option
1598
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1599
 * @return array
1600
 *    the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1601
 */
1602
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1603
  $terms = cdm_ws_fetch_all(
1604
    CDM_WS_TERM,
1605
    array(
1606
      'class' => $term_type,
1607
      'orderBy' => $order_by
1608
    )
1609
  );
1610
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1611
}
1612

    
1613
/**
1614
 * @param array $none_option
1615
 *    Will add a filter option to search for NULL values
1616
 * @param $with_empty_option
1617
 *    Will add an empty option to the beginning. Choosing this option will disable the filtering.
1618
 * @return array
1619
 *   An array of options with uuids as key and the localized term representation as value
1620
 */
1621
function cdm_type_designation_status_filter_terms_as_options($none_option_label, $with_empty_option = false){
1622
  $filter_terms = cdm_ws_get(CDM_WS_TYPE_DESIGNATION_STATUS_FILTER_TERMS);
1623

    
1624
  if(isset($filter_terms) && is_array($filter_terms)) {
1625
    foreach ($filter_terms as $filter_term) {
1626
      $options[join(',', $filter_term->uuids)] = $filter_term->label;
1627
    }
1628
  }
1629

    
1630
  if(is_string($none_option_label)){
1631
    $options = array_merge(array('NULL' => $none_option_label), $options);
1632
  }
1633

    
1634
  if($with_empty_option !== FALSE){
1635
    array_unshift ($options, "");
1636
  }
1637

    
1638

    
1639
  return $options;
1640
}
1641

    
1642

    
1643

    
1644
/**
1645
 * Callback function which provides the localized representation of a cdm term.
1646
 *
1647
 * The representation is build by concatenating the abbreviated label with the label
1648
 * and thus is especially useful for relationship terms
1649
 * The localized representation provided by the cdm can be overwritten by
1650
 * providing a drupal translation.
1651
 *
1652
 */
1653
function _cdm_relationship_type_term_label_callback($term) {
1654
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1655
    return $term->representation_L10n_abbreviatedLabel . ' : '
1656
    . t('@term', array('@term' => $term->representation_L10n));
1657
  }
1658
else {
1659
    return t('@term', array('@term' => $term->representation_L10n));
1660
  }
1661
}
1662

    
1663
/**
1664
 * Callback function which provides the localized inverse representation of a cdm term.
1665
 *
1666
 * The representation is build by concatenating the abbreviated label with the label
1667
 * and thus is especially useful for relationship terms
1668
 * The localized representation provided by the cdm can be overwritten by
1669
 * providing a drupal translation.
1670
 *
1671
 */
1672
function _cdm_relationship_type_term_inverse_label_callback($term) {
1673
  if (isset($term->inverseRepresentation_L10n_abbreviatedLabel)) {
1674
    return $term->inverseRepresentation_L10n_abbreviatedLabel . ' : '
1675
      . t('@term', array('@term' => $term->inverseRepresentation_L10n));
1676
  }
1677
  else {
1678
    return t('@term', array('@term' => $term->inverseRepresentation_L10n));
1679
  }
1680
}
1681

    
1682
/**
1683
 * Returns the localized abbreviated label of the relationship term.
1684
 *
1685
 * In case the abbreviated label is not set the normal representation is returned.
1686
 *
1687
 * @param $term
1688
 * @param bool $is_inverse_relation
1689
 * @return string
1690
 *   The abbreviated label
1691
 */
1692
function cdm_relationship_type_term_abbreviated_label($term, $is_inverse_relation = false){
1693

    
1694
  if($is_inverse_relation) {
1695
    if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1696
      $abbr_label = $term->inverseResentation_L10n_abbreviatedLabel;
1697
    } else {
1698
      $abbr_label = $term->inverseRepresentation_L10n;
1699
    }
1700
  } else {
1701
    if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1702
      $abbr_label = $term->representation_L10n_abbreviatedLabel;
1703
    } else {
1704
      $abbr_label = $term->representation_L10n;
1705
    }
1706
  }
1707
  return $abbr_label;
1708
}
1709

    
1710
/**
1711
 * Returns the symbol of the relationship term.
1712
 *
1713
 * In case the symbol is not set the function falls back to use the abbreviated label or
1714
 * the normal representation..
1715
 *
1716
 * @param $term
1717
 * @param bool $is_inverse_relation
1718
 * @return string
1719
 *   The abbreviated label
1720
 */
1721
function cdm_relationship_type_term_symbol($term, $is_inverse_relation = false){
1722

    
1723
  if($is_inverse_relation) {
1724
    if (isset($term->inverseSymbol) && $term->inverseSymbol) {
1725
      $symbol = $term->inverseSymbol;
1726
    } else if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1727
      $symbol = $term->inverseResentation_L10n_abbreviatedLabel;
1728
    } else {
1729
      $symbol = $term->inverseRepresentation_L10n;
1730
    }
1731
  } else {
1732
    if (isset($term->symbol) && $term->symbol) {
1733
      $symbol = $term->symbol;
1734
    } else if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1735
      $symbol = $term->representation_L10n_abbreviatedLabel;
1736
    } else {
1737
      $symbol = $term->representation_L10n;
1738
    }
1739
  }
1740
  return $symbol;
1741
}
1742

    
1743
// ========================================================================================== //
1744
/**
1745
 * @todo Improve documentation of this function.
1746
 *
1747
 * eu.etaxonomy.cdm.model.description.
1748
 * CategoricalData
1749
 * CommonTaxonName
1750
 * Distribution
1751
 * IndividualsAssociation
1752
 * QuantitativeData
1753
 * TaxonInteraction
1754
 * TextData
1755
 */
1756
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1757
  static $types = array(
1758
    "CategoricalData",
1759
    "CommonTaxonName",
1760
    "Distribution",
1761
    "IndividualsAssociation",
1762
    "QuantitativeData",
1763
    "TaxonInteraction",
1764
    "TextData",
1765
  );
1766

    
1767
  static $options = NULL;
1768
  if ($options == NULL) {
1769
    $options = array();
1770
    if ($prependEmptyElement) {
1771
      $options[' '] = '';
1772
    }
1773
    foreach ($types as $type) {
1774
      // No internatianalization here since these are purely technical terms.
1775
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1776
    }
1777
  }
1778
  return $options;
1779
}
1780

    
1781

    
1782
/**
1783
 * Fetches all TaxonDescription descriptions elements which are associated to the
1784
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1785
 * feature tree.
1786
 * @param $feature_tree
1787
 *     The CDM FeatureTree to be used as template
1788
 * @param $taxon_uuid
1789
 *     The UUID of the taxon
1790
 * @param $excludes
1791
 *     UUIDs of features to be excluded
1792
 * @return object
1793
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1794
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1795
 *     witch will hold the according $descriptionElements.
1796
 */
1797
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1798

    
1799
  if (!$feature_tree) {
1800
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1801
      In order to see the species profiles of your taxa, please select a
1802
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1803
    return FALSE;
1804
  }
1805

    
1806
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1807
      array(
1808
      'taxon' => $taxon_uuid,
1809
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1810
      ),
1811
      'POST'
1812
  );
1813

    
1814
  // Combine all descriptions into one feature tree.
1815
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1816
  $feature_tree->root->childNodes = $merged_nodes;
1817

    
1818
  return $feature_tree;
1819
}
1820

    
1821
/**
1822
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdm_entity.
1823
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1824
 * be requested for the annotations.
1825
 *
1826
 * @param string $cdm_entity
1827
 *   An annotatable cdm entity.
1828
 * @param array $include_types
1829
 *   If an array of annotation type uuids is supplied by this parameter the
1830
 *   list of annotations is resticted to those which belong to this type.
1831
 *
1832
 * @return array
1833
 *   An array of Annotation objects or an empty array.
1834
 */
1835
function cdm_ws_fetch_annotations(&$cdm_entity, $include_types = FALSE) {
1836

    
1837
  if(!isset($cdm_entity->annotations)){
1838
    $annotation_url = cdm_compose_annotations_uri($cdm_entity);
1839
    $cdm_entity->annotations = cdm_ws_fetch_all($annotation_url, array(), 'GET', TRUE);
1840
  }
1841

    
1842
  $annotations = array();
1843
  foreach ($cdm_entity->annotations as $annotation) {
1844
    if ($include_types) {
1845
      if (
1846
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $include_types, TRUE) )
1847
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $include_types, TRUE))
1848
      ) {
1849
        $annotations[] = $annotation;
1850
      }
1851
    }
1852
    else {
1853
      $annotations[] = $annotation;
1854
    }
1855
  }
1856
  return $annotations;
1857

    
1858
}
1859

    
1860
/**
1861
 * Provides the list of visible annotations for the $cdm_entity.
1862
 *
1863
 * @param $cdm_entity
1864
 *     The annotatable CDM entity
1865
 *
1866
 * @return array of the annotations which are visible according to the settings as stored in ANNOTATION_TYPES_VISIBLE
1867
 */
1868
function cdm_fetch_visible_annotations($cdm_entity){
1869

    
1870
  static $annotations_types_filter = null;
1871
  if(!$annotations_types_filter) {
1872
    $annotations_types_filter = unserialize(EXTENSION_TYPES_VISIBLE_DEFAULT);
1873
  }
1874
  return cdm_ws_fetch_annotations($cdm_entity, variable_get(ANNOTATION_TYPES_VISIBLE, $annotations_types_filter));
1875
}
1876

    
1877
/**
1878
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1879
 *
1880
 * NOTE: The annotations are not filtered by the ANNOTATION_TYPES_VISIBLE settings since this method is meant to act
1881
 * like the annotations have been fetched in the ORM-framework in the service.
1882
 *
1883
 * @param object $annotatable_entity
1884
 *   The CDM AnnotatableEntity to load annotations for
1885
 */
1886
function cdm_load_annotations(&$annotatable_entity) {
1887
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1888
    $annotations = cdm_ws_fetch_annotations($annotatable_entity);
1889
    if (is_array($annotations)) {
1890
      $annotatable_entity->annotations = $annotations;
1891
    }
1892
  }
1893
}
1894

    
1895
function cdm_load_tagged_full_title($taxon_name){
1896
  if(isset($taxon_name) && !isset($taxon_name->taggedFullTitle)){
1897
    $tagged_full_title = cdm_ws_get(CDM_WS_NAME, array($taxon_name->uuid, 'taggedFullTitle'));
1898
    if(is_array($tagged_full_title)){
1899
      $taxon_name->taggedFullTitle = $tagged_full_title;
1900

    
1901
    }
1902
  }
1903
}
1904

    
1905
/**
1906
 * Extends the $cdm_entity object by the field if it is not already existing.
1907
 *
1908
 * This function can only be used for fields with 1 to many relations.
1909
  *
1910
 * @param $cdm_base_type
1911
 * @param $field_name
1912
 * @param $cdm_entity
1913
 */
1914
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1915
{
1916
  if (!isset($cdm_entity->$field_name)) {
1917
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1918
    $cdm_entity->$field_name = $items;
1919
  }
1920
}
1921

    
1922

    
1923
/**
1924
 * Get a NomenclaturalReference string.
1925
 *
1926
 * Returns the NomenclaturalReference string with correctly placed
1927
 * microreference (= reference detail) e.g.
1928
 * in Phytotaxa 43: 1-48. 2012.
1929
 *
1930
 * @param string $referenceUuid
1931
 *   UUID of the reference.
1932
 * @param string $microreference
1933
 *   Reference detail.
1934
 *
1935
 * @return string
1936
 *   a NomenclaturalReference.
1937
 */
1938
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1939

    
1940
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1941
  if(is_array($microreference) || is_object($microreference)) {
1942
    return '';
1943
  }
1944

    
1945
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1946
    $referenceUuid,
1947
  ), "microReference=" . urlencode($microreference));
1948

    
1949
  if ($obj) {
1950
    return $obj->String;
1951
  }
1952
  else {
1953
    return NULL;
1954
  }
1955
}
1956

    
1957
/**
1958
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1959
 *
1960
 * @param $feature_tree_nodes
1961
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1962
 * @param $feature_uuid
1963
 *    The UUID of the Feature
1964
 * @return object
1965
 *    the FeatureNode or null
1966
 */
1967
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1968

    
1969
  // 1. scan this level
1970
  foreach ($feature_tree_nodes as $node){
1971
    if($node->term->uuid == $feature_uuid){
1972
      return $node;
1973
    }
1974
  }
1975

    
1976
  // 2. descend into childen
1977
  foreach ($feature_tree_nodes as $node){
1978
    if(is_array($node->childNodes)){
1979
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1980
      if($node) {
1981
        return $node;
1982
      }
1983
    }
1984
  }
1985
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1986
  return $null_var;
1987
}
1988

    
1989
/**
1990
 * Merges the given featureNodes structure with the descriptionElements.
1991
 *
1992
 * This method is used in preparation for rendering the descriptionElements.
1993
 * The descriptionElements which belong to a specific feature node are appended
1994
 * to a the feature node by creating a new field:
1995
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1996
 * The descriptionElements will be cleared in advance in order to allow reusing the
1997
 * same feature tree without the risk of mixing sets of description elements.
1998
 *
1999
 * which originally is not existing in the cdm.
2000
 *
2001
 *
2002
 *
2003
 * @param array $featureNodes
2004
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
2005
 *    may have children.
2006
 * @param array $descriptionElements
2007
 *    An flat array of cdm DescriptionElements
2008
 * @return array
2009
 *    The $featureNodes structure enriched with the according $descriptionElements
2010
 */
2011
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
2012

    
2013
  foreach ($featureNodes as &$feature_node) {
2014
    // since the $featureNodes array is reused for each description
2015
    // it is necessary to clear the custom node fields in advance
2016
    if(isset($feature_node->descriptionElements)){
2017
      unset($feature_node->descriptionElements);
2018
    }
2019

    
2020
    // Append corresponding elements to an additional node field:
2021
    // $node->descriptionElements.
2022
    foreach ($descriptionElements as $element) {
2023
      if ($element->feature->uuid == $feature_node->term->uuid) {
2024
        if (!isset($feature_node->descriptionElements)) {
2025
          $feature_node->descriptionElements = array();
2026
        }
2027
        $feature_node->descriptionElements[] = $element;
2028
      }
2029
    }
2030

    
2031
    // Recurse into node children.
2032
    if (isset($feature_node->childNodes[0])) {
2033
      $mergedChildNodes = _mergeFeatureTreeDescriptions($feature_node->childNodes, $descriptionElements);
2034
      $feature_node->childNodes = $mergedChildNodes;
2035
    }
2036

    
2037
    if(!isset($feature_node->descriptionElements) && !isset($feature_node->childNodes[0])){
2038
      unset($feature_node);
2039
    }
2040

    
2041
  }
2042

    
2043
  return $featureNodes;
2044
}
2045

    
2046
/**
2047
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
2048
 *
2049
 * The response from the HTTP GET request is returned as object.
2050
 * The response objects coming from the webservice configured in the
2051
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
2052
 *  in a level 2 (L2) cache.
2053
 *
2054
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
2055
 * function, this cache persists only per each single page execution.
2056
 * Any object coming from the webservice is stored into it by default.
2057
 * In contrast to this default caching mechanism the L2 cache only is used if
2058
 * the 'cdm_webservice_cache' variable is set to TRUE,
2059
 * which can be set using the modules administrative settings section.
2060
 * Objects stored in this L2 cache are serialized and stored
2061
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
2062
 * objects that are stored in the database will persist as
2063
 * long as the drupal cache is not being cleared and are available across
2064
 * multiple script executions.
2065
 *
2066
 * @param string $uri
2067
 *   URL to the webservice.
2068
 * @param array $pathParameters
2069
 *   An array of path parameters.
2070
 * @param string $query_string
2071
 *   A query_string string to be appended to the URL.
2072
 * @param string $method
2073
 *   The HTTP method to use, valid values are "GET" or "POST";
2074
 * @param bool $absoluteURI
2075
 *   TRUE when the URL should be treated as absolute URL.
2076
 *
2077
 * @return object| array
2078
 *   The de-serialized webservice response object.
2079
 */
2080
function cdm_ws_get($uri, $pathParameters = array(), $query_string = NULL, $method = "GET", $absoluteURI = FALSE) {
2081

    
2082
  static $cacheL1 = array();
2083

    
2084
  $data = NULL;
2085
  // store query_string string in $data and clear the query_string, $data will be set as HTTP request body
2086
  if($method == 'POST'){
2087
    $data = $query_string;
2088
    $query_string = NULL;
2089
  }
2090

    
2091
  // Transform the given uri path or pattern into a proper webservice uri.
2092
  if (!$absoluteURI) {
2093
    $uri = cdm_compose_ws_url($uri, $pathParameters, $query_string);
2094
  } else {
2095
    if($query_string){
2096
      $uri = append_query_parameters($uri, $query_string);
2097
    }
2098
  }
2099
  cdm_ws_apply_classification_subtree_filter($uri);
2100

    
2101
  // read request parameter 'cacheL2_refresh'
2102
  // which allows refreshing the level 2 cache
2103
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
2104

    
2105
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
2106
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
2107

    
2108
  if($method == 'GET'){
2109
    $cache_key = $uri;
2110
  } else {
2111
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
2112
    // crc32 is faster but creates much shorter hashes
2113
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
2114
  }
2115

    
2116
  if (array_key_exists($cache_key, $cacheL1)) {
2117
    $cacheL1_obj = $cacheL1[$uri];
2118
  }
2119

    
2120
  $set_cacheL1 = FALSE;
2121
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
2122
    $set_cacheL1 = TRUE;
2123
  }
2124

    
2125
  // Only cache cdm webservice URIs.
2126
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
2127
  $cacheL2_entry = FALSE;
2128

    
2129
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
2130
    // Try to get object from cacheL2.
2131
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
2132
  }
2133

    
2134
  if (isset($cacheL1_obj)) {
2135
    //
2136
    // The object has been found in the L1 cache.
2137
    //
2138
    $obj = $cacheL1_obj;
2139
    if (cdm_debug_block_visible()) {
2140
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
2141
    }
2142
  }
2143
  elseif ($cacheL2_entry) {
2144
    //
2145
    // The object has been found in the L2 cache.
2146
    //
2147
    $duration_parse_start = microtime(TRUE);
2148
    $obj = unserialize($cacheL2_entry->data);
2149
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2150

    
2151
    if (cdm_debug_block_visible()) {
2152
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
2153
    }
2154
  }
2155
  else {
2156
    //
2157
    // Get the object from the webservice and cache it.
2158
    //
2159
    $duration_fetch_start = microtime(TRUE);
2160
    // Request data from webservice JSON or XML.
2161
    $response = cdm_http_request($uri, $method, $data);
2162
    $response_body = NULL;
2163
    if (isset($response->data)) {
2164
      $response_body = $response->data;
2165
    }
2166
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2167
    $duration_parse_start = microtime(TRUE);
2168

    
2169
    // Parse data and create object.
2170
    $obj = cdm_load_obj($response_body);
2171

    
2172
    if(isset($obj->servlet) && isset($obj->status) && is_numeric($obj->status)){
2173
      // this is json error message returned by jetty #8914
2174
      // wee need to replace it by null to avoid breaking existing assumptions in the code here
2175
      // this is also related to #2711
2176
      $obj = null;
2177
    }
2178

    
2179
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2180

    
2181
    if (cdm_debug_block_visible()) {
2182
      if ($obj || $response_body == "[]") {
2183
        $status = 'valid';
2184
      }
2185
      else {
2186
        $status = 'invalid';
2187
      }
2188
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2189
    }
2190
    if ($set_cacheL2) {
2191
      // Store the object in cache L2.
2192
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2193
      // flag serialized is set properly in the cache table.
2194
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2195
    }
2196
  }
2197
  if ($obj) {
2198
    // Store the object in cache L1.
2199
    if ($set_cacheL1) {
2200
      $cacheL1[$cache_key] = $obj;
2201
    }
2202
  }
2203
  return $obj;
2204
}
2205

    
2206
function cdm_ws_apply_classification_subtree_filter(&$uri){
2207

    
2208
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
2209
    "#/classification/[0-9a-f\-]{36}/childNodes#",
2210
    /* covered by above pattern:
2211
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2212
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2213
    */
2214
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
2215
    /* covered by above pattern:
2216
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2217
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2218
    */
2219
    '#/portal/classification/[0-9a-f\-]{36}/pathFrom/[0-9a-f\-]{36}#',
2220
    "#/portal/taxon/search#",
2221
    "#/portal/taxon/find#",
2222
    /* covered by above pattern:
2223
    "#/portal/taxon/findByDescriptionElementFullText#",
2224
    "#/portal/taxon/findByFullText#",
2225
    "#/portal/taxon/findByEverythingFullText#",
2226
    "#/portal/taxon/findByIdentifier#",
2227
    "#/portal/taxon/findByMarker#",
2228
    "#/portal/taxon/findByMarker#",
2229
    "#/portal/taxon/findByMarker#",
2230
    */
2231
    "#/portal/taxon/[0-9a-f\-]{36}#"
2232
    /* covered by above pattern:
2233
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
2234
    */
2235
  ));
2236

    
2237
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
2238
  if(is_uuid($sub_tree_filter_uuid_value)){
2239
    foreach($classification_subtree_filter_patterns as $preg_pattern){
2240
      if(preg_match($preg_pattern, $uri)){
2241
        // no need to take care for uri fragments with ws uris!
2242
        if(strpos( $uri, '?')){
2243
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
2244
        } else {
2245
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
2246
        }
2247
        break;
2248
      }
2249
    }
2250
  }
2251

    
2252
}
2253
/**
2254
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2255
 *
2256
 * The cdm_ws_debug block will display the debug information.
2257
 *
2258
 * @param $uri
2259
 *    The CDM REST URI to which the request has been send
2260
 * @param string $method
2261
 *    The HTTP request method, either 'GET' or 'POST'
2262
 * @param string $post_data
2263
 *    The datastring send with a post request
2264
 * @param $duration_fetch
2265
 *    The time in seconds it took to fetch the data from the web service
2266
 * @param $duration_parse
2267
 *    Time in seconds which was needed to parse the json response
2268
 * @param $datasize
2269
 *    Size of the data received from the server
2270
 * @param $status
2271
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2272
 * @return bool
2273
 *    TRUE if adding the debug information was successful
2274
 */
2275
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2276

    
2277
  static $initial_time = NULL;
2278
  if(!$initial_time) {
2279
    $initial_time = microtime(TRUE);
2280
  }
2281
  $time = microtime(TRUE) - $initial_time;
2282

    
2283
  // Decompose uri into path and query element.
2284
  $uri_parts = explode("?", $uri);
2285
  $query = array();
2286
  if (count($uri_parts) == 2) {
2287
    $path = $uri_parts[0];
2288
  }
2289
  else {
2290
    $path = $uri;
2291
  }
2292

    
2293
  if(strpos($uri, '?') > 0){
2294
    $json_uri = str_replace('?', '.json?', $uri);
2295
    $xml_uri = str_replace('?', '.xml?', $uri);
2296
  } else {
2297
    $json_uri = $uri . '.json';
2298
    $xml_uri = $json_uri . '.xml';
2299
  }
2300

    
2301
  // data links to make data accecsible as json and xml
2302
  $data_links = '';
2303
  if (_is_cdm_ws_uri($path)) {
2304

    
2305
    // see ./js/http-method-link.js
2306

    
2307
    if($method == 'GET'){
2308
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2309
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2310
      $data_links .= '<br/>';
2311
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2312
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2313
    } else {
2314
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2315
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2316
      $data_links .= '<br/>';
2317
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2318
    }
2319
  }
2320
  else {
2321
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2322
  }
2323

    
2324
  //
2325
  $data = array(
2326
      'ws_uri' => $uri,
2327
      'method' => $method,
2328
      'post_data' => $post_data,
2329
      'time' => sprintf('%3.3f', $time),
2330
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2331
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2332
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2333
      'status' => $status,
2334
      'data_links' => $data_links
2335
  );
2336
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2337
    $_SESSION['cdm']['ws_debug'] = array();
2338
  }
2339
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2340

    
2341
  // Mark this page as being uncacheable.
2342
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2343
  drupal_page_is_cacheable(FALSE);
2344

    
2345
  // Messages not set when DB connection fails.
2346
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2347
}
2348

    
2349
/**
2350
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2351
 * the visibility depends on whether
2352
 *  - the block is enabled
2353
 *  - the visibility restrictions in the block settings are satisfied
2354
 */
2355
function cdm_debug_block_visible() {
2356
  static $is_visible = null;
2357

    
2358
  if($is_visible === null){
2359
      $block = block_load('cdm_api', 'cdm_ws_debug');
2360
      $is_visible = isset($block->status) && $block->status == 1;
2361
      if($is_visible){
2362
        $blocks = array($block);
2363
        // Checks the page, user role, and user-specific visibilty settings.
2364
        block_block_list_alter($blocks);
2365
        $is_visible = count($blocks) > 0;
2366
      }
2367
  }
2368
  return $is_visible;
2369
}
2370

    
2371
/**
2372
 * @todo Please document this function.
2373
 * @see http://drupal.org/node/1354
2374
 */
2375
function cdm_load_obj($response_body) {
2376
  $obj = json_decode($response_body);
2377

    
2378
  if (!(is_object($obj) || is_array($obj))) {
2379
    ob_start();
2380
    $obj_dump = ob_get_contents();
2381
    ob_clean();
2382
    return FALSE;
2383
  }
2384

    
2385
  return $obj;
2386
}
2387

    
2388
/**
2389
 * Do a http request to a CDM RESTful web service.
2390
 *
2391
 * @param string $uri
2392
 *   The webservice url.
2393
 * @param string $method
2394
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2395
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2396
 * @param $data: A string containing the request body, formatted as
2397
 *     'param=value&param=value&...'. Defaults to NULL.
2398
 *
2399
 * @return object
2400
 *   The object as returned by drupal_http_request():
2401
 *   An object that can have one or more of the following components:
2402
 *   - request: A string containing the request body that was sent.
2403
 *   - code: An integer containing the response status code, or the error code
2404
 *     if an error occurred.
2405
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2406
 *   - status_message: The status message from the response, if a response was
2407
 *     received.
2408
 *   - redirect_code: If redirected, an integer containing the initial response
2409
 *     status code.
2410
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2411
 *     target.
2412
 *   - error: If an error occurred, the error message. Otherwise not set.
2413
 *   - headers: An array containing the response headers as name/value pairs.
2414
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2415
 *     easy access the array keys are returned in lower case.
2416
 *   - data: A string containing the response body that was received.
2417
 */
2418
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2419
  static $acceptLanguage = NULL;
2420
  $header = array();
2421
  
2422
  if(!$acceptLanguage && module_exists('i18n')){
2423
    $acceptLanguage = i18n_language_content()->language;
2424
  }
2425

    
2426
  if (!$acceptLanguage) {
2427
    if (function_exists('apache_request_headers')) {
2428
      $headers = apache_request_headers();
2429
      if (isset($headers['Accept-Language'])) {
2430
        $acceptLanguage = $headers['Accept-Language'];
2431
      }
2432
    }
2433
  }
2434

    
2435
  if ($method != "GET" && $method != "POST") {
2436
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2437
  }
2438

    
2439
  if (_is_cdm_ws_uri($uri)) {
2440
    $header['Accept'] = 'application/json';
2441
    $header['Accept-Language'] = $acceptLanguage;
2442
    $header['Accept-Charset'] = 'UTF-8';
2443
  }
2444

    
2445
  if($method == "POST") {
2446
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2447
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2448
  }
2449

    
2450

    
2451
  cdm_dd($uri);
2452
  return drupal_http_request($uri, array(
2453
      'headers' => $header,
2454
      'method' => $method,
2455
      'data' => $data,
2456
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2457
      )
2458
   );
2459
}
2460

    
2461
/**
2462
 * Concatenates recursively the fields of all features contained in the given
2463
 * CDM FeatureTree root node.
2464
 *
2465
 * @param $rootNode
2466
 *     A CDM FeatureTree node
2467
 * @param
2468
 *     The character to be used as glue for concatenation, default is ', '
2469
 * @param $field_name
2470
 *     The field name of the CDM Features
2471
 * @param $excludes
2472
 *     Allows defining a set of values to be excluded. This refers to the values
2473
 *     in the field denoted by the $field_name parameter
2474
 *
2475
 */
2476
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2477
  $out = '';
2478

    
2479
  $pre_child_separator = $separator;
2480
  $post_child_separator = '';
2481

    
2482
  foreach ($root_node->childNodes as $feature_node) {
2483
    $out .= ($out ? $separator : '');
2484
    if(!in_array($feature_node->term->$field_name, $excludes)) {
2485
      $out .= $feature_node->term->$field_name;
2486
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2487
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2488
        if (strlen($childlabels)) {
2489
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2490
        }
2491
      }
2492
    }
2493
  }
2494
  return $out;
2495
}
2496

    
2497
/**
2498
 * Create a one-dimensional form options array.
2499
 *
2500
 * Creates an array of all features in the feature tree of feature nodes,
2501
 * the node labels are indented by $node_char and $childIndent depending on the
2502
 * hierachy level.
2503
 *
2504
 * @param - $rootNode
2505
 * @param - $node_char
2506
 * @param - $childIndentStr
2507
 * @param - $childIndent
2508
 *   ONLY USED INTERNALLY!
2509
 *
2510
 * @return array
2511
 *   A one dimensional Drupal form options array.
2512
 */
2513
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2514
  $options = array();
2515
  foreach ($rootNode->childNodes as $featureNode) {
2516
    $indent_prefix = '';
2517
    if ($childIndent) {
2518
      $indent_prefix = $childIndent . $node_char . " ";
2519
    }
2520
    $options[$featureNode->term->uuid] = $indent_prefix . $featureNode->term->representation_L10n;
2521
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2522
      // Foreach ($featureNode->childNodes as $childNode){
2523
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2524
      $options = array_merge_recursive($options, $childList);
2525
      // }
2526
    }
2527
  }
2528
  return $options;
2529
}
2530

    
2531
/**
2532
 * Returns an array with all available FeatureTrees and the representations of the selected
2533
 * FeatureTree as a detail view.
2534
 *
2535
 * @param boolean $add_default_feature_free
2536
 * @param boolean $show_weight
2537
 *     Show the weight which will be applied to the according feature block
2538
 * @return array
2539
 *  associative array with following keys:
2540
 *  -options: Returns an array with all available Feature Trees
2541
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2542
 *
2543
 */
2544
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE, $show_weight = FALSE) {
2545

    
2546
  $options = array();
2547
  $tree_representations = array();
2548
  $feature_trees = array();
2549

    
2550
  // Set tree that contains all features.
2551
  if ($add_default_feature_free) {
2552
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2553
    $feature_trees[] = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
2554
  }
2555

    
2556
  // Get feature trees from database.
2557
  $persited_trees = cdm_ws_fetch_all(CDM_WS_TERMTREES, array("termType" => "Feature"));
2558
  if (is_array($persited_trees)) {
2559
    $feature_trees = array_merge($feature_trees, $persited_trees);
2560
  }
2561

    
2562
  foreach ($feature_trees as $featureTree) {
2563

    
2564
    if(!is_object($featureTree)){
2565
      continue;
2566
    }
2567
    // Do not add the DEFAULT_FEATURETREE again,
2568
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2569
      $options[$featureTree->uuid] = $featureTree->representation_L10n;
2570
    }
2571

    
2572
    // Render the hierarchic tree structure
2573
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2574

    
2575
      // Render the hierarchic tree structure.
2576
      $treeDetails = '<div class="featuretree_structure">'
2577
        . render_feature_tree_hierarchy($featureTree->uuid, $show_weight)
2578
        . '</div>';
2579

    
2580
      $form = array();
2581
      $form['featureTree-' .  $featureTree->uuid] = array(
2582
        '#type' => 'fieldset',
2583
        '#title' => 'Show details',
2584
        '#attributes' => array('class' => array('collapsible collapsed')),
2585
        // '#collapsible' => TRUE,
2586
        // '#collapsed' => TRUE,
2587
      );
2588
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2589
        '#markup' => $treeDetails,
2590
      );
2591

    
2592
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2593
    }
2594

    
2595
  } // END loop over feature trees
2596

    
2597
  // return $options;
2598
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2599
}
2600

    
2601
/**
2602
 * Provides the list of available classifications in form of an options array.
2603
 *
2604
 * The options array is suitable for drupal form API elements that allow multiple choices.
2605
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2606
 *
2607
 * The classifications are ordered alphabetically whereas the classification
2608
 * chosen as default will always appear on top of the array, followed by a
2609
 * blank line below.
2610
 *
2611
 * @param bool $add_none_option
2612
 *   is true an additional 'none' option will be added if and only if there are
2613
 *   more than one options. Defaults to FALSE
2614
 *
2615
 * @param $include_uuids
2616
 *   The taxon tree uuids to be included, other taxon trees will be filtered out.
2617
 *   You may want to use here:
2618
 *   variable_get(CDM_TAXONTREE_INCLUDES, [])
2619
 *
2620
 *
2621
 * @return array
2622
 *   classifications in an array as options for a form element that allows multiple choices.
2623
 */
2624
function cdm_get_taxontrees_as_options($add_none_option = FALSE, $include_uuids = []) {
2625

    
2626
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2627

    
2628
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2629
  $default_classification_label = '';
2630

    
2631
  // add all classifications
2632
  $taxonomic_tree_options = array();
2633
  if ($add_none_option) {
2634
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2635
  }
2636
  if ($taxonTrees) {
2637
    foreach ($taxonTrees as $tree) {
2638
      if(is_array($include_uuids) && count($include_uuids) > 0 && array_search($tree->uuid, $include_uuids) === FALSE){
2639
        continue;
2640
      }
2641
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2642
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2643
      } else {
2644
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2645
        $default_classification_label = $tree->titleCache;
2646
      }
2647
    }
2648
  }
2649
  // oder alphabetically the space
2650
  asort($taxonomic_tree_options);
2651

    
2652
  // now set the labels for none
2653
  if ($add_none_option && count($taxonomic_tree_options) > 2) {
2654
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2655
  } else {
2656
    unset($taxonomic_tree_options['NONE']);
2657
  }
2658

    
2659
  //   for default_classification
2660
  if (is_uuid($default_classification_uuid)) {
2661
    $taxonomic_tree_options[$default_classification_uuid] =
2662
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2663
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2664
  }
2665

    
2666
  return $taxonomic_tree_options;
2667
}
2668

    
2669
/**
2670
 * @todo Please document this function.
2671
 * @see http://drupal.org/node/1354
2672
 */
2673
function cdm_api_secref_cache_prefetch(&$secUuids) {
2674
  // Comment @WA: global variables should start with a single underscore
2675
  // followed by the module and another underscore.
2676
  global $_cdm_api_secref_cache;
2677
  if (!is_array($_cdm_api_secref_cache)) {
2678
    $_cdm_api_secref_cache = array();
2679
  }
2680
  $uniqueUuids = array_unique($secUuids);
2681
  $i = 0;
2682
  $param = '';
2683
  while ($i++ < count($uniqueUuids)) {
2684
    $param .= $secUuids[$i] . ',';
2685
    if (strlen($param) + 37 > 2000) {
2686
      _cdm_api_secref_cache_add($param);
2687
      $param = '';
2688
    }
2689
  }
2690
  if ($param) {
2691
    _cdm_api_secref_cache_add($param);
2692
  }
2693
}
2694

    
2695
/**
2696
 * @todo Please document this function.
2697
 * @see http://drupal.org/node/1354
2698
 */
2699
function cdm_api_secref_cache_get($secUuid) {
2700
  global $_cdm_api_secref_cache;
2701
  if (!is_array($_cdm_api_secref_cache)) {
2702
    $_cdm_api_secref_cache = array();
2703
  }
2704
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2705
    _cdm_api_secref_cache_add($secUuid);
2706
  }
2707
  return $_cdm_api_secref_cache[$secUuid];
2708
}
2709

    
2710
/**
2711
 * @todo Please document this function.
2712
 * @see http://drupal.org/node/1354
2713
 */
2714
function cdm_api_secref_cache_clear() {
2715
  global $_cdm_api_secref_cache;
2716
  $_cdm_api_secref_cache = array();
2717
}
2718

    
2719

    
2720
/**
2721
 * @todo Please document this function.
2722
 * @see http://drupal.org/node/1354
2723
 */
2724
function _cdm_api_secref_cache_add($secUuidsStr) {
2725
  global $_cdm_api_secref_cache;
2726
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2727
  // Batch fetching not jet reimplemented thus:
2728
  /*
2729
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2730
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2731
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2732
  */
2733
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2734
}
2735

    
2736
/**
2737
 * Checks if the given uri starts with a cdm webservice url.
2738
 *
2739
 * Checks if the uri starts with the cdm webservice url stored in the
2740
 * Drupal variable 'cdm_webservice_url'.
2741
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2742
 *
2743
 * @param string $uri
2744
 *   The URI to test.
2745
 *
2746
 * @return bool
2747
 *   True if the uri starts with a cdm webservice url.
2748
 */
2749
function _is_cdm_ws_uri($uri) {
2750
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2751
}
2752

    
2753
/**
2754
 * @todo Please document this function.
2755
 * @see http://drupal.org/node/1354
2756
 */
2757
function queryString($elements) {
2758
  $query = '';
2759
  foreach ($elements as $key => $value) {
2760
    if (is_array($value)) {
2761
      foreach ($value as $v) {
2762
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2763
      }
2764
    }
2765
    else {
2766
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2767
    }
2768
  }
2769
  return $query;
2770
}
2771

    
2772
/**
2773
 * Compares the given CDM Term instances by the  representationL10n.
2774
 *
2775
 * Can also be used with TermDTOs. To be used in usort()
2776
 *
2777
 * @see http://php.net/manual/en/function.usort.php
2778
 *
2779
 * @param $term1
2780
 *   The first CDM Term instance
2781
 * @param $term2
2782
 *   The second CDM Term instance
2783
 * @return int
2784
 *   The result of the comparison
2785
 */
2786
function compare_terms_by_representationL10n($term1, $term2) {
2787

    
2788
  if (!isset($term1->representation_L10n)) {
2789
    $term1->representationL10n = '';
2790
  }
2791
  if (!isset($term2->representation_L10n)) {
2792
    $term2->representationL10n = '';
2793
  }
2794

    
2795
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2796
}
2797

    
2798
function compare_terms_by_order_index($term1, $term2) {
2799

    
2800

    
2801
  if (!isset($term1->orderIndex)) {
2802
    $a = 0;
2803
  } else {
2804
    $a = $term1->orderIndex;
2805
  }
2806
  if (!isset($term2->orderIndex)) {
2807
    $b = 0;
2808
  } else {
2809
    $b = $term2->orderIndex;
2810
  }
2811

    
2812
  if ($a == $b) {
2813
    return 0;
2814
  }
2815
  return ($a < $b) ? -1 : 1;
2816

    
2817
}
2818

    
2819

    
2820
/**
2821
 * Make a 'deep copy' of an array.
2822
 *
2823
 * Make a complete deep copy of an array replacing
2824
 * references with deep copies until a certain depth is reached
2825
 * ($maxdepth) whereupon references are copied as-is...
2826
 *
2827
 * @see http://us3.php.net/manual/en/ref.array.php
2828
 *
2829
 * @param array $array
2830
 * @param array $copy passed by reference
2831
 * @param int $maxdepth
2832
 * @param int $depth
2833
 */
2834
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2835
  if ($depth > $maxdepth) {
2836
    $copy = $array;
2837
    return;
2838
  }
2839
  if (!is_array($copy)) {
2840
    $copy = array();
2841
  }
2842
  foreach ($array as $k => &$v) {
2843
    if (is_array($v)) {
2844
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2845
    }
2846
    else {
2847
      $copy[$k] = $v;
2848
    }
2849
  }
2850
}
2851

    
2852
/**
2853
 * Concatenated the uuids of the passed cdm entity with `,` as glue.
2854
 * The returned string is suitable for cdm webservices consuming UUIDList as
2855
 * parameter
2856
 *
2857
 * @param array $cdm_entities
2858
 *
2859
 * @return string
2860
 */
2861
function cdm_uuid_list_parameter_value(array $cdm_entities){
2862
  $uuids = [];
2863
  foreach ($cdm_entities as $entity){
2864
    if(isset($entity) && is_uuid($entity->uuid) ){
2865
      $uuids[] = $entity->uuid;
2866
    }
2867
  }
2868
  return  join(',', $uuids);
2869
}
2870

    
2871
/**
2872
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2873
 *
2874
 */
2875
function _add_js_ws_debug() {
2876

    
2877
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2878
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2879
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2880
    // use the developer versions of js libs
2881
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2882
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2883
  }
2884
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2885
    array(
2886
      'type' => 'file',
2887
      'weight' => JS_LIBRARY,
2888
      'cache' => TRUE)
2889
    );
2890

    
2891
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2892
    array(
2893
      'type' => 'file',
2894
      'weight' => JS_LIBRARY,
2895
      'cache' => TRUE)
2896
    );
2897
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2898
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2899

    
2900
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2901
    array(
2902
      'type' => 'file',
2903
      'weight' => JS_LIBRARY,
2904
      'cache' => TRUE)
2905
    );
2906
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2907
    array(
2908
    'type' => 'file',
2909
    'weight' => JS_LIBRARY,
2910
    'cache' => TRUE)
2911
    );
2912

    
2913
}
2914

    
2915
/**
2916
 * @todo Please document this function.
2917
 * @see http://drupal.org/node/1354
2918
 */
2919
function _no_classfication_uuid_message() {
2920
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2921
    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.');
2922
  }
2923
  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.');
2924
}
2925

    
2926
/**
2927
 * Implementation of hook flush_caches
2928
 *
2929
 * Add custom cache tables to the list of cache tables that
2930
 * will be cleared by the Clear button on the Performance page or whenever
2931
 * drupal_flush_all_caches is invoked.
2932
 *
2933
 * @author W.Addink <waddink@eti.uva.nl>
2934
 *
2935
 * @return array
2936
 *   An array with custom cache tables to include.
2937
 */
2938
function cdm_api_flush_caches() {
2939
  return array('cache_cdm_ws');
2940
}
2941

    
2942
/**
2943
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2944
 *
2945
 * @param $data
2946
 *   The variable to log to the drupal_debug.txt log file.
2947
 * @param $label
2948
 *   (optional) If set, a label to output before $data in the log file.
2949
 *
2950
 * @return
2951
 *   No return value if successful, FALSE if the log file could not be written
2952
 *   to.
2953
 *
2954
 * @see cdm_dataportal_init() where the log file is reset on each requests
2955
 * @see dd()
2956
 * @see http://drupal.org/node/314112
2957
 *
2958
 */
2959
function cdm_dd($data, $label = NULL) {
2960
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2961
    return dd($data, $label);
2962
  }
2963
}
2964

    
(5-5/12)