Project

General

Profile

Download (89.2 KB) Statistics
| Branch: | Tag: | Revision:
1 6657531f Andreas Kohlbecker
<?php
2 54cfa718 Andreas Kohlbecker
  /**
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 6657531f Andreas Kohlbecker
24 54cfa718 Andreas Kohlbecker
  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 2978b0c8 Andreas Kohlbecker
  module_load_include('inc', 'cdm_api', 'tagged_text');
31 6657531f Andreas Kohlbecker
32 54cfa718 Andreas Kohlbecker
  /**
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 1042dbc0 Andreas Kohlbecker
41 7ca5ef1e Andreas Kohlbecker
42
43
/**
44
 * orderBy webservice query parameter value
45
 */
46 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_ID_ASC', 'BY_ID_ASC');
47 7ca5ef1e Andreas Kohlbecker
48
/**
49
 * orderBy webservice query parameter value
50
 */
51 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_ID_DESC', 'BY_ID_DESC');
52 7ca5ef1e Andreas Kohlbecker
/**
53
 * orderBy webservice query parameter value
54
 */
55 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'BY_TITLE_CACHE_ASC');
56 7ca5ef1e Andreas Kohlbecker
/**
57
 * orderBy webservice query parameter value
58
 */
59 f8234b76 Andreas Kohlbecker
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'BY_TITLE_CACHE_DESC');
60 7ca5ef1e Andreas Kohlbecker
/**
61
 * orderBy webservice query parameter value
62
 */
63 a33be830 Andreas Kohlbecker
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_ASC', 'BY_NOMENCLATURAL_ORDER_ASC');
64 7ca5ef1e Andreas Kohlbecker
/**
65
 * orderBy webservice query parameter value
66
 */
67 a33be830 Andreas Kohlbecker
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_DESC', 'BY_NOMENCLATURAL_ORDER_DESC');
68 7ca5ef1e Andreas Kohlbecker
/**
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 fa782b11 Andreas Kohlbecker
78 6657531f Andreas Kohlbecker
/**
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 c6fe437b Andreas Kohlbecker
      'access cdm content',
89 6657531f Andreas Kohlbecker
    ),
90
    'type' => MENU_CALLBACK,
91
  );
92
93
  $items['cdm_api/setvalue/session'] = array(
94
    'page callback' => 'setvalue_session',
95
    'access arguments' => array(
96 c6fe437b Andreas Kohlbecker
      'access cdm content',
97 6657531f Andreas Kohlbecker
    ),
98
    'type' => MENU_CALLBACK,
99
  );
100
101
  return $items;
102
}
103
104 e2464cf8 Andreas Kohlbecker
/**
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 6b5815cd Andreas Kohlbecker
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
124
125 e2464cf8 Andreas Kohlbecker
    $field_map = array(
126 6b5815cd Andreas Kohlbecker
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
127 e2464cf8 Andreas Kohlbecker
        '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 6b5815cd Andreas Kohlbecker
146 e2464cf8 Andreas Kohlbecker
      $data = unserialize($data);
147 6b5815cd Andreas Kohlbecker
148
      // stip of webservice base url
149
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
150 2ebf0428 Andreas Kohlbecker
      if($data['method'] == 'POST'){
151
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
152
      }
153 6b5815cd Andreas Kohlbecker
154
      $cells = array();
155 e2464cf8 Andreas Kohlbecker
      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 86b65fa0 Andreas Kohlbecker
    $block['subject'] = ''; // no subject, title in content for having a defined element id
166
    // otherwise it would depend on the theme
167 63f6d312 Saskia Gennrich
    $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 86b65fa0 Andreas Kohlbecker
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
171 e2464cf8 Andreas Kohlbecker
        . $header
172
        . '<tbody>' . join('', $rows) . '</tbody>'
173
        . $footer
174 63f6d312 Saskia Gennrich
        . '</table></div>',
175
      '#attached' => array(
176
        'css' => array(
177
          drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_ws_debug.css'
178
        )
179
      )
180
    );
181 e2464cf8 Andreas Kohlbecker
    return $block;
182
  }
183
}
184
185 6657531f Andreas Kohlbecker
/**
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 61b6ee11 Andreas Kohlbecker
/**
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 9dddc68a Andreas Kohlbecker
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);
206 61b6ee11 Andreas Kohlbecker
}
207
208 6657531f Andreas Kohlbecker
/**
209 9dddc68a Andreas Kohlbecker
 * Returns the chosen FeatureTree to be used as FeatureTree for the taxon profile.
210 6657531f Andreas Kohlbecker
 *
211 9dddc68a Andreas Kohlbecker
 * The FeatureTree returned is the term tree one that has been set in the
212 6657531f Andreas Kohlbecker
 * 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 9dddc68a Andreas Kohlbecker
 * @return object
217
 *   A cdm TermTree object.
218 6657531f Andreas Kohlbecker
 */
219 642b323b Andreas Kohlbecker
function get_profile_feature_tree() {
220 bfb2b81a Andreas Kohlbecker
  static $profile_featureTree;
221
222
  if($profile_featureTree == NULL) {
223 6657531f Andreas Kohlbecker
    $profile_featureTree = cdm_ws_get(
224 9dddc68a Andreas Kohlbecker
      CDM_WS_TERMTREE,
225 bfb2b81a Andreas Kohlbecker
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
226 6657531f Andreas Kohlbecker
    );
227 bfb2b81a Andreas Kohlbecker
    if (!$profile_featureTree) {
228 9dddc68a Andreas Kohlbecker
      $profile_featureTree = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
229 bfb2b81a Andreas Kohlbecker
    }
230 6657531f Andreas Kohlbecker
  }
231 092744e1 Andreas Kohlbecker
232 6657531f Andreas Kohlbecker
  return $profile_featureTree;
233
}
234
235 f19f47fa Andreas Kohlbecker
/**
236 9dddc68a Andreas Kohlbecker
 * Returns the chosen TermTree to be used as FeatureTree for SpecimenDescriptions.
237 f19f47fa Andreas Kohlbecker
 *
238 9dddc68a Andreas Kohlbecker
 * The TermTree returned is the one that has been set in the
239 f19f47fa Andreas Kohlbecker
 * dataportal settings (layout->taxon:specimen).
240 9dddc68a Andreas Kohlbecker
 * When the chosen TermTree is not found in the database,
241
 * the standard term tree (UUID_DEFAULT_TERMTREE) will be returned.
242 f19f47fa Andreas Kohlbecker
 *
243 9dddc68a Andreas Kohlbecker
 * @return object
244
 *   A cdm TermTree object.
245 bfb2b81a Andreas Kohlbecker
 */
246 f19f47fa Andreas Kohlbecker
function cdm_get_occurrence_featureTree() {
247 bfb2b81a Andreas Kohlbecker
  static $occurrence_featureTree;
248
249
  if($occurrence_featureTree == NULL) {
250
    $occurrence_featureTree = cdm_ws_get(
251 9dddc68a Andreas Kohlbecker
      CDM_WS_TERMTREE,
252 bfb2b81a Andreas Kohlbecker
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
253
    );
254
    if (!$occurrence_featureTree) {
255 9dddc68a Andreas Kohlbecker
      $occurrence_featureTree = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
256 bfb2b81a Andreas Kohlbecker
    }
257
  }
258 f19f47fa Andreas Kohlbecker
  return $occurrence_featureTree;
259 bfb2b81a Andreas Kohlbecker
}
260
261 f19f47fa Andreas Kohlbecker
/**
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 bfb2b81a Andreas Kohlbecker
  if($structured_description_featureTree == NULL) {
276 f19f47fa Andreas Kohlbecker
    $structured_description_featureTree = cdm_ws_get(
277 9dddc68a Andreas Kohlbecker
        CDM_WS_TERMTREE,
278 f19f47fa Andreas Kohlbecker
        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 9dddc68a Andreas Kohlbecker
          CDM_WS_TERMTREE,
283 f19f47fa Andreas Kohlbecker
          UUID_DEFAULT_FEATURETREE
284
      );
285 bfb2b81a Andreas Kohlbecker
    }
286 f19f47fa Andreas Kohlbecker
  }
287
  return $structured_description_featureTree;
288 bfb2b81a Andreas Kohlbecker
}
289
290 6657531f Andreas Kohlbecker
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 4a462641 Andreas Kohlbecker
 * NOTE: The cdm-library provides a very similar server side function. See
314
 * eu.etaxonomy.cdm.model.media.MediaUtils.filterAndOrderMediaRepresentations()
315 6657531f Andreas Kohlbecker
 *
316
 * @param object $media
317
 * @param array $mimeTypes
318 4fa6f9ba Andreas Kohlbecker
 *    an array of mimetypes in their order of preference. e.g:
319
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
320 6657531f Andreas Kohlbecker
 * @param int $width
321 673929dd Andreas Kohlbecker
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
322 6657531f Andreas Kohlbecker
 * @param int $height
323 673929dd Andreas Kohlbecker
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
324 6657531f Andreas Kohlbecker
 *
325
 * @return array
326
 *   An array with preferred media representations or else an empty array.
327
 */
328 5dc25a7d Andreas Kohlbecker
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
329 6657531f Andreas Kohlbecker
  $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 673929dd Andreas Kohlbecker
        $expansionDeltaSum = 0;
351 275b2642 Andreas Kohlbecker
        $valid_parts_cnt = 0;
352 6657531f Andreas Kohlbecker
        // Look for part with the best matching size.
353
        foreach ($representation->parts as $part) {
354 4fa6f9ba Andreas Kohlbecker
          if (empty($part->uri)) {
355 275b2642 Andreas Kohlbecker
            // skip part if URI is missing
356
            continue;
357
          }
358
          $valid_parts_cnt++;
359 f6408572 Andreas Kohlbecker
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
360 4fa6f9ba Andreas Kohlbecker
361
          // determine the optimal size
362 6657531f Andreas Kohlbecker
          if (isset($part->width) && isset($part->height)) {
363 673929dd Andreas Kohlbecker
            $expansion = $part->width * $part->height;
364 4fa6f9ba Andreas Kohlbecker
            if ($width != null && $height != null) {
365 673929dd Andreas Kohlbecker
              $optimalExpansion = $height * $width;
366 4fa6f9ba Andreas Kohlbecker
            } else {
367 673929dd Andreas Kohlbecker
              $optimalExpansion = PHP_INT_MAX;
368 4fa6f9ba Andreas Kohlbecker
            }
369
            // determine the difference
370 673929dd Andreas Kohlbecker
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
371 6657531f Andreas Kohlbecker
          }
372 673929dd Andreas Kohlbecker
          // sum up the expansionDeltas of all parts contained in the representation
373
          $expansionDeltaSum += $expansionDelta;
374 6657531f Andreas Kohlbecker
        }
375 275b2642 Andreas Kohlbecker
        if($valid_parts_cnt > 0){
376 673929dd Andreas Kohlbecker
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
377
          $prefRepr[$expansionDeltaSum] = $representation;
378 275b2642 Andreas Kohlbecker
        }
379 6657531f Andreas Kohlbecker
      }
380
    }
381
  }
382 4fa6f9ba Andreas Kohlbecker
  // Sort the array so that the smallest key value is the first in the array
383
  ksort($prefRepr);
384 6657531f Andreas Kohlbecker
  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 250f2a96 Andreas Kohlbecker
/**
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 ef6a4ce9 Andreas Kohlbecker
function format_datetime($datetime, $format = 'Y-m-d H:i:s', $strip_zeros = true){
435 250f2a96 Andreas Kohlbecker
  return date($format, strtotime($datetime));
436
}
437
438 6657531f Andreas Kohlbecker
/**
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 d0e8e73c Andreas Kohlbecker
    $year = drupal_substr($partial, 0, 4);
453 6657531f Andreas Kohlbecker
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
454
      return $year;
455
    }
456
  }
457 c7f92453 Andreas Kohlbecker
  return '';
458 6657531f Andreas Kohlbecker
}
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 d0e8e73c Andreas Kohlbecker
    $month = drupal_substr($partial, 5, 2);
476 6657531f Andreas Kohlbecker
    if (preg_match("/[0-9][0-9]/", $month)) {
477
      return $month;
478
    }
479
  }
480 c7f92453 Andreas Kohlbecker
  return '';
481 6657531f Andreas Kohlbecker
}
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 d0e8e73c Andreas Kohlbecker
    $day = drupal_substr($partial, 8, 2);
499 6657531f Andreas Kohlbecker
    if (preg_match("/[0-9][0-9]/", $day)) {
500
      return $day;
501
    }
502
  }
503 c7f92453 Andreas Kohlbecker
  return '';
504 6657531f Andreas Kohlbecker
}
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 fe2edf33 Andreas Kohlbecker
 * @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 6657531f Andreas Kohlbecker
 *
528
 * @return string
529
 *   YYYY-MM-DD formatted year, month, day.
530
 */
531 fe2edf33 Andreas Kohlbecker
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
532
533
  $y = NULL; $m = NULL; $d = NULL;
534
535 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'YY') !== FALSE){
536 fe2edf33 Andreas Kohlbecker
    $y = partialToYear($partial);
537
  }
538 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'MM') !== FALSE){
539 fe2edf33 Andreas Kohlbecker
    $m = partialToMonth($partial);
540
  }
541 8dfe695c Andreas Kohlbecker
  if(strpos($format, 'DD') !== FALSE){
542 fe2edf33 Andreas Kohlbecker
    $d = partialToDay($partial);
543
  }
544 6657531f Andreas Kohlbecker
545 ef6a4ce9 Andreas Kohlbecker
  $y = $y ? $y : '0000';
546 6657531f Andreas Kohlbecker
  $m = $m ? $m : '00';
547
  $d = $d ? $d : '00';
548
549
  $date = '';
550
551 ef6a4ce9 Andreas Kohlbecker
  if ($y == '0000' && $stripZeros && $m == '00' && $d == '00') {
552 c7f92453 Andreas Kohlbecker
    return '';
553 6657531f Andreas Kohlbecker
  }
554
  else {
555
    $date = $y;
556
  }
557
558 ef6a4ce9 Andreas Kohlbecker
  if ($m == '00' && $stripZeros && $d == '00') {
559 6657531f Andreas Kohlbecker
    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 fe2edf33 Andreas Kohlbecker
 * @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 6657531f Andreas Kohlbecker
 *
589
 * @return string
590
 *   Returns a date in the form of a string.
591
 */
592 fe2edf33 Andreas Kohlbecker
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
593 6657531f Andreas Kohlbecker
  $dateString = '';
594 0a288588 Andreas Kohlbecker
  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 c0223d83 Andreas Kohlbecker
      $end_str = partialToDate($period->end, $stripZeros, $format);
602 d0e8e73c Andreas Kohlbecker
      $dateString .= ($dateString && $end_str ? ' ' . t('to') . ' ' : '') . $end_str;
603 0a288588 Andreas Kohlbecker
    }
604 6657531f Andreas Kohlbecker
  }
605
  return $dateString;
606
}
607 fe2edf33 Andreas Kohlbecker
608 c2486c6b Andreas Kohlbecker
/**
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 6657531f Andreas Kohlbecker
635
/**
636 42f2e1e0 Andreas Kohlbecker
 * Composes a absolute CDM web service URI with parameters and querystring.
637 6657531f Andreas Kohlbecker
 *
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_url($uri_pattern, $pathParameters = array(), $query = NULL) {
650
  if (empty($pathParameters)) {
651
    $pathParameters = array();
652
  }
653
654
  // (1)
655
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
656
  // according element of the $pathParameters array.
657
  static $helperArray = array();
658
  if (isset($pathParameters) && !is_array($pathParameters)) {
659
    $helperArray[0] = $pathParameters;
660
    $pathParameters = $helperArray;
661
  }
662
663
  $i = 0;
664
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
665
    if (count($pathParameters) <= $i) {
666 7cc085da Andreas Kohlbecker
        drupal_set_message(
667
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
668 5213125b Andreas Kohlbecker
            array('@index' => $i, '!uri_pattern' => $uri_pattern )),
669 7cc085da Andreas Kohlbecker
          'error');
670 6657531f Andreas Kohlbecker
      break;
671
    }
672
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
673
    ++$i;
674
  }
675
676
  // (2)
677
  // Append all remaining element of the $pathParameters array as path
678
  // elements.
679
  if (count($pathParameters) > $i) {
680
    // Strip trailing slashes.
681
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
682
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
683
    }
684
    while (count($pathParameters) > $i) {
685
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
686
      ++$i;
687
    }
688
  }
689
690
  // (3)
691
  // Append the query string supplied by $query.
692
  if (isset($query)) {
693
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
694
  }
695
696
  $path = $uri_pattern;
697
698
  $uri = variable_get('cdm_webservice_url', '') . $path;
699
  return $uri;
700
}
701
702
/**
703 5ba85170 Andreas Kohlbecker
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
704
 *     together with a theme name to such a proxy function?
705
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
706
 *     Maybe we want to have two different proxy functions, one with theming and one without?
707 088448e1 Andreas Kohlbecker
 *
708
 * @param string $uri
709
 *     A URI to a CDM Rest service from which to retrieve an object
710 f1f05758 Andreas Kohlbecker
 * @param string|null $hook
711
 *     (optional) The hook name to which the retrieved object should be passed.
712
 *     Hooks can either be a theme_hook() or compose_hook() implementation
713
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
714 088448e1 Andreas Kohlbecker
 *     suitable for drupal_render()
715
 *
716 6657531f Andreas Kohlbecker
 * @todo Please document this function.
717
 * @see http://drupal.org/node/1354
718
 */
719 f1f05758 Andreas Kohlbecker
function proxy_content($uri, $hook = NULL) {
720 2ebf0428 Andreas Kohlbecker
721 6657531f Andreas Kohlbecker
  $args = func_get_args();
722 104dde69 Andreas Kohlbecker
  $do_gzip = function_exists('gzencode');
723 6657531f Andreas Kohlbecker
  $uriEncoded = array_shift($args);
724
  $uri = urldecode($uriEncoded);
725 f1f05758 Andreas Kohlbecker
  $hook = array_shift($args);
726 2ebf0428 Andreas Kohlbecker
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
727
728 68ab2885 Andreas Kohlbecker
  $post_data = null;
729
730 2ebf0428 Andreas Kohlbecker
  if ($request_method == "POST" || $request_method == "PUT") {
731
    // read response body via inputstream module
732
    $post_data = file_get_contents("php://input");
733
  }
734 6657531f Andreas Kohlbecker
735
  // Find and deserialize arrays.
736
  foreach ($args as &$arg) {
737
    // FIXME use regex to find serialized arrays.
738 2ebf0428 Andreas Kohlbecker
    //       or should we accept json instead of php serializations?
739 6657531f Andreas Kohlbecker
    if (strpos($arg, "a:") === 0) {
740
      $arg = unserialize($arg);
741
    }
742
  }
743
744 2ebf0428 Andreas Kohlbecker
  // In all these cases perform a simple get request.
745
  // TODO reconsider caching logic in this function.
746 6657531f Andreas Kohlbecker
747 2ebf0428 Andreas Kohlbecker
  if (empty($hook)) {
748
    // simply return the webservice response
749
    // Print out JSON, the cache cannot be used since it contains objects.
750
    $http_response = cdm_http_request($uri, $request_method, $post_data);
751
    if (isset($http_response->headers)) {
752
      foreach ($http_response->headers as $hname => $hvalue) {
753
        drupal_add_http_header($hname, $hvalue);
754 088448e1 Andreas Kohlbecker
      }
755 2ebf0428 Andreas Kohlbecker
    }
756
    if (isset($http_response->data)) {
757
      print $http_response->data;
758
      flush();
759
    }
760
    exit(); // leave drupal here
761
  } else {
762
    // $hook has been supplied
763 34a67c62 Andreas Kohlbecker
    // handle $hook either as compose or theme hook
764
    // pass through theme or compose hook
765 0af3ce28 Andreas Kohlbecker
    // compose hooks can be called without data, therefore
766
    // passing the $uri in this case is not always a requirement
767 2ebf0428 Andreas Kohlbecker
768 0af3ce28 Andreas Kohlbecker
    if($uri && $uri != 'NULL') {
769 2ebf0428 Andreas Kohlbecker
    // do a security check since the $uri will be passed
770
    // as absolute URI to cdm_ws_get()
771 0af3ce28 Andreas Kohlbecker
      if (!_is_cdm_ws_uri($uri)) {
772
        drupal_set_message(
773
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
774
          'error'
775
        );
776
        return '';
777
      }
778 088448e1 Andreas Kohlbecker
779 0af3ce28 Andreas Kohlbecker
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
780
    } else {
781
      $obj = NULL;
782
    }
783 2fe78f3c Andreas Kohlbecker
784 2ebf0428 Andreas Kohlbecker
    $reponse_data = NULL;
785 5b3d713e Andreas Kohlbecker
786 2ebf0428 Andreas Kohlbecker
    if (function_exists('compose_' . $hook)){
787
      // call compose hook
788
789
      $elements =  call_user_func('compose_' . $hook, $obj);
790
      // pass the render array to drupal_render()
791
      $reponse_data = drupal_render($elements);
792
    } else {
793
      // call theme hook
794
795
      // TODO use theme registry to get the registered hook info and
796
      //    use these defaults
797
      switch($hook) {
798
        case 'cdm_taxontree':
799
          $variables = array(
800 9c9d11f7 Andreas Kohlbecker
            'tree' => $obj,
801
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
802
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
803
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
804
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
805
            );
806 2ebf0428 Andreas Kohlbecker
          $reponse_data = theme($hook, $variables);
807
          break;
808
809 9c9d11f7 Andreas Kohlbecker
        case 'cdm_list_of_taxa':
810
            $variables = array(
811
              'records' => $obj,
812
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
813
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
814
            $reponse_data = theme($hook, $variables);
815
            break;
816
817 2ebf0428 Andreas Kohlbecker
        case 'cdm_media_caption':
818 cf4b9055 Andreas Kohlbecker
          $variables = $arg;
819
          $variables['media'] = $obj;
820
821 2ebf0428 Andreas Kohlbecker
          $reponse_data = theme($hook, $variables);
822
          break;
823
824
        default:
825
          drupal_set_message(t(
826 9c9d11f7 Andreas Kohlbecker
          'Theme !theme is not yet supported by the function !function.', array(
827 2ebf0428 Andreas Kohlbecker
          '!theme' => $hook,
828
          '!function' => __FUNCTION__,
829
          )), 'error');
830
          break;
831
      } // END of theme hook switch
832
    } // END of tread as theme hook
833
834
835
    if($do_gzip){
836
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
837
      drupal_add_http_header('Content-Encoding', 'gzip');
838
    }
839
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
840
    drupal_add_http_header('Content-Length', strlen($reponse_data));
841
842
    print $reponse_data;
843
  } // END of handle $hook either as compose ot theme hook
844 5b3d713e Andreas Kohlbecker
845 6657531f Andreas Kohlbecker
}
846
847
/**
848
 * @todo Please document this function.
849
 * @see http://drupal.org/node/1354
850
 */
851
function setvalue_session() {
852
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
853 0af3ce28 Andreas Kohlbecker
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
854
    $var_keys = explode('][', $var_keys);
855 6657531f Andreas Kohlbecker
  }
856
  else {
857
    return;
858
  }
859 1d69a96c Andreas Kohlbecker
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
860 6657531f Andreas Kohlbecker
861
  // Prevent from malicous tags.
862
  $val = strip_tags($val);
863
864 0af3ce28 Andreas Kohlbecker
  $session_var = &$_SESSION;
865
  //$i = 0;
866
  foreach ($var_keys as $key) {
867
    // $hasMoreKeys = ++$i < count($session);
868
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
869
      $session_var[$key] = array();
870 6657531f Andreas Kohlbecker
    }
871 0af3ce28 Andreas Kohlbecker
    $session_var = &$session_var[$key];
872 6657531f Andreas Kohlbecker
  }
873 0af3ce28 Andreas Kohlbecker
  $session_var = $val;
874 6657531f Andreas Kohlbecker
  if (isset($_REQUEST['destination'])) {
875
    drupal_goto($_REQUEST['destination']);
876
  }
877
}
878
879
/**
880
 * @todo Please document this function.
881
 * @see http://drupal.org/node/1354
882
 */
883
function uri_uriByProxy($uri, $theme = FALSE) {
884
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
885
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
886
}
887
888
/**
889 42f2e1e0 Andreas Kohlbecker
 * Composes the the absolute REST service URI to the annotations pager
890
 * for the given CDM entity.
891
 *
892
 * NOTE: Not all CDM Base types are yet supported.
893
 *
894 0e617798 Andreas Kohlbecker
 * @param $cdm_entity
895 42f2e1e0 Andreas Kohlbecker
 *   The CDM entity to construct the annotations pager uri for
896 6657531f Andreas Kohlbecker
 */
897 0e617798 Andreas Kohlbecker
function cdm_compose_annotations_uri($cdm_entity) {
898
899
  $cdm_entity_type = $cdm_entity->class;
900
901
  if($cdm_entity_type == 'DerivedUnitFacade'){
902
    // TODO we may want to implement a derivedUnitFacade/{uuid}/annotations service and use that instead
903
    $cdm_entity_type = $cdm_entity->fieldUnitEntityReference->type;
904
    $cdm_entity_uuid = $cdm_entity->fieldUnitEntityReference->uuid;
905 991ae630 Andreas Kohlbecker
  } elseif ($cdm_entity_type == 'TypedEntityReference'){
906
    $cdm_entity_type = $cdm_entity->type;
907
    $cdm_entity_uuid = $cdm_entity->uuid;
908 0e617798 Andreas Kohlbecker
  } else {
909
    if (isset($cdm_entity->uuid)) {
910
      $cdm_entity_uuid = $cdm_entity->uuid;
911
    }
912
  }
913 afe99f4d Andreas Kohlbecker
914 0e617798 Andreas Kohlbecker
  if(!$cdm_entity_uuid){
915
    // silently give up
916 6657531f Andreas Kohlbecker
    return;
917
  }
918
919 0e617798 Andreas Kohlbecker
  $ws_base_uri = cdm_ws_base_uri($cdm_entity_type);
920 afe99f4d Andreas Kohlbecker
921
  if($ws_base_uri === null){
922 0e617798 Andreas Kohlbecker
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdm_entity_type), E_USER_ERROR);
923 afe99f4d Andreas Kohlbecker
  }
924
  return cdm_compose_url($ws_base_uri, array(
925 0e617798 Andreas Kohlbecker
    $cdm_entity_uuid,
926 afe99f4d Andreas Kohlbecker
    'annotations',
927
  ));
928
}
929
930
/**
931
 * Provides the base URI of the cdm REST service responsible for the passed simple name
932
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
933
 *
934
 * @param $cdm_type_simple
935
 *    simple name of a CDM java class
936
 * @return null|string
937
 */
938
function cdm_ws_base_uri($cdm_type_simple)
939
{
940 6657531f Andreas Kohlbecker
  $ws_base_uri = NULL;
941 afe99f4d Andreas Kohlbecker
  switch ($cdm_type_simple) {
942 178d1ae6 Andreas Kohlbecker
943
    case 'TaxonNode':
944 64cfdac1 Andreas Kohlbecker
    case 'TaxonNodeDto':
945 178d1ae6 Andreas Kohlbecker
      $ws_base_uri = CDM_WS_TAXONNODE;
946 6657531f Andreas Kohlbecker
    case 'TaxonBase':
947
    case 'Taxon':
948
    case 'Synonym':
949
      $ws_base_uri = CDM_WS_TAXON;
950
      break;
951
952 b20f6a5f Andreas Kohlbecker
    case 'TaxonName':
953 6657531f Andreas Kohlbecker
      $ws_base_uri = CDM_WS_NAME;
954
      break;
955
956
    case 'Media':
957
      $ws_base_uri = CDM_WS_MEDIA;
958
      break;
959
960
    case 'Reference':
961
      $ws_base_uri = CDM_WS_REFERENCE;
962
      break;
963
964 5213125b Andreas Kohlbecker
    case 'Registration':
965
      $ws_base_uri = CDM_WS_REFERENCE;
966
      break;
967
968
    case 'FieldUnit':
969
    case 'DerivedUnit':
970
    case 'DnaSample':
971
    case 'MediaSpecimen':
972
      $ws_base_uri = CDM_WS_OCCURRENCE;
973
      break;
974
975
    case 'Amplification':
976
    case 'DerivationEvent':
977
    case 'DeterminationEvent':
978
    case 'GatheringEvent':
979
    case 'MaterialOrMethodEvent':
980
    case 'SingleRead':
981
      $ws_base_uri = CDM_WS_EVENTBASE;
982
      break;
983
984 6657531f Andreas Kohlbecker
    case 'Distribution':
985
    case 'TextData':
986
    case 'TaxonInteraction':
987
    case 'QuantitativeData':
988
    case 'IndividualsAssociation':
989
    case 'CommonTaxonName':
990
    case 'CategoricalData':
991
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
992
      break;
993
994 e2617c7e Andreas Kohlbecker
    case 'Person':
995
    case 'Team':
996
    case 'AgentBase':
997
      $ws_base_uri = CDM_WS_AGENT;
998
      break;
999
1000 6657531f Andreas Kohlbecker
    case 'PolytomousKey':
1001
    case 'MediaKey':
1002
    case 'MultiAccessKey':
1003 afe99f4d Andreas Kohlbecker
      $ws_base_uri = $cdm_type_simple;
1004 6657531f Andreas Kohlbecker
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1005
      break;
1006
1007 2d95e99f Andreas Kohlbecker
    case 'TextualTypeDesignation':
1008
    case 'SpecimenTypeDesignation':
1009
    case 'NameTypeDesignation':
1010
      $ws_base_uri = CDM_WS_TYPEDESIGNATION;
1011
      break;
1012 6657531f Andreas Kohlbecker
    default:
1013 afe99f4d Andreas Kohlbecker
      $ws_base_uri = null;
1014 5213125b Andreas Kohlbecker
      drupal_set_message(
1015
        t('cdm_ws_base_uri()  - cdm type name "@cdm_type_simple" unsupported',
1016
          array('@cdm_type_simple' => $cdm_type_simple )),
1017
        'error');
1018 6657531f Andreas Kohlbecker
  }
1019 afe99f4d Andreas Kohlbecker
  return $ws_base_uri;
1020 6657531f Andreas Kohlbecker
}
1021
1022
/**
1023
 * Enter description here...
1024
 *
1025 a6c4c53c Andreas Kohlbecker
 * @param string $resource_uri
1026
 * @param int $page_size
1027 b5dca1e2 Andreas Kohlbecker
 *   The maximum number of entities returned per page.
1028
 *   The default page size as configured in the cdm server
1029
 *   will be used if set to NULL
1030 6657531f Andreas Kohlbecker
 *   to return all entities in a single page).
1031 a6c4c53c Andreas Kohlbecker
 * @param int $page_index
1032 6657531f Andreas Kohlbecker
 *   The number of the page to be returned, the first page has the
1033 a6c4c53c Andreas Kohlbecker
 *   page_index = 0
1034 2ebf0428 Andreas Kohlbecker
 * @param array $query
1035
 *   A array holding the HTTP request query parameters for the request
1036
 * @param string $method
1037
 *   The HTTP method to use, valid values are "GET" or "POST"
1038 a6c4c53c Andreas Kohlbecker
 * @param bool $absolute_uri
1039 42f2e1e0 Andreas Kohlbecker
 *   TRUE when the URL should be treated as absolute URL.
1040 2ebf0428 Andreas Kohlbecker
 *
1041 fb308159 Andreas Kohlbecker
 * @return object
1042
 *   A CDM Pager object
1043 6657531f Andreas Kohlbecker
 *
1044
 */
1045 a6c4c53c Andreas Kohlbecker
function cdm_ws_page($resource_uri, $page_size, $page_index, array $query = array(), $method = 'GET', $absolute_uri = FALSE) {
1046
1047
  $query['page_index'] = $page_index;
1048
  $query['page_size'] = $page_size;
1049
1050
  $pager = cdm_ws_get($resource_uri, NULL, queryString($query), $method, $absolute_uri);
1051
  if(is_array($pager)){
1052 3a81b245 Andreas Kohlbecker
    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);
1053 a6c4c53c Andreas Kohlbecker
    $records = $pager;
1054
    $pager = new stdClass();
1055
    $pager->records = $records;
1056
    $pager->count = count($records);
1057
    $pager->pageSize = $pager->count;
1058
    $pager->nextIndex = null;
1059
  }
1060
  return $pager;
1061 6657531f Andreas Kohlbecker
}
1062
1063 fb308159 Andreas Kohlbecker
1064
/**
1065
 * Sends a http GET request to the generic page method which allows for filtering entities by Restrictions.
1066
 *
1067
 * @param $cdm_entity_type
1068 e2617c7e Andreas Kohlbecker
 * @param $class_restriction
1069
 *   Optional param to narrow down polymorph types to a specific type.
1070 fb308159 Andreas Kohlbecker
 * @param array $restrictions
1071
 *   An array of Restriction objects
1072
 * @param array $init_strategy
1073
 *   The init strategy to initialize the entity beans while being loaded from the
1074
 *   persistent storage by the cdm
1075
 * @param int $page_size
1076
 *   The maximum number of entities returned per page.
1077
 *   The default page size as configured in the cdm server
1078
 *   will be used if set to NULL
1079
 *   to return all entities in a single page).
1080
 * @param int $page_index
1081
 *   The number of the page to be returned, the first page has the
1082
 *   pageNumber = 0
1083
 *
1084
 * @return object
1085
 *   A CDM Pager object
1086
 */
1087 e2617c7e Andreas Kohlbecker
function cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy, $page_size, $page_index) {
1088 fb308159 Andreas Kohlbecker
1089
  $restrictions_json = array(); // json_encode($restrictions);
1090
  foreach ($restrictions as $restr){
1091
    $restrictions_json[] = json_encode($restr);
1092
  }
1093 e2617c7e Andreas Kohlbecker
  $filter_parameters = [
1094
    'restriction' => $restrictions_json,
1095
    'initStrategy' => $init_strategy
1096
  ];
1097
  if($class_restriction){
1098
    $filter_parameters['class'] = $class_restriction;
1099
  }
1100
1101 fb308159 Andreas Kohlbecker
  return cdm_ws_page(
1102
      'portal/' . cdm_ws_base_uri($cdm_entity_type),
1103
      $page_size,
1104
      $page_index,
1105 e2617c7e Andreas Kohlbecker
    $filter_parameters,
1106
    "GET"
1107 fb308159 Andreas Kohlbecker
    );
1108
}
1109
1110 b5dca1e2 Andreas Kohlbecker
/**
1111 fb308159 Andreas Kohlbecker
 * Fetches all entities returned by the the generic page method for the Restrictions applied as filter.
1112
 *
1113
 * @param $cdm_entity_type
1114 e2617c7e Andreas Kohlbecker
 * @param $class_restriction
1115
 *   Optional param to narrow down polymorph types to a specific type.
1116 fb308159 Andreas Kohlbecker
 * @param array $restrictions
1117
 *   An array of Restriction objects
1118
 * @param array $init_strategy
1119
 *   The init strategy to initialize the entity beans while being loaded from the
1120
 *   persistent storage by the cdm
1121
 *
1122
 * @return array
1123
 *   A array of CDM entities
1124
 */
1125 e2617c7e Andreas Kohlbecker
function cdm_ws_fetch_all_by_restriction($cdm_entity_type, $class_restriction, array $restrictions, array $init_strategy){
1126 fb308159 Andreas Kohlbecker
  $page_index = 0;
1127
  // using a bigger page size to avoid to many multiple requests
1128
  $page_size = 500;
1129
  $entities = array();
1130
1131
  while ($page_index !== FALSE && $page_index < 1){
1132 e2617c7e Andreas Kohlbecker
    $pager =  cdm_ws_page_by_restriction($cdm_entity_type, $class_restriction, $restrictions, $init_strategy, $page_size, $page_index);
1133 fb308159 Andreas Kohlbecker
    if(isset($pager->records) && is_array($pager->records)) {
1134
      $entities = array_merge($entities, $pager->records);
1135
      if(!empty($pager->nextIndex)){
1136
        $page_index = $pager->nextIndex;
1137
      } else {
1138
        $page_index = FALSE;
1139
      }
1140
    } else {
1141
      $page_index = FALSE;
1142
    }
1143
  }
1144
  return $entities;
1145
}
1146
1147
1148
  /**
1149 b5dca1e2 Andreas Kohlbecker
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1150
 *
1151
 * @param string $resourceURI
1152 2ebf0428 Andreas Kohlbecker
 * @param array $query
1153
 *   A array holding the HTTP request query parameters for the request
1154
 * @param string $method
1155
 *   The HTTP method to use, valid values are "GET" or "POST";
1156 42f2e1e0 Andreas Kohlbecker
 * @param bool $absoluteURI
1157
 *   TRUE when the URL should be treated as absolute URL.
1158 b5dca1e2 Andreas Kohlbecker
 *
1159
 * @return array
1160
 *     A list of CDM entitites
1161
 *
1162
 */
1163 2ebf0428 Andreas Kohlbecker
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1164 b5dca1e2 Andreas Kohlbecker
  $page_index = 0;
1165 0b6d2193 Andreas Kohlbecker
  // using a bigger page size to avoid too many multiple requests
1166 f9da0eb9 Andreas Kohlbecker
  $page_size = 500;
1167 0b6d2193 Andreas Kohlbecker
  $entities = [];
1168 b5dca1e2 Andreas Kohlbecker
1169
  while ($page_index !== FALSE){
1170 2ebf0428 Andreas Kohlbecker
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1171 b5dca1e2 Andreas Kohlbecker
    if(isset($pager->records) && is_array($pager->records)) {
1172 dc66315d Andreas Kohlbecker
      $entities = array_merge($entities, $pager->records);
1173 b5dca1e2 Andreas Kohlbecker
      if(!empty($pager->nextIndex)){
1174
        $page_index = $pager->nextIndex;
1175
      } else {
1176
        $page_index = FALSE;
1177
      }
1178
    } else {
1179
      $page_index = FALSE;
1180
    }
1181
  }
1182
  return $entities;
1183
}
1184
1185 6657531f Andreas Kohlbecker
/*
1186
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1187
  $viewrank = _cdm_taxonomy_compose_viewrank();
1188
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1189
  ? '/' . $path : '') ;
1190
}
1191
*/
1192
1193
/**
1194
 * @todo Enter description here...
1195
 *
1196 50172c55 Andreas Kohlbecker
 * @param string $taxon_uuid
1197
 *  The UUID of a cdm taxon instance
1198
 * @param string $ignore_rank_limit
1199
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1200 6657531f Andreas Kohlbecker
 *
1201 aaa81689 Andreas Kohlbecker
 * @return string
1202
 *   A cdm REST service URL path to a Classification
1203 6657531f Andreas Kohlbecker
 */
1204 50172c55 Andreas Kohlbecker
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1205
1206 7663cd0b Andreas Kohlbecker
  $view_uuid = get_current_classification_uuid();
1207 50172c55 Andreas Kohlbecker
  $rank_uuid = NULL;
1208
  if (!$ignore_rank_limit) {
1209 aaa81689 Andreas Kohlbecker
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1210 50172c55 Andreas Kohlbecker
  }
1211 6657531f Andreas Kohlbecker
1212 50172c55 Andreas Kohlbecker
  if (!empty($taxon_uuid)) {
1213 6657531f Andreas Kohlbecker
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1214 50172c55 Andreas Kohlbecker
      $view_uuid,
1215
      $taxon_uuid,
1216 6657531f Andreas Kohlbecker
    ));
1217
  }
1218
  else {
1219 aaa81689 Andreas Kohlbecker
    if (is_uuid($rank_uuid)) {
1220 6657531f Andreas Kohlbecker
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1221 50172c55 Andreas Kohlbecker
        $view_uuid,
1222
        $rank_uuid,
1223 6657531f Andreas Kohlbecker
      ));
1224
    }
1225
    else {
1226 50172c55 Andreas Kohlbecker
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1227
        $view_uuid,
1228 6657531f Andreas Kohlbecker
      ));
1229
    }
1230
  }
1231
}
1232
1233
/**
1234 50172c55 Andreas Kohlbecker
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1235
 *
1236
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1237
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1238
 *
1239
 * Operates in two modes depending on whether the parameter
1240
 * $taxon_uuid is set or NULL.
1241
 *
1242
 * A) $taxon_uuid = NULL:
1243
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1244
 *  2. otherwise return the default classification as defined by the admin via the settings
1245
 *
1246
 * b) $taxon_uuid is set:
1247
 *   return the classification to whcih the taxon belongs to.
1248
 *
1249
 * @param UUID $taxon_uuid
1250
 *   The UUID of a cdm taxon instance
1251 6657531f Andreas Kohlbecker
 */
1252 50172c55 Andreas Kohlbecker
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1253 6657531f Andreas Kohlbecker
1254 50172c55 Andreas Kohlbecker
    $response = NULL;
1255 6657531f Andreas Kohlbecker
1256 50172c55 Andreas Kohlbecker
    // 1st try
1257 2ebf0428 Andreas Kohlbecker
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1258 50172c55 Andreas Kohlbecker
1259
    if ($response == NULL) {
1260
      // 2dn try by ignoring the rank limit
1261 2ebf0428 Andreas Kohlbecker
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1262 6657531f Andreas Kohlbecker
    }
1263 50172c55 Andreas Kohlbecker
1264
    if ($response == NULL) {
1265
      // 3rd try, last fallback:
1266
      //    return the default classification
1267
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1268
        // Delete the session value and try again with the default.
1269
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1270 795fcdb3 Andreas Kohlbecker
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1271 50172c55 Andreas Kohlbecker
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1272
      }
1273
      else {
1274
        // Check if taxonomictree_uuid is valid.
1275 a50c8468 Andreas Kohlbecker
        // expecting an array of taxonNodes,
1276
        // empty classifications are ok so no warning in this case!
1277 2ebf0428 Andreas Kohlbecker
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1278 a50c8468 Andreas Kohlbecker
        if (!is_array($test)) {
1279 50172c55 Andreas Kohlbecker
          // The default set by the admin seems to be invalid or is not even set.
1280
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1281
        }
1282 a50c8468 Andreas Kohlbecker
        if (count($test) == 0) {
1283
          // The default set by the admin seems to be invalid or is not even set.
1284
          drupal_set_message("The chosen classification is empty.", 'status');
1285
        }
1286 6657531f Andreas Kohlbecker
      }
1287
    }
1288
1289
  return $response;
1290
}
1291
1292
/**
1293 aaa81689 Andreas Kohlbecker
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1294
 * 
1295
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1296
 * variable is set.
1297 6657531f Andreas Kohlbecker
 *
1298 50172c55 Andreas Kohlbecker
 * @param string $taxon_uuid
1299 6657531f Andreas Kohlbecker
 *
1300 eb9fdcf7 Andreas Kohlbecker
 * @return array
1301 aaa81689 Andreas Kohlbecker
 *   An array of CDM TaxonNodeDTO objects
1302 6657531f Andreas Kohlbecker
 */
1303 50172c55 Andreas Kohlbecker
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1304 7663cd0b Andreas Kohlbecker
  $view_uuid = get_current_classification_uuid();
1305 aaa81689 Andreas Kohlbecker
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1306 6657531f Andreas Kohlbecker
1307
  $response = NULL;
1308 aaa81689 Andreas Kohlbecker
  if (is_uuid($rank_uuid)) {
1309 6657531f Andreas Kohlbecker
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1310 50172c55 Andreas Kohlbecker
      $view_uuid,
1311
      $taxon_uuid,
1312
      $rank_uuid,
1313 6657531f Andreas Kohlbecker
    ));
1314
  }
1315
  else {
1316
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1317 50172c55 Andreas Kohlbecker
      $view_uuid,
1318
      $taxon_uuid,
1319 6657531f Andreas Kohlbecker
    ));
1320
  }
1321
1322
  if ($response == NULL) {
1323
    // Error handing.
1324 0af3ce28 Andreas Kohlbecker
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1325
//      // Delete the session value and try again with the default.
1326
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1327
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1328
//    }
1329
//    else {
1330 6657531f Andreas Kohlbecker
      // Check if taxonomictree_uuid is valid.
1331 2ebf0428 Andreas Kohlbecker
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1332 6657531f Andreas Kohlbecker
      if ($test == NULL) {
1333
        // The default set by the admin seems to be invalid or is not even set.
1334
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1335
      }
1336 0af3ce28 Andreas Kohlbecker
//    }
1337 6657531f Andreas Kohlbecker
  }
1338
1339
  return $response;
1340
}
1341
1342 d8e85b2d Andreas Kohlbecker
1343
// =============================Terms and Vocabularies ========================================= //
1344 6657531f Andreas Kohlbecker
1345
/**
1346 0686f307 Andreas Kohlbecker
 * Returns the localized representation for the given term.
1347 6657531f Andreas Kohlbecker
 *
1348
 * @param Object $definedTermBase
1349
 * 	  of cdm type DefinedTermBase
1350
 * @return string
1351
 * 	  the localized representation_L10n of the term,
1352
 *    otherwise the titleCache as fall back,
1353 28c5c87a Andreas Kohlbecker
 *    otherwise the default_representation which defaults to an empty string
1354 6657531f Andreas Kohlbecker
 */
1355 28c5c87a Andreas Kohlbecker
function cdm_term_representation($definedTermBase, $default_representation = '') {
1356 6657531f Andreas Kohlbecker
  if ( isset($definedTermBase->representation_L10n) ) {
1357
    return $definedTermBase->representation_L10n;
1358
  } elseif ( isset($definedTermBase->titleCache)) {
1359
    return $definedTermBase->titleCache;
1360
  }
1361 28c5c87a Andreas Kohlbecker
  return $default_representation;
1362 6657531f Andreas Kohlbecker
}
1363
1364 0686f307 Andreas Kohlbecker
/**
1365
 * Returns the abbreviated localized representation for the given term.
1366
 *
1367
 * @param Object $definedTermBase
1368
 * 	  of cdm type DefinedTermBase
1369
 * @return string
1370
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1371
 *    if this representation is not available the function delegates the
1372
 *    call to cdm_term_representation()
1373
 */
1374
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1375
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1376
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1377
  } else {
1378
    cdm_term_representation($definedTermBase, $default_representation);
1379
  }
1380
}
1381
1382 d8e85b2d Andreas Kohlbecker
/**
1383
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1384
 *
1385
 * The options array is suitable for drupal form API elements that allow multiple choices.
1386
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1387
 *
1388
 * @param array $terms
1389
 *   a list of CDM DefinedTermBase instances
1390
 *
1391
 * @param $term_label_callback
1392
 *   A callback function to override the term representations
1393
 *
1394 a6ae799b Andreas Kohlbecker
 * @param bool $empty_option
1395
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1396
 *
1397 d8e85b2d Andreas Kohlbecker
 * @return array
1398 ef686dd8 Andreas Kohlbecker
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1399
1400 d8e85b2d Andreas Kohlbecker
 */
1401 a6ae799b Andreas Kohlbecker
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1402 d8e85b2d Andreas Kohlbecker
  $options = array();
1403 7ca5ef1e Andreas Kohlbecker
  if(isset($terms) && is_array($terms)) {
1404
    foreach ($terms as $term) {
1405 d8e85b2d Andreas Kohlbecker
      if ($term_label_callback && function_exists($term_label_callback)) {
1406
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1407
      } else {
1408
        //TODO use cdm_term_representation() here?
1409 7cc085da Andreas Kohlbecker
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1410 d8e85b2d Andreas Kohlbecker
      }
1411
    }
1412
  }
1413
1414 a6ae799b Andreas Kohlbecker
  if($empty_option !== FALSE){
1415
    array_unshift ($options, "");
1416
  }
1417
1418 d8e85b2d Andreas Kohlbecker
  return $options;
1419
}
1420
1421
/**
1422 7ca5ef1e Andreas Kohlbecker
 * Creates and array of options for drupal select form elements.
1423
 *
1424
 * @param $vocabulary_uuid
1425
 *   The UUID of the CDM Term Vocabulary
1426
 * @param $term_label_callback
1427
 *   An optional call back function which can be used to modify the term label
1428 a6ae799b Andreas Kohlbecker
 * @param bool $empty_option
1429 7ca5ef1e Andreas Kohlbecker
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1430 efa372e9 Andreas Kohlbecker
 * @param array $include_filter
1431
 *   An associative array consisting of a field name an regular expression. All term matching
1432
 *   these filter are included. The value of the field is converted to a String by var_export()
1433
 *   so a boolean 'true' can be matched by '/true/'
1434
 * @param string $order_by
1435 7ca5ef1e Andreas Kohlbecker
 *   One of the order by constants defined in this file
1436 ef686dd8 Andreas Kohlbecker
 * @return array
1437
 *   the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1438 d8e85b2d Andreas Kohlbecker
 */
1439 a6ae799b Andreas Kohlbecker
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1440 efa372e9 Andreas Kohlbecker
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1441
1442 d8e85b2d Andreas Kohlbecker
  static $vocabularyOptions = array();
1443
1444 7ca5ef1e Andreas Kohlbecker
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1445
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1446
      array(
1447
        'orderBy' => $order_by
1448
      )
1449
    );
1450 efa372e9 Andreas Kohlbecker
1451
    // apply the include filter
1452
    if($include_filter != null){
1453
      $included_terms = array();
1454
1455
      foreach ($terms as $term){
1456
        $include = true;
1457
        foreach ($include_filter as $field=>$regex){
1458
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1459
          if(!$include){
1460
            break;
1461
          }
1462
        }
1463
        if($include){
1464
          $included_terms[] = $term;
1465
        }
1466
      }
1467
1468
      $terms = $included_terms;
1469
    }
1470
1471
    // make options list
1472 a6ae799b Andreas Kohlbecker
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1473 d8e85b2d Andreas Kohlbecker
  }
1474 f5bc56a0 Andreas Kohlbecker
1475 7ca5ef1e Andreas Kohlbecker
  $options = $vocabularyOptions[$vocabulary_uuid];
1476 a6ae799b Andreas Kohlbecker
1477 f5bc56a0 Andreas Kohlbecker
  return $options;
1478 d8e85b2d Andreas Kohlbecker
}
1479
1480 85669a85 Andreas Kohlbecker
/**
1481
 * Creates and array of defaults for drupal select form elements.
1482
 *
1483
 * @param $vocabulary_uuid
1484
 *   The UUID of the CDM Term Vocabulary
1485
 * @param $term_label_callback
1486
 *   An optional call back function which can be used to modify the term label
1487
 * @param bool $empty_option
1488
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1489
 * @param array $include_filter
1490
 *   An associative array consisting of a field name an regular expression. All term matching
1491
 *   these filter are included. The value of the field is converted to a String by var_export()
1492
 *   so a boolean 'true' can be matched by '/true/'
1493
 * @param string $order_by
1494
 *   One of the order by constants defined in this file
1495
 * @return array
1496
 *   the terms in an array (key: uuid => value: uuid) as defaults for a form element that allows multiple choices.
1497
 */
1498
function cdm_vocabulary_as_defaults($vocabulary_uuid, array $include_filter = null) {
1499
1500
  $options = cdm_vocabulary_as_option($vocabulary_uuid, null, null, $include_filter);
1501
  $defaults = array();
1502
  foreach ($options as $uuid => $value){
1503
    $defaults[$uuid] = $uuid;
1504
  }
1505
1506
  return $defaults;
1507
}
1508
1509 d8e85b2d Andreas Kohlbecker
/**
1510 a6ae799b Andreas Kohlbecker
 * @param $term_type string one of
1511 d8e85b2d Andreas Kohlbecker
 *  - Unknown
1512
 *  - Language
1513
 *  - NamedArea
1514
 *  - Rank
1515
 *  - Feature
1516
 *  - AnnotationType
1517
 *  - MarkerType
1518
 *  - ExtensionType
1519
 *  - DerivationEventType
1520
 *  - PresenceAbsenceTerm
1521
 *  - NomenclaturalStatusType
1522
 *  - NameRelationshipType
1523
 *  - HybridRelationshipType
1524
 *  - SynonymRelationshipType
1525
 *  - TaxonRelationshipType
1526
 *  - NameTypeDesignationStatus
1527
 *  - SpecimenTypeDesignationStatus
1528
 *  - InstitutionType
1529
 *  - NamedAreaType
1530
 *  - NamedAreaLevel
1531
 *  - RightsType
1532
 *  - MeasurementUnit
1533
 *  - StatisticalMeasure
1534
 *  - MaterialOrMethod
1535
 *  - Material
1536
 *  - Method
1537
 *  - Modifier
1538
 *  - Scope
1539
 *  - Stage
1540
 *  - KindOfUnit
1541
 *  - Sex
1542
 *  - ReferenceSystem
1543
 *  - State
1544
 *  - NaturalLanguageTerm
1545
 *  - TextFormat
1546
 *  - DeterminationModifier
1547
 *  - DnaMarker
1548 7ca5ef1e Andreas Kohlbecker
 *
1549
 * @param  $order_by
1550
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1551
 *  possible values:
1552
 *    - CDM_ORDER_BY_ID_ASC
1553
 *    - CDM_ORDER_BY_ID_DESC
1554
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1555
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1556
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1557
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1558 a6ae799b Andreas Kohlbecker
 * @param bool $empty_option
1559
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1560 2d3d6556 Andreas Kohlbecker
 * @return array
1561 ef686dd8 Andreas Kohlbecker
 *    the terms in an array (key: uuid => value: label) as options for a form element that allows multiple choices.
1562 d8e85b2d Andreas Kohlbecker
 */
1563 a6ae799b Andreas Kohlbecker
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1564 7ca5ef1e Andreas Kohlbecker
  $terms = cdm_ws_fetch_all(
1565
    CDM_WS_TERM,
1566
    array(
1567
      'class' => $term_type,
1568
      'orderBy' => $order_by
1569
    )
1570
  );
1571 a6ae799b Andreas Kohlbecker
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1572 d8e85b2d Andreas Kohlbecker
}
1573
1574 dc58a71b Andreas Kohlbecker
/**
1575
 * @param array $none_option
1576
 *    Will add a filter option to search for NULL values
1577
 * @param $with_empty_option
1578
 *    Will add an empty option to the beginning. Choosing this option will disable the filtering.
1579
 * @return array
1580
 *   An array of options with uuids as key and the localized term representation as value
1581
 */
1582
function cdm_type_designation_status_filter_terms_as_options($none_option_label, $with_empty_option = false){
1583
  $filter_terms = cdm_ws_get(CDM_WS_TYPE_DESIGNATION_STATUS_FILTER_TERMS);
1584
1585
  if(isset($filter_terms) && is_array($filter_terms)) {
1586
    foreach ($filter_terms as $filter_term) {
1587
      $options[join(',', $filter_term->uuids)] = $filter_term->label;
1588
    }
1589
  }
1590
1591
  if(is_string($none_option_label)){
1592
    $options = array_merge(array('NULL' => $none_option_label), $options);
1593
  }
1594
1595
  if($with_empty_option !== FALSE){
1596
    array_unshift ($options, "");
1597
  }
1598
1599
1600
  return $options;
1601
}
1602
1603
1604 d8e85b2d Andreas Kohlbecker
1605
/**
1606 cd4f8f20 Andreas Kohlbecker
 * Callback function which provides the localized representation of a cdm term.
1607
 *
1608
 * The representation is build by concatenating the abbreviated label with the label
1609
 * and thus is especially useful for relationship terms
1610
 * The localized representation provided by the cdm can be overwritten by
1611
 * providing a drupal translation.
1612
 *
1613 d8e85b2d Andreas Kohlbecker
 */
1614
function _cdm_relationship_type_term_label_callback($term) {
1615
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1616 7cc085da Andreas Kohlbecker
    return $term->representation_L10n_abbreviatedLabel . ' : '
1617
    . t('@term', array('@term' => $term->representation_L10n));
1618 d8e85b2d Andreas Kohlbecker
  }
1619
else {
1620 7cc085da Andreas Kohlbecker
    return t('@term', array('@term' => $term->representation_L10n));
1621 d8e85b2d Andreas Kohlbecker
  }
1622
}
1623
1624 cd4f8f20 Andreas Kohlbecker
/**
1625
 * Callback function which provides the localized inverse representation of a cdm term.
1626
 *
1627
 * The representation is build by concatenating the abbreviated label with the label
1628
 * and thus is especially useful for relationship terms
1629
 * The localized representation provided by the cdm can be overwritten by
1630
 * providing a drupal translation.
1631
 *
1632
 */
1633
function _cdm_relationship_type_term_inverse_label_callback($term) {
1634
  if (isset($term->inverseRepresentation_L10n_abbreviatedLabel)) {
1635
    return $term->inverseRepresentation_L10n_abbreviatedLabel . ' : '
1636
      . t('@term', array('@term' => $term->inverseRepresentation_L10n));
1637
  }
1638
  else {
1639
    return t('@term', array('@term' => $term->inverseRepresentation_L10n));
1640
  }
1641
}
1642
1643 ef686dd8 Andreas Kohlbecker
/**
1644
 * Returns the localized abbreviated label of the relationship term.
1645
 *
1646
 * In case the abbreviated label is not set the normal representation is returned.
1647
 *
1648
 * @param $term
1649
 * @param bool $is_inverse_relation
1650
 * @return string
1651
 *   The abbreviated label
1652
 */
1653
function cdm_relationship_type_term_abbreviated_label($term, $is_inverse_relation = false){
1654
1655
  if($is_inverse_relation) {
1656
    if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1657
      $abbr_label = $term->inverseResentation_L10n_abbreviatedLabel;
1658
    } else {
1659
      $abbr_label = $term->inverseRepresentation_L10n;
1660
    }
1661
  } else {
1662
    if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1663
      $abbr_label = $term->representation_L10n_abbreviatedLabel;
1664
    } else {
1665
      $abbr_label = $term->representation_L10n;
1666
    }
1667
  }
1668
  return $abbr_label;
1669
}
1670
1671
/**
1672
 * Returns the symbol of the relationship term.
1673
 *
1674
 * In case the symbol is not set the function falls back to use the abbreviated label or
1675
 * the normal representation..
1676
 *
1677
 * @param $term
1678
 * @param bool $is_inverse_relation
1679
 * @return string
1680
 *   The abbreviated label
1681
 */
1682
function cdm_relationship_type_term_symbol($term, $is_inverse_relation = false){
1683
1684
  if($is_inverse_relation) {
1685
    if (isset($term->inverseSymbol) && $term->inverseSymbol) {
1686
      $symbol = $term->inverseSymbol;
1687
    } else if (isset($term->inverseRepresentation_L10n_abbreviatedLabel) && $term->inverseRepresentation_L10n_abbreviatedLabel) {
1688
      $symbol = $term->inverseResentation_L10n_abbreviatedLabel;
1689
    } else {
1690
      $symbol = $term->inverseRepresentation_L10n;
1691
    }
1692
  } else {
1693
    if (isset($term->symbol) && $term->symbol) {
1694
      $symbol = $term->symbol;
1695
    } else if (isset($term->representation_L10n_abbreviatedLabel) && $term->representation_L10n_abbreviatedLabel) {
1696
      $symbol = $term->representation_L10n_abbreviatedLabel;
1697
    } else {
1698
      $symbol = $term->representation_L10n;
1699
    }
1700
  }
1701
  return $symbol;
1702
}
1703
1704 d8e85b2d Andreas Kohlbecker
// ========================================================================================== //
1705 6657531f Andreas Kohlbecker
/**
1706
 * @todo Improve documentation of this function.
1707
 *
1708
 * eu.etaxonomy.cdm.model.description.
1709
 * CategoricalData
1710
 * CommonTaxonName
1711
 * Distribution
1712
 * IndividualsAssociation
1713
 * QuantitativeData
1714
 * TaxonInteraction
1715
 * TextData
1716
 */
1717
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1718
  static $types = array(
1719
    "CategoricalData",
1720
    "CommonTaxonName",
1721
    "Distribution",
1722
    "IndividualsAssociation",
1723
    "QuantitativeData",
1724
    "TaxonInteraction",
1725
    "TextData",
1726
  );
1727
1728
  static $options = NULL;
1729
  if ($options == NULL) {
1730
    $options = array();
1731
    if ($prependEmptyElement) {
1732
      $options[' '] = '';
1733
    }
1734
    foreach ($types as $type) {
1735
      // No internatianalization here since these are purely technical terms.
1736
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1737
    }
1738
  }
1739
  return $options;
1740
}
1741
1742
1743
/**
1744 8cbbc22a Andreas Kohlbecker
 * Fetches all TaxonDescription descriptions elements which are associated to the
1745
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1746 37252893 Andreas Kohlbecker
 * feature tree.
1747
 * @param $feature_tree
1748
 *     The CDM FeatureTree to be used as template
1749
 * @param $taxon_uuid
1750
 *     The UUID of the taxon
1751 092744e1 Andreas Kohlbecker
 * @param $excludes
1752
 *     UUIDs of features to be excluded
1753 6527c2f5 Andreas Kohlbecker
 * @return object
1754 8cbbc22a Andreas Kohlbecker
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1755
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1756
 *     witch will hold the according $descriptionElements.
1757 6657531f Andreas Kohlbecker
 */
1758 092744e1 Andreas Kohlbecker
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1759 37252893 Andreas Kohlbecker
1760
  if (!$feature_tree) {
1761 6657531f Andreas Kohlbecker
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1762
      In order to see the species profiles of your taxa, please select a
1763
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1764
    return FALSE;
1765
  }
1766
1767 092744e1 Andreas Kohlbecker
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1768 37252893 Andreas Kohlbecker
      array(
1769
      'taxon' => $taxon_uuid,
1770 092744e1 Andreas Kohlbecker
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1771 2ebf0428 Andreas Kohlbecker
      ),
1772
      'POST'
1773 37252893 Andreas Kohlbecker
  );
1774 6657531f Andreas Kohlbecker
1775 7508605c Andreas Kohlbecker
  // Combine all descriptions into one feature tree.
1776 092744e1 Andreas Kohlbecker
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1777 fae36a2a Andreas Kohlbecker
  $feature_tree->root->childNodes = $merged_nodes;
1778 6657531f Andreas Kohlbecker
1779 37252893 Andreas Kohlbecker
  return $feature_tree;
1780 6657531f Andreas Kohlbecker
}
1781
1782
/**
1783 a6c4c53c Andreas Kohlbecker
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdm_entity.
1784 4a15731a Andreas Kohlbecker
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1785
 * be requested for the annotations.
1786 6657531f Andreas Kohlbecker
 *
1787 a6c4c53c Andreas Kohlbecker
 * @param string $cdm_entity
1788 6657531f Andreas Kohlbecker
 *   An annotatable cdm entity.
1789 a6c4c53c Andreas Kohlbecker
 * @param array $include_types
1790 6657531f Andreas Kohlbecker
 *   If an array of annotation type uuids is supplied by this parameter the
1791
 *   list of annotations is resticted to those which belong to this type.
1792
 *
1793
 * @return array
1794
 *   An array of Annotation objects or an empty array.
1795
 */
1796 0e617798 Andreas Kohlbecker
function cdm_ws_fetch_annotations(&$cdm_entity, $include_types = FALSE) {
1797 4a15731a Andreas Kohlbecker
1798 a6c4c53c Andreas Kohlbecker
  if(!isset($cdm_entity->annotations)){
1799
    $annotation_url = cdm_compose_annotations_uri($cdm_entity);
1800
    $cdm_entity->annotations = cdm_ws_fetch_all($annotation_url, array(), 'GET', TRUE);
1801 6657531f Andreas Kohlbecker
  }
1802 4a15731a Andreas Kohlbecker
1803 b5dca1e2 Andreas Kohlbecker
  $annotations = array();
1804 a6c4c53c Andreas Kohlbecker
  foreach ($cdm_entity->annotations as $annotation) {
1805
    if ($include_types) {
1806 d8e85b2d Andreas Kohlbecker
      if (
1807 a6c4c53c Andreas Kohlbecker
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $include_types, TRUE) )
1808
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $include_types, TRUE))
1809 d8e85b2d Andreas Kohlbecker
      ) {
1810 4a15731a Andreas Kohlbecker
        $annotations[] = $annotation;
1811
      }
1812
    }
1813
    else {
1814
      $annotations[] = $annotation;
1815
    }
1816
  }
1817
  return $annotations;
1818
1819 6657531f Andreas Kohlbecker
}
1820
1821 7370f4f7 Andreas Kohlbecker
/**
1822 a6c4c53c Andreas Kohlbecker
 * Provides the list of visible annotations for the $cdm_entity.
1823 7370f4f7 Andreas Kohlbecker
 *
1824 a6c4c53c Andreas Kohlbecker
 * @param $cdm_entity
1825 7370f4f7 Andreas Kohlbecker
 *     The annotatable CDM entity
1826
 *
1827
 * @return array of the annotations which are visible according to the settings as stored in ANNOTATION_TYPES_VISIBLE
1828
 */
1829 a6c4c53c Andreas Kohlbecker
function cdm_fetch_visible_annotations($cdm_entity){
1830 7370f4f7 Andreas Kohlbecker
1831
  static $annotations_types_filter = null;
1832
  if(!$annotations_types_filter) {
1833 e2617c7e Andreas Kohlbecker
    $annotations_types_filter = unserialize(EXTENSION_TYPES_VISIBLE_DEFAULT);
1834 7370f4f7 Andreas Kohlbecker
  }
1835 0e617798 Andreas Kohlbecker
  return cdm_ws_fetch_annotations($cdm_entity, variable_get(ANNOTATION_TYPES_VISIBLE, $annotations_types_filter));
1836 7370f4f7 Andreas Kohlbecker
}
1837
1838 eeb98da8 Andreas Kohlbecker
/**
1839
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1840
 *
1841 7370f4f7 Andreas Kohlbecker
 * NOTE: The annotations are not filtered by the ANNOTATION_TYPES_VISIBLE settings since this method is meant to act
1842
 * like the annotations have been fetched in the ORM-framework in the service.
1843
 *
1844 eeb98da8 Andreas Kohlbecker
 * @param object $annotatable_entity
1845
 *   The CDM AnnotatableEntity to load annotations for
1846
 */
1847
function cdm_load_annotations(&$annotatable_entity) {
1848
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1849 0e617798 Andreas Kohlbecker
    $annotations = cdm_ws_fetch_annotations($annotatable_entity);
1850 eeb98da8 Andreas Kohlbecker
    if (is_array($annotations)) {
1851
      $annotatable_entity->annotations = $annotations;
1852
    }
1853
  }
1854
}
1855
1856 de7bcbcc Andreas Kohlbecker
function cdm_load_tagged_full_title($taxon_name){
1857
  if(isset($taxon_name) && !isset($taxon_name->taggedFullTitle)){
1858
    $tagged_full_title = cdm_ws_get(CDM_WS_NAME, array($taxon_name->uuid, 'taggedFullTitle'));
1859
    if(is_array($tagged_full_title)){
1860
      $taxon_name->taggedFullTitle = $tagged_full_title;
1861
1862
    }
1863
  }
1864
}
1865
1866 0c2b9b9d Andreas Kohlbecker
/**
1867
 * Extends the $cdm_entity object by the field if it is not already existing.
1868
 *
1869
 * This function can only be used for fields with 1 to many relations.
1870
  *
1871
 * @param $cdm_base_type
1872
 * @param $field_name
1873
 * @param $cdm_entity
1874
 */
1875
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1876
{
1877
  if (!isset($cdm_entity->$field_name)) {
1878
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1879
    $cdm_entity->$field_name = $items;
1880
  }
1881
}
1882
1883
1884 6657531f Andreas Kohlbecker
/**
1885
 * Get a NomenclaturalReference string.
1886
 *
1887
 * Returns the NomenclaturalReference string with correctly placed
1888
 * microreference (= reference detail) e.g.
1889
 * in Phytotaxa 43: 1-48. 2012.
1890
 *
1891
 * @param string $referenceUuid
1892
 *   UUID of the reference.
1893
 * @param string $microreference
1894
 *   Reference detail.
1895
 *
1896
 * @return string
1897
 *   a NomenclaturalReference.
1898
 */
1899
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1900 ecb8526d Andreas Kohlbecker
1901
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1902
  if(is_array($microreference) || is_object($microreference)) {
1903
    return '';
1904
  }
1905
1906 6657531f Andreas Kohlbecker
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1907
    $referenceUuid,
1908
  ), "microReference=" . urlencode($microreference));
1909
1910
  if ($obj) {
1911
    return $obj->String;
1912
  }
1913
  else {
1914
    return NULL;
1915
  }
1916
}
1917
1918 092744e1 Andreas Kohlbecker
/**
1919
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1920
 *
1921
 * @param $feature_tree_nodes
1922
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1923
 * @param $feature_uuid
1924
 *    The UUID of the Feature
1925 9dddc68a Andreas Kohlbecker
 * @return object
1926
 *    the FeatureNode or null
1927 092744e1 Andreas Kohlbecker
 */
1928
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1929
1930
  // 1. scan this level
1931
  foreach ($feature_tree_nodes as $node){
1932 b011743c Andreas Kohlbecker
    if($node->term->uuid == $feature_uuid){
1933 092744e1 Andreas Kohlbecker
      return $node;
1934
    }
1935
  }
1936
1937
  // 2. descend into childen
1938
  foreach ($feature_tree_nodes as $node){
1939
    if(is_array($node->childNodes)){
1940 4b4ae204 Andreas Kohlbecker
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1941 092744e1 Andreas Kohlbecker
      if($node) {
1942
        return $node;
1943
      }
1944
    }
1945
  }
1946 4b4ae204 Andreas Kohlbecker
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1947
  return $null_var;
1948 092744e1 Andreas Kohlbecker
}
1949
1950 6657531f Andreas Kohlbecker
/**
1951 bfb2b81a Andreas Kohlbecker
 * Merges the given featureNodes structure with the descriptionElements.
1952
 *
1953
 * This method is used in preparation for rendering the descriptionElements.
1954 28c5c87a Andreas Kohlbecker
 * The descriptionElements which belong to a specific feature node are appended
1955 fae36a2a Andreas Kohlbecker
 * to a the feature node by creating a new field:
1956 328005fd Andreas Kohlbecker
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1957
 * The descriptionElements will be cleared in advance in order to allow reusing the
1958 28c5c87a Andreas Kohlbecker
 * same feature tree without the risk of mixing sets of description elements.
1959 328005fd Andreas Kohlbecker
 *
1960 bfb2b81a Andreas Kohlbecker
 * which originally is not existing in the cdm.
1961
 *
1962 328005fd Andreas Kohlbecker
 *
1963
 *
1964 bfb2b81a Andreas Kohlbecker
 * @param array $featureNodes
1965 28c5c87a Andreas Kohlbecker
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1966 bfb2b81a Andreas Kohlbecker
 *    may have children.
1967
 * @param array $descriptionElements
1968
 *    An flat array of cdm DescriptionElements
1969
 * @return array
1970 28c5c87a Andreas Kohlbecker
 *    The $featureNodes structure enriched with the according $descriptionElements
1971 6657531f Andreas Kohlbecker
 */
1972
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1973 a67e7364 Andreas Kohlbecker
1974 c5a114a8 Andreas Kohlbecker
  foreach ($featureNodes as &$feature_node) {
1975 a67e7364 Andreas Kohlbecker
    // since the $featureNodes array is reused for each description
1976 28c5c87a Andreas Kohlbecker
    // it is necessary to clear the custom node fields in advance
1977 c5a114a8 Andreas Kohlbecker
    if(isset($feature_node->descriptionElements)){
1978
      unset($feature_node->descriptionElements);
1979 a67e7364 Andreas Kohlbecker
    }
1980
1981 6657531f Andreas Kohlbecker
    // Append corresponding elements to an additional node field:
1982
    // $node->descriptionElements.
1983
    foreach ($descriptionElements as $element) {
1984 c5a114a8 Andreas Kohlbecker
      if ($element->feature->uuid == $feature_node->term->uuid) {
1985
        if (!isset($feature_node->descriptionElements)) {
1986
          $feature_node->descriptionElements = array();
1987 6657531f Andreas Kohlbecker
        }
1988 c5a114a8 Andreas Kohlbecker
        $feature_node->descriptionElements[] = $element;
1989 6657531f Andreas Kohlbecker
      }
1990
    }
1991
1992
    // Recurse into node children.
1993 c5a114a8 Andreas Kohlbecker
    if (isset($feature_node->childNodes[0])) {
1994
      $mergedChildNodes = _mergeFeatureTreeDescriptions($feature_node->childNodes, $descriptionElements);
1995
      $feature_node->childNodes = $mergedChildNodes;
1996 6657531f Andreas Kohlbecker
    }
1997 a67e7364 Andreas Kohlbecker
1998 c5a114a8 Andreas Kohlbecker
    if(!isset($feature_node->descriptionElements) && !isset($feature_node->childNodes[0])){
1999
      unset($feature_node);
2000 328005fd Andreas Kohlbecker
    }
2001
2002 6657531f Andreas Kohlbecker
  }
2003 a67e7364 Andreas Kohlbecker
2004 6657531f Andreas Kohlbecker
  return $featureNodes;
2005
}
2006
2007
/**
2008 84fdac2a Andreas Kohlbecker
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
2009 6657531f Andreas Kohlbecker
 *
2010
 * The response from the HTTP GET request is returned as object.
2011
 * The response objects coming from the webservice configured in the
2012 84fdac2a Andreas Kohlbecker
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
2013 6657531f Andreas Kohlbecker
 *  in a level 2 (L2) cache.
2014
 *
2015
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
2016
 * function, this cache persists only per each single page execution.
2017
 * Any object coming from the webservice is stored into it by default.
2018
 * In contrast to this default caching mechanism the L2 cache only is used if
2019
 * the 'cdm_webservice_cache' variable is set to TRUE,
2020
 * which can be set using the modules administrative settings section.
2021
 * Objects stored in this L2 cache are serialized and stored
2022
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
2023
 * objects that are stored in the database will persist as
2024 84fdac2a Andreas Kohlbecker
 * long as the drupal cache is not being cleared and are available across
2025 6657531f Andreas Kohlbecker
 * multiple script executions.
2026
 *
2027
 * @param string $uri
2028
 *   URL to the webservice.
2029
 * @param array $pathParameters
2030
 *   An array of path parameters.
2031
 * @param string $query
2032
 *   A query string to be appended to the URL.
2033
 * @param string $method
2034
 *   The HTTP method to use, valid values are "GET" or "POST";
2035
 * @param bool $absoluteURI
2036
 *   TRUE when the URL should be treated as absolute URL.
2037
 *
2038 4d3c2389 Andreas Kohlbecker
 * @return object| array
2039 84fdac2a Andreas Kohlbecker
 *   The de-serialized webservice response object.
2040 6657531f Andreas Kohlbecker
 */
2041
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
2042 d071bed7 Andreas Kohlbecker
2043 6657531f Andreas Kohlbecker
  static $cacheL1 = array();
2044
2045 2ebf0428 Andreas Kohlbecker
  $data = NULL;
2046
  // store query string in $data and clear the query, $data will be set as HTTP request body
2047
  if($method == 'POST'){
2048
    $data = $query;
2049
    $query = NULL;
2050
  }
2051
2052 088448e1 Andreas Kohlbecker
  // Transform the given uri path or pattern into a proper webservice uri.
2053 6657531f Andreas Kohlbecker
  if (!$absoluteURI) {
2054
    $uri = cdm_compose_url($uri, $pathParameters, $query);
2055
  }
2056 80d21b78 Andreas Kohlbecker
  cdm_ws_apply_classification_subtree_filter($uri);
2057 6657531f Andreas Kohlbecker
2058 72032ea6 Andreas Kohlbecker
  // read request parameter 'cacheL2_refresh'
2059 84fdac2a Andreas Kohlbecker
  // which allows refreshing the level 2 cache
2060 72032ea6 Andreas Kohlbecker
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
2061
2062 6657531f Andreas Kohlbecker
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
2063
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
2064
2065 2ebf0428 Andreas Kohlbecker
  if($method == 'GET'){
2066
    $cache_key = $uri;
2067
  } else {
2068
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
2069
    // crc32 is faster but creates much shorter hashes
2070
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
2071
  }
2072
2073
  if (array_key_exists($cache_key, $cacheL1)) {
2074 6657531f Andreas Kohlbecker
    $cacheL1_obj = $cacheL1[$uri];
2075
  }
2076
2077
  $set_cacheL1 = FALSE;
2078
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
2079
    $set_cacheL1 = TRUE;
2080
  }
2081
2082
  // Only cache cdm webservice URIs.
2083
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
2084
  $cacheL2_entry = FALSE;
2085
2086 72032ea6 Andreas Kohlbecker
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
2087 6657531f Andreas Kohlbecker
    // Try to get object from cacheL2.
2088 2ebf0428 Andreas Kohlbecker
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
2089 6657531f Andreas Kohlbecker
  }
2090
2091
  if (isset($cacheL1_obj)) {
2092
    //
2093
    // The object has been found in the L1 cache.
2094
    //
2095
    $obj = $cacheL1_obj;
2096 a4f964ee Andreas Kohlbecker
    if (cdm_debug_block_visible()) {
2097 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
2098 6657531f Andreas Kohlbecker
    }
2099
  }
2100
  elseif ($cacheL2_entry) {
2101
    //
2102
    // The object has been found in the L2 cache.
2103
    //
2104 e2464cf8 Andreas Kohlbecker
    $duration_parse_start = microtime(TRUE);
2105 6657531f Andreas Kohlbecker
    $obj = unserialize($cacheL2_entry->data);
2106 e2464cf8 Andreas Kohlbecker
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2107 6657531f Andreas Kohlbecker
2108 a4f964ee Andreas Kohlbecker
    if (cdm_debug_block_visible()) {
2109 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
2110 6657531f Andreas Kohlbecker
    }
2111
  }
2112
  else {
2113
    //
2114
    // Get the object from the webservice and cache it.
2115
    //
2116 e2464cf8 Andreas Kohlbecker
    $duration_fetch_start = microtime(TRUE);
2117 6657531f Andreas Kohlbecker
    // Request data from webservice JSON or XML.
2118 2ebf0428 Andreas Kohlbecker
    $response = cdm_http_request($uri, $method, $data);
2119
    $response_body = NULL;
2120 2fe78f3c Andreas Kohlbecker
    if (isset($response->data)) {
2121 2ebf0428 Andreas Kohlbecker
      $response_body = $response->data;
2122 2fe78f3c Andreas Kohlbecker
    }
2123 e2464cf8 Andreas Kohlbecker
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2124
    $duration_parse_start = microtime(TRUE);
2125 6657531f Andreas Kohlbecker
2126
    // Parse data and create object.
2127 2ebf0428 Andreas Kohlbecker
    $obj = cdm_load_obj($response_body);
2128 6657531f Andreas Kohlbecker
2129 4e5b23ae Andreas Kohlbecker
    if(isset($obj->servlet) && isset($obj->status) && is_numeric($obj->status)){
2130
      // this is json error message returned by jetty #8914
2131
      // wee need to replace it by null to avoid breaking existing assumptions in the code here
2132
      // this is also related to #2711
2133
      $obj = null;
2134
    }
2135
2136 e2464cf8 Andreas Kohlbecker
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2137 a4f964ee Andreas Kohlbecker
2138
    if (cdm_debug_block_visible()) {
2139 2ebf0428 Andreas Kohlbecker
      if ($obj || $response_body == "[]") {
2140 e2464cf8 Andreas Kohlbecker
        $status = 'valid';
2141 6657531f Andreas Kohlbecker
      }
2142
      else {
2143 e2464cf8 Andreas Kohlbecker
        $status = 'invalid';
2144 6657531f Andreas Kohlbecker
      }
2145 2ebf0428 Andreas Kohlbecker
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2146 6657531f Andreas Kohlbecker
    }
2147
    if ($set_cacheL2) {
2148
      // Store the object in cache L2.
2149 2ebf0428 Andreas Kohlbecker
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2150 6657531f Andreas Kohlbecker
      // flag serialized is set properly in the cache table.
2151 2ebf0428 Andreas Kohlbecker
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2152 6657531f Andreas Kohlbecker
    }
2153
  }
2154
  if ($obj) {
2155
    // Store the object in cache L1.
2156
    if ($set_cacheL1) {
2157 2ebf0428 Andreas Kohlbecker
      $cacheL1[$cache_key] = $obj;
2158 6657531f Andreas Kohlbecker
    }
2159
  }
2160
  return $obj;
2161
}
2162
2163 80d21b78 Andreas Kohlbecker
function cdm_ws_apply_classification_subtree_filter(&$uri){
2164
2165
  $classification_subtree_filter_patterns = &drupal_static('classification_subtree_filter_patterns', array(
2166
    "#/classification/[0-9a-f\-]{36}/childNodes#",
2167 6e2a9ba9 Andreas Kohlbecker
    /* covered by above pattern:
2168
    "#/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2169
    '#/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2170
    */
2171 80d21b78 Andreas Kohlbecker
    "#/portal/classification/[0-9a-f\-]{36}/childNodes#",
2172 6e2a9ba9 Andreas Kohlbecker
    /* covered by above pattern:
2173 80d21b78 Andreas Kohlbecker
    "#/portal/classification/[0-9a-f\-]{36}/childNodesAt/[0-9a-f\-]{36}#",
2174 6e2a9ba9 Andreas Kohlbecker
    '#/portal/classification/[0-9a-f\-]{36}/childNodesOf/[0-9a-f\-]{36}#',
2175
    */
2176 d961cf30 Andreas Kohlbecker
    '#/portal/classification/[0-9a-f\-]{36}/pathFrom/[0-9a-f\-]{36}#',
2177 80d21b78 Andreas Kohlbecker
    "#/portal/taxon/search#",
2178
    "#/portal/taxon/find#",
2179 6e2a9ba9 Andreas Kohlbecker
    /* covered by above pattern:
2180 80d21b78 Andreas Kohlbecker
    "#/portal/taxon/findByDescriptionElementFullText#",
2181
    "#/portal/taxon/findByFullText#",
2182
    "#/portal/taxon/findByEverythingFullText#",
2183
    "#/portal/taxon/findByIdentifier#",
2184 6e2a9ba9 Andreas Kohlbecker
    "#/portal/taxon/findByMarker#",
2185
    "#/portal/taxon/findByMarker#",
2186
    "#/portal/taxon/findByMarker#",
2187
    */
2188
    "#/portal/taxon/[0-9a-f\-]{36}#"
2189
    /* covered by above pattern:
2190
    "#/portal/taxon/[0-9a-f\-]{36}/taxonNodes#",
2191
    */
2192 80d21b78 Andreas Kohlbecker
  ));
2193
2194
  $sub_tree_filter_uuid_value = variable_get(CDM_SUB_TREE_FILTER_UUID, FALSE);
2195
  if(is_uuid($sub_tree_filter_uuid_value)){
2196
    foreach($classification_subtree_filter_patterns as $preg_pattern){
2197
      if(preg_match($preg_pattern, $uri)){
2198
        // no need to take care for uri fragments with ws uris!
2199
        if(strpos( $uri, '?')){
2200
          $uri .= '&subtree=' . $sub_tree_filter_uuid_value;
2201
        } else {
2202
          $uri .= '?subtree='. $sub_tree_filter_uuid_value;
2203
        }
2204
        break;
2205
      }
2206
    }
2207
  }
2208
2209
}
2210 6657531f Andreas Kohlbecker
/**
2211 e2464cf8 Andreas Kohlbecker
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2212
 *
2213
 * The cdm_ws_debug block will display the debug information.
2214
 *
2215
 * @param $uri
2216
 *    The CDM REST URI to which the request has been send
2217 2ebf0428 Andreas Kohlbecker
 * @param string $method
2218
 *    The HTTP request method, either 'GET' or 'POST'
2219
 * @param string $post_data
2220
 *    The datastring send with a post request
2221 e2464cf8 Andreas Kohlbecker
 * @param $duration_fetch
2222
 *    The time in seconds it took to fetch the data from the web service
2223
 * @param $duration_parse
2224
 *    Time in seconds which was needed to parse the json response
2225
 * @param $datasize
2226
 *    Size of the data received from the server
2227
 * @param $status
2228
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2229
 * @return bool
2230
 *    TRUE if adding the debug information was successful
2231 6657531f Andreas Kohlbecker
 */
2232 2ebf0428 Andreas Kohlbecker
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2233 6657531f Andreas Kohlbecker
2234 e2464cf8 Andreas Kohlbecker
  static $initial_time = NULL;
2235
  if(!$initial_time) {
2236
    $initial_time = microtime(TRUE);
2237
  }
2238
  $time = microtime(TRUE) - $initial_time;
2239 6657531f Andreas Kohlbecker
2240
  // Decompose uri into path and query element.
2241
  $uri_parts = explode("?", $uri);
2242 98038f4c w.addink
  $query = array();
2243 6657531f Andreas Kohlbecker
  if (count($uri_parts) == 2) {
2244
    $path = $uri_parts[0];
2245
  }
2246
  else {
2247
    $path = $uri;
2248
  }
2249
2250 c1bcfc1b Andreas Kohlbecker
  if(strpos($uri, '?') > 0){
2251
    $json_uri = str_replace('?', '.json?', $uri);
2252
    $xml_uri = str_replace('?', '.xml?', $uri);
2253
  } else {
2254
    $json_uri = $uri . '.json';
2255
    $xml_uri = $json_uri . '.xml';
2256
  }
2257
2258 e2464cf8 Andreas Kohlbecker
  // data links to make data accecsible as json and xml
2259
  $data_links = '';
2260 6657531f Andreas Kohlbecker
  if (_is_cdm_ws_uri($path)) {
2261 2ebf0428 Andreas Kohlbecker
2262
    // see ./js/http-method-link.js
2263
2264
    if($method == 'GET'){
2265
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2266
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2267
      $data_links .= '<br/>';
2268
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2269
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2270
    } else {
2271
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2272
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2273
      $data_links .= '<br/>';
2274
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2275
    }
2276 6657531f Andreas Kohlbecker
  }
2277
  else {
2278 c1bcfc1b Andreas Kohlbecker
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2279 e2464cf8 Andreas Kohlbecker
  }
2280
2281
  //
2282
  $data = array(
2283
      'ws_uri' => $uri,
2284 2ebf0428 Andreas Kohlbecker
      'method' => $method,
2285
      'post_data' => $post_data,
2286 e2464cf8 Andreas Kohlbecker
      'time' => sprintf('%3.3f', $time),
2287
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2288
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2289
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2290
      'status' => $status,
2291
      'data_links' => $data_links
2292
  );
2293
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2294
    $_SESSION['cdm']['ws_debug'] = array();
2295 6657531f Andreas Kohlbecker
  }
2296 e2464cf8 Andreas Kohlbecker
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2297
2298
  // Mark this page as being uncacheable.
2299
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2300
  drupal_page_is_cacheable(FALSE);
2301
2302
  // Messages not set when DB connection fails.
2303
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2304 6657531f Andreas Kohlbecker
}
2305
2306 a4f964ee Andreas Kohlbecker
/**
2307
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2308
 * the visibility depends on whether
2309
 *  - the block is enabled
2310
 *  - the visibility restrictions in the block settings are satisfied
2311
 */
2312
function cdm_debug_block_visible() {
2313
  static $is_visible = null;
2314
2315
  if($is_visible === null){
2316
      $block = block_load('cdm_api', 'cdm_ws_debug');
2317 af932304 Andreas Kohlbecker
      $is_visible = isset($block->status) && $block->status == 1;
2318 a4f964ee Andreas Kohlbecker
      if($is_visible){
2319
        $blocks = array($block);
2320
        // Checks the page, user role, and user-specific visibilty settings.
2321
        block_block_list_alter($blocks);
2322
        $is_visible = count($blocks) > 0;
2323
      }
2324
  }
2325
  return $is_visible;
2326
}
2327
2328 6657531f Andreas Kohlbecker
/**
2329
 * @todo Please document this function.
2330
 * @see http://drupal.org/node/1354
2331
 */
2332 2ebf0428 Andreas Kohlbecker
function cdm_load_obj($response_body) {
2333
  $obj = json_decode($response_body);
2334 6657531f Andreas Kohlbecker
2335
  if (!(is_object($obj) || is_array($obj))) {
2336
    ob_start();
2337
    $obj_dump = ob_get_contents();
2338
    ob_clean();
2339
    return FALSE;
2340
  }
2341
2342
  return $obj;
2343
}
2344
2345
/**
2346 2fe78f3c Andreas Kohlbecker
 * Do a http request to a CDM RESTful web service.
2347 6657531f Andreas Kohlbecker
 *
2348
 * @param string $uri
2349
 *   The webservice url.
2350
 * @param string $method
2351
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2352
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2353 2ebf0428 Andreas Kohlbecker
 * @param $data: A string containing the request body, formatted as
2354
 *     'param=value&param=value&...'. Defaults to NULL.
2355 6657531f Andreas Kohlbecker
 *
2356 2fe78f3c Andreas Kohlbecker
 * @return object
2357
 *   The object as returned by drupal_http_request():
2358
 *   An object that can have one or more of the following components:
2359
 *   - request: A string containing the request body that was sent.
2360
 *   - code: An integer containing the response status code, or the error code
2361
 *     if an error occurred.
2362
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2363
 *   - status_message: The status message from the response, if a response was
2364
 *     received.
2365
 *   - redirect_code: If redirected, an integer containing the initial response
2366
 *     status code.
2367
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2368
 *     target.
2369
 *   - error: If an error occurred, the error message. Otherwise not set.
2370
 *   - headers: An array containing the response headers as name/value pairs.
2371
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2372
 *     easy access the array keys are returned in lower case.
2373
 *   - data: A string containing the response body that was received.
2374 6657531f Andreas Kohlbecker
 */
2375 2ebf0428 Andreas Kohlbecker
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2376 6657531f Andreas Kohlbecker
  static $acceptLanguage = NULL;
2377 0b606c0d Andreas Kohlbecker
  $header = array();
2378 af0cde1a Andreas Kohlbecker
  
2379
  if(!$acceptLanguage && module_exists('i18n')){
2380
    $acceptLanguage = i18n_language_content()->language;
2381
  }
2382 6657531f Andreas Kohlbecker
2383
  if (!$acceptLanguage) {
2384
    if (function_exists('apache_request_headers')) {
2385
      $headers = apache_request_headers();
2386
      if (isset($headers['Accept-Language'])) {
2387
        $acceptLanguage = $headers['Accept-Language'];
2388
      }
2389
    }
2390
  }
2391
2392
  if ($method != "GET" && $method != "POST") {
2393 2ebf0428 Andreas Kohlbecker
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2394 6657531f Andreas Kohlbecker
  }
2395
2396 0b606c0d Andreas Kohlbecker
  if (_is_cdm_ws_uri($uri)) {
2397 3db2866c Andreas Kohlbecker
    $header['Accept'] = 'application/json';
2398 6657531f Andreas Kohlbecker
    $header['Accept-Language'] = $acceptLanguage;
2399
    $header['Accept-Charset'] = 'UTF-8';
2400
  }
2401
2402 2ebf0428 Andreas Kohlbecker
  if($method == "POST") {
2403
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2404
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2405
  }
2406
2407 2dd59bb5 Andreas Kohlbecker
2408
  cdm_dd($uri);
2409 2fe78f3c Andreas Kohlbecker
  return drupal_http_request($uri, array(
2410
      'headers' => $header,
2411
      'method' => $method,
2412 2ebf0428 Andreas Kohlbecker
      'data' => $data,
2413 2fe78f3c Andreas Kohlbecker
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2414
      )
2415
   );
2416 6657531f Andreas Kohlbecker
}
2417
2418
/**
2419 37252893 Andreas Kohlbecker
 * Concatenates recursively the fields of all features contained in the given
2420
 * CDM FeatureTree root node.
2421
 *
2422
 * @param $rootNode
2423
 *     A CDM FeatureTree node
2424
 * @param
2425
 *     The character to be used as glue for concatenation, default is ', '
2426
 * @param $field_name
2427
 *     The field name of the CDM Features
2428 092744e1 Andreas Kohlbecker
 * @param $excludes
2429
 *     Allows defining a set of values to be excluded. This refers to the values
2430
 *     in the field denoted by the $field_name parameter
2431
 *
2432 6657531f Andreas Kohlbecker
 */
2433 092744e1 Andreas Kohlbecker
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2434 6657531f Andreas Kohlbecker
  $out = '';
2435
2436 37252893 Andreas Kohlbecker
  $pre_child_separator = $separator;
2437
  $post_child_separator = '';
2438
2439 fae36a2a Andreas Kohlbecker
  foreach ($root_node->childNodes as $feature_node) {
2440 6657531f Andreas Kohlbecker
    $out .= ($out ? $separator : '');
2441 b011743c Andreas Kohlbecker
    if(!in_array($feature_node->term->$field_name, $excludes)) {
2442
      $out .= $feature_node->term->$field_name;
2443 092744e1 Andreas Kohlbecker
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2444
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2445
        if (strlen($childlabels)) {
2446
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2447
        }
2448 6657531f Andreas Kohlbecker
      }
2449
    }
2450
  }
2451
  return $out;
2452
}
2453
2454
/**
2455
 * Create a one-dimensional form options array.
2456
 *
2457
 * Creates an array of all features in the feature tree of feature nodes,
2458
 * the node labels are indented by $node_char and $childIndent depending on the
2459
 * hierachy level.
2460
 *
2461
 * @param - $rootNode
2462
 * @param - $node_char
2463
 * @param - $childIndentStr
2464
 * @param - $childIndent
2465
 *   ONLY USED INTERNALLY!
2466
 *
2467
 * @return array
2468
 *   A one dimensional Drupal form options array.
2469
 */
2470
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2471
  $options = array();
2472 fae36a2a Andreas Kohlbecker
  foreach ($rootNode->childNodes as $featureNode) {
2473 6657531f Andreas Kohlbecker
    $indent_prefix = '';
2474
    if ($childIndent) {
2475
      $indent_prefix = $childIndent . $node_char . " ";
2476
    }
2477 b011743c Andreas Kohlbecker
    $options[$featureNode->term->uuid] = $indent_prefix . $featureNode->term->representation_L10n;
2478 fae36a2a Andreas Kohlbecker
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2479
      // Foreach ($featureNode->childNodes as $childNode){
2480 6657531f Andreas Kohlbecker
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2481
      $options = array_merge_recursive($options, $childList);
2482
      // }
2483
    }
2484
  }
2485
  return $options;
2486
}
2487
2488
/**
2489 72294996 Andreas Kohlbecker
 * Returns an array with all available FeatureTrees and the representations of the selected
2490
 * FeatureTree as a detail view.
2491
 *
2492 cdafd99f Alexander Oppermann
 * @param boolean $add_default_feature_free
2493 c3a41ddb Andreas Kohlbecker
 * @param boolean $show_weight
2494
 *     Show the weight which will be applied to the according feature block
2495 72294996 Andreas Kohlbecker
 * @return array
2496 cdafd99f Alexander Oppermann
 *  associative array with following keys:
2497
 *  -options: Returns an array with all available Feature Trees
2498
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2499 72294996 Andreas Kohlbecker
 *
2500 6657531f Andreas Kohlbecker
 */
2501 c3a41ddb Andreas Kohlbecker
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE, $show_weight = FALSE) {
2502 3f485c6d Andreas Kohlbecker
2503
  $options = array();
2504
  $tree_representations = array();
2505 6657531f Andreas Kohlbecker
  $feature_trees = array();
2506
2507
  // Set tree that contains all features.
2508 6188d24e Andreas Kohlbecker
  if ($add_default_feature_free) {
2509 3f485c6d Andreas Kohlbecker
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2510 9dddc68a Andreas Kohlbecker
    $feature_trees[] = cdm_ws_get(CDM_WS_TERMTREE, UUID_DEFAULT_FEATURETREE);
2511 3f485c6d Andreas Kohlbecker
  }
2512
2513
  // Get feature trees from database.
2514 9725f08e Andreas Kohlbecker
  $persited_trees = cdm_ws_fetch_all(CDM_WS_TERMTREES, array("termType" => "Feature"));
2515 3f485c6d Andreas Kohlbecker
  if (is_array($persited_trees)) {
2516
    $feature_trees = array_merge($feature_trees, $persited_trees);
2517 6657531f Andreas Kohlbecker
  }
2518
2519 3f485c6d Andreas Kohlbecker
  foreach ($feature_trees as $featureTree) {
2520 6657531f Andreas Kohlbecker
2521 8c962983 Andreas Kohlbecker
    if(!is_object($featureTree)){
2522
      continue;
2523
    }
2524 3f485c6d Andreas Kohlbecker
    // Do not add the DEFAULT_FEATURETREE again,
2525
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2526 1717116c Andreas Kohlbecker
      $options[$featureTree->uuid] = $featureTree->titleCache;
2527 3f485c6d Andreas Kohlbecker
    }
2528
2529
    // Render the hierarchic tree structure
2530 fae36a2a Andreas Kohlbecker
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2531 3f485c6d Andreas Kohlbecker
2532
      // Render the hierarchic tree structure.
2533
      $treeDetails = '<div class="featuretree_structure">'
2534 c3a41ddb Andreas Kohlbecker
        . render_feature_tree_hierarchy($featureTree->uuid, $show_weight)
2535 3f485c6d Andreas Kohlbecker
        . '</div>';
2536
2537
      $form = array();
2538
      $form['featureTree-' .  $featureTree->uuid] = array(
2539
        '#type' => 'fieldset',
2540
        '#title' => 'Show details',
2541
        '#attributes' => array('class' => array('collapsible collapsed')),
2542
        // '#collapsible' => TRUE,
2543
        // '#collapsed' => TRUE,
2544
      );
2545
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2546
        '#markup' => $treeDetails,
2547
      );
2548
2549
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2550 6657531f Andreas Kohlbecker
    }
2551 8734e506 Alexander Oppermann
2552 3f485c6d Andreas Kohlbecker
  } // END loop over feature trees
2553 6657531f Andreas Kohlbecker
2554 3f485c6d Andreas Kohlbecker
  // return $options;
2555
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2556 6657531f Andreas Kohlbecker
}
2557
2558
/**
2559 0af3ce28 Andreas Kohlbecker
 * Provides the list of available classifications in form of an options array.
2560 de8b5b32 Andreas Kohlbecker
 *
2561
 * The options array is suitable for drupal form API elements that allow multiple choices.
2562
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2563
 *
2564
 * The classifications are ordered alphabetically whereas the classification
2565
 * chosen as default will always appear on top of the array, followed by a
2566
 * blank line below.
2567
 *
2568 61b6ee11 Andreas Kohlbecker
 * @param bool $add_none_option
2569 1717116c Andreas Kohlbecker
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2570 61b6ee11 Andreas Kohlbecker
 *
2571 de8b5b32 Andreas Kohlbecker
 * @return array
2572
 *   classifications in an array as options for a form element that allows multiple choices.
2573 6657531f Andreas Kohlbecker
 */
2574 61b6ee11 Andreas Kohlbecker
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2575
2576 a488aeb6 Andreas Kohlbecker
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2577 de8b5b32 Andreas Kohlbecker
2578
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2579
  $default_classification_label = '';
2580
2581
  // add all classifications
2582 6188d24e Andreas Kohlbecker
  $taxonomic_tree_options = array();
2583 61b6ee11 Andreas Kohlbecker
  if ($add_none_option) {
2584
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2585
  }
2586 6657531f Andreas Kohlbecker
  if ($taxonTrees) {
2587
    foreach ($taxonTrees as $tree) {
2588 de8b5b32 Andreas Kohlbecker
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2589
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2590
      } else {
2591 61b6ee11 Andreas Kohlbecker
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2592 de8b5b32 Andreas Kohlbecker
        $default_classification_label = $tree->titleCache;
2593
      }
2594 6657531f Andreas Kohlbecker
    }
2595
  }
2596 61b6ee11 Andreas Kohlbecker
  // oder alphabetically the space
2597 de8b5b32 Andreas Kohlbecker
  asort($taxonomic_tree_options);
2598
2599 61b6ee11 Andreas Kohlbecker
  // now set the labels
2600
  //   for none
2601 f19f47fa Andreas Kohlbecker
  if ($add_none_option) {
2602 8ae3cfe3 Andreas Kohlbecker
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2603 61b6ee11 Andreas Kohlbecker
  }
2604
2605
  //   for default_classification
2606 805795b6 Andreas Kohlbecker
  if (is_uuid($default_classification_uuid)) {
2607 d88a1df7 Andreas Kohlbecker
    $taxonomic_tree_options[$default_classification_uuid] =
2608
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2609 6b1e5ae3 Andreas Kohlbecker
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2610 de8b5b32 Andreas Kohlbecker
  }
2611
2612 6188d24e Andreas Kohlbecker
  return $taxonomic_tree_options;
2613 6657531f Andreas Kohlbecker
}
2614
2615
/**
2616
 * @todo Please document this function.
2617
 * @see http://drupal.org/node/1354
2618
 */
2619
function cdm_api_secref_cache_prefetch(&$secUuids) {
2620
  // Comment @WA: global variables should start with a single underscore
2621
  // followed by the module and another underscore.
2622
  global $_cdm_api_secref_cache;
2623
  if (!is_array($_cdm_api_secref_cache)) {
2624
    $_cdm_api_secref_cache = array();
2625
  }
2626
  $uniqueUuids = array_unique($secUuids);
2627
  $i = 0;
2628
  $param = '';
2629
  while ($i++ < count($uniqueUuids)) {
2630
    $param .= $secUuids[$i] . ',';
2631
    if (strlen($param) + 37 > 2000) {
2632
      _cdm_api_secref_cache_add($param);
2633
      $param = '';
2634
    }
2635
  }
2636
  if ($param) {
2637
    _cdm_api_secref_cache_add($param);
2638
  }
2639
}
2640
2641
/**
2642
 * @todo Please document this function.
2643
 * @see http://drupal.org/node/1354
2644
 */
2645
function cdm_api_secref_cache_get($secUuid) {
2646
  global $_cdm_api_secref_cache;
2647
  if (!is_array($_cdm_api_secref_cache)) {
2648
    $_cdm_api_secref_cache = array();
2649
  }
2650
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2651
    _cdm_api_secref_cache_add($secUuid);
2652
  }
2653
  return $_cdm_api_secref_cache[$secUuid];
2654
}
2655
2656
/**
2657
 * @todo Please document this function.
2658
 * @see http://drupal.org/node/1354
2659
 */
2660
function cdm_api_secref_cache_clear() {
2661
  global $_cdm_api_secref_cache;
2662
  $_cdm_api_secref_cache = array();
2663
}
2664
2665 f26245c8 Andreas Kohlbecker
2666 6657531f Andreas Kohlbecker
/**
2667
 * @todo Please document this function.
2668
 * @see http://drupal.org/node/1354
2669
 */
2670
function _cdm_api_secref_cache_add($secUuidsStr) {
2671
  global $_cdm_api_secref_cache;
2672
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2673
  // Batch fetching not jet reimplemented thus:
2674
  /*
2675
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2676
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2677
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2678
  */
2679
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2680
}
2681
2682
/**
2683
 * Checks if the given uri starts with a cdm webservice url.
2684
 *
2685
 * Checks if the uri starts with the cdm webservice url stored in the
2686
 * Drupal variable 'cdm_webservice_url'.
2687
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2688
 *
2689
 * @param string $uri
2690
 *   The URI to test.
2691
 *
2692
 * @return bool
2693
 *   True if the uri starts with a cdm webservice url.
2694
 */
2695
function _is_cdm_ws_uri($uri) {
2696
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2697
}
2698
2699
/**
2700
 * @todo Please document this function.
2701
 * @see http://drupal.org/node/1354
2702
 */
2703
function queryString($elements) {
2704
  $query = '';
2705
  foreach ($elements as $key => $value) {
2706
    if (is_array($value)) {
2707
      foreach ($value as $v) {
2708
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2709
      }
2710
    }
2711
    else {
2712
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2713
    }
2714
  }
2715
  return $query;
2716
}
2717
2718 a783afbc Andreas Kohlbecker
/**
2719
 * Compares the given CDM Term instances by the  representationL10n.
2720
 *
2721
 * Can also be used with TermDTOs. To be used in usort()
2722
 *
2723
 * @see http://php.net/manual/en/function.usort.php
2724
 *
2725
 * @param $term1
2726
 *   The first CDM Term instance
2727
 * @param $term2
2728
 *   The second CDM Term instance
2729
 * @return int
2730
 *   The result of the comparison
2731
 */
2732
function compare_terms_by_representationL10n($term1, $term2) {
2733
2734
  if (!isset($term1->representation_L10n)) {
2735
    $term1->representationL10n = '';
2736
  }
2737
  if (!isset($term2->representation_L10n)) {
2738
    $term2->representationL10n = '';
2739
  }
2740
2741
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2742
}
2743
2744 c079337e Andreas Kohlbecker
function compare_terms_by_order_index($term1, $term2) {
2745
2746
2747
  if (!isset($term1->orderIndex)) {
2748
    $a = 0;
2749
  } else {
2750
    $a = $term1->orderIndex;
2751
  }
2752
  if (!isset($term2->orderIndex)) {
2753
    $b = 0;
2754
  } else {
2755
    $b = $term2->orderIndex;
2756
  }
2757
2758
  if ($a == $b) {
2759
    return 0;
2760
  }
2761
  return ($a < $b) ? -1 : 1;
2762
2763
}
2764
2765 a783afbc Andreas Kohlbecker
2766 6657531f Andreas Kohlbecker
/**
2767
 * Make a 'deep copy' of an array.
2768
 *
2769
 * Make a complete deep copy of an array replacing
2770
 * references with deep copies until a certain depth is reached
2771
 * ($maxdepth) whereupon references are copied as-is...
2772
 *
2773
 * @see http://us3.php.net/manual/en/ref.array.php
2774
 *
2775
 * @param array $array
2776 cc3c9807 Andreas Kohlbecker
 * @param array $copy passed by reference
2777 6657531f Andreas Kohlbecker
 * @param int $maxdepth
2778
 * @param int $depth
2779
 */
2780
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2781
  if ($depth > $maxdepth) {
2782
    $copy = $array;
2783
    return;
2784
  }
2785
  if (!is_array($copy)) {
2786
    $copy = array();
2787
  }
2788
  foreach ($array as $k => &$v) {
2789
    if (is_array($v)) {
2790
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2791
    }
2792
    else {
2793
      $copy[$k] = $v;
2794
    }
2795
  }
2796
}
2797
2798 7844642a Andreas Kohlbecker
/**
2799
 * Concatenated the uuids of the passed cdm entity with `,` as glue.
2800
 * The returned string is suitable for cdm webservices consuming UUIDList as
2801
 * parameter
2802
 *
2803
 * @param array $cdm_entities
2804
 *
2805
 * @return string
2806
 */
2807
function cdm_uuid_list_parameter_value(array $cdm_entities){
2808
  $uuids = [];
2809
  foreach ($cdm_entities as $entity){
2810
    if(isset($entity) && is_uuid($entity->uuid) ){
2811
      $uuids[] = $entity->uuid;
2812
    }
2813
  }
2814
  return  join(',', $uuids);
2815
}
2816
2817 6657531f Andreas Kohlbecker
/**
2818 e2464cf8 Andreas Kohlbecker
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2819 6657531f Andreas Kohlbecker
 *
2820
 */
2821 e2464cf8 Andreas Kohlbecker
function _add_js_ws_debug() {
2822
2823 5ea8b301 Andreas Kohlbecker
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2824
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2825
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2826
    // use the developer versions of js libs
2827
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2828
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2829
  }
2830
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2831 e2464cf8 Andreas Kohlbecker
    array(
2832
      'type' => 'file',
2833
      'weight' => JS_LIBRARY,
2834
      'cache' => TRUE)
2835
    );
2836
2837 5ea8b301 Andreas Kohlbecker
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2838 e2464cf8 Andreas Kohlbecker
    array(
2839
      'type' => 'file',
2840
      'weight' => JS_LIBRARY,
2841
      'cache' => TRUE)
2842
    );
2843
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2844
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2845
2846
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2847
    array(
2848
      'type' => 'file',
2849
      'weight' => JS_LIBRARY,
2850
      'cache' => TRUE)
2851
    );
2852 2ebf0428 Andreas Kohlbecker
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2853
    array(
2854
    'type' => 'file',
2855
    'weight' => JS_LIBRARY,
2856
    'cache' => TRUE)
2857
    );
2858 6657531f Andreas Kohlbecker
2859
}
2860
2861
/**
2862
 * @todo Please document this function.
2863
 * @see http://drupal.org/node/1354
2864
 */
2865
function _no_classfication_uuid_message() {
2866
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2867
    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.');
2868
  }
2869
  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.');
2870
}
2871
2872
/**
2873
 * Implementation of hook flush_caches
2874
 *
2875
 * Add custom cache tables to the list of cache tables that
2876
 * will be cleared by the Clear button on the Performance page or whenever
2877
 * drupal_flush_all_caches is invoked.
2878
 *
2879
 * @author W.Addink <waddink@eti.uva.nl>
2880
 *
2881
 * @return array
2882
 *   An array with custom cache tables to include.
2883
 */
2884
function cdm_api_flush_caches() {
2885
  return array('cache_cdm_ws');
2886
}
2887 f26245c8 Andreas Kohlbecker
2888 2dd59bb5 Andreas Kohlbecker
/**
2889
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2890
 *
2891
 * @param $data
2892
 *   The variable to log to the drupal_debug.txt log file.
2893
 * @param $label
2894
 *   (optional) If set, a label to output before $data in the log file.
2895
 *
2896
 * @return
2897
 *   No return value if successful, FALSE if the log file could not be written
2898
 *   to.
2899
 *
2900
 * @see cdm_dataportal_init() where the log file is reset on each requests
2901
 * @see dd()
2902
 * @see http://drupal.org/node/314112
2903
 *
2904
 */
2905
function cdm_dd($data, $label = NULL) {
2906 43251923 Andreas Kohlbecker
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2907 2dd59bb5 Andreas Kohlbecker
    return dd($data, $label);
2908
  }
2909
}