Project

General

Profile

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