Project

General

Profile

Download (82.8 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 string $tag
240
 *   Html tag name to convert the items into, default is 'span'.
241
 * @param string $glue
242
 *   The string by which the chained text tokens are concatenated together.
243
 *   Default is a blank character.
244
 *
245
 * @return string
246
 *   A string with HTML.
247
 */
248
function cdm_tagged_text_to_markup(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
249
  $out = '';
250
  $i = 0;
251
  foreach ($taggedtxt as $tt) {
252
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
253
      $class_attr = $tt->type;
254
      if(isset($tt->entityReference)){
255
        $class_attr .= " " . html_class_attribute_ref($tt->entityReference);
256
      }
257
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '')
258
        . '<' . $tag . ' class="' . $class_attr . '">'
259
        . t('@text', array('@text' => $tt->text))
260
        . '</' . $tag . '>';
261
    }
262
  }
263
  return $out;
264
}
265

    
266

    
267
/**
268
 * Finds the text tagged with $tag_type in an array of taggedText instances.
269
 *
270
 * Note: This function is currently unused.
271
 *
272
 * @param array $taggedtxt
273
 *   Array with text items.
274
 * @param string $tag_type
275
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
276
 *   to return all texts.
277
 *
278
 * @return array
279
 *   An array with the texts mapped by $tag_type.
280
 */
281
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
282
  $tokens = array();
283
  if (!empty($taggedtxt)) {
284
    foreach ($taggedtxt as $tagtxt) {
285
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
286
        $tokens[] = $tagtxt->text;
287
      }
288
    }
289
  }
290
  return $tokens;
291
}
292

    
293
/**
294
 * Preprocess the taggedTitle arrays.
295
 *
296
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
297
 * into tag type "name"
298
 *
299
 * Step 2: Two taggedTexts which have the same type and which have
300
 * a separator between them are merged together.
301
 *
302
 * @param array $taggedTextList
303
 *    An array of TaggedText objects
304
 */
305
function normalize_tagged_text(&$taggedTextList) {
306

    
307
  if (is_array($taggedTextList)) {
308

    
309
    // First pass: rename.
310
    for ($i = 0; $i < count($taggedTextList); $i++) {
311

    
312
      if ($taggedTextList[$i]->type == "hybridSign") {
313
        $taggedTextList[$i]->type = "name";
314
      }
315
    }
316

    
317
    // Second pass: resolve separators.
318
    $taggedNameListNew = array();
319
    for ($i = 0; $i < count($taggedTextList); $i++) {
320

    
321
      // elements of the same type concatenated by a separator should be merged together
322
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
323
        $taggedName = clone $taggedTextList[$i];
324
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
325
        $taggedNameListNew[] = $taggedName;
326
        ++$i;
327
        ++$i;
328
        continue;
329
      }
330
      // no special handling
331
      $taggedNameListNew[] = $taggedTextList[$i];
332

    
333
    }
334
    $taggedTextList = $taggedNameListNew;
335
  }
336
}
337

    
338
function split_secref_from_tagged_text(&$tagged_text) {
339

    
340
  $extracted_tt = array();
341
  if (is_array($tagged_text)) {
342
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
343
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
344
        $extracted_tt[0] = $tagged_text[$i];
345
        $extracted_tt[1] = $tagged_text[$i + 1];
346
        unset($tagged_text[$i]);
347
        unset($tagged_text[$i + 1]);
348
        // also get the microfererence which could be in $tagged_text[$i + 3]
349
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
350
          $extracted_tt[2] = $tagged_text[$i + 2];
351
          $extracted_tt[3] = $tagged_text[$i + 3];
352
        }
353
        break;
354
      }
355
    }
356
  }
357
  return $extracted_tt;
358
}
359

    
360

    
361
function split_nomstatus_from_tagged_text(&$tagged_text) {
362

    
363
  $extracted_tt = array();
364
  if (is_array($tagged_text)) {
365
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
366
      if ($tagged_text[$i]->type == "nomStatus"){
367
        $extracted_tt[] = $tagged_text[$i];
368
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
369
          $extracted_tt[] = $tagged_text[$i + 1];
370
          unset($tagged_text[$i + 1]);
371
        }
372
        if ($tagged_text[$i - 1]->type == "separator"){
373
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
374
          unset($tagged_text[$i - 1]);
375
        }
376
        unset($tagged_text[$i]);
377
        break;
378
      }
379
    }
380
  }
381
  return $extracted_tt;
382
}
383

    
384
function find_tagged_text_elements($taggedTextList, $type){
385
  $matching_elements = array();
386
  if (is_array($taggedTextList)) {
387
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
388
      if($taggedTextList[$i]->type == $type){
389
        $matching_elements[] = $taggedTextList[$i];
390
      }
391
    }
392
  }
393
  return $matching_elements;
394
}
395

    
396
// ===================== END of Tagged Text functions ================== //
397

    
398
/**
399
 * Lists the classifications a taxon belongs to
400
 *
401
 * @param CDM type Taxon $taxon
402
 *   the taxon
403
 *
404
 * @return array
405
 *   aray of CDM instances of Type Classification
406
 */
407
function get_classifications_for_taxon($taxon) {
408

    
409
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
410
}
411

    
412
/**
413
 * Returns the chosen FeatureTree for the taxon profile.
414
 *
415
 * The FeatureTree profile returned is the one that has been set in the
416
 * dataportal settings (layout->taxon:profile).
417
 * When the chosen FeatureTree is not found in the database,
418
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
419
 *
420
 * @return mixed
421
 *   A cdm FeatureTree object.
422
 */
423
function get_profile_feature_tree() {
424
  static $profile_featureTree;
425

    
426
  if($profile_featureTree == NULL) {
427
    $profile_featureTree = cdm_ws_get(
428
      CDM_WS_FEATURETREE,
429
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
430
    );
431
    if (!$profile_featureTree) {
432
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
433
    }
434
  }
435

    
436
  return $profile_featureTree;
437
}
438

    
439
/**
440
 * Returns the chosen FeatureTree for SpecimenDescriptions.
441
 *
442
 * The FeatureTree returned is the one that has been set in the
443
 * dataportal settings (layout->taxon:specimen).
444
 * When the chosen FeatureTree is not found in the database,
445
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
446
 *
447
 * @return mixed
448
 *   A cdm FeatureTree object.
449
 */
450
function cdm_get_occurrence_featureTree() {
451
  static $occurrence_featureTree;
452

    
453
  if($occurrence_featureTree == NULL) {
454
    $occurrence_featureTree = cdm_ws_get(
455
      CDM_WS_FEATURETREE,
456
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
457
    );
458
    if (!$occurrence_featureTree) {
459
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
460
    }
461
  }
462
  return $occurrence_featureTree;
463
}
464

    
465
/**
466
 * Returns the FeatureTree for structured descriptions
467
 *
468
 * The FeatureTree returned is the one that has been set in the
469
 * dataportal settings (layout->taxon:profile).
470
 * When the chosen FeatureTree is not found in the database,
471
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
472
 *
473
 * @return mixed
474
 *   A cdm FeatureTree object.
475
 */
476
function get_structured_description_featureTree() {
477
  static $structured_description_featureTree;
478

    
479
  if($structured_description_featureTree == NULL) {
480
    $structured_description_featureTree = cdm_ws_get(
481
        CDM_WS_FEATURETREE,
482
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
483
    );
484
    if (!$structured_description_featureTree) {
485
      $structured_description_featureTree = cdm_ws_get(
486
          CDM_WS_FEATURETREE,
487
          UUID_DEFAULT_FEATURETREE
488
      );
489
    }
490
  }
491
  return $structured_description_featureTree;
492
}
493

    
494

    
495
/**
496
 * @todo Please document this function.
497
 * @see http://drupal.org/node/1354
498
 */
499
function set_last_taxon_page_tab($taxonPageTab) {
500
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
501
}
502

    
503
/**
504
 * @todo Please document this function.
505
 * @see http://drupal.org/node/1354
506
 */
507
function get_last_taxon_page_tab() {
508
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
509
    return $_SESSION['cdm']['taxon_page_tab'];
510
  }
511
  else {
512
    return FALSE;
513
  }
514
}
515

    
516
/**
517
 *
518
 * @param object $media
519
 * @param array $mimeTypes
520
 *    an array of mimetypes in their order of preference. e.g:
521
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
522
 * @param int $width
523
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
524
 * @param int $height
525
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
526
 *
527
 * @return array
528
 *   An array with preferred media representations or else an empty array.
529
 */
530
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
531
  $prefRepr = array();
532
  if (!isset($media->representations[0])) {
533
    return $prefRepr;
534
  }
535

    
536
  while (count($mimeTypes) > 0) {
537
    // getRepresentationByMimeType
538
    $mimeType = array_shift($mimeTypes);
539

    
540
    foreach ($media->representations as &$representation) {
541
      // If the mimetype is not known, try inferring it.
542
      if (!$representation->mimeType) {
543
        if (isset($representation->parts[0])) {
544
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
545
        }
546
      }
547

    
548
      if ($representation->mimeType == $mimeType) {
549
        // Preferred mimetype found -> erase all remaining mimetypes
550
        // to end loop.
551
        $mimeTypes = array();
552
        $expansionDeltaSum = 0;
553
        $valid_parts_cnt = 0;
554
        // Look for part with the best matching size.
555
        foreach ($representation->parts as $part) {
556
          if (empty($part->uri)) {
557
            // skip part if URI is missing
558
            continue;
559
          }
560
          $valid_parts_cnt++;
561
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
562

    
563
          // determine the optimal size
564
          if (isset($part->width) && isset($part->height)) {
565
            $expansion = $part->width * $part->height;
566
            if ($width != null && $height != null) {
567
              $optimalExpansion = $height * $width;
568
            } else {
569
              $optimalExpansion = PHP_INT_MAX;
570
            }
571
            // determine the difference
572
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
573
          }
574
          // sum up the expansionDeltas of all parts contained in the representation
575
          $expansionDeltaSum += $expansionDelta;
576
        }
577
        if($valid_parts_cnt > 0){
578
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
579
          $prefRepr[$expansionDeltaSum] = $representation;
580
        }
581
      }
582
    }
583
  }
584
  // Sort the array so that the smallest key value is the first in the array
585
  ksort($prefRepr);
586
  return $prefRepr;
587
}
588

    
589
/**
590
 * Infers the mime type of a file using the filename extension.
591
 *
592
 * The filename extension is used to infer the mime type.
593
 *
594
 * @param string $filepath
595
 *   The path to the respective file.
596
 *
597
 * @return string
598
 *   The mimetype for the file or FALSE if the according mime type could
599
 *   not be found.
600
 */
601
function infer_mime_type($filepath) {
602
  static $mimemap = NULL;
603
  if (!$mimemap) {
604
    $mimemap = array(
605
      'jpg' => 'image/jpeg',
606
      'jpeg' => 'image/jpeg',
607
      'png' => 'image/png',
608
      'gif' => 'image/gif',
609
      'giff' => 'image/gif',
610
      'tif' => 'image/tif',
611
      'tiff' => 'image/tif',
612
      'pdf' => 'application/pdf',
613
      'html' => 'text/html',
614
      'htm' => 'text/html',
615
    );
616
  }
617
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
618
  if (isset($mimemap[$extension])) {
619
    return $mimemap[$extension];
620
  }
621
  else {
622
    // FIXME remove this hack just return FALSE;
623
    return 'text/html';
624
  }
625
}
626

    
627
/**
628
 * Converts an ISO 8601 org.joda.time.Partial to a year.
629
 *
630
 * The function expects an ISO 8601 time representation of a
631
 * org.joda.time.Partial of the form yyyy-MM-dd.
632
 *
633
 * @param string $partial
634
 *   ISO 8601 time representation of a org.joda.time.Partial.
635
 *
636
 * @return string
637
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
638
 */
639
function partialToYear($partial) {
640
  if (is_string($partial)) {
641
    $year = substr($partial, 0, 4);
642
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
643
      return $year;
644
    }
645
  }
646
  return '';
647
}
648

    
649
/**
650
 * Converts an ISO 8601 org.joda.time.Partial to a month.
651
 *
652
 * This function expects an ISO 8601 time representation of a
653
 * org.joda.time.Partial of the form yyyy-MM-dd.
654
 * In case the month is unknown (= ???) NULL is returned.
655
 *
656
 * @param string $partial
657
 *   ISO 8601 time representation of a org.joda.time.Partial.
658
 *
659
 * @return string
660
 *   A month.
661
 */
662
function partialToMonth($partial) {
663
  if (is_string($partial)) {
664
    $month = substr($partial, 5, 2);
665
    if (preg_match("/[0-9][0-9]/", $month)) {
666
      return $month;
667
    }
668
  }
669
  return '';
670
}
671

    
672
/**
673
 * Converts an ISO 8601 org.joda.time.Partial to a day.
674
 *
675
 * This function expects an ISO 8601 time representation of a
676
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
677
 * In case the day is unknown (= ???) NULL is returned.
678
 *
679
 * @param string $partial
680
 *   ISO 8601 time representation of a org.joda.time.Partial.
681
 *
682
 * @return string
683
 *   A day.
684
 */
685
function partialToDay($partial) {
686
  if (is_string($partial)) {
687
    $day = substr($partial, 8, 2);
688
    if (preg_match("/[0-9][0-9]/", $day)) {
689
      return $day;
690
    }
691
  }
692
  return '';
693
}
694

    
695
/**
696
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
697
 *
698
 * This function expects an ISO 8601 time representations of a
699
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
700
 * four digit year, month and day with dashes:
701
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
702
 *
703
 * The partial may contain question marks eg: "1973-??-??",
704
 * these are turned in to '00' or are stripped depending of the $stripZeros
705
 * parameter.
706
 *
707
 * @param string $partial
708
 *   org.joda.time.Partial.
709
 * @param bool $stripZeros
710
 *   If set to TRUE the zero (00) month and days will be hidden:
711
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
712
 * @param string @format
713
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
714
 *    - "YYYY": Year only
715
 *    - "YYYY-MM-DD": this is the default
716
 *
717
 * @return string
718
 *   YYYY-MM-DD formatted year, month, day.
719
 */
720
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
721

    
722
  $y = NULL; $m = NULL; $d = NULL;
723

    
724
  if(strpos($format, 'YY') !== FALSE){
725
    $y = partialToYear($partial);
726
  }
727
  if(strpos($format, 'MM') !== FALSE){
728
    $m = partialToMonth($partial);
729
  }
730
  if(strpos($format, 'DD') !== FALSE){
731
    $d = partialToDay($partial);
732
  }
733

    
734
  $y = $y ? $y : '00';
735
  $m = $m ? $m : '00';
736
  $d = $d ? $d : '00';
737

    
738
  $date = '';
739

    
740
  if ($y == '00' && $stripZeros) {
741
    return '';
742
  }
743
  else {
744
    $date = $y;
745
  }
746

    
747
  if ($m == '00' && $stripZeros) {
748
    return $date;
749
  }
750
  else {
751
    $date .= "-" . $m;
752
  }
753

    
754
  if ($d == '00' && $stripZeros) {
755
    return $date;
756
  }
757
  else {
758
    $date .= "-" . $d;
759
  }
760
  return $date;
761
}
762

    
763
/**
764
 * Converts a time period to a string.
765
 *
766
 * See also partialToDate($partial, $stripZeros).
767
 *
768
 * @param object $period
769
 *   An JodaTime org.joda.time.Period object.
770
 * @param bool $stripZeros
771
 *   If set to True, the zero (00) month and days will be hidden:
772
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
773
 * @param string @format
774
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
775
 *    - "YYYY": Year only
776
 *    - "YYYY-MM-DD": this is the default
777
 *
778
 * @return string
779
 *   Returns a date in the form of a string.
780
 */
781
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
782
  $dateString = '';
783
  if($period->freeText){
784
    $dateString = $period->freeText;
785
  } else {
786
    if ($period->start) {
787
      $dateString = partialToDate($period->start, $stripZeros, $format);
788
    }
789
    if ($period->end) {
790
      $end_str = partialToDate($period->end, $stripZeros, $format);
791
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
792
    }
793
  }
794
  return $dateString;
795
}
796

    
797
/**
798
 * returns the earliest date available in the $period in a normalized
799
 * form suitable for sorting, e.g.:
800
 *
801
 *  - 1956-00-00
802
 *  - 0000-00-00
803
 *  - 1957-03-00
804
 *
805
 * that is either the start date is returned if set otherwise the
806
 * end date
807
 *
808
 * @param  $period
809
 *    An JodaTime org.joda.time.Period object.
810
 * @return string normalized form of the date
811
 *   suitable for sorting
812
 */
813
function timePeriodAsOrderKey($period) {
814
  $dateString = '';
815
  if ($period->start) {
816
    $dateString = partialToDate($period->start, false);
817
  }
818
  if ($period->end) {
819
    $dateString .= partialToDate($period->end, false);
820
  }
821
  return $dateString;
822
}
823

    
824
/**
825
 * Composes a absolute CDM web service URI with parameters and querystring.
826
 *
827
 * @param string $uri_pattern
828
 *   String with place holders ($0, $1, ..) that should be replaced by the
829
 *   according element of the $pathParameters array.
830
 * @param array $pathParameters
831
 *   An array of path elements, or a single element.
832
 * @param string $query
833
 *   A query string to append to the URL.
834
 *
835
 * @return string
836
 *   A complete URL with parameters to a CDM webservice.
837
 */
838
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
839
  if (empty($pathParameters)) {
840
    $pathParameters = array();
841
  }
842

    
843
  // (1)
844
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
845
  // according element of the $pathParameters array.
846
  static $helperArray = array();
847
  if (isset($pathParameters) && !is_array($pathParameters)) {
848
    $helperArray[0] = $pathParameters;
849
    $pathParameters = $helperArray;
850
  }
851

    
852
  $i = 0;
853
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
854
    if (count($pathParameters) <= $i) {
855
        drupal_set_message(
856
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
857
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
858
          'error');
859
      break;
860
    }
861
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
862
    ++$i;
863
  }
864

    
865
  // (2)
866
  // Append all remaining element of the $pathParameters array as path
867
  // elements.
868
  if (count($pathParameters) > $i) {
869
    // Strip trailing slashes.
870
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
871
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
872
    }
873
    while (count($pathParameters) > $i) {
874
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
875
      ++$i;
876
    }
877
  }
878

    
879
  // (3)
880
  // Append the query string supplied by $query.
881
  if (isset($query)) {
882
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
883
  }
884

    
885
  $path = $uri_pattern;
886

    
887
  $uri = variable_get('cdm_webservice_url', '') . $path;
888
  return $uri;
889
}
890

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

    
910
  $args = func_get_args();
911
  $do_gzip = function_exists('gzencode');
912
  $uriEncoded = array_shift($args);
913
  $uri = urldecode($uriEncoded);
914
  $hook = array_shift($args);
915
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
916

    
917
  $post_data = null;
918

    
919
  if ($request_method == "POST" || $request_method == "PUT") {
920
    // read response body via inputstream module
921
    $post_data = file_get_contents("php://input");
922
  }
923

    
924
  // Find and deserialize arrays.
925
  foreach ($args as &$arg) {
926
    // FIXME use regex to find serialized arrays.
927
    //       or should we accept json instead of php serializations?
928
    if (strpos($arg, "a:") === 0) {
929
      $arg = unserialize($arg);
930
    }
931
  }
932

    
933
  // In all these cases perform a simple get request.
934
  // TODO reconsider caching logic in this function.
935

    
936
  if (empty($hook)) {
937
    // simply return the webservice response
938
    // Print out JSON, the cache cannot be used since it contains objects.
939
    $http_response = cdm_http_request($uri, $request_method, $post_data);
940
    if (isset($http_response->headers)) {
941
      foreach ($http_response->headers as $hname => $hvalue) {
942
        drupal_add_http_header($hname, $hvalue);
943
      }
944
    }
945
    if (isset($http_response->data)) {
946
      print $http_response->data;
947
      flush();
948
    }
949
    exit(); // leave drupal here
950
  } else {
951
    // $hook has been supplied
952
    // handle $hook either as compose ot theme hook
953
    // pass through theme or comose hook
954
    // compose hooks can be called without data, therefore
955
    // passing the $uri in this case is not always a requirement
956

    
957
    if($uri && $uri != 'NULL') {
958
    // do a security check since the $uri will be passed
959
    // as absolute URI to cdm_ws_get()
960
      if (!_is_cdm_ws_uri($uri)) {
961
        drupal_set_message(
962
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
963
          'error'
964
        );
965
        return '';
966
      }
967

    
968
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
969
    } else {
970
      $obj = NULL;
971
    }
972

    
973
    $reponse_data = NULL;
974

    
975
    if (function_exists('compose_' . $hook)){
976
      // call compose hook
977

    
978
      $elements =  call_user_func('compose_' . $hook, $obj);
979
      // pass the render array to drupal_render()
980
      $reponse_data = drupal_render($elements);
981
    } else {
982
      // call theme hook
983

    
984
      // TODO use theme registry to get the registered hook info and
985
      //    use these defaults
986
      switch($hook) {
987
        case 'cdm_taxontree':
988
          $variables = array(
989
            'tree' => $obj,
990
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
991
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
992
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
993
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
994
            );
995
          $reponse_data = theme($hook, $variables);
996
          break;
997

    
998
        case 'cdm_list_of_taxa':
999
            $variables = array(
1000
              'records' => $obj,
1001
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
1002
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
1003
            $reponse_data = theme($hook, $variables);
1004
            break;
1005

    
1006
        case 'cdm_media_caption':
1007
          $variables = array(
1008
            'media' => $obj,
1009
            // $args[0] is set in taxon_image_gallery_default in
1010
            // cdm_dataportal.page.theme.
1011
            'elements' => isset($args[0]) ? $args[0] : array(
1012
            'title',
1013
            'description',
1014
            'artist',
1015
            'location',
1016
            'rights',
1017
          ),
1018
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
1019
          );
1020
          $reponse_data = theme($hook, $variables);
1021
          break;
1022

    
1023
        default:
1024
          drupal_set_message(t(
1025
          'Theme !theme is not yet supported by the function !function.', array(
1026
          '!theme' => $hook,
1027
          '!function' => __FUNCTION__,
1028
          )), 'error');
1029
          break;
1030
      } // END of theme hook switch
1031
    } // END of tread as theme hook
1032

    
1033

    
1034
    if($do_gzip){
1035
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1036
      drupal_add_http_header('Content-Encoding', 'gzip');
1037
    }
1038
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1039
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1040

    
1041
    print $reponse_data;
1042
  } // END of handle $hook either as compose ot theme hook
1043

    
1044
}
1045

    
1046
/**
1047
 * @todo Please document this function.
1048
 * @see http://drupal.org/node/1354
1049
 */
1050
function setvalue_session() {
1051
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1052
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1053
    $var_keys = explode('][', $var_keys);
1054
  }
1055
  else {
1056
    return;
1057
  }
1058
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1059

    
1060
  // Prevent from malicous tags.
1061
  $val = strip_tags($val);
1062

    
1063
  $session_var = &$_SESSION;
1064
  //$i = 0;
1065
  foreach ($var_keys as $key) {
1066
    // $hasMoreKeys = ++$i < count($session);
1067
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1068
      $session_var[$key] = array();
1069
    }
1070
    $session_var = &$session_var[$key];
1071
  }
1072
  $session_var = $val;
1073
  if (isset($_REQUEST['destination'])) {
1074
    drupal_goto($_REQUEST['destination']);
1075
  }
1076
}
1077

    
1078
/**
1079
 * @todo Please document this function.
1080
 * @see http://drupal.org/node/1354
1081
 */
1082
function uri_uriByProxy($uri, $theme = FALSE) {
1083
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1084
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1085
}
1086

    
1087
/**
1088
 * Composes the the absolute REST service URI to the annotations pager
1089
 * for the given CDM entity.
1090
 *
1091
 * NOTE: Not all CDM Base types are yet supported.
1092
 *
1093
 * @param $cdmBase
1094
 *   The CDM entity to construct the annotations pager uri for
1095
 */
1096
function cdm_compose_annotations_uri($cdmBase) {
1097

    
1098
  if (!$cdmBase->uuid) {
1099
    return;
1100
  }
1101

    
1102
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
1103

    
1104
  if($ws_base_uri === null){
1105
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1106
  }
1107
  return cdm_compose_url($ws_base_uri, array(
1108
    $cdmBase->uuid,
1109
    'annotations',
1110
  ));
1111
}
1112

    
1113
/**
1114
 * Provides the base URI of the cdm REST service responsible for the passed simple name
1115
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
1116
 *
1117
 * @param $cdm_type_simple
1118
 *    simple name of a CDM java class
1119
 * @return null|string
1120
 */
1121
function cdm_ws_base_uri($cdm_type_simple)
1122
{
1123
  $ws_base_uri = NULL;
1124
  switch ($cdm_type_simple) {
1125
    case 'TaxonBase':
1126
    case 'Taxon':
1127
    case 'Synonym':
1128
      $ws_base_uri = CDM_WS_TAXON;
1129
      break;
1130

    
1131
    case 'TaxonName':
1132
      $ws_base_uri = CDM_WS_NAME;
1133
      break;
1134

    
1135
    case 'Media':
1136
      $ws_base_uri = CDM_WS_MEDIA;
1137
      break;
1138

    
1139
    case 'Reference':
1140
      $ws_base_uri = CDM_WS_REFERENCE;
1141
      break;
1142

    
1143
    case 'Distribution':
1144
    case 'TextData':
1145
    case 'TaxonInteraction':
1146
    case 'QuantitativeData':
1147
    case 'IndividualsAssociation':
1148
    case 'CommonTaxonName':
1149
    case 'CategoricalData':
1150
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1151
      break;
1152

    
1153
    case 'PolytomousKey':
1154
    case 'MediaKey':
1155
    case 'MultiAccessKey':
1156
      $ws_base_uri = $cdm_type_simple;
1157
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1158
      break;
1159

    
1160
    default:
1161
      $ws_base_uri = null;
1162
  }
1163
  return $ws_base_uri;
1164
}
1165

    
1166
/**
1167
 * Enter description here...
1168
 *
1169
 * @param string $resourceURI
1170
 * @param int $pageSize
1171
 *   The maximum number of entities returned per page.
1172
 *   The default page size as configured in the cdm server
1173
 *   will be used if set to NULL
1174
 *   to return all entities in a single page).
1175
 * @param int $pageNumber
1176
 *   The number of the page to be returned, the first page has the
1177
 *   pageNumber = 0
1178
 * @param array $query
1179
 *   A array holding the HTTP request query parameters for the request
1180
 * @param string $method
1181
 *   The HTTP method to use, valid values are "GET" or "POST"
1182
 * @param bool $absoluteURI
1183
 *   TRUE when the URL should be treated as absolute URL.
1184
 *
1185
 * @return the a CDM Pager object
1186
 *
1187
 */
1188
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1189

    
1190
  $query['pageNumber'] = $pageNumber;
1191
  $query['pageSize'] = $pageSize;
1192

    
1193
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1194
}
1195

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

    
1217
  while ($page_index !== FALSE){
1218
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1219
    if(isset($pager->records) && is_array($pager->records)) {
1220
      $entities = array_merge($entities, $pager->records);
1221
      if(!empty($pager->nextIndex)){
1222
        $page_index = $pager->nextIndex;
1223
      } else {
1224
        $page_index = FALSE;
1225
      }
1226
    } else {
1227
      $page_index = FALSE;
1228
    }
1229
  }
1230
  return $entities;
1231
}
1232

    
1233
/*
1234
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1235
  $viewrank = _cdm_taxonomy_compose_viewrank();
1236
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1237
  ? '/' . $path : '') ;
1238
}
1239
*/
1240

    
1241
/**
1242
 * @todo Enter description here...
1243
 *
1244
 * @param string $taxon_uuid
1245
 *  The UUID of a cdm taxon instance
1246
 * @param string $ignore_rank_limit
1247
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1248
 *
1249
 * @return string
1250
 *   A cdm REST service URL path to a Classification
1251
 */
1252
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1253

    
1254
  $view_uuid = get_current_classification_uuid();
1255
  $rank_uuid = NULL;
1256
  if (!$ignore_rank_limit) {
1257
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1258
  }
1259

    
1260
  if (!empty($taxon_uuid)) {
1261
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1262
      $view_uuid,
1263
      $taxon_uuid,
1264
    ));
1265
  }
1266
  else {
1267
    if (is_uuid($rank_uuid)) {
1268
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1269
        $view_uuid,
1270
        $rank_uuid,
1271
      ));
1272
    }
1273
    else {
1274
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1275
        $view_uuid,
1276
      ));
1277
    }
1278
  }
1279
}
1280

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

    
1302
    $response = NULL;
1303

    
1304
    // 1st try
1305
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1306

    
1307
    if ($response == NULL) {
1308
      // 2dn try by ignoring the rank limit
1309
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1310
    }
1311

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

    
1337
  return $response;
1338
}
1339

    
1340
/**
1341
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1342
 * 
1343
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1344
 * variable is set.
1345
 *
1346
 * @param string $taxon_uuid
1347
 *
1348
 * @return array
1349
 *   An array of CDM TaxonNodeDTO objects
1350
 */
1351
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1352
  $view_uuid = get_current_classification_uuid();
1353
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1354

    
1355
  $response = NULL;
1356
  if (is_uuid($rank_uuid)) {
1357
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1358
      $view_uuid,
1359
      $taxon_uuid,
1360
      $rank_uuid,
1361
    ));
1362
  }
1363
  else {
1364
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1365
      $view_uuid,
1366
      $taxon_uuid,
1367
    ));
1368
  }
1369

    
1370
  if ($response == NULL) {
1371
    // Error handing.
1372
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1373
//      // Delete the session value and try again with the default.
1374
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1375
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1376
//    }
1377
//    else {
1378
      // Check if taxonomictree_uuid is valid.
1379
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1380
      if ($test == NULL) {
1381
        // The default set by the admin seems to be invalid or is not even set.
1382
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1383
      }
1384
//    }
1385
  }
1386

    
1387
  return $response;
1388
}
1389

    
1390

    
1391
// =============================Terms and Vocabularies ========================================= //
1392

    
1393
/**
1394
 * Returns the localized representation for the given term.
1395
 *
1396
 * @param Object $definedTermBase
1397
 * 	  of cdm type DefinedTermBase
1398
 * @return string
1399
 * 	  the localized representation_L10n of the term,
1400
 *    otherwise the titleCache as fall back,
1401
 *    otherwise the default_representation which defaults to an empty string
1402
 */
1403
function cdm_term_representation($definedTermBase, $default_representation = '') {
1404
  if ( isset($definedTermBase->representation_L10n) ) {
1405
    return $definedTermBase->representation_L10n;
1406
  } elseif ( isset($definedTermBase->titleCache)) {
1407
    return $definedTermBase->titleCache;
1408
  }
1409
  return $default_representation;
1410
}
1411

    
1412
/**
1413
 * Returns the abbreviated localized representation for the given term.
1414
 *
1415
 * @param Object $definedTermBase
1416
 * 	  of cdm type DefinedTermBase
1417
 * @return string
1418
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1419
 *    if this representation is not available the function delegates the
1420
 *    call to cdm_term_representation()
1421
 */
1422
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1423
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1424
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1425
  } else {
1426
    cdm_term_representation($definedTermBase, $default_representation);
1427
  }
1428
}
1429

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

    
1461
  if($empty_option !== FALSE){
1462
    array_unshift ($options, "");
1463
  }
1464

    
1465
  return $options;
1466
}
1467

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

    
1488
  static $vocabularyOptions = array();
1489

    
1490
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1491
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1492
      array(
1493
        'orderBy' => $order_by
1494
      )
1495
    );
1496

    
1497
    // apply the include filter
1498
    if($include_filter != null){
1499
      $included_terms = array();
1500

    
1501
      foreach ($terms as $term){
1502
        $include = true;
1503
        foreach ($include_filter as $field=>$regex){
1504
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1505
          if(!$include){
1506
            break;
1507
          }
1508
        }
1509
        if($include){
1510
          $included_terms[] = $term;
1511
        }
1512
      }
1513

    
1514
      $terms = $included_terms;
1515
    }
1516

    
1517
    // make options list
1518
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1519
  }
1520

    
1521
  $options = $vocabularyOptions[$vocabulary_uuid];
1522

    
1523
  return $options;
1524
}
1525

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

    
1591

    
1592
/**
1593
 * @todo Please document this function.
1594
 * @see http://drupal.org/node/1354
1595
 */
1596
function _cdm_relationship_type_term_label_callback($term) {
1597
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1598
    return $term->representation_L10n_abbreviatedLabel . ' : '
1599
    . t('@term', array('@term' => $term->representation_L10n));
1600
  }
1601
else {
1602
    return t('@term', array('@term' => $term->representation_L10n));
1603
  }
1604
}
1605

    
1606
// ========================================================================================== //
1607
/**
1608
 * @todo Improve documentation of this function.
1609
 *
1610
 * eu.etaxonomy.cdm.model.description.
1611
 * CategoricalData
1612
 * CommonTaxonName
1613
 * Distribution
1614
 * IndividualsAssociation
1615
 * QuantitativeData
1616
 * TaxonInteraction
1617
 * TextData
1618
 */
1619
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1620
  static $types = array(
1621
    "CategoricalData",
1622
    "CommonTaxonName",
1623
    "Distribution",
1624
    "IndividualsAssociation",
1625
    "QuantitativeData",
1626
    "TaxonInteraction",
1627
    "TextData",
1628
  );
1629

    
1630
  static $options = NULL;
1631
  if ($options == NULL) {
1632
    $options = array();
1633
    if ($prependEmptyElement) {
1634
      $options[' '] = '';
1635
    }
1636
    foreach ($types as $type) {
1637
      // No internatianalization here since these are purely technical terms.
1638
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1639
    }
1640
  }
1641
  return $options;
1642
}
1643

    
1644

    
1645
/**
1646
 * Fetches all TaxonDescription descriptions elements which are associated to the
1647
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1648
 * feature tree.
1649
 * @param $feature_tree
1650
 *     The CDM FeatureTree to be used as template
1651
 * @param $taxon_uuid
1652
 *     The UUID of the taxon
1653
 * @param $excludes
1654
 *     UUIDs of features to be excluded
1655
 * @return$feature_tree
1656
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1657
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1658
 *     witch will hold the according $descriptionElements.
1659
 */
1660
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1661

    
1662
  if (!$feature_tree) {
1663
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1664
      In order to see the species profiles of your taxa, please select a
1665
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1666
    return FALSE;
1667
  }
1668

    
1669
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1670
      array(
1671
      'taxon' => $taxon_uuid,
1672
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1673
      ),
1674
      'POST'
1675
  );
1676

    
1677
  // Combine all descriptions into one feature tree.
1678
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1679
  $feature_tree->root->childNodes = $merged_nodes;
1680

    
1681
  return $feature_tree;
1682
}
1683

    
1684
/**
1685
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1686
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1687
 * be requested for the annotations.
1688
 *
1689
 * @param string $cdmBase
1690
 *   An annotatable cdm entity.
1691
 * @param array $includeTypes
1692
 *   If an array of annotation type uuids is supplied by this parameter the
1693
 *   list of annotations is resticted to those which belong to this type.
1694
 *
1695
 * @return array
1696
 *   An array of Annotation objects or an empty array.
1697
 */
1698
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1699

    
1700
  if(!isset($cdmBase->annotations)){
1701
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1702
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1703
  }
1704

    
1705
  $annotations = array();
1706
  foreach ($cdmBase->annotations as $annotation) {
1707
    if ($includeTypes) {
1708
      if (
1709
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1710
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1711
      ) {
1712
        $annotations[] = $annotation;
1713
      }
1714
    }
1715
    else {
1716
      $annotations[] = $annotation;
1717
    }
1718
  }
1719
  return $annotations;
1720

    
1721
}
1722

    
1723
/**
1724
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1725
 *
1726
 * @param object $annotatable_entity
1727
 *   The CDM AnnotatableEntity to load annotations for
1728
 */
1729
function cdm_load_annotations(&$annotatable_entity) {
1730
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1731
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1732
    if (is_array($annotations)) {
1733
      $annotatable_entity->annotations = $annotations;
1734
    }
1735
  }
1736
}
1737

    
1738
/**
1739
 * Extends the $cdm_entity object by the field if it is not already existing.
1740
 *
1741
 * This function can only be used for fields with 1 to many relations.
1742
  *
1743
 * @param $cdm_base_type
1744
 * @param $field_name
1745
 * @param $cdm_entity
1746
 */
1747
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1748
{
1749
  if (!isset($cdm_entity->$field_name)) {
1750
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1751
    $cdm_entity->$field_name = $items;
1752
  }
1753
}
1754

    
1755

    
1756
/**
1757
 * Get a NomenclaturalReference string.
1758
 *
1759
 * Returns the NomenclaturalReference string with correctly placed
1760
 * microreference (= reference detail) e.g.
1761
 * in Phytotaxa 43: 1-48. 2012.
1762
 *
1763
 * @param string $referenceUuid
1764
 *   UUID of the reference.
1765
 * @param string $microreference
1766
 *   Reference detail.
1767
 *
1768
 * @return string
1769
 *   a NomenclaturalReference.
1770
 */
1771
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1772

    
1773
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1774
  if(is_array($microreference) || is_object($microreference)) {
1775
    return '';
1776
  }
1777

    
1778
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1779
    $referenceUuid,
1780
  ), "microReference=" . urlencode($microreference));
1781

    
1782
  if ($obj) {
1783
    return $obj->String;
1784
  }
1785
  else {
1786
    return NULL;
1787
  }
1788
}
1789

    
1790
/**
1791
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1792
 *
1793
 * @param $feature_tree_nodes
1794
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1795
 * @param $feature_uuid
1796
 *    The UUID of the Feature
1797
 * @return returns the FeatureNode or null
1798
 */
1799
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1800

    
1801
  // 1. scan this level
1802
  foreach ($feature_tree_nodes as $node){
1803
    if($node->feature->uuid == $feature_uuid){
1804
      return $node;
1805
    }
1806
  }
1807

    
1808
  // 2. descend into childen
1809
  foreach ($feature_tree_nodes as $node){
1810
    if(is_array($node->childNodes)){
1811
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1812
      if($node) {
1813
        return $node;
1814
      }
1815
    }
1816
  }
1817
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1818
  return $null_var;
1819
}
1820

    
1821
/**
1822
 * Merges the given featureNodes structure with the descriptionElements.
1823
 *
1824
 * This method is used in preparation for rendering the descriptionElements.
1825
 * The descriptionElements which belong to a specific feature node are appended
1826
 * to a the feature node by creating a new field:
1827
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1828
 * The descriptionElements will be cleared in advance in order to allow reusing the
1829
 * same feature tree without the risk of mixing sets of description elements.
1830
 *
1831
 * which originally is not existing in the cdm.
1832
 *
1833
 *
1834
 *
1835
 * @param array $featureNodes
1836
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1837
 *    may have children.
1838
 * @param array $descriptionElements
1839
 *    An flat array of cdm DescriptionElements
1840
 * @return array
1841
 *    The $featureNodes structure enriched with the according $descriptionElements
1842
 */
1843
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1844

    
1845
  foreach ($featureNodes as &$node) {
1846
    // since the $featureNodes array is reused for each description
1847
    // it is necessary to clear the custom node fields in advance
1848
    if(isset($node->descriptionElements)){
1849
      unset($node->descriptionElements);
1850
    }
1851

    
1852
    // Append corresponding elements to an additional node field:
1853
    // $node->descriptionElements.
1854
    foreach ($descriptionElements as $element) {
1855
      if ($element->feature->uuid == $node->feature->uuid) {
1856
        if (!isset($node->descriptionElements)) {
1857
          $node->descriptionElements = array();
1858
        }
1859
        $node->descriptionElements[] = $element;
1860
      }
1861
    }
1862

    
1863
    // Recurse into node children.
1864
    if (isset($node->childNodes[0])) {
1865
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1866
      $node->childNodes = $mergedChildNodes;
1867
    }
1868

    
1869
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1870
      unset($node);
1871
    }
1872

    
1873
  }
1874

    
1875
  return $featureNodes;
1876
}
1877

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

    
1914
  static $cacheL1 = array();
1915

    
1916
  $data = NULL;
1917
  // store query string in $data and clear the query, $data will be set as HTTP request body
1918
  if($method == 'POST'){
1919
    $data = $query;
1920
    $query = NULL;
1921
  }
1922

    
1923
  // Transform the given uri path or pattern into a proper webservice uri.
1924
  if (!$absoluteURI) {
1925
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1926
  }
1927

    
1928
  // read request parameter 'cacheL2_refresh'
1929
  // which allows refreshing the level 2 cache
1930
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1931

    
1932
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1933
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1934

    
1935
  if($method == 'GET'){
1936
    $cache_key = $uri;
1937
  } else {
1938
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1939
    // crc32 is faster but creates much shorter hashes
1940
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1941
  }
1942

    
1943
  if (array_key_exists($cache_key, $cacheL1)) {
1944
    $cacheL1_obj = $cacheL1[$uri];
1945
  }
1946

    
1947
  $set_cacheL1 = FALSE;
1948
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1949
    $set_cacheL1 = TRUE;
1950
  }
1951

    
1952
  // Only cache cdm webservice URIs.
1953
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1954
  $cacheL2_entry = FALSE;
1955

    
1956
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1957
    // Try to get object from cacheL2.
1958
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1959
  }
1960

    
1961
  if (isset($cacheL1_obj)) {
1962
    //
1963
    // The object has been found in the L1 cache.
1964
    //
1965
    $obj = $cacheL1_obj;
1966
    if (cdm_debug_block_visible()) {
1967
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1968
    }
1969
  }
1970
  elseif ($cacheL2_entry) {
1971
    //
1972
    // The object has been found in the L2 cache.
1973
    //
1974
    $duration_parse_start = microtime(TRUE);
1975
    $obj = unserialize($cacheL2_entry->data);
1976
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1977

    
1978
    if (cdm_debug_block_visible()) {
1979
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1980
    }
1981
  }
1982
  else {
1983
    //
1984
    // Get the object from the webservice and cache it.
1985
    //
1986
    $duration_fetch_start = microtime(TRUE);
1987
    // Request data from webservice JSON or XML.
1988
    $response = cdm_http_request($uri, $method, $data);
1989
    $response_body = NULL;
1990
    if (isset($response->data)) {
1991
      $response_body = $response->data;
1992
    }
1993
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1994
    $duration_parse_start = microtime(TRUE);
1995

    
1996
    // Parse data and create object.
1997
    $obj = cdm_load_obj($response_body);
1998

    
1999
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2000

    
2001
    if (cdm_debug_block_visible()) {
2002
      if ($obj || $response_body == "[]") {
2003
        $status = 'valid';
2004
      }
2005
      else {
2006
        $status = 'invalid';
2007
      }
2008
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2009
    }
2010
    if ($set_cacheL2) {
2011
      // Store the object in cache L2.
2012
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2013
      // flag serialized is set properly in the cache table.
2014
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2015
    }
2016
  }
2017
  if ($obj) {
2018
    // Store the object in cache L1.
2019
    if ($set_cacheL1) {
2020
      $cacheL1[$cache_key] = $obj;
2021
    }
2022
  }
2023
  return $obj;
2024
}
2025

    
2026
/**
2027
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2028
 *
2029
 * The cdm_ws_debug block will display the debug information.
2030
 *
2031
 * @param $uri
2032
 *    The CDM REST URI to which the request has been send
2033
 * @param string $method
2034
 *    The HTTP request method, either 'GET' or 'POST'
2035
 * @param string $post_data
2036
 *    The datastring send with a post request
2037
 * @param $duration_fetch
2038
 *    The time in seconds it took to fetch the data from the web service
2039
 * @param $duration_parse
2040
 *    Time in seconds which was needed to parse the json response
2041
 * @param $datasize
2042
 *    Size of the data received from the server
2043
 * @param $status
2044
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2045
 * @return bool
2046
 *    TRUE if adding the debug information was successful
2047
 */
2048
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2049

    
2050
  static $initial_time = NULL;
2051
  if(!$initial_time) {
2052
    $initial_time = microtime(TRUE);
2053
  }
2054
  $time = microtime(TRUE) - $initial_time;
2055

    
2056
  // Decompose uri into path and query element.
2057
  $uri_parts = explode("?", $uri);
2058
  $query = array();
2059
  if (count($uri_parts) == 2) {
2060
    $path = $uri_parts[0];
2061
  }
2062
  else {
2063
    $path = $uri;
2064
  }
2065

    
2066
  if(strpos($uri, '?') > 0){
2067
    $json_uri = str_replace('?', '.json?', $uri);
2068
    $xml_uri = str_replace('?', '.xml?', $uri);
2069
  } else {
2070
    $json_uri = $uri . '.json';
2071
    $xml_uri = $json_uri . '.xml';
2072
  }
2073

    
2074
  // data links to make data accecsible as json and xml
2075
  $data_links = '';
2076
  if (_is_cdm_ws_uri($path)) {
2077

    
2078
    // see ./js/http-method-link.js
2079

    
2080
    if($method == 'GET'){
2081
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2082
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2083
      $data_links .= '<br/>';
2084
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2085
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2086
    } else {
2087
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2088
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2089
      $data_links .= '<br/>';
2090
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2091
    }
2092
  }
2093
  else {
2094
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2095
  }
2096

    
2097
  //
2098
  $data = array(
2099
      'ws_uri' => $uri,
2100
      'method' => $method,
2101
      'post_data' => $post_data,
2102
      'time' => sprintf('%3.3f', $time),
2103
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2104
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2105
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2106
      'status' => $status,
2107
      'data_links' => $data_links
2108
  );
2109
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2110
    $_SESSION['cdm']['ws_debug'] = array();
2111
  }
2112
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2113

    
2114
  // Mark this page as being uncacheable.
2115
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2116
  drupal_page_is_cacheable(FALSE);
2117

    
2118
  // Messages not set when DB connection fails.
2119
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2120
}
2121

    
2122
/**
2123
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2124
 * the visibility depends on whether
2125
 *  - the block is enabled
2126
 *  - the visibility restrictions in the block settings are satisfied
2127
 */
2128
function cdm_debug_block_visible() {
2129
  static $is_visible = null;
2130

    
2131
  if($is_visible === null){
2132
      $block = block_load('cdm_api', 'cdm_ws_debug');
2133
      $is_visible = isset($block->status) && $block->status == 1;
2134
      if($is_visible){
2135
        $blocks = array($block);
2136
        // Checks the page, user role, and user-specific visibilty settings.
2137
        block_block_list_alter($blocks);
2138
        $is_visible = count($blocks) > 0;
2139
      }
2140
  }
2141
  return $is_visible;
2142
}
2143

    
2144
/**
2145
 * @todo Please document this function.
2146
 * @see http://drupal.org/node/1354
2147
 */
2148
function cdm_load_obj($response_body) {
2149
  $obj = json_decode($response_body);
2150

    
2151
  if (!(is_object($obj) || is_array($obj))) {
2152
    ob_start();
2153
    $obj_dump = ob_get_contents();
2154
    ob_clean();
2155
    return FALSE;
2156
  }
2157

    
2158
  return $obj;
2159
}
2160

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

    
2199
  if (!$acceptLanguage) {
2200
    if (function_exists('apache_request_headers')) {
2201
      $headers = apache_request_headers();
2202
      if (isset($headers['Accept-Language'])) {
2203
        $acceptLanguage = $headers['Accept-Language'];
2204
      }
2205
    }
2206
  }
2207

    
2208
  if ($method != "GET" && $method != "POST") {
2209
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2210
  }
2211

    
2212
  if (_is_cdm_ws_uri($uri)) {
2213
    $header['Accept'] = 'application/json';
2214
    $header['Accept-Language'] = $acceptLanguage;
2215
    $header['Accept-Charset'] = 'UTF-8';
2216
  }
2217

    
2218
  if($method == "POST") {
2219
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2220
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2221
  }
2222

    
2223

    
2224
  cdm_dd($uri);
2225
  return drupal_http_request($uri, array(
2226
      'headers' => $header,
2227
      'method' => $method,
2228
      'data' => $data,
2229
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2230
      )
2231
   );
2232
}
2233

    
2234
/**
2235
 * Concatenates recursively the fields of all features contained in the given
2236
 * CDM FeatureTree root node.
2237
 *
2238
 * @param $rootNode
2239
 *     A CDM FeatureTree node
2240
 * @param
2241
 *     The character to be used as glue for concatenation, default is ', '
2242
 * @param $field_name
2243
 *     The field name of the CDM Features
2244
 * @param $excludes
2245
 *     Allows defining a set of values to be excluded. This refers to the values
2246
 *     in the field denoted by the $field_name parameter
2247
 *
2248
 */
2249
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2250
  $out = '';
2251

    
2252
  $pre_child_separator = $separator;
2253
  $post_child_separator = '';
2254

    
2255
  foreach ($root_node->childNodes as $feature_node) {
2256
    $out .= ($out ? $separator : '');
2257
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2258
      $out .= $feature_node->feature->$field_name;
2259
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2260
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2261
        if (strlen($childlabels)) {
2262
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2263
        }
2264
      }
2265
    }
2266
  }
2267
  return $out;
2268
}
2269

    
2270
/**
2271
 * Create a one-dimensional form options array.
2272
 *
2273
 * Creates an array of all features in the feature tree of feature nodes,
2274
 * the node labels are indented by $node_char and $childIndent depending on the
2275
 * hierachy level.
2276
 *
2277
 * @param - $rootNode
2278
 * @param - $node_char
2279
 * @param - $childIndentStr
2280
 * @param - $childIndent
2281
 *   ONLY USED INTERNALLY!
2282
 *
2283
 * @return array
2284
 *   A one dimensional Drupal form options array.
2285
 */
2286
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2287
  $options = array();
2288
  foreach ($rootNode->childNodes as $featureNode) {
2289
    $indent_prefix = '';
2290
    if ($childIndent) {
2291
      $indent_prefix = $childIndent . $node_char . " ";
2292
    }
2293
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2294
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2295
      // Foreach ($featureNode->childNodes as $childNode){
2296
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2297
      $options = array_merge_recursive($options, $childList);
2298
      // }
2299
    }
2300
  }
2301
  return $options;
2302
}
2303

    
2304
/**
2305
 * Returns an array with all available FeatureTrees and the representations of the selected
2306
 * FeatureTree as a detail view.
2307
 *
2308
 * @param boolean $add_default_feature_free
2309
 * @return array
2310
 *  associative array with following keys:
2311
 *  -options: Returns an array with all available Feature Trees
2312
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2313
 *
2314
 */
2315
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2316

    
2317
  $options = array();
2318
  $tree_representations = array();
2319
  $feature_trees = array();
2320

    
2321
  // Set tree that contains all features.
2322
  if ($add_default_feature_free) {
2323
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2324
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2325
  }
2326

    
2327
  // Get feature trees from database.
2328
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2329
  if (is_array($persited_trees)) {
2330
    $feature_trees = array_merge($feature_trees, $persited_trees);
2331
  }
2332

    
2333
  foreach ($feature_trees as $featureTree) {
2334

    
2335
    if(!is_object($featureTree)){
2336
      continue;
2337
    }
2338
    // Do not add the DEFAULT_FEATURETREE again,
2339
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2340
      $options[$featureTree->uuid] = $featureTree->titleCache;
2341
    }
2342

    
2343
    // Render the hierarchic tree structure
2344
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2345

    
2346
      // Render the hierarchic tree structure.
2347
      $treeDetails = '<div class="featuretree_structure">'
2348
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2349
        . '</div>';
2350

    
2351
      $form = array();
2352
      $form['featureTree-' .  $featureTree->uuid] = array(
2353
        '#type' => 'fieldset',
2354
        '#title' => 'Show details',
2355
        '#attributes' => array('class' => array('collapsible collapsed')),
2356
        // '#collapsible' => TRUE,
2357
        // '#collapsed' => TRUE,
2358
      );
2359
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2360
        '#markup' => $treeDetails,
2361
      );
2362

    
2363
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2364
    }
2365

    
2366
  } // END loop over feature trees
2367

    
2368
  // return $options;
2369
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2370
}
2371

    
2372
/**
2373
 * Provides the list of available classifications in form of an options array.
2374
 *
2375
 * The options array is suitable for drupal form API elements that allow multiple choices.
2376
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2377
 *
2378
 * The classifications are ordered alphabetically whereas the classification
2379
 * chosen as default will always appear on top of the array, followed by a
2380
 * blank line below.
2381
 *
2382
 * @param bool $add_none_option
2383
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2384
 *
2385
 * @return array
2386
 *   classifications in an array as options for a form element that allows multiple choices.
2387
 */
2388
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2389

    
2390
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2391

    
2392
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2393
  $default_classification_label = '';
2394

    
2395
  // add all classifications
2396
  $taxonomic_tree_options = array();
2397
  if ($add_none_option) {
2398
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2399
  }
2400
  if ($taxonTrees) {
2401
    foreach ($taxonTrees as $tree) {
2402
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2403
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2404
      } else {
2405
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2406
        $default_classification_label = $tree->titleCache;
2407
      }
2408
    }
2409
  }
2410
  // oder alphabetically the space
2411
  asort($taxonomic_tree_options);
2412

    
2413
  // now set the labels
2414
  //   for none
2415
  if ($add_none_option) {
2416
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2417
  }
2418

    
2419
  //   for default_classification
2420
  if (is_uuid($default_classification_uuid)) {
2421
    $taxonomic_tree_options[$default_classification_uuid] =
2422
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2423
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2424
  }
2425

    
2426
  return $taxonomic_tree_options;
2427
}
2428

    
2429
/**
2430
 * @todo Please document this function.
2431
 * @see http://drupal.org/node/1354
2432
 */
2433
function cdm_api_secref_cache_prefetch(&$secUuids) {
2434
  // Comment @WA: global variables should start with a single underscore
2435
  // followed by the module and another underscore.
2436
  global $_cdm_api_secref_cache;
2437
  if (!is_array($_cdm_api_secref_cache)) {
2438
    $_cdm_api_secref_cache = array();
2439
  }
2440
  $uniqueUuids = array_unique($secUuids);
2441
  $i = 0;
2442
  $param = '';
2443
  while ($i++ < count($uniqueUuids)) {
2444
    $param .= $secUuids[$i] . ',';
2445
    if (strlen($param) + 37 > 2000) {
2446
      _cdm_api_secref_cache_add($param);
2447
      $param = '';
2448
    }
2449
  }
2450
  if ($param) {
2451
    _cdm_api_secref_cache_add($param);
2452
  }
2453
}
2454

    
2455
/**
2456
 * @todo Please document this function.
2457
 * @see http://drupal.org/node/1354
2458
 */
2459
function cdm_api_secref_cache_get($secUuid) {
2460
  global $_cdm_api_secref_cache;
2461
  if (!is_array($_cdm_api_secref_cache)) {
2462
    $_cdm_api_secref_cache = array();
2463
  }
2464
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2465
    _cdm_api_secref_cache_add($secUuid);
2466
  }
2467
  return $_cdm_api_secref_cache[$secUuid];
2468
}
2469

    
2470
/**
2471
 * @todo Please document this function.
2472
 * @see http://drupal.org/node/1354
2473
 */
2474
function cdm_api_secref_cache_clear() {
2475
  global $_cdm_api_secref_cache;
2476
  $_cdm_api_secref_cache = array();
2477
}
2478

    
2479

    
2480
/**
2481
 * Validates if the given string is a uuid.
2482
 *
2483
 * @param string $str
2484
 *   The string to validate.
2485
 *
2486
 * return bool
2487
 *   TRUE if the string is a UUID.
2488
 */
2489
function is_uuid($str) {
2490
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2491
}
2492

    
2493
/**
2494
 * Checks if the given $object is a valid cdm entity.
2495
 *
2496
 * An object is considered a cdm entity if it has a string field $object->class
2497
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2498
 * The function is null save.
2499
 *
2500
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2501
 *
2502
 * @param mixed $object
2503
 *   The object to validate
2504
 *
2505
 * @return bool
2506
 *   True if the object is a cdm entity.
2507
 */
2508
function is_cdm_entity($object) {
2509
  return
2510
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2511
    && is_string($object->uuid) && is_uuid($object->uuid);
2512
}
2513

    
2514
/**
2515
 * @todo Please document this function.
2516
 * @see http://drupal.org/node/1354
2517
 */
2518
function _cdm_api_secref_cache_add($secUuidsStr) {
2519
  global $_cdm_api_secref_cache;
2520
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2521
  // Batch fetching not jet reimplemented thus:
2522
  /*
2523
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2524
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2525
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2526
  */
2527
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2528
}
2529

    
2530
/**
2531
 * Checks if the given uri starts with a cdm webservice url.
2532
 *
2533
 * Checks if the uri starts with the cdm webservice url stored in the
2534
 * Drupal variable 'cdm_webservice_url'.
2535
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2536
 *
2537
 * @param string $uri
2538
 *   The URI to test.
2539
 *
2540
 * @return bool
2541
 *   True if the uri starts with a cdm webservice url.
2542
 */
2543
function _is_cdm_ws_uri($uri) {
2544
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2545
}
2546

    
2547
/**
2548
 * @todo Please document this function.
2549
 * @see http://drupal.org/node/1354
2550
 */
2551
function queryString($elements) {
2552
  $query = '';
2553
  foreach ($elements as $key => $value) {
2554
    if (is_array($value)) {
2555
      foreach ($value as $v) {
2556
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2557
      }
2558
    }
2559
    else {
2560
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2561
    }
2562
  }
2563
  return $query;
2564
}
2565

    
2566
/**
2567
 * Implementation of the magic method __clone to allow deep cloning of objects
2568
 * and arrays.
2569
 */
2570
function __clone() {
2571
  foreach ($this as $name => $value) {
2572
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2573
      $this->$name = clone($this->$name);
2574
    }
2575
  }
2576
}
2577

    
2578
/**
2579
 * Compares the given CDM Term instances by the  representationL10n.
2580
 *
2581
 * Can also be used with TermDTOs. To be used in usort()
2582
 *
2583
 * @see http://php.net/manual/en/function.usort.php
2584
 *
2585
 * @param $term1
2586
 *   The first CDM Term instance
2587
 * @param $term2
2588
 *   The second CDM Term instance
2589
 * @return int
2590
 *   The result of the comparison
2591
 */
2592
function compare_terms_by_representationL10n($term1, $term2) {
2593

    
2594
  if (!isset($term1->representation_L10n)) {
2595
    $term1->representationL10n = '';
2596
  }
2597
  if (!isset($term2->representation_L10n)) {
2598
    $term2->representationL10n = '';
2599
  }
2600

    
2601
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2602
}
2603

    
2604
function compare_terms_by_order_index($term1, $term2) {
2605

    
2606

    
2607
  if (!isset($term1->orderIndex)) {
2608
    $a = 0;
2609
  } else {
2610
    $a = $term1->orderIndex;
2611
  }
2612
  if (!isset($term2->orderIndex)) {
2613
    $b = 0;
2614
  } else {
2615
    $b = $term2->orderIndex;
2616
  }
2617

    
2618
  if ($a == $b) {
2619
    return 0;
2620
  }
2621
  return ($a < $b) ? -1 : 1;
2622

    
2623
}
2624

    
2625

    
2626
/**
2627
 * Make a 'deep copy' of an array.
2628
 *
2629
 * Make a complete deep copy of an array replacing
2630
 * references with deep copies until a certain depth is reached
2631
 * ($maxdepth) whereupon references are copied as-is...
2632
 *
2633
 * @see http://us3.php.net/manual/en/ref.array.php
2634
 *
2635
 * @param array $array
2636
 * @param array $copy passed by reference
2637
 * @param int $maxdepth
2638
 * @param int $depth
2639
 */
2640
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2641
  if ($depth > $maxdepth) {
2642
    $copy = $array;
2643
    return;
2644
  }
2645
  if (!is_array($copy)) {
2646
    $copy = array();
2647
  }
2648
  foreach ($array as $k => &$v) {
2649
    if (is_array($v)) {
2650
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2651
    }
2652
    else {
2653
      $copy[$k] = $v;
2654
    }
2655
  }
2656
}
2657

    
2658
/**
2659
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2660
 *
2661
 */
2662
function _add_js_ws_debug() {
2663

    
2664
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2665
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2666
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2667
    // use the developer versions of js libs
2668
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2669
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2670
  }
2671
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2672
    array(
2673
      'type' => 'file',
2674
      'weight' => JS_LIBRARY,
2675
      'cache' => TRUE)
2676
    );
2677

    
2678
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2679
    array(
2680
      'type' => 'file',
2681
      'weight' => JS_LIBRARY,
2682
      'cache' => TRUE)
2683
    );
2684
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2685
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2686

    
2687
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2688
    array(
2689
      'type' => 'file',
2690
      'weight' => JS_LIBRARY,
2691
      'cache' => TRUE)
2692
    );
2693
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2694
    array(
2695
    'type' => 'file',
2696
    'weight' => JS_LIBRARY,
2697
    'cache' => TRUE)
2698
    );
2699

    
2700
}
2701

    
2702
/**
2703
 * @todo Please document this function.
2704
 * @see http://drupal.org/node/1354
2705
 */
2706
function _no_classfication_uuid_message() {
2707
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2708
    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.');
2709
  }
2710
  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.');
2711
}
2712

    
2713
/**
2714
 * Implementation of hook flush_caches
2715
 *
2716
 * Add custom cache tables to the list of cache tables that
2717
 * will be cleared by the Clear button on the Performance page or whenever
2718
 * drupal_flush_all_caches is invoked.
2719
 *
2720
 * @author W.Addink <waddink@eti.uva.nl>
2721
 *
2722
 * @return array
2723
 *   An array with custom cache tables to include.
2724
 */
2725
function cdm_api_flush_caches() {
2726
  return array('cache_cdm_ws');
2727
}
2728

    
2729
/**
2730
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2731
 *
2732
 * @param $data
2733
 *   The variable to log to the drupal_debug.txt log file.
2734
 * @param $label
2735
 *   (optional) If set, a label to output before $data in the log file.
2736
 *
2737
 * @return
2738
 *   No return value if successful, FALSE if the log file could not be written
2739
 *   to.
2740
 *
2741
 * @see cdm_dataportal_init() where the log file is reset on each requests
2742
 * @see dd()
2743
 * @see http://drupal.org/node/314112
2744
 *
2745
 */
2746
function cdm_dd($data, $label = NULL) {
2747
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2748
    return dd($data, $label);
2749
  }
2750
}
2751

    
(5-5/11)