Project

General

Profile

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