Project

General

Profile

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

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

    
31
  /**
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

    
40

    
41

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

    
47
/**
48
 * orderBy webservice query parameter value
49
 */
50
define('CDM_ORDER_BY_ID_DESC', 'BY_ID_DESC');
51
/**
52
 * orderBy webservice query parameter value
53
 */
54
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'BY_TITLE_CACHE_ASC');
55
/**
56
 * orderBy webservice query parameter value
57
 */
58
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'BY_TITLE_CACHE_DESC');
59
/**
60
 * orderBy webservice query parameter value
61
 */
62
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_ASC', 'BY_NOMENCLATURAL_ORDER_ASC');
63
/**
64
 * orderBy webservice query parameter value
65
 */
66
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_DESC', 'BY_NOMENCLATURAL_ORDER_DESC');
67
/**
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

    
77
/**
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
      'access cdm content',
88
    ),
89
    'type' => MENU_CALLBACK,
90
  );
91

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

    
100
  return $items;
101
}
102

    
103
/**
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
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
123

    
124
    $field_map = array(
125
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
126
        '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

    
145
      $data = unserialize($data);
146

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

    
153
      $cells = array();
154
      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
    $block['subject'] = ''; // no subject, title in content for having a defined element id
165
    // otherwise it would depend on the theme
166
    $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
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
170
        . $header
171
        . '<tbody>' . join('', $rows) . '</tbody>'
172
        . $footer
173
        . '</table></div>',
174
      '#attached' => array(
175
        'css' => array(
176
          drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_ws_debug.css'
177
        )
178
      )
179
    );
180
    return $block;
181
  }
182
}
183

    
184
/**
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
// ===================== Tagged Text functions ================== //
194

    
195
/**
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
/**
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
 * @param array $skiptags
240
 *   Array of tag names to skip
241
 *
242
 * @return string
243
 *   A string with HTML.
244
 */
245
function cdm_tagged_text_to_markup(array $taggedtxt, $skiptags = array()) {
246

    
247
  $tag = 'span';
248
  $out = '';
249
  $was_separator = false;
250
  foreach ($taggedtxt as $tt) {
251
    if (!in_array($tt->type, $skiptags) && $tt->text) {
252
      $class_attr = $tt->type;
253

    
254
      if(isset($tt->entityReference)){
255
        $class_attr .= " " . html_class_attribute_ref($tt->entityReference);
256
      }
257
      $is_separator = is_tagged_text_sepatator_type($tt->type);
258
      $glue = !$is_separator && !$was_separator ? ' ' : '';
259
      $out .= '<' . $tag . ' class="' . $class_attr . '">'
260
        . t('@text', array('@text' => $tt->text))
261
        . '</' . $tag . '>'
262
        . $glue;
263
      $was_separator = $is_separator;
264
    }
265
  }
266
  return $out;
267
}
268

    
269
/**
270
 * See cdmlib: boolean eu.etaxonomy.cdm.strategy.cache.TagEnum.isSeparator();
271
 *
272
 * @return bool
273
 */
274
function is_tagged_text_sepatator_type($tagged_text_type){
275
    static $separator_names = array('separator', 'postSeparator');
276
		$result = array_search($tagged_text_type, $separator_names) !== false;
277
    return $result;
278
}
279

    
280

    
281
/**
282
 * Finds the text tagged with $tag_type in an array of taggedText instances.
283
 *
284
 * Note: This function is currently unused.
285
 *
286
 * @param array $taggedtxt
287
 *   Array with text items.
288
 * @param string $tag_type
289
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
290
 *   to return all texts.
291
 *
292
 * @return array
293
 *   An array with the texts mapped by $tag_type.
294
 */
295
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
296
  $tokens = array();
297
  if (!empty($taggedtxt)) {
298
    foreach ($taggedtxt as $tagtxt) {
299
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
300
        $tokens[] = $tagtxt->text;
301
      }
302
    }
303
  }
304
  return $tokens;
305
}
306

    
307
/**
308
 * Preprocess the taggedTitle arrays.
309
 *
310
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
311
 * into tag type "name"
312
 *
313
 * Step 2: Two taggedTexts which have the same type and which have
314
 * a separator between them are merged together.
315
 *
316
 * @param array $taggedTextList
317
 *    An array of TaggedText objects
318
 */
319
function normalize_tagged_text(&$taggedTextList) {
320

    
321
  if (is_array($taggedTextList)) {
322

    
323
    // First pass: rename.
324
    for ($i = 0; $i < count($taggedTextList); $i++) {
325

    
326
      if ($taggedTextList[$i]->type == "hybridSign") {
327
        $taggedTextList[$i]->type = "name";
328
      }
329
    }
330

    
331
    // Second pass: resolve separators.
332
    $taggedNameListNew = array();
333
    for ($i = 0; $i < count($taggedTextList); $i++) {
334

    
335
      // elements of the same type concatenated by a separator should be merged together
336
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
337
        $taggedName = clone $taggedTextList[$i];
338
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
339
        $taggedNameListNew[] = $taggedName;
340
        ++$i;
341
        ++$i;
342
        continue;
343
      }
344
      // no special handling
345
      $taggedNameListNew[] = $taggedTextList[$i];
346

    
347
    }
348
    $taggedTextList = $taggedNameListNew;
349
  }
350
}
351

    
352
function split_secref_from_tagged_text(&$tagged_text) {
353

    
354
  $extracted_tt = array();
355
  if (is_array($tagged_text)) {
356
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
357
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
358
        $extracted_tt[0] = $tagged_text[$i];
359
        $extracted_tt[1] = $tagged_text[$i + 1];
360
        unset($tagged_text[$i]);
361
        unset($tagged_text[$i + 1]);
362
        // also get the microfererence which could be in $tagged_text[$i + 3]
363
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
364
          $extracted_tt[2] = $tagged_text[$i + 2];
365
          $extracted_tt[3] = $tagged_text[$i + 3];
366
        }
367
        break;
368
      }
369
    }
370
  }
371
  return $extracted_tt;
372
}
373

    
374

    
375
function split_nomstatus_from_tagged_text(&$tagged_text) {
376

    
377
  $extracted_tt = array();
378
  if (is_array($tagged_text)) {
379
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
380
      if ($tagged_text[$i]->type == "nomStatus"){
381
        $extracted_tt[] = $tagged_text[$i];
382
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
383
          $extracted_tt[] = $tagged_text[$i + 1];
384
          unset($tagged_text[$i + 1]);
385
        }
386
        if ($tagged_text[$i - 1]->type == "separator"){
387
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
388
          unset($tagged_text[$i - 1]);
389
        }
390
        unset($tagged_text[$i]);
391
        break;
392
      }
393
    }
394
  }
395
  return $extracted_tt;
396
}
397

    
398
function find_tagged_text_elements($taggedTextList, $type){
399
  $matching_elements = array();
400
  if (is_array($taggedTextList)) {
401
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
402
      if($taggedTextList[$i]->type == $type){
403
        $matching_elements[] = $taggedTextList[$i];
404
      }
405
    }
406
  }
407
  return $matching_elements;
408
}
409

    
410
// ===================== END of Tagged Text functions ================== //
411

    
412
/**
413
 * Lists the classifications a taxon belongs to
414
 *
415
 * @param CDM type Taxon $taxon
416
 *   the taxon
417
 *
418
 * @return array
419
 *   aray of CDM instances of Type Classification
420
 */
421
function get_classifications_for_taxon($taxon) {
422

    
423
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
424
}
425

    
426
/**
427
 * Returns the chosen FeatureTree for the taxon profile.
428
 *
429
 * The FeatureTree profile returned is the one that has been set in the
430
 * dataportal settings (layout->taxon:profile).
431
 * When the chosen FeatureTree is not found in the database,
432
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
433
 *
434
 * @return mixed
435
 *   A cdm FeatureTree object.
436
 */
437
function get_profile_feature_tree() {
438
  static $profile_featureTree;
439

    
440
  if($profile_featureTree == NULL) {
441
    $profile_featureTree = cdm_ws_get(
442
      CDM_WS_FEATURETREE,
443
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
444
    );
445
    if (!$profile_featureTree) {
446
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
447
    }
448
  }
449

    
450
  return $profile_featureTree;
451
}
452

    
453
/**
454
 * Returns the chosen FeatureTree for SpecimenDescriptions.
455
 *
456
 * The FeatureTree returned is the one that has been set in the
457
 * dataportal settings (layout->taxon:specimen).
458
 * When the chosen FeatureTree is not found in the database,
459
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
460
 *
461
 * @return mixed
462
 *   A cdm FeatureTree object.
463
 */
464
function cdm_get_occurrence_featureTree() {
465
  static $occurrence_featureTree;
466

    
467
  if($occurrence_featureTree == NULL) {
468
    $occurrence_featureTree = cdm_ws_get(
469
      CDM_WS_FEATURETREE,
470
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
471
    );
472
    if (!$occurrence_featureTree) {
473
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
474
    }
475
  }
476
  return $occurrence_featureTree;
477
}
478

    
479
/**
480
 * Returns the FeatureTree for structured descriptions
481
 *
482
 * The FeatureTree returned is the one that has been set in the
483
 * dataportal settings (layout->taxon:profile).
484
 * When the chosen FeatureTree is not found in the database,
485
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
486
 *
487
 * @return mixed
488
 *   A cdm FeatureTree object.
489
 */
490
function get_structured_description_featureTree() {
491
  static $structured_description_featureTree;
492

    
493
  if($structured_description_featureTree == NULL) {
494
    $structured_description_featureTree = cdm_ws_get(
495
        CDM_WS_FEATURETREE,
496
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
497
    );
498
    if (!$structured_description_featureTree) {
499
      $structured_description_featureTree = cdm_ws_get(
500
          CDM_WS_FEATURETREE,
501
          UUID_DEFAULT_FEATURETREE
502
      );
503
    }
504
  }
505
  return $structured_description_featureTree;
506
}
507

    
508

    
509
/**
510
 * @todo Please document this function.
511
 * @see http://drupal.org/node/1354
512
 */
513
function set_last_taxon_page_tab($taxonPageTab) {
514
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
515
}
516

    
517
/**
518
 * @todo Please document this function.
519
 * @see http://drupal.org/node/1354
520
 */
521
function get_last_taxon_page_tab() {
522
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
523
    return $_SESSION['cdm']['taxon_page_tab'];
524
  }
525
  else {
526
    return FALSE;
527
  }
528
}
529

    
530
/**
531
 *
532
 * @param object $media
533
 * @param array $mimeTypes
534
 *    an array of mimetypes in their order of preference. e.g:
535
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
536
 * @param int $width
537
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
538
 * @param int $height
539
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
540
 *
541
 * @return array
542
 *   An array with preferred media representations or else an empty array.
543
 */
544
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
545
  $prefRepr = array();
546
  if (!isset($media->representations[0])) {
547
    return $prefRepr;
548
  }
549

    
550
  while (count($mimeTypes) > 0) {
551
    // getRepresentationByMimeType
552
    $mimeType = array_shift($mimeTypes);
553

    
554
    foreach ($media->representations as &$representation) {
555
      // If the mimetype is not known, try inferring it.
556
      if (!$representation->mimeType) {
557
        if (isset($representation->parts[0])) {
558
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
559
        }
560
      }
561

    
562
      if ($representation->mimeType == $mimeType) {
563
        // Preferred mimetype found -> erase all remaining mimetypes
564
        // to end loop.
565
        $mimeTypes = array();
566
        $expansionDeltaSum = 0;
567
        $valid_parts_cnt = 0;
568
        // Look for part with the best matching size.
569
        foreach ($representation->parts as $part) {
570
          if (empty($part->uri)) {
571
            // skip part if URI is missing
572
            continue;
573
          }
574
          $valid_parts_cnt++;
575
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
576

    
577
          // determine the optimal size
578
          if (isset($part->width) && isset($part->height)) {
579
            $expansion = $part->width * $part->height;
580
            if ($width != null && $height != null) {
581
              $optimalExpansion = $height * $width;
582
            } else {
583
              $optimalExpansion = PHP_INT_MAX;
584
            }
585
            // determine the difference
586
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
587
          }
588
          // sum up the expansionDeltas of all parts contained in the representation
589
          $expansionDeltaSum += $expansionDelta;
590
        }
591
        if($valid_parts_cnt > 0){
592
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
593
          $prefRepr[$expansionDeltaSum] = $representation;
594
        }
595
      }
596
    }
597
  }
598
  // Sort the array so that the smallest key value is the first in the array
599
  ksort($prefRepr);
600
  return $prefRepr;
601
}
602

    
603
/**
604
 * Infers the mime type of a file using the filename extension.
605
 *
606
 * The filename extension is used to infer the mime type.
607
 *
608
 * @param string $filepath
609
 *   The path to the respective file.
610
 *
611
 * @return string
612
 *   The mimetype for the file or FALSE if the according mime type could
613
 *   not be found.
614
 */
615
function infer_mime_type($filepath) {
616
  static $mimemap = NULL;
617
  if (!$mimemap) {
618
    $mimemap = array(
619
      'jpg' => 'image/jpeg',
620
      'jpeg' => 'image/jpeg',
621
      'png' => 'image/png',
622
      'gif' => 'image/gif',
623
      'giff' => 'image/gif',
624
      'tif' => 'image/tif',
625
      'tiff' => 'image/tif',
626
      'pdf' => 'application/pdf',
627
      'html' => 'text/html',
628
      'htm' => 'text/html',
629
    );
630
  }
631
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
632
  if (isset($mimemap[$extension])) {
633
    return $mimemap[$extension];
634
  }
635
  else {
636
    // FIXME remove this hack just return FALSE;
637
    return 'text/html';
638
  }
639
}
640

    
641
/**
642
 * Converts an ISO 8601 org.joda.time.Partial to a year.
643
 *
644
 * The function expects an ISO 8601 time representation of a
645
 * org.joda.time.Partial of the form yyyy-MM-dd.
646
 *
647
 * @param string $partial
648
 *   ISO 8601 time representation of a org.joda.time.Partial.
649
 *
650
 * @return string
651
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
652
 */
653
function partialToYear($partial) {
654
  if (is_string($partial)) {
655
    $year = substr($partial, 0, 4);
656
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
657
      return $year;
658
    }
659
  }
660
  return '';
661
}
662

    
663
/**
664
 * Converts an ISO 8601 org.joda.time.Partial to a month.
665
 *
666
 * This function expects an ISO 8601 time representation of a
667
 * org.joda.time.Partial of the form yyyy-MM-dd.
668
 * In case the month is unknown (= ???) NULL is returned.
669
 *
670
 * @param string $partial
671
 *   ISO 8601 time representation of a org.joda.time.Partial.
672
 *
673
 * @return string
674
 *   A month.
675
 */
676
function partialToMonth($partial) {
677
  if (is_string($partial)) {
678
    $month = substr($partial, 5, 2);
679
    if (preg_match("/[0-9][0-9]/", $month)) {
680
      return $month;
681
    }
682
  }
683
  return '';
684
}
685

    
686
/**
687
 * Converts an ISO 8601 org.joda.time.Partial to a day.
688
 *
689
 * This function expects an ISO 8601 time representation of a
690
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
691
 * In case the day is unknown (= ???) NULL is returned.
692
 *
693
 * @param string $partial
694
 *   ISO 8601 time representation of a org.joda.time.Partial.
695
 *
696
 * @return string
697
 *   A day.
698
 */
699
function partialToDay($partial) {
700
  if (is_string($partial)) {
701
    $day = substr($partial, 8, 2);
702
    if (preg_match("/[0-9][0-9]/", $day)) {
703
      return $day;
704
    }
705
  }
706
  return '';
707
}
708

    
709
/**
710
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
711
 *
712
 * This function expects an ISO 8601 time representations of a
713
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
714
 * four digit year, month and day with dashes:
715
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
716
 *
717
 * The partial may contain question marks eg: "1973-??-??",
718
 * these are turned in to '00' or are stripped depending of the $stripZeros
719
 * parameter.
720
 *
721
 * @param string $partial
722
 *   org.joda.time.Partial.
723
 * @param bool $stripZeros
724
 *   If set to TRUE the zero (00) month and days will be hidden:
725
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
726
 * @param string @format
727
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
728
 *    - "YYYY": Year only
729
 *    - "YYYY-MM-DD": this is the default
730
 *
731
 * @return string
732
 *   YYYY-MM-DD formatted year, month, day.
733
 */
734
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
735

    
736
  $y = NULL; $m = NULL; $d = NULL;
737

    
738
  if(strpos($format, 'YY') !== FALSE){
739
    $y = partialToYear($partial);
740
  }
741
  if(strpos($format, 'MM') !== FALSE){
742
    $m = partialToMonth($partial);
743
  }
744
  if(strpos($format, 'DD') !== FALSE){
745
    $d = partialToDay($partial);
746
  }
747

    
748
  $y = $y ? $y : '00';
749
  $m = $m ? $m : '00';
750
  $d = $d ? $d : '00';
751

    
752
  $date = '';
753

    
754
  if ($y == '00' && $stripZeros) {
755
    return '';
756
  }
757
  else {
758
    $date = $y;
759
  }
760

    
761
  if ($m == '00' && $stripZeros) {
762
    return $date;
763
  }
764
  else {
765
    $date .= "-" . $m;
766
  }
767

    
768
  if ($d == '00' && $stripZeros) {
769
    return $date;
770
  }
771
  else {
772
    $date .= "-" . $d;
773
  }
774
  return $date;
775
}
776

    
777
/**
778
 * Converts a time period to a string.
779
 *
780
 * See also partialToDate($partial, $stripZeros).
781
 *
782
 * @param object $period
783
 *   An JodaTime org.joda.time.Period object.
784
 * @param bool $stripZeros
785
 *   If set to True, the zero (00) month and days will be hidden:
786
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
787
 * @param string @format
788
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
789
 *    - "YYYY": Year only
790
 *    - "YYYY-MM-DD": this is the default
791
 *
792
 * @return string
793
 *   Returns a date in the form of a string.
794
 */
795
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
796
  $dateString = '';
797
  if($period->freeText){
798
    $dateString = $period->freeText;
799
  } else {
800
    if ($period->start) {
801
      $dateString = partialToDate($period->start, $stripZeros, $format);
802
    }
803
    if ($period->end) {
804
      $end_str = partialToDate($period->end, $stripZeros, $format);
805
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
806
    }
807
  }
808
  return $dateString;
809
}
810

    
811
/**
812
 * returns the earliest date available in the $period in a normalized
813
 * form suitable for sorting, e.g.:
814
 *
815
 *  - 1956-00-00
816
 *  - 0000-00-00
817
 *  - 1957-03-00
818
 *
819
 * that is either the start date is returned if set otherwise the
820
 * end date
821
 *
822
 * @param  $period
823
 *    An JodaTime org.joda.time.Period object.
824
 * @return string normalized form of the date
825
 *   suitable for sorting
826
 */
827
function timePeriodAsOrderKey($period) {
828
  $dateString = '';
829
  if ($period->start) {
830
    $dateString = partialToDate($period->start, false);
831
  }
832
  if ($period->end) {
833
    $dateString .= partialToDate($period->end, false);
834
  }
835
  return $dateString;
836
}
837

    
838
/**
839
 * Composes a absolute CDM web service URI with parameters and querystring.
840
 *
841
 * @param string $uri_pattern
842
 *   String with place holders ($0, $1, ..) that should be replaced by the
843
 *   according element of the $pathParameters array.
844
 * @param array $pathParameters
845
 *   An array of path elements, or a single element.
846
 * @param string $query
847
 *   A query string to append to the URL.
848
 *
849
 * @return string
850
 *   A complete URL with parameters to a CDM webservice.
851
 */
852
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
853
  if (empty($pathParameters)) {
854
    $pathParameters = array();
855
  }
856

    
857
  // (1)
858
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
859
  // according element of the $pathParameters array.
860
  static $helperArray = array();
861
  if (isset($pathParameters) && !is_array($pathParameters)) {
862
    $helperArray[0] = $pathParameters;
863
    $pathParameters = $helperArray;
864
  }
865

    
866
  $i = 0;
867
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
868
    if (count($pathParameters) <= $i) {
869
        drupal_set_message(
870
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
871
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
872
          'error');
873
      break;
874
    }
875
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
876
    ++$i;
877
  }
878

    
879
  // (2)
880
  // Append all remaining element of the $pathParameters array as path
881
  // elements.
882
  if (count($pathParameters) > $i) {
883
    // Strip trailing slashes.
884
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
885
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
886
    }
887
    while (count($pathParameters) > $i) {
888
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
889
      ++$i;
890
    }
891
  }
892

    
893
  // (3)
894
  // Append the query string supplied by $query.
895
  if (isset($query)) {
896
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
897
  }
898

    
899
  $path = $uri_pattern;
900

    
901
  $uri = variable_get('cdm_webservice_url', '') . $path;
902
  return $uri;
903
}
904

    
905
/**
906
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
907
 *     together with a theme name to such a proxy function?
908
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
909
 *     Maybe we want to have two different proxy functions, one with theming and one without?
910
 *
911
 * @param string $uri
912
 *     A URI to a CDM Rest service from which to retrieve an object
913
 * @param string|null $hook
914
 *     (optional) The hook name to which the retrieved object should be passed.
915
 *     Hooks can either be a theme_hook() or compose_hook() implementation
916
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
917
 *     suitable for drupal_render()
918
 *
919
 * @todo Please document this function.
920
 * @see http://drupal.org/node/1354
921
 */
922
function proxy_content($uri, $hook = NULL) {
923

    
924
  $args = func_get_args();
925
  $do_gzip = function_exists('gzencode');
926
  $uriEncoded = array_shift($args);
927
  $uri = urldecode($uriEncoded);
928
  $hook = array_shift($args);
929
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
930

    
931
  $post_data = null;
932

    
933
  if ($request_method == "POST" || $request_method == "PUT") {
934
    // read response body via inputstream module
935
    $post_data = file_get_contents("php://input");
936
  }
937

    
938
  // Find and deserialize arrays.
939
  foreach ($args as &$arg) {
940
    // FIXME use regex to find serialized arrays.
941
    //       or should we accept json instead of php serializations?
942
    if (strpos($arg, "a:") === 0) {
943
      $arg = unserialize($arg);
944
    }
945
  }
946

    
947
  // In all these cases perform a simple get request.
948
  // TODO reconsider caching logic in this function.
949

    
950
  if (empty($hook)) {
951
    // simply return the webservice response
952
    // Print out JSON, the cache cannot be used since it contains objects.
953
    $http_response = cdm_http_request($uri, $request_method, $post_data);
954
    if (isset($http_response->headers)) {
955
      foreach ($http_response->headers as $hname => $hvalue) {
956
        drupal_add_http_header($hname, $hvalue);
957
      }
958
    }
959
    if (isset($http_response->data)) {
960
      print $http_response->data;
961
      flush();
962
    }
963
    exit(); // leave drupal here
964
  } else {
965
    // $hook has been supplied
966
    // handle $hook either as compose ot theme hook
967
    // pass through theme or comose hook
968
    // compose hooks can be called without data, therefore
969
    // passing the $uri in this case is not always a requirement
970

    
971
    if($uri && $uri != 'NULL') {
972
    // do a security check since the $uri will be passed
973
    // as absolute URI to cdm_ws_get()
974
      if (!_is_cdm_ws_uri($uri)) {
975
        drupal_set_message(
976
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
977
          'error'
978
        );
979
        return '';
980
      }
981

    
982
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
983
    } else {
984
      $obj = NULL;
985
    }
986

    
987
    $reponse_data = NULL;
988

    
989
    if (function_exists('compose_' . $hook)){
990
      // call compose hook
991

    
992
      $elements =  call_user_func('compose_' . $hook, $obj);
993
      // pass the render array to drupal_render()
994
      $reponse_data = drupal_render($elements);
995
    } else {
996
      // call theme hook
997

    
998
      // TODO use theme registry to get the registered hook info and
999
      //    use these defaults
1000
      switch($hook) {
1001
        case 'cdm_taxontree':
1002
          $variables = array(
1003
            'tree' => $obj,
1004
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
1005
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
1006
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
1007
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
1008
            );
1009
          $reponse_data = theme($hook, $variables);
1010
          break;
1011

    
1012
        case 'cdm_list_of_taxa':
1013
            $variables = array(
1014
              'records' => $obj,
1015
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
1016
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
1017
            $reponse_data = theme($hook, $variables);
1018
            break;
1019

    
1020
        case 'cdm_media_caption':
1021
          $variables = array(
1022
            'media' => $obj,
1023
            // $args[0] is set in taxon_image_gallery_default in
1024
            // cdm_dataportal.page.theme.
1025
            'elements' => isset($args[0]) ? $args[0] : array(
1026
            'title',
1027
            'description',
1028
            'artist',
1029
            'location',
1030
            'rights',
1031
          ),
1032
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
1033
          );
1034
          $reponse_data = theme($hook, $variables);
1035
          break;
1036

    
1037
        default:
1038
          drupal_set_message(t(
1039
          'Theme !theme is not yet supported by the function !function.', array(
1040
          '!theme' => $hook,
1041
          '!function' => __FUNCTION__,
1042
          )), 'error');
1043
          break;
1044
      } // END of theme hook switch
1045
    } // END of tread as theme hook
1046

    
1047

    
1048
    if($do_gzip){
1049
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1050
      drupal_add_http_header('Content-Encoding', 'gzip');
1051
    }
1052
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1053
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1054

    
1055
    print $reponse_data;
1056
  } // END of handle $hook either as compose ot theme hook
1057

    
1058
}
1059

    
1060
/**
1061
 * @todo Please document this function.
1062
 * @see http://drupal.org/node/1354
1063
 */
1064
function setvalue_session() {
1065
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1066
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1067
    $var_keys = explode('][', $var_keys);
1068
  }
1069
  else {
1070
    return;
1071
  }
1072
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1073

    
1074
  // Prevent from malicous tags.
1075
  $val = strip_tags($val);
1076

    
1077
  $session_var = &$_SESSION;
1078
  //$i = 0;
1079
  foreach ($var_keys as $key) {
1080
    // $hasMoreKeys = ++$i < count($session);
1081
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1082
      $session_var[$key] = array();
1083
    }
1084
    $session_var = &$session_var[$key];
1085
  }
1086
  $session_var = $val;
1087
  if (isset($_REQUEST['destination'])) {
1088
    drupal_goto($_REQUEST['destination']);
1089
  }
1090
}
1091

    
1092
/**
1093
 * @todo Please document this function.
1094
 * @see http://drupal.org/node/1354
1095
 */
1096
function uri_uriByProxy($uri, $theme = FALSE) {
1097
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1098
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1099
}
1100

    
1101
/**
1102
 * Composes the the absolute REST service URI to the annotations pager
1103
 * for the given CDM entity.
1104
 *
1105
 * NOTE: Not all CDM Base types are yet supported.
1106
 *
1107
 * @param $cdmBase
1108
 *   The CDM entity to construct the annotations pager uri for
1109
 */
1110
function cdm_compose_annotations_uri($cdmBase) {
1111

    
1112
  if (!$cdmBase->uuid) {
1113
    return;
1114
  }
1115

    
1116
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
1117

    
1118
  if($ws_base_uri === null){
1119
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1120
  }
1121
  return cdm_compose_url($ws_base_uri, array(
1122
    $cdmBase->uuid,
1123
    'annotations',
1124
  ));
1125
}
1126

    
1127
/**
1128
 * Provides the base URI of the cdm REST service responsible for the passed simple name
1129
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
1130
 *
1131
 * @param $cdm_type_simple
1132
 *    simple name of a CDM java class
1133
 * @return null|string
1134
 */
1135
function cdm_ws_base_uri($cdm_type_simple)
1136
{
1137
  $ws_base_uri = NULL;
1138
  switch ($cdm_type_simple) {
1139
    case 'TaxonBase':
1140
    case 'Taxon':
1141
    case 'Synonym':
1142
      $ws_base_uri = CDM_WS_TAXON;
1143
      break;
1144

    
1145
    case 'TaxonName':
1146
      $ws_base_uri = CDM_WS_NAME;
1147
      break;
1148

    
1149
    case 'Media':
1150
      $ws_base_uri = CDM_WS_MEDIA;
1151
      break;
1152

    
1153
    case 'Reference':
1154
      $ws_base_uri = CDM_WS_REFERENCE;
1155
      break;
1156

    
1157
    case 'Distribution':
1158
    case 'TextData':
1159
    case 'TaxonInteraction':
1160
    case 'QuantitativeData':
1161
    case 'IndividualsAssociation':
1162
    case 'CommonTaxonName':
1163
    case 'CategoricalData':
1164
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1165
      break;
1166

    
1167
    case 'PolytomousKey':
1168
    case 'MediaKey':
1169
    case 'MultiAccessKey':
1170
      $ws_base_uri = $cdm_type_simple;
1171
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1172
      break;
1173

    
1174
    default:
1175
      $ws_base_uri = null;
1176
  }
1177
  return $ws_base_uri;
1178
}
1179

    
1180
/**
1181
 * Enter description here...
1182
 *
1183
 * @param string $resourceURI
1184
 * @param int $pageSize
1185
 *   The maximum number of entities returned per page.
1186
 *   The default page size as configured in the cdm server
1187
 *   will be used if set to NULL
1188
 *   to return all entities in a single page).
1189
 * @param int $pageNumber
1190
 *   The number of the page to be returned, the first page has the
1191
 *   pageNumber = 0
1192
 * @param array $query
1193
 *   A array holding the HTTP request query parameters for the request
1194
 * @param string $method
1195
 *   The HTTP method to use, valid values are "GET" or "POST"
1196
 * @param bool $absoluteURI
1197
 *   TRUE when the URL should be treated as absolute URL.
1198
 *
1199
 * @return the a CDM Pager object
1200
 *
1201
 */
1202
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1203

    
1204
  $query['pageNumber'] = $pageNumber;
1205
  $query['pageSize'] = $pageSize;
1206

    
1207
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1208
}
1209

    
1210
/**
1211
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1212
 *
1213
 * @param string $resourceURI
1214
 * @param array $query
1215
 *   A array holding the HTTP request query parameters for the request
1216
 * @param string $method
1217
 *   The HTTP method to use, valid values are "GET" or "POST";
1218
 * @param bool $absoluteURI
1219
 *   TRUE when the URL should be treated as absolute URL.
1220
 *
1221
 * @return array
1222
 *     A list of CDM entitites
1223
 *
1224
 */
1225
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1226
  $page_index = 0;
1227
  // using a bigger page size to avoid to many multiple requests
1228
  $page_size = 500;
1229
  $entities = array();
1230

    
1231
  while ($page_index !== FALSE){
1232
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1233
    if(isset($pager->records) && is_array($pager->records)) {
1234
      $entities = array_merge($entities, $pager->records);
1235
      if(!empty($pager->nextIndex)){
1236
        $page_index = $pager->nextIndex;
1237
      } else {
1238
        $page_index = FALSE;
1239
      }
1240
    } else {
1241
      $page_index = FALSE;
1242
    }
1243
  }
1244
  return $entities;
1245
}
1246

    
1247
/*
1248
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1249
  $viewrank = _cdm_taxonomy_compose_viewrank();
1250
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1251
  ? '/' . $path : '') ;
1252
}
1253
*/
1254

    
1255
/**
1256
 * @todo Enter description here...
1257
 *
1258
 * @param string $taxon_uuid
1259
 *  The UUID of a cdm taxon instance
1260
 * @param string $ignore_rank_limit
1261
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1262
 *
1263
 * @return string
1264
 *   A cdm REST service URL path to a Classification
1265
 */
1266
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1267

    
1268
  $view_uuid = get_current_classification_uuid();
1269
  $rank_uuid = NULL;
1270
  if (!$ignore_rank_limit) {
1271
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1272
  }
1273

    
1274
  if (!empty($taxon_uuid)) {
1275
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1276
      $view_uuid,
1277
      $taxon_uuid,
1278
    ));
1279
  }
1280
  else {
1281
    if (is_uuid($rank_uuid)) {
1282
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1283
        $view_uuid,
1284
        $rank_uuid,
1285
      ));
1286
    }
1287
    else {
1288
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1289
        $view_uuid,
1290
      ));
1291
    }
1292
  }
1293
}
1294

    
1295
/**
1296
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1297
 *
1298
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1299
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1300
 *
1301
 * Operates in two modes depending on whether the parameter
1302
 * $taxon_uuid is set or NULL.
1303
 *
1304
 * A) $taxon_uuid = NULL:
1305
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1306
 *  2. otherwise return the default classification as defined by the admin via the settings
1307
 *
1308
 * b) $taxon_uuid is set:
1309
 *   return the classification to whcih the taxon belongs to.
1310
 *
1311
 * @param UUID $taxon_uuid
1312
 *   The UUID of a cdm taxon instance
1313
 */
1314
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1315

    
1316
    $response = NULL;
1317

    
1318
    // 1st try
1319
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1320

    
1321
    if ($response == NULL) {
1322
      // 2dn try by ignoring the rank limit
1323
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1324
    }
1325

    
1326
    if ($response == NULL) {
1327
      // 3rd try, last fallback:
1328
      //    return the default classification
1329
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1330
        // Delete the session value and try again with the default.
1331
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1332
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1333
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1334
      }
1335
      else {
1336
        // Check if taxonomictree_uuid is valid.
1337
        // expecting an array of taxonNodes,
1338
        // empty classifications are ok so no warning in this case!
1339
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1340
        if (!is_array($test)) {
1341
          // The default set by the admin seems to be invalid or is not even set.
1342
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1343
        }
1344
        if (count($test) == 0) {
1345
          // The default set by the admin seems to be invalid or is not even set.
1346
          drupal_set_message("The chosen classification is empty.", 'status');
1347
        }
1348
      }
1349
    }
1350

    
1351
  return $response;
1352
}
1353

    
1354
/**
1355
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1356
 * 
1357
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1358
 * variable is set.
1359
 *
1360
 * @param string $taxon_uuid
1361
 *
1362
 * @return array
1363
 *   An array of CDM TaxonNodeDTO objects
1364
 */
1365
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1366
  $view_uuid = get_current_classification_uuid();
1367
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1368

    
1369
  $response = NULL;
1370
  if (is_uuid($rank_uuid)) {
1371
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1372
      $view_uuid,
1373
      $taxon_uuid,
1374
      $rank_uuid,
1375
    ));
1376
  }
1377
  else {
1378
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1379
      $view_uuid,
1380
      $taxon_uuid,
1381
    ));
1382
  }
1383

    
1384
  if ($response == NULL) {
1385
    // Error handing.
1386
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1387
//      // Delete the session value and try again with the default.
1388
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1389
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1390
//    }
1391
//    else {
1392
      // Check if taxonomictree_uuid is valid.
1393
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1394
      if ($test == NULL) {
1395
        // The default set by the admin seems to be invalid or is not even set.
1396
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1397
      }
1398
//    }
1399
  }
1400

    
1401
  return $response;
1402
}
1403

    
1404

    
1405
// =============================Terms and Vocabularies ========================================= //
1406

    
1407
/**
1408
 * Returns the localized representation for the given term.
1409
 *
1410
 * @param Object $definedTermBase
1411
 * 	  of cdm type DefinedTermBase
1412
 * @return string
1413
 * 	  the localized representation_L10n of the term,
1414
 *    otherwise the titleCache as fall back,
1415
 *    otherwise the default_representation which defaults to an empty string
1416
 */
1417
function cdm_term_representation($definedTermBase, $default_representation = '') {
1418
  if ( isset($definedTermBase->representation_L10n) ) {
1419
    return $definedTermBase->representation_L10n;
1420
  } elseif ( isset($definedTermBase->titleCache)) {
1421
    return $definedTermBase->titleCache;
1422
  }
1423
  return $default_representation;
1424
}
1425

    
1426
/**
1427
 * Returns the abbreviated localized representation for the given term.
1428
 *
1429
 * @param Object $definedTermBase
1430
 * 	  of cdm type DefinedTermBase
1431
 * @return string
1432
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1433
 *    if this representation is not available the function delegates the
1434
 *    call to cdm_term_representation()
1435
 */
1436
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1437
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1438
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1439
  } else {
1440
    cdm_term_representation($definedTermBase, $default_representation);
1441
  }
1442
}
1443

    
1444
/**
1445
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1446
 *
1447
 * The options array is suitable for drupal form API elements that allow multiple choices.
1448
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1449
 *
1450
 * @param array $terms
1451
 *   a list of CDM DefinedTermBase instances
1452
 *
1453
 * @param $term_label_callback
1454
 *   A callback function to override the term representations
1455
 *
1456
 * @param bool $empty_option
1457
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1458
 *
1459
 * @return array
1460
 *   the terms in an array as options for a form element that allows multiple choices.
1461
 */
1462
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1463
  $options = array();
1464
  if(isset($terms) && is_array($terms)) {
1465
    foreach ($terms as $term) {
1466
      if ($term_label_callback && function_exists($term_label_callback)) {
1467
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1468
      } else {
1469
        //TODO use cdm_term_representation() here?
1470
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1471
      }
1472
    }
1473
  }
1474

    
1475
  if($empty_option !== FALSE){
1476
    array_unshift ($options, "");
1477
  }
1478

    
1479
  return $options;
1480
}
1481

    
1482
/**
1483
 * Creates and array of options for drupal select form elements.
1484
 *
1485
 * @param $vocabulary_uuid
1486
 *   The UUID of the CDM Term Vocabulary
1487
 * @param $term_label_callback
1488
 *   An optional call back function which can be used to modify the term label
1489
 * @param bool $empty_option
1490
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1491
 * @param array $include_filter
1492
 *   An associative array consisting of a field name an regular expression. All term matching
1493
 *   these filter are included. The value of the field is converted to a String by var_export()
1494
 *   so a boolean 'true' can be matched by '/true/'
1495
 * @param string $order_by
1496
 *   One of the order by constants defined in this file
1497
 * @return mixed
1498
 */
1499
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1500
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1501

    
1502
  static $vocabularyOptions = array();
1503

    
1504
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1505
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1506
      array(
1507
        'orderBy' => $order_by
1508
      )
1509
    );
1510

    
1511
    // apply the include filter
1512
    if($include_filter != null){
1513
      $included_terms = array();
1514

    
1515
      foreach ($terms as $term){
1516
        $include = true;
1517
        foreach ($include_filter as $field=>$regex){
1518
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1519
          if(!$include){
1520
            break;
1521
          }
1522
        }
1523
        if($include){
1524
          $included_terms[] = $term;
1525
        }
1526
      }
1527

    
1528
      $terms = $included_terms;
1529
    }
1530

    
1531
    // make options list
1532
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1533
  }
1534

    
1535
  $options = $vocabularyOptions[$vocabulary_uuid];
1536

    
1537
  return $options;
1538
}
1539

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

    
1605

    
1606
/**
1607
 * @todo Please document this function.
1608
 * @see http://drupal.org/node/1354
1609
 */
1610
function _cdm_relationship_type_term_label_callback($term) {
1611
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1612
    return $term->representation_L10n_abbreviatedLabel . ' : '
1613
    . t('@term', array('@term' => $term->representation_L10n));
1614
  }
1615
else {
1616
    return t('@term', array('@term' => $term->representation_L10n));
1617
  }
1618
}
1619

    
1620
// ========================================================================================== //
1621
/**
1622
 * @todo Improve documentation of this function.
1623
 *
1624
 * eu.etaxonomy.cdm.model.description.
1625
 * CategoricalData
1626
 * CommonTaxonName
1627
 * Distribution
1628
 * IndividualsAssociation
1629
 * QuantitativeData
1630
 * TaxonInteraction
1631
 * TextData
1632
 */
1633
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1634
  static $types = array(
1635
    "CategoricalData",
1636
    "CommonTaxonName",
1637
    "Distribution",
1638
    "IndividualsAssociation",
1639
    "QuantitativeData",
1640
    "TaxonInteraction",
1641
    "TextData",
1642
  );
1643

    
1644
  static $options = NULL;
1645
  if ($options == NULL) {
1646
    $options = array();
1647
    if ($prependEmptyElement) {
1648
      $options[' '] = '';
1649
    }
1650
    foreach ($types as $type) {
1651
      // No internatianalization here since these are purely technical terms.
1652
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1653
    }
1654
  }
1655
  return $options;
1656
}
1657

    
1658

    
1659
/**
1660
 * Fetches all TaxonDescription descriptions elements which are associated to the
1661
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1662
 * feature tree.
1663
 * @param $feature_tree
1664
 *     The CDM FeatureTree to be used as template
1665
 * @param $taxon_uuid
1666
 *     The UUID of the taxon
1667
 * @param $excludes
1668
 *     UUIDs of features to be excluded
1669
 * @return$feature_tree
1670
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1671
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1672
 *     witch will hold the according $descriptionElements.
1673
 */
1674
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1675

    
1676
  if (!$feature_tree) {
1677
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1678
      In order to see the species profiles of your taxa, please select a
1679
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1680
    return FALSE;
1681
  }
1682

    
1683
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1684
      array(
1685
      'taxon' => $taxon_uuid,
1686
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1687
      ),
1688
      'POST'
1689
  );
1690

    
1691
  // Combine all descriptions into one feature tree.
1692
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1693
  $feature_tree->root->childNodes = $merged_nodes;
1694

    
1695
  return $feature_tree;
1696
}
1697

    
1698
/**
1699
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1700
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1701
 * be requested for the annotations.
1702
 *
1703
 * @param string $cdmBase
1704
 *   An annotatable cdm entity.
1705
 * @param array $includeTypes
1706
 *   If an array of annotation type uuids is supplied by this parameter the
1707
 *   list of annotations is resticted to those which belong to this type.
1708
 *
1709
 * @return array
1710
 *   An array of Annotation objects or an empty array.
1711
 */
1712
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1713

    
1714
  if(!isset($cdmBase->annotations)){
1715
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1716
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1717
  }
1718

    
1719
  $annotations = array();
1720
  foreach ($cdmBase->annotations as $annotation) {
1721
    if ($includeTypes) {
1722
      if (
1723
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1724
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1725
      ) {
1726
        $annotations[] = $annotation;
1727
      }
1728
    }
1729
    else {
1730
      $annotations[] = $annotation;
1731
    }
1732
  }
1733
  return $annotations;
1734

    
1735
}
1736

    
1737
/**
1738
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1739
 *
1740
 * @param object $annotatable_entity
1741
 *   The CDM AnnotatableEntity to load annotations for
1742
 */
1743
function cdm_load_annotations(&$annotatable_entity) {
1744
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1745
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1746
    if (is_array($annotations)) {
1747
      $annotatable_entity->annotations = $annotations;
1748
    }
1749
  }
1750
}
1751

    
1752
/**
1753
 * Extends the $cdm_entity object by the field if it is not already existing.
1754
 *
1755
 * This function can only be used for fields with 1 to many relations.
1756
  *
1757
 * @param $cdm_base_type
1758
 * @param $field_name
1759
 * @param $cdm_entity
1760
 */
1761
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1762
{
1763
  if (!isset($cdm_entity->$field_name)) {
1764
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1765
    $cdm_entity->$field_name = $items;
1766
  }
1767
}
1768

    
1769

    
1770
/**
1771
 * Get a NomenclaturalReference string.
1772
 *
1773
 * Returns the NomenclaturalReference string with correctly placed
1774
 * microreference (= reference detail) e.g.
1775
 * in Phytotaxa 43: 1-48. 2012.
1776
 *
1777
 * @param string $referenceUuid
1778
 *   UUID of the reference.
1779
 * @param string $microreference
1780
 *   Reference detail.
1781
 *
1782
 * @return string
1783
 *   a NomenclaturalReference.
1784
 */
1785
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1786

    
1787
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1788
  if(is_array($microreference) || is_object($microreference)) {
1789
    return '';
1790
  }
1791

    
1792
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1793
    $referenceUuid,
1794
  ), "microReference=" . urlencode($microreference));
1795

    
1796
  if ($obj) {
1797
    return $obj->String;
1798
  }
1799
  else {
1800
    return NULL;
1801
  }
1802
}
1803

    
1804
/**
1805
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1806
 *
1807
 * @param $feature_tree_nodes
1808
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1809
 * @param $feature_uuid
1810
 *    The UUID of the Feature
1811
 * @return returns the FeatureNode or null
1812
 */
1813
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1814

    
1815
  // 1. scan this level
1816
  foreach ($feature_tree_nodes as $node){
1817
    if($node->feature->uuid == $feature_uuid){
1818
      return $node;
1819
    }
1820
  }
1821

    
1822
  // 2. descend into childen
1823
  foreach ($feature_tree_nodes as $node){
1824
    if(is_array($node->childNodes)){
1825
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1826
      if($node) {
1827
        return $node;
1828
      }
1829
    }
1830
  }
1831
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1832
  return $null_var;
1833
}
1834

    
1835
/**
1836
 * Merges the given featureNodes structure with the descriptionElements.
1837
 *
1838
 * This method is used in preparation for rendering the descriptionElements.
1839
 * The descriptionElements which belong to a specific feature node are appended
1840
 * to a the feature node by creating a new field:
1841
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1842
 * The descriptionElements will be cleared in advance in order to allow reusing the
1843
 * same feature tree without the risk of mixing sets of description elements.
1844
 *
1845
 * which originally is not existing in the cdm.
1846
 *
1847
 *
1848
 *
1849
 * @param array $featureNodes
1850
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1851
 *    may have children.
1852
 * @param array $descriptionElements
1853
 *    An flat array of cdm DescriptionElements
1854
 * @return array
1855
 *    The $featureNodes structure enriched with the according $descriptionElements
1856
 */
1857
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1858

    
1859
  foreach ($featureNodes as &$node) {
1860
    // since the $featureNodes array is reused for each description
1861
    // it is necessary to clear the custom node fields in advance
1862
    if(isset($node->descriptionElements)){
1863
      unset($node->descriptionElements);
1864
    }
1865

    
1866
    // Append corresponding elements to an additional node field:
1867
    // $node->descriptionElements.
1868
    foreach ($descriptionElements as $element) {
1869
      if ($element->feature->uuid == $node->feature->uuid) {
1870
        if (!isset($node->descriptionElements)) {
1871
          $node->descriptionElements = array();
1872
        }
1873
        $node->descriptionElements[] = $element;
1874
      }
1875
    }
1876

    
1877
    // Recurse into node children.
1878
    if (isset($node->childNodes[0])) {
1879
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1880
      $node->childNodes = $mergedChildNodes;
1881
    }
1882

    
1883
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1884
      unset($node);
1885
    }
1886

    
1887
  }
1888

    
1889
  return $featureNodes;
1890
}
1891

    
1892
/**
1893
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1894
 *
1895
 * The response from the HTTP GET request is returned as object.
1896
 * The response objects coming from the webservice configured in the
1897
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1898
 *  in a level 2 (L2) cache.
1899
 *
1900
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1901
 * function, this cache persists only per each single page execution.
1902
 * Any object coming from the webservice is stored into it by default.
1903
 * In contrast to this default caching mechanism the L2 cache only is used if
1904
 * the 'cdm_webservice_cache' variable is set to TRUE,
1905
 * which can be set using the modules administrative settings section.
1906
 * Objects stored in this L2 cache are serialized and stored
1907
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1908
 * objects that are stored in the database will persist as
1909
 * long as the drupal cache is not being cleared and are available across
1910
 * multiple script executions.
1911
 *
1912
 * @param string $uri
1913
 *   URL to the webservice.
1914
 * @param array $pathParameters
1915
 *   An array of path parameters.
1916
 * @param string $query
1917
 *   A query string to be appended to the URL.
1918
 * @param string $method
1919
 *   The HTTP method to use, valid values are "GET" or "POST";
1920
 * @param bool $absoluteURI
1921
 *   TRUE when the URL should be treated as absolute URL.
1922
 *
1923
 * @return object| array
1924
 *   The de-serialized webservice response object.
1925
 */
1926
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1927

    
1928
  static $cacheL1 = array();
1929

    
1930
  $data = NULL;
1931
  // store query string in $data and clear the query, $data will be set as HTTP request body
1932
  if($method == 'POST'){
1933
    $data = $query;
1934
    $query = NULL;
1935
  }
1936

    
1937
  // Transform the given uri path or pattern into a proper webservice uri.
1938
  if (!$absoluteURI) {
1939
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1940
  }
1941

    
1942
  // read request parameter 'cacheL2_refresh'
1943
  // which allows refreshing the level 2 cache
1944
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1945

    
1946
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1947
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1948

    
1949
  if($method == 'GET'){
1950
    $cache_key = $uri;
1951
  } else {
1952
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1953
    // crc32 is faster but creates much shorter hashes
1954
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1955
  }
1956

    
1957
  if (array_key_exists($cache_key, $cacheL1)) {
1958
    $cacheL1_obj = $cacheL1[$uri];
1959
  }
1960

    
1961
  $set_cacheL1 = FALSE;
1962
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1963
    $set_cacheL1 = TRUE;
1964
  }
1965

    
1966
  // Only cache cdm webservice URIs.
1967
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1968
  $cacheL2_entry = FALSE;
1969

    
1970
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1971
    // Try to get object from cacheL2.
1972
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1973
  }
1974

    
1975
  if (isset($cacheL1_obj)) {
1976
    //
1977
    // The object has been found in the L1 cache.
1978
    //
1979
    $obj = $cacheL1_obj;
1980
    if (cdm_debug_block_visible()) {
1981
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1982
    }
1983
  }
1984
  elseif ($cacheL2_entry) {
1985
    //
1986
    // The object has been found in the L2 cache.
1987
    //
1988
    $duration_parse_start = microtime(TRUE);
1989
    $obj = unserialize($cacheL2_entry->data);
1990
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1991

    
1992
    if (cdm_debug_block_visible()) {
1993
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1994
    }
1995
  }
1996
  else {
1997
    //
1998
    // Get the object from the webservice and cache it.
1999
    //
2000
    $duration_fetch_start = microtime(TRUE);
2001
    // Request data from webservice JSON or XML.
2002
    $response = cdm_http_request($uri, $method, $data);
2003
    $response_body = NULL;
2004
    if (isset($response->data)) {
2005
      $response_body = $response->data;
2006
    }
2007
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2008
    $duration_parse_start = microtime(TRUE);
2009

    
2010
    // Parse data and create object.
2011
    $obj = cdm_load_obj($response_body);
2012

    
2013
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2014

    
2015
    if (cdm_debug_block_visible()) {
2016
      if ($obj || $response_body == "[]") {
2017
        $status = 'valid';
2018
      }
2019
      else {
2020
        $status = 'invalid';
2021
      }
2022
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2023
    }
2024
    if ($set_cacheL2) {
2025
      // Store the object in cache L2.
2026
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2027
      // flag serialized is set properly in the cache table.
2028
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2029
    }
2030
  }
2031
  if ($obj) {
2032
    // Store the object in cache L1.
2033
    if ($set_cacheL1) {
2034
      $cacheL1[$cache_key] = $obj;
2035
    }
2036
  }
2037
  return $obj;
2038
}
2039

    
2040
/**
2041
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2042
 *
2043
 * The cdm_ws_debug block will display the debug information.
2044
 *
2045
 * @param $uri
2046
 *    The CDM REST URI to which the request has been send
2047
 * @param string $method
2048
 *    The HTTP request method, either 'GET' or 'POST'
2049
 * @param string $post_data
2050
 *    The datastring send with a post request
2051
 * @param $duration_fetch
2052
 *    The time in seconds it took to fetch the data from the web service
2053
 * @param $duration_parse
2054
 *    Time in seconds which was needed to parse the json response
2055
 * @param $datasize
2056
 *    Size of the data received from the server
2057
 * @param $status
2058
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2059
 * @return bool
2060
 *    TRUE if adding the debug information was successful
2061
 */
2062
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2063

    
2064
  static $initial_time = NULL;
2065
  if(!$initial_time) {
2066
    $initial_time = microtime(TRUE);
2067
  }
2068
  $time = microtime(TRUE) - $initial_time;
2069

    
2070
  // Decompose uri into path and query element.
2071
  $uri_parts = explode("?", $uri);
2072
  $query = array();
2073
  if (count($uri_parts) == 2) {
2074
    $path = $uri_parts[0];
2075
  }
2076
  else {
2077
    $path = $uri;
2078
  }
2079

    
2080
  if(strpos($uri, '?') > 0){
2081
    $json_uri = str_replace('?', '.json?', $uri);
2082
    $xml_uri = str_replace('?', '.xml?', $uri);
2083
  } else {
2084
    $json_uri = $uri . '.json';
2085
    $xml_uri = $json_uri . '.xml';
2086
  }
2087

    
2088
  // data links to make data accecsible as json and xml
2089
  $data_links = '';
2090
  if (_is_cdm_ws_uri($path)) {
2091

    
2092
    // see ./js/http-method-link.js
2093

    
2094
    if($method == 'GET'){
2095
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2096
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2097
      $data_links .= '<br/>';
2098
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2099
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2100
    } else {
2101
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2102
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2103
      $data_links .= '<br/>';
2104
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2105
    }
2106
  }
2107
  else {
2108
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2109
  }
2110

    
2111
  //
2112
  $data = array(
2113
      'ws_uri' => $uri,
2114
      'method' => $method,
2115
      'post_data' => $post_data,
2116
      'time' => sprintf('%3.3f', $time),
2117
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2118
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2119
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2120
      'status' => $status,
2121
      'data_links' => $data_links
2122
  );
2123
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2124
    $_SESSION['cdm']['ws_debug'] = array();
2125
  }
2126
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2127

    
2128
  // Mark this page as being uncacheable.
2129
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2130
  drupal_page_is_cacheable(FALSE);
2131

    
2132
  // Messages not set when DB connection fails.
2133
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2134
}
2135

    
2136
/**
2137
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2138
 * the visibility depends on whether
2139
 *  - the block is enabled
2140
 *  - the visibility restrictions in the block settings are satisfied
2141
 */
2142
function cdm_debug_block_visible() {
2143
  static $is_visible = null;
2144

    
2145
  if($is_visible === null){
2146
      $block = block_load('cdm_api', 'cdm_ws_debug');
2147
      $is_visible = isset($block->status) && $block->status == 1;
2148
      if($is_visible){
2149
        $blocks = array($block);
2150
        // Checks the page, user role, and user-specific visibilty settings.
2151
        block_block_list_alter($blocks);
2152
        $is_visible = count($blocks) > 0;
2153
      }
2154
  }
2155
  return $is_visible;
2156
}
2157

    
2158
/**
2159
 * @todo Please document this function.
2160
 * @see http://drupal.org/node/1354
2161
 */
2162
function cdm_load_obj($response_body) {
2163
  $obj = json_decode($response_body);
2164

    
2165
  if (!(is_object($obj) || is_array($obj))) {
2166
    ob_start();
2167
    $obj_dump = ob_get_contents();
2168
    ob_clean();
2169
    return FALSE;
2170
  }
2171

    
2172
  return $obj;
2173
}
2174

    
2175
/**
2176
 * Do a http request to a CDM RESTful web service.
2177
 *
2178
 * @param string $uri
2179
 *   The webservice url.
2180
 * @param string $method
2181
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2182
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2183
 * @param $data: A string containing the request body, formatted as
2184
 *     'param=value&param=value&...'. Defaults to NULL.
2185
 *
2186
 * @return object
2187
 *   The object as returned by drupal_http_request():
2188
 *   An object that can have one or more of the following components:
2189
 *   - request: A string containing the request body that was sent.
2190
 *   - code: An integer containing the response status code, or the error code
2191
 *     if an error occurred.
2192
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2193
 *   - status_message: The status message from the response, if a response was
2194
 *     received.
2195
 *   - redirect_code: If redirected, an integer containing the initial response
2196
 *     status code.
2197
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2198
 *     target.
2199
 *   - error: If an error occurred, the error message. Otherwise not set.
2200
 *   - headers: An array containing the response headers as name/value pairs.
2201
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2202
 *     easy access the array keys are returned in lower case.
2203
 *   - data: A string containing the response body that was received.
2204
 */
2205
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2206
  static $acceptLanguage = NULL;
2207
  $header = array();
2208
  
2209
  if(!$acceptLanguage && module_exists('i18n')){
2210
    $acceptLanguage = i18n_language_content()->language;
2211
  }
2212

    
2213
  if (!$acceptLanguage) {
2214
    if (function_exists('apache_request_headers')) {
2215
      $headers = apache_request_headers();
2216
      if (isset($headers['Accept-Language'])) {
2217
        $acceptLanguage = $headers['Accept-Language'];
2218
      }
2219
    }
2220
  }
2221

    
2222
  if ($method != "GET" && $method != "POST") {
2223
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2224
  }
2225

    
2226
  if (_is_cdm_ws_uri($uri)) {
2227
    $header['Accept'] = 'application/json';
2228
    $header['Accept-Language'] = $acceptLanguage;
2229
    $header['Accept-Charset'] = 'UTF-8';
2230
  }
2231

    
2232
  if($method == "POST") {
2233
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2234
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2235
  }
2236

    
2237

    
2238
  cdm_dd($uri);
2239
  return drupal_http_request($uri, array(
2240
      'headers' => $header,
2241
      'method' => $method,
2242
      'data' => $data,
2243
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2244
      )
2245
   );
2246
}
2247

    
2248
/**
2249
 * Concatenates recursively the fields of all features contained in the given
2250
 * CDM FeatureTree root node.
2251
 *
2252
 * @param $rootNode
2253
 *     A CDM FeatureTree node
2254
 * @param
2255
 *     The character to be used as glue for concatenation, default is ', '
2256
 * @param $field_name
2257
 *     The field name of the CDM Features
2258
 * @param $excludes
2259
 *     Allows defining a set of values to be excluded. This refers to the values
2260
 *     in the field denoted by the $field_name parameter
2261
 *
2262
 */
2263
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2264
  $out = '';
2265

    
2266
  $pre_child_separator = $separator;
2267
  $post_child_separator = '';
2268

    
2269
  foreach ($root_node->childNodes as $feature_node) {
2270
    $out .= ($out ? $separator : '');
2271
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2272
      $out .= $feature_node->feature->$field_name;
2273
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2274
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2275
        if (strlen($childlabels)) {
2276
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2277
        }
2278
      }
2279
    }
2280
  }
2281
  return $out;
2282
}
2283

    
2284
/**
2285
 * Create a one-dimensional form options array.
2286
 *
2287
 * Creates an array of all features in the feature tree of feature nodes,
2288
 * the node labels are indented by $node_char and $childIndent depending on the
2289
 * hierachy level.
2290
 *
2291
 * @param - $rootNode
2292
 * @param - $node_char
2293
 * @param - $childIndentStr
2294
 * @param - $childIndent
2295
 *   ONLY USED INTERNALLY!
2296
 *
2297
 * @return array
2298
 *   A one dimensional Drupal form options array.
2299
 */
2300
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2301
  $options = array();
2302
  foreach ($rootNode->childNodes as $featureNode) {
2303
    $indent_prefix = '';
2304
    if ($childIndent) {
2305
      $indent_prefix = $childIndent . $node_char . " ";
2306
    }
2307
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2308
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2309
      // Foreach ($featureNode->childNodes as $childNode){
2310
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2311
      $options = array_merge_recursive($options, $childList);
2312
      // }
2313
    }
2314
  }
2315
  return $options;
2316
}
2317

    
2318
/**
2319
 * Returns an array with all available FeatureTrees and the representations of the selected
2320
 * FeatureTree as a detail view.
2321
 *
2322
 * @param boolean $add_default_feature_free
2323
 * @return array
2324
 *  associative array with following keys:
2325
 *  -options: Returns an array with all available Feature Trees
2326
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2327
 *
2328
 */
2329
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2330

    
2331
  $options = array();
2332
  $tree_representations = array();
2333
  $feature_trees = array();
2334

    
2335
  // Set tree that contains all features.
2336
  if ($add_default_feature_free) {
2337
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2338
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2339
  }
2340

    
2341
  // Get feature trees from database.
2342
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2343
  if (is_array($persited_trees)) {
2344
    $feature_trees = array_merge($feature_trees, $persited_trees);
2345
  }
2346

    
2347
  foreach ($feature_trees as $featureTree) {
2348

    
2349
    if(!is_object($featureTree)){
2350
      continue;
2351
    }
2352
    // Do not add the DEFAULT_FEATURETREE again,
2353
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2354
      $options[$featureTree->uuid] = $featureTree->titleCache;
2355
    }
2356

    
2357
    // Render the hierarchic tree structure
2358
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2359

    
2360
      // Render the hierarchic tree structure.
2361
      $treeDetails = '<div class="featuretree_structure">'
2362
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2363
        . '</div>';
2364

    
2365
      $form = array();
2366
      $form['featureTree-' .  $featureTree->uuid] = array(
2367
        '#type' => 'fieldset',
2368
        '#title' => 'Show details',
2369
        '#attributes' => array('class' => array('collapsible collapsed')),
2370
        // '#collapsible' => TRUE,
2371
        // '#collapsed' => TRUE,
2372
      );
2373
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2374
        '#markup' => $treeDetails,
2375
      );
2376

    
2377
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2378
    }
2379

    
2380
  } // END loop over feature trees
2381

    
2382
  // return $options;
2383
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2384
}
2385

    
2386
/**
2387
 * Provides the list of available classifications in form of an options array.
2388
 *
2389
 * The options array is suitable for drupal form API elements that allow multiple choices.
2390
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2391
 *
2392
 * The classifications are ordered alphabetically whereas the classification
2393
 * chosen as default will always appear on top of the array, followed by a
2394
 * blank line below.
2395
 *
2396
 * @param bool $add_none_option
2397
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2398
 *
2399
 * @return array
2400
 *   classifications in an array as options for a form element that allows multiple choices.
2401
 */
2402
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2403

    
2404
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2405

    
2406
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2407
  $default_classification_label = '';
2408

    
2409
  // add all classifications
2410
  $taxonomic_tree_options = array();
2411
  if ($add_none_option) {
2412
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2413
  }
2414
  if ($taxonTrees) {
2415
    foreach ($taxonTrees as $tree) {
2416
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2417
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2418
      } else {
2419
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2420
        $default_classification_label = $tree->titleCache;
2421
      }
2422
    }
2423
  }
2424
  // oder alphabetically the space
2425
  asort($taxonomic_tree_options);
2426

    
2427
  // now set the labels
2428
  //   for none
2429
  if ($add_none_option) {
2430
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2431
  }
2432

    
2433
  //   for default_classification
2434
  if (is_uuid($default_classification_uuid)) {
2435
    $taxonomic_tree_options[$default_classification_uuid] =
2436
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2437
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2438
  }
2439

    
2440
  return $taxonomic_tree_options;
2441
}
2442

    
2443
/**
2444
 * @todo Please document this function.
2445
 * @see http://drupal.org/node/1354
2446
 */
2447
function cdm_api_secref_cache_prefetch(&$secUuids) {
2448
  // Comment @WA: global variables should start with a single underscore
2449
  // followed by the module and another underscore.
2450
  global $_cdm_api_secref_cache;
2451
  if (!is_array($_cdm_api_secref_cache)) {
2452
    $_cdm_api_secref_cache = array();
2453
  }
2454
  $uniqueUuids = array_unique($secUuids);
2455
  $i = 0;
2456
  $param = '';
2457
  while ($i++ < count($uniqueUuids)) {
2458
    $param .= $secUuids[$i] . ',';
2459
    if (strlen($param) + 37 > 2000) {
2460
      _cdm_api_secref_cache_add($param);
2461
      $param = '';
2462
    }
2463
  }
2464
  if ($param) {
2465
    _cdm_api_secref_cache_add($param);
2466
  }
2467
}
2468

    
2469
/**
2470
 * @todo Please document this function.
2471
 * @see http://drupal.org/node/1354
2472
 */
2473
function cdm_api_secref_cache_get($secUuid) {
2474
  global $_cdm_api_secref_cache;
2475
  if (!is_array($_cdm_api_secref_cache)) {
2476
    $_cdm_api_secref_cache = array();
2477
  }
2478
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2479
    _cdm_api_secref_cache_add($secUuid);
2480
  }
2481
  return $_cdm_api_secref_cache[$secUuid];
2482
}
2483

    
2484
/**
2485
 * @todo Please document this function.
2486
 * @see http://drupal.org/node/1354
2487
 */
2488
function cdm_api_secref_cache_clear() {
2489
  global $_cdm_api_secref_cache;
2490
  $_cdm_api_secref_cache = array();
2491
}
2492

    
2493

    
2494
/**
2495
 * Validates if the given string is a uuid.
2496
 *
2497
 * @param string $str
2498
 *   The string to validate.
2499
 *
2500
 * return bool
2501
 *   TRUE if the string is a UUID.
2502
 */
2503
function is_uuid($str) {
2504
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2505
}
2506

    
2507
/**
2508
 * Checks if the given $object is a valid cdm entity.
2509
 *
2510
 * An object is considered a cdm entity if it has a string field $object->class
2511
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2512
 * The function is null save.
2513
 *
2514
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2515
 *
2516
 * @param mixed $object
2517
 *   The object to validate
2518
 *
2519
 * @return bool
2520
 *   True if the object is a cdm entity.
2521
 */
2522
function is_cdm_entity($object) {
2523
  return
2524
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2525
    && is_string($object->uuid) && is_uuid($object->uuid);
2526
}
2527

    
2528
/**
2529
 * @todo Please document this function.
2530
 * @see http://drupal.org/node/1354
2531
 */
2532
function _cdm_api_secref_cache_add($secUuidsStr) {
2533
  global $_cdm_api_secref_cache;
2534
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2535
  // Batch fetching not jet reimplemented thus:
2536
  /*
2537
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2538
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2539
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2540
  */
2541
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2542
}
2543

    
2544
/**
2545
 * Checks if the given uri starts with a cdm webservice url.
2546
 *
2547
 * Checks if the uri starts with the cdm webservice url stored in the
2548
 * Drupal variable 'cdm_webservice_url'.
2549
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2550
 *
2551
 * @param string $uri
2552
 *   The URI to test.
2553
 *
2554
 * @return bool
2555
 *   True if the uri starts with a cdm webservice url.
2556
 */
2557
function _is_cdm_ws_uri($uri) {
2558
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2559
}
2560

    
2561
/**
2562
 * @todo Please document this function.
2563
 * @see http://drupal.org/node/1354
2564
 */
2565
function queryString($elements) {
2566
  $query = '';
2567
  foreach ($elements as $key => $value) {
2568
    if (is_array($value)) {
2569
      foreach ($value as $v) {
2570
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2571
      }
2572
    }
2573
    else {
2574
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2575
    }
2576
  }
2577
  return $query;
2578
}
2579

    
2580
/**
2581
 * Implementation of the magic method __clone to allow deep cloning of objects
2582
 * and arrays.
2583
 */
2584
function __clone() {
2585
  foreach ($this as $name => $value) {
2586
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2587
      $this->$name = clone($this->$name);
2588
    }
2589
  }
2590
}
2591

    
2592
/**
2593
 * Compares the given CDM Term instances by the  representationL10n.
2594
 *
2595
 * Can also be used with TermDTOs. To be used in usort()
2596
 *
2597
 * @see http://php.net/manual/en/function.usort.php
2598
 *
2599
 * @param $term1
2600
 *   The first CDM Term instance
2601
 * @param $term2
2602
 *   The second CDM Term instance
2603
 * @return int
2604
 *   The result of the comparison
2605
 */
2606
function compare_terms_by_representationL10n($term1, $term2) {
2607

    
2608
  if (!isset($term1->representation_L10n)) {
2609
    $term1->representationL10n = '';
2610
  }
2611
  if (!isset($term2->representation_L10n)) {
2612
    $term2->representationL10n = '';
2613
  }
2614

    
2615
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2616
}
2617

    
2618
function compare_terms_by_order_index($term1, $term2) {
2619

    
2620

    
2621
  if (!isset($term1->orderIndex)) {
2622
    $a = 0;
2623
  } else {
2624
    $a = $term1->orderIndex;
2625
  }
2626
  if (!isset($term2->orderIndex)) {
2627
    $b = 0;
2628
  } else {
2629
    $b = $term2->orderIndex;
2630
  }
2631

    
2632
  if ($a == $b) {
2633
    return 0;
2634
  }
2635
  return ($a < $b) ? -1 : 1;
2636

    
2637
}
2638

    
2639

    
2640
/**
2641
 * Make a 'deep copy' of an array.
2642
 *
2643
 * Make a complete deep copy of an array replacing
2644
 * references with deep copies until a certain depth is reached
2645
 * ($maxdepth) whereupon references are copied as-is...
2646
 *
2647
 * @see http://us3.php.net/manual/en/ref.array.php
2648
 *
2649
 * @param array $array
2650
 * @param array $copy passed by reference
2651
 * @param int $maxdepth
2652
 * @param int $depth
2653
 */
2654
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2655
  if ($depth > $maxdepth) {
2656
    $copy = $array;
2657
    return;
2658
  }
2659
  if (!is_array($copy)) {
2660
    $copy = array();
2661
  }
2662
  foreach ($array as $k => &$v) {
2663
    if (is_array($v)) {
2664
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2665
    }
2666
    else {
2667
      $copy[$k] = $v;
2668
    }
2669
  }
2670
}
2671

    
2672
/**
2673
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2674
 *
2675
 */
2676
function _add_js_ws_debug() {
2677

    
2678
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2679
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2680
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2681
    // use the developer versions of js libs
2682
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2683
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2684
  }
2685
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2686
    array(
2687
      'type' => 'file',
2688
      'weight' => JS_LIBRARY,
2689
      'cache' => TRUE)
2690
    );
2691

    
2692
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2693
    array(
2694
      'type' => 'file',
2695
      'weight' => JS_LIBRARY,
2696
      'cache' => TRUE)
2697
    );
2698
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2699
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2700

    
2701
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2702
    array(
2703
      'type' => 'file',
2704
      'weight' => JS_LIBRARY,
2705
      'cache' => TRUE)
2706
    );
2707
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2708
    array(
2709
    'type' => 'file',
2710
    'weight' => JS_LIBRARY,
2711
    'cache' => TRUE)
2712
    );
2713

    
2714
}
2715

    
2716
/**
2717
 * @todo Please document this function.
2718
 * @see http://drupal.org/node/1354
2719
 */
2720
function _no_classfication_uuid_message() {
2721
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2722
    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.');
2723
  }
2724
  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.');
2725
}
2726

    
2727
/**
2728
 * Implementation of hook flush_caches
2729
 *
2730
 * Add custom cache tables to the list of cache tables that
2731
 * will be cleared by the Clear button on the Performance page or whenever
2732
 * drupal_flush_all_caches is invoked.
2733
 *
2734
 * @author W.Addink <waddink@eti.uva.nl>
2735
 *
2736
 * @return array
2737
 *   An array with custom cache tables to include.
2738
 */
2739
function cdm_api_flush_caches() {
2740
  return array('cache_cdm_ws');
2741
}
2742

    
2743
/**
2744
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2745
 *
2746
 * @param $data
2747
 *   The variable to log to the drupal_debug.txt log file.
2748
 * @param $label
2749
 *   (optional) If set, a label to output before $data in the log file.
2750
 *
2751
 * @return
2752
 *   No return value if successful, FALSE if the log file could not be written
2753
 *   to.
2754
 *
2755
 * @see cdm_dataportal_init() where the log file is reset on each requests
2756
 * @see dd()
2757
 * @see http://drupal.org/node/314112
2758
 *
2759
 */
2760
function cdm_dd($data, $label = NULL) {
2761
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2762
    return dd($data, $label);
2763
  }
2764
}
2765

    
(5-5/11)