Project

General

Profile

Download (81.1 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
 * Converts an array of TaggedText items into corresponding html tags.
197
 *
198
 * Each item is provided with a class attribute which is set to the key of the
199
 * TaggedText item.
200
 *
201
 * @param array $taggedtxt
202
 *   Array with text items to convert.
203
 * @param string $tag
204
 *   Html tag name to convert the items into, default is 'span'.
205
 * @param string $glue
206
 *   The string by which the chained text tokens are concatenated together.
207
 *   Default is a blank character.
208
 *
209
 * @return string
210
 *   A string with HTML.
211
 */
212
function cdm_tagged_text_to_markup(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
213
  $out = '';
214
  $i = 0;
215
  foreach ($taggedtxt as $tt) {
216
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
217
      $class_attr = $tt->type;
218
      if(isset($tt->entityReference)){
219
        $class_attr .= " " . html_class_attribute_ref($tt->entityReference);
220
      }
221
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '')
222
        . '<' . $tag . ' class="' . $class_attr . '">'
223
        . t('@text', array('@text' => $tt->text))
224
        . '</' . $tag . '>';
225
    }
226
  }
227
  return $out;
228
}
229

    
230

    
231
/**
232
 * Finds the text tagged with $tag_type in an array of taggedText instances.
233
 *
234
 * Note: This function is currently unused.
235
 *
236
 * @param array $taggedtxt
237
 *   Array with text items.
238
 * @param string $tag_type
239
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
240
 *   to return all texts.
241
 *
242
 * @return array
243
 *   An array with the texts mapped by $tag_type.
244
 */
245
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
246
  $tokens = array();
247
  if (!empty($taggedtxt)) {
248
    foreach ($taggedtxt as $tagtxt) {
249
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
250
        $tokens[] = $tagtxt->text;
251
      }
252
    }
253
  }
254
  return $tokens;
255
}
256

    
257
/**
258
 * Preprocess the taggedTitle arrays.
259
 *
260
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
261
 * into tag type "name"
262
 *
263
 * Step 2: Two taggedTexts which have the same type and which have
264
 * a separator between them are merged together.
265
 *
266
 * @param array $taggedTextList
267
 *    An array of TaggedText objects
268
 */
269
function normalize_tagged_text(&$taggedTextList) {
270

    
271
  if (is_array($taggedTextList)) {
272

    
273
    // First pass: rename.
274
    for ($i = 0; $i < count($taggedTextList); $i++) {
275

    
276
      if ($taggedTextList[$i]->type == "hybridSign") {
277
        $taggedTextList[$i]->type = "name";
278
      }
279
    }
280

    
281
    // Second pass: resolve separators.
282
    $taggedNameListNew = array();
283
    for ($i = 0; $i < count($taggedTextList); $i++) {
284

    
285
      // elements of the same type concatenated by a separator should be merged together
286
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
287
        $taggedName = clone $taggedTextList[$i];
288
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
289
        $taggedNameListNew[] = $taggedName;
290
        ++$i;
291
        ++$i;
292
        continue;
293
      }
294
      // no special handling
295
      $taggedNameListNew[] = $taggedTextList[$i];
296

    
297
    }
298
    $taggedTextList = $taggedNameListNew;
299
  }
300
}
301

    
302
function split_secref_from_tagged_text(&$tagged_text) {
303

    
304
  $extracted_tt = array();
305
  if (is_array($tagged_text)) {
306
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
307
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
308
        $extracted_tt[0] = $tagged_text[$i];
309
        $extracted_tt[1] = $tagged_text[$i + 1];
310
        unset($tagged_text[$i]);
311
        unset($tagged_text[$i + 1]);
312
        // also get the microfererence which could be in $tagged_text[$i + 3]
313
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
314
          $extracted_tt[2] = $tagged_text[$i + 2];
315
          $extracted_tt[3] = $tagged_text[$i + 3];
316
        }
317
        break;
318
      }
319
    }
320
  }
321
  return $extracted_tt;
322
}
323

    
324

    
325
function split_nomstatus_from_tagged_text(&$tagged_text) {
326

    
327
  $extracted_tt = array();
328
  if (is_array($tagged_text)) {
329
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
330
      if ($tagged_text[$i]->type == "nomStatus"){
331
        $extracted_tt[] = $tagged_text[$i];
332
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
333
          $extracted_tt[] = $tagged_text[$i + 1];
334
          unset($tagged_text[$i + 1]);
335
        }
336
        if ($tagged_text[$i - 1]->type == "separator"){
337
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
338
          unset($tagged_text[$i - 1]);
339
        }
340
        unset($tagged_text[$i]);
341
        break;
342
      }
343
    }
344
  }
345
  return $extracted_tt;
346
}
347

    
348
function find_tagged_text_elements($taggedTextList, $type){
349
  $matching_elements = array();
350
  if (is_array($taggedTextList)) {
351
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
352
      if($taggedTextList[$i]->type == $type){
353
        $matching_elements[] = $taggedTextList[$i];
354
      }
355
    }
356
  }
357
  return $matching_elements;
358
}
359

    
360
// ===================== END of Tagged Text functions ================== //
361

    
362
/**
363
 * Lists the classifications a taxon belongs to
364
 *
365
 * @param CDM type Taxon $taxon
366
 *   the taxon
367
 *
368
 * @return array
369
 *   aray of CDM instances of Type Classification
370
 */
371
function get_classifications_for_taxon($taxon) {
372

    
373
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
374
}
375

    
376
/**
377
 * Returns the chosen FeatureTree for the taxon profile.
378
 *
379
 * The FeatureTree profile returned is the one that has been set in the
380
 * dataportal settings (layout->taxon:profile).
381
 * When the chosen FeatureTree is not found in the database,
382
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
383
 *
384
 * @return mixed
385
 *   A cdm FeatureTree object.
386
 */
387
function get_profile_feature_tree() {
388
  static $profile_featureTree;
389

    
390
  if($profile_featureTree == NULL) {
391
    $profile_featureTree = cdm_ws_get(
392
      CDM_WS_FEATURETREE,
393
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
394
    );
395
    if (!$profile_featureTree) {
396
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
397
    }
398
  }
399

    
400
  return $profile_featureTree;
401
}
402

    
403
/**
404
 * Returns the chosen FeatureTree for SpecimenDescriptions.
405
 *
406
 * The FeatureTree returned is the one that has been set in the
407
 * dataportal settings (layout->taxon:specimen).
408
 * When the chosen FeatureTree is not found in the database,
409
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
410
 *
411
 * @return mixed
412
 *   A cdm FeatureTree object.
413
 */
414
function cdm_get_occurrence_featureTree() {
415
  static $occurrence_featureTree;
416

    
417
  if($occurrence_featureTree == NULL) {
418
    $occurrence_featureTree = cdm_ws_get(
419
      CDM_WS_FEATURETREE,
420
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
421
    );
422
    if (!$occurrence_featureTree) {
423
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
424
    }
425
  }
426
  return $occurrence_featureTree;
427
}
428

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

    
443
  if($structured_description_featureTree == NULL) {
444
    $structured_description_featureTree = cdm_ws_get(
445
        CDM_WS_FEATURETREE,
446
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
447
    );
448
    if (!$structured_description_featureTree) {
449
      $structured_description_featureTree = cdm_ws_get(
450
          CDM_WS_FEATURETREE,
451
          UUID_DEFAULT_FEATURETREE
452
      );
453
    }
454
  }
455
  return $structured_description_featureTree;
456
}
457

    
458

    
459
/**
460
 * @todo Please document this function.
461
 * @see http://drupal.org/node/1354
462
 */
463
function set_last_taxon_page_tab($taxonPageTab) {
464
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
465
}
466

    
467
/**
468
 * @todo Please document this function.
469
 * @see http://drupal.org/node/1354
470
 */
471
function get_last_taxon_page_tab() {
472
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
473
    return $_SESSION['cdm']['taxon_page_tab'];
474
  }
475
  else {
476
    return FALSE;
477
  }
478
}
479

    
480
/**
481
 *
482
 * @param object $media
483
 * @param array $mimeTypes
484
 *    an array of mimetypes in their order of preference. e.g:
485
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
486
 * @param int $width
487
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
488
 * @param int $height
489
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
490
 *
491
 * @return array
492
 *   An array with preferred media representations or else an empty array.
493
 */
494
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
495
  $prefRepr = array();
496
  if (!isset($media->representations[0])) {
497
    return $prefRepr;
498
  }
499

    
500
  while (count($mimeTypes) > 0) {
501
    // getRepresentationByMimeType
502
    $mimeType = array_shift($mimeTypes);
503

    
504
    foreach ($media->representations as &$representation) {
505
      // If the mimetype is not known, try inferring it.
506
      if (!$representation->mimeType) {
507
        if (isset($representation->parts[0])) {
508
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
509
        }
510
      }
511

    
512
      if ($representation->mimeType == $mimeType) {
513
        // Preferred mimetype found -> erase all remaining mimetypes
514
        // to end loop.
515
        $mimeTypes = array();
516
        $expansionDeltaSum = 0;
517
        $valid_parts_cnt = 0;
518
        // Look for part with the best matching size.
519
        foreach ($representation->parts as $part) {
520
          if (empty($part->uri)) {
521
            // skip part if URI is missing
522
            continue;
523
          }
524
          $valid_parts_cnt++;
525
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
526

    
527
          // determine the optimal size
528
          if (isset($part->width) && isset($part->height)) {
529
            $expansion = $part->width * $part->height;
530
            if ($width != null && $height != null) {
531
              $optimalExpansion = $height * $width;
532
            } else {
533
              $optimalExpansion = PHP_INT_MAX;
534
            }
535
            // determine the difference
536
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
537
          }
538
          // sum up the expansionDeltas of all parts contained in the representation
539
          $expansionDeltaSum += $expansionDelta;
540
        }
541
        if($valid_parts_cnt > 0){
542
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
543
          $prefRepr[$expansionDeltaSum] = $representation;
544
        }
545
      }
546
    }
547
  }
548
  // Sort the array so that the smallest key value is the first in the array
549
  ksort($prefRepr);
550
  return $prefRepr;
551
}
552

    
553
/**
554
 * Infers the mime type of a file using the filename extension.
555
 *
556
 * The filename extension is used to infer the mime type.
557
 *
558
 * @param string $filepath
559
 *   The path to the respective file.
560
 *
561
 * @return string
562
 *   The mimetype for the file or FALSE if the according mime type could
563
 *   not be found.
564
 */
565
function infer_mime_type($filepath) {
566
  static $mimemap = NULL;
567
  if (!$mimemap) {
568
    $mimemap = array(
569
      'jpg' => 'image/jpeg',
570
      'jpeg' => 'image/jpeg',
571
      'png' => 'image/png',
572
      'gif' => 'image/gif',
573
      'giff' => 'image/gif',
574
      'tif' => 'image/tif',
575
      'tiff' => 'image/tif',
576
      'pdf' => 'application/pdf',
577
      'html' => 'text/html',
578
      'htm' => 'text/html',
579
    );
580
  }
581
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
582
  if (isset($mimemap[$extension])) {
583
    return $mimemap[$extension];
584
  }
585
  else {
586
    // FIXME remove this hack just return FALSE;
587
    return 'text/html';
588
  }
589
}
590

    
591
/**
592
 * Converts an ISO 8601 org.joda.time.Partial to a year.
593
 *
594
 * The function expects an ISO 8601 time representation of a
595
 * org.joda.time.Partial of the form yyyy-MM-dd.
596
 *
597
 * @param string $partial
598
 *   ISO 8601 time representation of a org.joda.time.Partial.
599
 *
600
 * @return string
601
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
602
 */
603
function partialToYear($partial) {
604
  if (is_string($partial)) {
605
    $year = substr($partial, 0, 4);
606
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
607
      return $year;
608
    }
609
  }
610
  return '';
611
}
612

    
613
/**
614
 * Converts an ISO 8601 org.joda.time.Partial to a month.
615
 *
616
 * This function expects an ISO 8601 time representation of a
617
 * org.joda.time.Partial of the form yyyy-MM-dd.
618
 * In case the month is unknown (= ???) NULL is returned.
619
 *
620
 * @param string $partial
621
 *   ISO 8601 time representation of a org.joda.time.Partial.
622
 *
623
 * @return string
624
 *   A month.
625
 */
626
function partialToMonth($partial) {
627
  if (is_string($partial)) {
628
    $month = substr($partial, 5, 2);
629
    if (preg_match("/[0-9][0-9]/", $month)) {
630
      return $month;
631
    }
632
  }
633
  return '';
634
}
635

    
636
/**
637
 * Converts an ISO 8601 org.joda.time.Partial to a day.
638
 *
639
 * This function expects an ISO 8601 time representation of a
640
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
641
 * In case the day is unknown (= ???) NULL is returned.
642
 *
643
 * @param string $partial
644
 *   ISO 8601 time representation of a org.joda.time.Partial.
645
 *
646
 * @return string
647
 *   A day.
648
 */
649
function partialToDay($partial) {
650
  if (is_string($partial)) {
651
    $day = substr($partial, 8, 2);
652
    if (preg_match("/[0-9][0-9]/", $day)) {
653
      return $day;
654
    }
655
  }
656
  return '';
657
}
658

    
659
/**
660
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
661
 *
662
 * This function expects an ISO 8601 time representations of a
663
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
664
 * four digit year, month and day with dashes:
665
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
666
 *
667
 * The partial may contain question marks eg: "1973-??-??",
668
 * these are turned in to '00' or are stripped depending of the $stripZeros
669
 * parameter.
670
 *
671
 * @param string $partial
672
 *   org.joda.time.Partial.
673
 * @param bool $stripZeros
674
 *   If set to TRUE the zero (00) month and days will be hidden:
675
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
676
 * @param string @format
677
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
678
 *    - "YYYY": Year only
679
 *    - "YYYY-MM-DD": this is the default
680
 *
681
 * @return string
682
 *   YYYY-MM-DD formatted year, month, day.
683
 */
684
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
685

    
686
  $y = NULL; $m = NULL; $d = NULL;
687

    
688
  if(strpos($format, 'YY') !== FALSE){
689
    $y = partialToYear($partial);
690
  }
691
  if(strpos($format, 'MM') !== FALSE){
692
    $m = partialToMonth($partial);
693
  }
694
  if(strpos($format, 'DD') !== FALSE){
695
    $d = partialToDay($partial);
696
  }
697

    
698
  $y = $y ? $y : '00';
699
  $m = $m ? $m : '00';
700
  $d = $d ? $d : '00';
701

    
702
  $date = '';
703

    
704
  if ($y == '00' && $stripZeros) {
705
    return '';
706
  }
707
  else {
708
    $date = $y;
709
  }
710

    
711
  if ($m == '00' && $stripZeros) {
712
    return $date;
713
  }
714
  else {
715
    $date .= "-" . $m;
716
  }
717

    
718
  if ($d == '00' && $stripZeros) {
719
    return $date;
720
  }
721
  else {
722
    $date .= "-" . $d;
723
  }
724
  return $date;
725
}
726

    
727
/**
728
 * Converts a time period to a string.
729
 *
730
 * See also partialToDate($partial, $stripZeros).
731
 *
732
 * @param object $period
733
 *   An JodaTime org.joda.time.Period object.
734
 * @param bool $stripZeros
735
 *   If set to True, the zero (00) month and days will be hidden:
736
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
737
 * @param string @format
738
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
739
 *    - "YYYY": Year only
740
 *    - "YYYY-MM-DD": this is the default
741
 *
742
 * @return string
743
 *   Returns a date in the form of a string.
744
 */
745
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
746
  $dateString = '';
747
  if($period->freeText){
748
    $dateString = $period->freeText;
749
  } else {
750
    if ($period->start) {
751
      $dateString = partialToDate($period->start, $stripZeros, $format);
752
    }
753
    if ($period->end) {
754
      $end_str = partialToDate($period->end, $stripZeros, $format);
755
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
756
    }
757
  }
758
  return $dateString;
759
}
760

    
761
/**
762
 * returns the earliest date available in the $period in a normalized
763
 * form suitable for sorting, e.g.:
764
 *
765
 *  - 1956-00-00
766
 *  - 0000-00-00
767
 *  - 1957-03-00
768
 *
769
 * that is either the start date is returned if set otherwise the
770
 * end date
771
 *
772
 * @param  $period
773
 *    An JodaTime org.joda.time.Period object.
774
 * @return string normalized form of the date
775
 *   suitable for sorting
776
 */
777
function timePeriodAsOrderKey($period) {
778
  $dateString = '';
779
  if ($period->start) {
780
    $dateString = partialToDate($period->start, false);
781
  }
782
  if ($period->end) {
783
    $dateString .= partialToDate($period->end, false);
784
  }
785
  return $dateString;
786
}
787

    
788
/**
789
 * Composes a absolute CDM web service URI with parameters and querystring.
790
 *
791
 * @param string $uri_pattern
792
 *   String with place holders ($0, $1, ..) that should be replaced by the
793
 *   according element of the $pathParameters array.
794
 * @param array $pathParameters
795
 *   An array of path elements, or a single element.
796
 * @param string $query
797
 *   A query string to append to the URL.
798
 *
799
 * @return string
800
 *   A complete URL with parameters to a CDM webservice.
801
 */
802
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
803
  if (empty($pathParameters)) {
804
    $pathParameters = array();
805
  }
806

    
807
  // (1)
808
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
809
  // according element of the $pathParameters array.
810
  static $helperArray = array();
811
  if (isset($pathParameters) && !is_array($pathParameters)) {
812
    $helperArray[0] = $pathParameters;
813
    $pathParameters = $helperArray;
814
  }
815

    
816
  $i = 0;
817
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
818
    if (count($pathParameters) <= $i) {
819
        drupal_set_message(
820
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
821
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
822
          'error');
823
      break;
824
    }
825
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
826
    ++$i;
827
  }
828

    
829
  // (2)
830
  // Append all remaining element of the $pathParameters array as path
831
  // elements.
832
  if (count($pathParameters) > $i) {
833
    // Strip trailing slashes.
834
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
835
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
836
    }
837
    while (count($pathParameters) > $i) {
838
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
839
      ++$i;
840
    }
841
  }
842

    
843
  // (3)
844
  // Append the query string supplied by $query.
845
  if (isset($query)) {
846
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
847
  }
848

    
849
  $path = $uri_pattern;
850

    
851
  $uri = variable_get('cdm_webservice_url', '') . $path;
852
  return $uri;
853
}
854

    
855
/**
856
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
857
 *     together with a theme name to such a proxy function?
858
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
859
 *     Maybe we want to have two different proxy functions, one with theming and one without?
860
 *
861
 * @param string $uri
862
 *     A URI to a CDM Rest service from which to retrieve an object
863
 * @param string|null $hook
864
 *     (optional) The hook name to which the retrieved object should be passed.
865
 *     Hooks can either be a theme_hook() or compose_hook() implementation
866
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
867
 *     suitable for drupal_render()
868
 *
869
 * @todo Please document this function.
870
 * @see http://drupal.org/node/1354
871
 */
872
function proxy_content($uri, $hook = NULL) {
873

    
874
  $args = func_get_args();
875
  $do_gzip = function_exists('gzencode');
876
  $uriEncoded = array_shift($args);
877
  $uri = urldecode($uriEncoded);
878
  $hook = array_shift($args);
879
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
880

    
881
  $post_data = null;
882

    
883
  if ($request_method == "POST" || $request_method == "PUT") {
884
    // read response body via inputstream module
885
    $post_data = file_get_contents("php://input");
886
  }
887

    
888
  // Find and deserialize arrays.
889
  foreach ($args as &$arg) {
890
    // FIXME use regex to find serialized arrays.
891
    //       or should we accept json instead of php serializations?
892
    if (strpos($arg, "a:") === 0) {
893
      $arg = unserialize($arg);
894
    }
895
  }
896

    
897
  // In all these cases perform a simple get request.
898
  // TODO reconsider caching logic in this function.
899

    
900
  if (empty($hook)) {
901
    // simply return the webservice response
902
    // Print out JSON, the cache cannot be used since it contains objects.
903
    $http_response = cdm_http_request($uri, $request_method, $post_data);
904
    if (isset($http_response->headers)) {
905
      foreach ($http_response->headers as $hname => $hvalue) {
906
        drupal_add_http_header($hname, $hvalue);
907
      }
908
    }
909
    if (isset($http_response->data)) {
910
      print $http_response->data;
911
      flush();
912
    }
913
    exit(); // leave drupal here
914
  } else {
915
    // $hook has been supplied
916
    // handle $hook either as compose ot theme hook
917
    // pass through theme or comose hook
918
    // compose hooks can be called without data, therefore
919
    // passing the $uri in this case is not always a requirement
920

    
921
    if($uri && $uri != 'NULL') {
922
    // do a security check since the $uri will be passed
923
    // as absolute URI to cdm_ws_get()
924
      if (!_is_cdm_ws_uri($uri)) {
925
        drupal_set_message(
926
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
927
          'error'
928
        );
929
        return '';
930
      }
931

    
932
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
933
    } else {
934
      $obj = NULL;
935
    }
936

    
937
    $reponse_data = NULL;
938

    
939
    if (function_exists('compose_' . $hook)){
940
      // call compose hook
941

    
942
      $elements =  call_user_func('compose_' . $hook, $obj);
943
      // pass the render array to drupal_render()
944
      $reponse_data = drupal_render($elements);
945
    } else {
946
      // call theme hook
947

    
948
      // TODO use theme registry to get the registered hook info and
949
      //    use these defaults
950
      switch($hook) {
951
        case 'cdm_taxontree':
952
          $variables = array(
953
            'tree' => $obj,
954
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
955
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
956
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
957
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
958
            );
959
          $reponse_data = theme($hook, $variables);
960
          break;
961

    
962
        case 'cdm_list_of_taxa':
963
            $variables = array(
964
              'records' => $obj,
965
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
966
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
967
            $reponse_data = theme($hook, $variables);
968
            break;
969

    
970
        case 'cdm_media_caption':
971
          $variables = array(
972
            'media' => $obj,
973
            // $args[0] is set in taxon_image_gallery_default in
974
            // cdm_dataportal.page.theme.
975
            'elements' => isset($args[0]) ? $args[0] : array(
976
            'title',
977
            'description',
978
            'artist',
979
            'location',
980
            'rights',
981
          ),
982
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
983
          );
984
          $reponse_data = theme($hook, $variables);
985
          break;
986

    
987
        default:
988
          drupal_set_message(t(
989
          'Theme !theme is not yet supported by the function !function.', array(
990
          '!theme' => $hook,
991
          '!function' => __FUNCTION__,
992
          )), 'error');
993
          break;
994
      } // END of theme hook switch
995
    } // END of tread as theme hook
996

    
997

    
998
    if($do_gzip){
999
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1000
      drupal_add_http_header('Content-Encoding', 'gzip');
1001
    }
1002
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1003
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1004

    
1005
    print $reponse_data;
1006
  } // END of handle $hook either as compose ot theme hook
1007

    
1008
}
1009

    
1010
/**
1011
 * @todo Please document this function.
1012
 * @see http://drupal.org/node/1354
1013
 */
1014
function setvalue_session() {
1015
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1016
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1017
    $var_keys = explode('][', $var_keys);
1018
  }
1019
  else {
1020
    return;
1021
  }
1022
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1023

    
1024
  // Prevent from malicous tags.
1025
  $val = strip_tags($val);
1026

    
1027
  $session_var = &$_SESSION;
1028
  //$i = 0;
1029
  foreach ($var_keys as $key) {
1030
    // $hasMoreKeys = ++$i < count($session);
1031
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1032
      $session_var[$key] = array();
1033
    }
1034
    $session_var = &$session_var[$key];
1035
  }
1036
  $session_var = $val;
1037
  if (isset($_REQUEST['destination'])) {
1038
    drupal_goto($_REQUEST['destination']);
1039
  }
1040
}
1041

    
1042
/**
1043
 * @todo Please document this function.
1044
 * @see http://drupal.org/node/1354
1045
 */
1046
function uri_uriByProxy($uri, $theme = FALSE) {
1047
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1048
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1049
}
1050

    
1051
/**
1052
 * Composes the the absolute REST service URI to the annotations pager
1053
 * for the given CDM entity.
1054
 *
1055
 * NOTE: Not all CDM Base types are yet supported.
1056
 *
1057
 * @param $cdmBase
1058
 *   The CDM entity to construct the annotations pager uri for
1059
 */
1060
function cdm_compose_annotations_uri($cdmBase) {
1061
  if (!$cdmBase->uuid) {
1062
    return;
1063
  }
1064

    
1065
  $ws_base_uri = NULL;
1066
  switch ($cdmBase->class) {
1067
    case 'TaxonBase':
1068
    case 'Taxon':
1069
    case 'Synonym':
1070
      $ws_base_uri = CDM_WS_TAXON;
1071
      break;
1072

    
1073
    case 'TaxonName':
1074
      $ws_base_uri = CDM_WS_NAME;
1075
      break;
1076

    
1077
    case 'Media':
1078
      $ws_base_uri = CDM_WS_MEDIA;
1079
      break;
1080

    
1081
    case 'Reference':
1082
      $ws_base_uri = CDM_WS_REFERENCE;
1083
      break;
1084

    
1085
    case 'Distribution':
1086
    case 'TextData':
1087
    case 'TaxonInteraction':
1088
    case 'QuantitativeData':
1089
    case 'IndividualsAssociation':
1090
    case 'Distribution':
1091
    case 'CommonTaxonName':
1092
    case 'CategoricalData':
1093
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1094
      break;
1095

    
1096
    case 'PolytomousKey':
1097
    case 'MediaKey':
1098
    case 'MultiAccessKey':
1099
      $ws_base_uri = $cdmBase->class;
1100
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1101
      break;
1102

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

    
1113
/**
1114
 * Enter description here...
1115
 *
1116
 * @param string $resourceURI
1117
 * @param int $pageSize
1118
 *   The maximum number of entities returned per page.
1119
 *   The default page size as configured in the cdm server
1120
 *   will be used if set to NULL
1121
 *   to return all entities in a single page).
1122
 * @param int $pageNumber
1123
 *   The number of the page to be returned, the first page has the
1124
 *   pageNumber = 0
1125
 * @param array $query
1126
 *   A array holding the HTTP request query parameters for the request
1127
 * @param string $method
1128
 *   The HTTP method to use, valid values are "GET" or "POST"
1129
 * @param bool $absoluteURI
1130
 *   TRUE when the URL should be treated as absolute URL.
1131
 *
1132
 * @return the a CDM Pager object
1133
 *
1134
 */
1135
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1136

    
1137
  $query['pageNumber'] = $pageNumber;
1138
  $query['pageSize'] = $pageSize;
1139

    
1140
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1141
}
1142

    
1143
/**
1144
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1145
 *
1146
 * @param string $resourceURI
1147
 * @param array $query
1148
 *   A array holding the HTTP request query parameters for the request
1149
 * @param string $method
1150
 *   The HTTP method to use, valid values are "GET" or "POST";
1151
 * @param bool $absoluteURI
1152
 *   TRUE when the URL should be treated as absolute URL.
1153
 *
1154
 * @return array
1155
 *     A list of CDM entitites
1156
 *
1157
 */
1158
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1159
  $page_index = 0;
1160
  // using a bigger page size to avoid to many multiple requests
1161
  $page_size = 500;
1162
  $entities = array();
1163

    
1164
  while ($page_index !== FALSE){
1165
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1166
    if(isset($pager->records) && is_array($pager->records)) {
1167
      $entities = array_merge($entities, $pager->records);
1168
      if(!empty($pager->nextIndex)){
1169
        $page_index = $pager->nextIndex;
1170
      } else {
1171
        $page_index = FALSE;
1172
      }
1173
    } else {
1174
      $page_index = FALSE;
1175
    }
1176
  }
1177
  return $entities;
1178
}
1179

    
1180
/*
1181
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1182
  $viewrank = _cdm_taxonomy_compose_viewrank();
1183
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1184
  ? '/' . $path : '') ;
1185
}
1186
*/
1187

    
1188
/**
1189
 * @todo Enter description here...
1190
 *
1191
 * @param string $taxon_uuid
1192
 *  The UUID of a cdm taxon instance
1193
 * @param string $ignore_rank_limit
1194
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1195
 *
1196
 * @return string
1197
 *   A cdm REST service URL path to a Classification
1198
 */
1199
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1200

    
1201
  $view_uuid = get_current_classification_uuid();
1202
  $rank_uuid = NULL;
1203
  if (!$ignore_rank_limit) {
1204
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1205
  }
1206

    
1207
  if (!empty($taxon_uuid)) {
1208
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1209
      $view_uuid,
1210
      $taxon_uuid,
1211
    ));
1212
  }
1213
  else {
1214
    if (is_uuid($rank_uuid)) {
1215
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1216
        $view_uuid,
1217
        $rank_uuid,
1218
      ));
1219
    }
1220
    else {
1221
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1222
        $view_uuid,
1223
      ));
1224
    }
1225
  }
1226
}
1227

    
1228
/**
1229
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1230
 *
1231
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1232
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1233
 *
1234
 * Operates in two modes depending on whether the parameter
1235
 * $taxon_uuid is set or NULL.
1236
 *
1237
 * A) $taxon_uuid = NULL:
1238
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1239
 *  2. otherwise return the default classification as defined by the admin via the settings
1240
 *
1241
 * b) $taxon_uuid is set:
1242
 *   return the classification to whcih the taxon belongs to.
1243
 *
1244
 * @param UUID $taxon_uuid
1245
 *   The UUID of a cdm taxon instance
1246
 */
1247
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1248

    
1249
    $response = NULL;
1250

    
1251
    // 1st try
1252
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1253

    
1254
    if ($response == NULL) {
1255
      // 2dn try by ignoring the rank limit
1256
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1257
    }
1258

    
1259
    if ($response == NULL) {
1260
      // 3rd try, last fallback:
1261
      //    return the default classification
1262
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1263
        // Delete the session value and try again with the default.
1264
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1265
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1266
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1267
      }
1268
      else {
1269
        // Check if taxonomictree_uuid is valid.
1270
        // expecting an array of taxonNodes,
1271
        // empty classifications are ok so no warning in this case!
1272
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1273
        if (!is_array($test)) {
1274
          // The default set by the admin seems to be invalid or is not even set.
1275
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1276
        }
1277
        if (count($test) == 0) {
1278
          // The default set by the admin seems to be invalid or is not even set.
1279
          drupal_set_message("The chosen classification is empty.", 'status');
1280
        }
1281
      }
1282
    }
1283

    
1284
  return $response;
1285
}
1286

    
1287
/**
1288
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1289
 * 
1290
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1291
 * variable is set.
1292
 *
1293
 * @param string $taxon_uuid
1294
 *
1295
 * @return array
1296
 *   An array of CDM TaxonNodeDTO objects
1297
 */
1298
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1299
  $view_uuid = get_current_classification_uuid();
1300
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1301

    
1302
  $response = NULL;
1303
  if (is_uuid($rank_uuid)) {
1304
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1305
      $view_uuid,
1306
      $taxon_uuid,
1307
      $rank_uuid,
1308
    ));
1309
  }
1310
  else {
1311
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1312
      $view_uuid,
1313
      $taxon_uuid,
1314
    ));
1315
  }
1316

    
1317
  if ($response == NULL) {
1318
    // Error handing.
1319
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1320
//      // Delete the session value and try again with the default.
1321
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1322
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1323
//    }
1324
//    else {
1325
      // Check if taxonomictree_uuid is valid.
1326
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1327
      if ($test == NULL) {
1328
        // The default set by the admin seems to be invalid or is not even set.
1329
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1330
      }
1331
//    }
1332
  }
1333

    
1334
  return $response;
1335
}
1336

    
1337

    
1338
// =============================Terms and Vocabularies ========================================= //
1339

    
1340
/**
1341
 * Returns the localized representation for the given term.
1342
 *
1343
 * @param Object $definedTermBase
1344
 * 	  of cdm type DefinedTermBase
1345
 * @return string
1346
 * 	  the localized representation_L10n of the term,
1347
 *    otherwise the titleCache as fall back,
1348
 *    otherwise the default_representation which defaults to an empty string
1349
 */
1350
function cdm_term_representation($definedTermBase, $default_representation = '') {
1351
  if ( isset($definedTermBase->representation_L10n) ) {
1352
    return $definedTermBase->representation_L10n;
1353
  } elseif ( isset($definedTermBase->titleCache)) {
1354
    return $definedTermBase->titleCache;
1355
  }
1356
  return $default_representation;
1357
}
1358

    
1359
/**
1360
 * Returns the abbreviated localized representation for the given term.
1361
 *
1362
 * @param Object $definedTermBase
1363
 * 	  of cdm type DefinedTermBase
1364
 * @return string
1365
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1366
 *    if this representation is not available the function delegates the
1367
 *    call to cdm_term_representation()
1368
 */
1369
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1370
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1371
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1372
  } else {
1373
    cdm_term_representation($definedTermBase, $default_representation);
1374
  }
1375
}
1376

    
1377
/**
1378
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1379
 *
1380
 * The options array is suitable for drupal form API elements that allow multiple choices.
1381
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1382
 *
1383
 * @param array $terms
1384
 *   a list of CDM DefinedTermBase instances
1385
 *
1386
 * @param $term_label_callback
1387
 *   A callback function to override the term representations
1388
 *
1389
 * @param bool $empty_option
1390
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1391
 *
1392
 * @return array
1393
 *   the terms in an array as options for a form element that allows multiple choices.
1394
 */
1395
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1396
  $options = array();
1397
  if(isset($terms) && is_array($terms)) {
1398
    foreach ($terms as $term) {
1399
      if ($term_label_callback && function_exists($term_label_callback)) {
1400
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1401
      } else {
1402
        //TODO use cdm_term_representation() here?
1403
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1404
      }
1405
    }
1406
  }
1407

    
1408
  if($empty_option !== FALSE){
1409
    array_unshift ($options, "");
1410
  }
1411

    
1412
  return $options;
1413
}
1414

    
1415
/**
1416
 * Creates and array of options for drupal select form elements.
1417
 *
1418
 * @param $vocabulary_uuid
1419
 *   The UUID of the CDM Term Vocabulary
1420
 * @param $term_label_callback
1421
 *   An optional call back function which can be used to modify the term label
1422
 * @param bool $empty_option
1423
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1424
 * @param array $include_filter
1425
 *   An associative array consisting of a field name an regular expression. All term matching
1426
 *   these filter are included. The value of the field is converted to a String by var_export()
1427
 *   so a boolean 'true' can be matched by '/true/'
1428
 * @param string $order_by
1429
 *   One of the order by constants defined in this file
1430
 * @return mixed
1431
 */
1432
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1433
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1434

    
1435
  static $vocabularyOptions = array();
1436

    
1437
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1438
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1439
      array(
1440
        'orderBy' => $order_by
1441
      )
1442
    );
1443

    
1444
    // apply the include filter
1445
    if($include_filter != null){
1446
      $included_terms = array();
1447

    
1448
      foreach ($terms as $term){
1449
        $include = true;
1450
        foreach ($include_filter as $field=>$regex){
1451
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1452
          if(!$include){
1453
            break;
1454
          }
1455
        }
1456
        if($include){
1457
          $included_terms[] = $term;
1458
        }
1459
      }
1460

    
1461
      $terms = $included_terms;
1462
    }
1463

    
1464
    // make options list
1465
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1466
  }
1467

    
1468
  $options = $vocabularyOptions[$vocabulary_uuid];
1469

    
1470
  return $options;
1471
}
1472

    
1473
/**
1474
 * @param $term_type string one of
1475
 *  - Unknown
1476
 *  - Language
1477
 *  - NamedArea
1478
 *  - Rank
1479
 *  - Feature
1480
 *  - AnnotationType
1481
 *  - MarkerType
1482
 *  - ExtensionType
1483
 *  - DerivationEventType
1484
 *  - PresenceAbsenceTerm
1485
 *  - NomenclaturalStatusType
1486
 *  - NameRelationshipType
1487
 *  - HybridRelationshipType
1488
 *  - SynonymRelationshipType
1489
 *  - TaxonRelationshipType
1490
 *  - NameTypeDesignationStatus
1491
 *  - SpecimenTypeDesignationStatus
1492
 *  - InstitutionType
1493
 *  - NamedAreaType
1494
 *  - NamedAreaLevel
1495
 *  - RightsType
1496
 *  - MeasurementUnit
1497
 *  - StatisticalMeasure
1498
 *  - MaterialOrMethod
1499
 *  - Material
1500
 *  - Method
1501
 *  - Modifier
1502
 *  - Scope
1503
 *  - Stage
1504
 *  - KindOfUnit
1505
 *  - Sex
1506
 *  - ReferenceSystem
1507
 *  - State
1508
 *  - NaturalLanguageTerm
1509
 *  - TextFormat
1510
 *  - DeterminationModifier
1511
 *  - DnaMarker
1512
 *
1513
 * @param  $order_by
1514
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1515
 *  possible values:
1516
 *    - CDM_ORDER_BY_ID_ASC
1517
 *    - CDM_ORDER_BY_ID_DESC
1518
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1519
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1520
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1521
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1522
 * @param bool $empty_option
1523
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1524
 * @return array
1525
 *    the terms in an array as options for a form element that allows multiple choices.
1526
 */
1527
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1528
  $terms = cdm_ws_fetch_all(
1529
    CDM_WS_TERM,
1530
    array(
1531
      'class' => $term_type,
1532
      'orderBy' => $order_by
1533
    )
1534
  );
1535
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1536
}
1537

    
1538

    
1539
/**
1540
 * @todo Please document this function.
1541
 * @see http://drupal.org/node/1354
1542
 */
1543
function _cdm_relationship_type_term_label_callback($term) {
1544
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1545
    return $term->representation_L10n_abbreviatedLabel . ' : '
1546
    . t('@term', array('@term' => $term->representation_L10n));
1547
  }
1548
else {
1549
    return t('@term', array('@term' => $term->representation_L10n));
1550
  }
1551
}
1552

    
1553
// ========================================================================================== //
1554
/**
1555
 * @todo Improve documentation of this function.
1556
 *
1557
 * eu.etaxonomy.cdm.model.description.
1558
 * CategoricalData
1559
 * CommonTaxonName
1560
 * Distribution
1561
 * IndividualsAssociation
1562
 * QuantitativeData
1563
 * TaxonInteraction
1564
 * TextData
1565
 */
1566
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1567
  static $types = array(
1568
    "CategoricalData",
1569
    "CommonTaxonName",
1570
    "Distribution",
1571
    "IndividualsAssociation",
1572
    "QuantitativeData",
1573
    "TaxonInteraction",
1574
    "TextData",
1575
  );
1576

    
1577
  static $options = NULL;
1578
  if ($options == NULL) {
1579
    $options = array();
1580
    if ($prependEmptyElement) {
1581
      $options[' '] = '';
1582
    }
1583
    foreach ($types as $type) {
1584
      // No internatianalization here since these are purely technical terms.
1585
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1586
    }
1587
  }
1588
  return $options;
1589
}
1590

    
1591

    
1592
/**
1593
 * Fetches all TaxonDescription descriptions elements which are associated to the
1594
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1595
 * feature tree.
1596
 * @param $feature_tree
1597
 *     The CDM FeatureTree to be used as template
1598
 * @param $taxon_uuid
1599
 *     The UUID of the taxon
1600
 * @param $excludes
1601
 *     UUIDs of features to be excluded
1602
 * @return$feature_tree
1603
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1604
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1605
 *     witch will hold the according $descriptionElements.
1606
 */
1607
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1608

    
1609
  if (!$feature_tree) {
1610
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1611
      In order to see the species profiles of your taxa, please select a
1612
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1613
    return FALSE;
1614
  }
1615

    
1616
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1617
      array(
1618
      'taxon' => $taxon_uuid,
1619
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1620
      ),
1621
      'POST'
1622
  );
1623

    
1624
  // Combine all descriptions into one feature tree.
1625
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1626
  $feature_tree->root->childNodes = $merged_nodes;
1627

    
1628
  return $feature_tree;
1629
}
1630

    
1631
/**
1632
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1633
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1634
 * be requested for the annotations.
1635
 *
1636
 * @param string $cdmBase
1637
 *   An annotatable cdm entity.
1638
 * @param array $includeTypes
1639
 *   If an array of annotation type uuids is supplied by this parameter the
1640
 *   list of annotations is resticted to those which belong to this type.
1641
 *
1642
 * @return array
1643
 *   An array of Annotation objects or an empty array.
1644
 */
1645
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1646

    
1647
  if(!isset($cdmBase->annotations)){
1648
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1649
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1650
  }
1651

    
1652
  $annotations = array();
1653
  foreach ($cdmBase->annotations as $annotation) {
1654
    if ($includeTypes) {
1655
      if (
1656
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1657
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1658
      ) {
1659
        $annotations[] = $annotation;
1660
      }
1661
    }
1662
    else {
1663
      $annotations[] = $annotation;
1664
    }
1665
  }
1666
  return $annotations;
1667

    
1668
}
1669

    
1670
/**
1671
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1672
 *
1673
 * @param object $annotatable_entity
1674
 *   The CDM AnnotatableEntity to load annotations for
1675
 */
1676
function cdm_load_annotations(&$annotatable_entity) {
1677
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1678
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1679
    if (is_array($annotations)) {
1680
      $annotatable_entity->annotations = $annotations;
1681
    }
1682
  }
1683
}
1684

    
1685
/**
1686
 * Extends the $cdm_entity object by the field if it is not already existing.
1687
 *
1688
 * This function can only be used for fields with 1 to many relations.
1689
  *
1690
 * @param $cdm_base_type
1691
 * @param $field_name
1692
 * @param $cdm_entity
1693
 */
1694
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1695
{
1696
  if (!isset($cdm_entity->$field_name)) {
1697
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1698
    $cdm_entity->$field_name = $items;
1699
  }
1700
}
1701

    
1702

    
1703
/**
1704
 * Get a NomenclaturalReference string.
1705
 *
1706
 * Returns the NomenclaturalReference string with correctly placed
1707
 * microreference (= reference detail) e.g.
1708
 * in Phytotaxa 43: 1-48. 2012.
1709
 *
1710
 * @param string $referenceUuid
1711
 *   UUID of the reference.
1712
 * @param string $microreference
1713
 *   Reference detail.
1714
 *
1715
 * @return string
1716
 *   a NomenclaturalReference.
1717
 */
1718
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1719

    
1720
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1721
  if(is_array($microreference) || is_object($microreference)) {
1722
    return '';
1723
  }
1724

    
1725
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1726
    $referenceUuid,
1727
  ), "microReference=" . urlencode($microreference));
1728

    
1729
  if ($obj) {
1730
    return $obj->String;
1731
  }
1732
  else {
1733
    return NULL;
1734
  }
1735
}
1736

    
1737
/**
1738
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1739
 *
1740
 * @param $feature_tree_nodes
1741
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1742
 * @param $feature_uuid
1743
 *    The UUID of the Feature
1744
 * @return returns the FeatureNode or null
1745
 */
1746
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1747

    
1748
  // 1. scan this level
1749
  foreach ($feature_tree_nodes as $node){
1750
    if($node->feature->uuid == $feature_uuid){
1751
      return $node;
1752
    }
1753
  }
1754

    
1755
  // 2. descend into childen
1756
  foreach ($feature_tree_nodes as $node){
1757
    if(is_array($node->childNodes)){
1758
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1759
      if($node) {
1760
        return $node;
1761
      }
1762
    }
1763
  }
1764
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1765
  return $null_var;
1766
}
1767

    
1768
/**
1769
 * Merges the given featureNodes structure with the descriptionElements.
1770
 *
1771
 * This method is used in preparation for rendering the descriptionElements.
1772
 * The descriptionElements which belong to a specific feature node are appended
1773
 * to a the feature node by creating a new field:
1774
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1775
 * The descriptionElements will be cleared in advance in order to allow reusing the
1776
 * same feature tree without the risk of mixing sets of description elements.
1777
 *
1778
 * which originally is not existing in the cdm.
1779
 *
1780
 *
1781
 *
1782
 * @param array $featureNodes
1783
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1784
 *    may have children.
1785
 * @param array $descriptionElements
1786
 *    An flat array of cdm DescriptionElements
1787
 * @return array
1788
 *    The $featureNodes structure enriched with the according $descriptionElements
1789
 */
1790
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1791

    
1792
  foreach ($featureNodes as &$node) {
1793
    // since the $featureNodes array is reused for each description
1794
    // it is necessary to clear the custom node fields in advance
1795
    if(isset($node->descriptionElements)){
1796
      unset($node->descriptionElements);
1797
    }
1798

    
1799
    // Append corresponding elements to an additional node field:
1800
    // $node->descriptionElements.
1801
    foreach ($descriptionElements as $element) {
1802
      if ($element->feature->uuid == $node->feature->uuid) {
1803
        if (!isset($node->descriptionElements)) {
1804
          $node->descriptionElements = array();
1805
        }
1806
        $node->descriptionElements[] = $element;
1807
      }
1808
    }
1809

    
1810
    // Recurse into node children.
1811
    if (isset($node->childNodes[0])) {
1812
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1813
      $node->childNodes = $mergedChildNodes;
1814
    }
1815

    
1816
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1817
      unset($node);
1818
    }
1819

    
1820
  }
1821

    
1822
  return $featureNodes;
1823
}
1824

    
1825
/**
1826
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1827
 *
1828
 * The response from the HTTP GET request is returned as object.
1829
 * The response objects coming from the webservice configured in the
1830
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1831
 *  in a level 2 (L2) cache.
1832
 *
1833
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1834
 * function, this cache persists only per each single page execution.
1835
 * Any object coming from the webservice is stored into it by default.
1836
 * In contrast to this default caching mechanism the L2 cache only is used if
1837
 * the 'cdm_webservice_cache' variable is set to TRUE,
1838
 * which can be set using the modules administrative settings section.
1839
 * Objects stored in this L2 cache are serialized and stored
1840
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1841
 * objects that are stored in the database will persist as
1842
 * long as the drupal cache is not being cleared and are available across
1843
 * multiple script executions.
1844
 *
1845
 * @param string $uri
1846
 *   URL to the webservice.
1847
 * @param array $pathParameters
1848
 *   An array of path parameters.
1849
 * @param string $query
1850
 *   A query string to be appended to the URL.
1851
 * @param string $method
1852
 *   The HTTP method to use, valid values are "GET" or "POST";
1853
 * @param bool $absoluteURI
1854
 *   TRUE when the URL should be treated as absolute URL.
1855
 *
1856
 * @return object| array
1857
 *   The de-serialized webservice response object.
1858
 */
1859
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1860

    
1861
  static $cacheL1 = array();
1862

    
1863
  $data = NULL;
1864
  // store query string in $data and clear the query, $data will be set as HTTP request body
1865
  if($method == 'POST'){
1866
    $data = $query;
1867
    $query = NULL;
1868
  }
1869

    
1870
  // Transform the given uri path or pattern into a proper webservice uri.
1871
  if (!$absoluteURI) {
1872
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1873
  }
1874

    
1875
  // read request parameter 'cacheL2_refresh'
1876
  // which allows refreshing the level 2 cache
1877
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1878

    
1879
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1880
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1881

    
1882
  if($method == 'GET'){
1883
    $cache_key = $uri;
1884
  } else {
1885
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1886
    // crc32 is faster but creates much shorter hashes
1887
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1888
  }
1889

    
1890
  if (array_key_exists($cache_key, $cacheL1)) {
1891
    $cacheL1_obj = $cacheL1[$uri];
1892
  }
1893

    
1894
  $set_cacheL1 = FALSE;
1895
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1896
    $set_cacheL1 = TRUE;
1897
  }
1898

    
1899
  // Only cache cdm webservice URIs.
1900
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1901
  $cacheL2_entry = FALSE;
1902

    
1903
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1904
    // Try to get object from cacheL2.
1905
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1906
  }
1907

    
1908
  if (isset($cacheL1_obj)) {
1909
    //
1910
    // The object has been found in the L1 cache.
1911
    //
1912
    $obj = $cacheL1_obj;
1913
    if (cdm_debug_block_visible()) {
1914
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1915
    }
1916
  }
1917
  elseif ($cacheL2_entry) {
1918
    //
1919
    // The object has been found in the L2 cache.
1920
    //
1921
    $duration_parse_start = microtime(TRUE);
1922
    $obj = unserialize($cacheL2_entry->data);
1923
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1924

    
1925
    if (cdm_debug_block_visible()) {
1926
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1927
    }
1928
  }
1929
  else {
1930
    //
1931
    // Get the object from the webservice and cache it.
1932
    //
1933
    $duration_fetch_start = microtime(TRUE);
1934
    // Request data from webservice JSON or XML.
1935
    $response = cdm_http_request($uri, $method, $data);
1936
    $response_body = NULL;
1937
    if (isset($response->data)) {
1938
      $response_body = $response->data;
1939
    }
1940
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1941
    $duration_parse_start = microtime(TRUE);
1942

    
1943
    // Parse data and create object.
1944
    $obj = cdm_load_obj($response_body);
1945

    
1946
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1947

    
1948
    if (cdm_debug_block_visible()) {
1949
      if ($obj || $response_body == "[]") {
1950
        $status = 'valid';
1951
      }
1952
      else {
1953
        $status = 'invalid';
1954
      }
1955
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1956
    }
1957
    if ($set_cacheL2) {
1958
      // Store the object in cache L2.
1959
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1960
      // flag serialized is set properly in the cache table.
1961
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1962
    }
1963
  }
1964
  if ($obj) {
1965
    // Store the object in cache L1.
1966
    if ($set_cacheL1) {
1967
      $cacheL1[$cache_key] = $obj;
1968
    }
1969
  }
1970
  return $obj;
1971
}
1972

    
1973
/**
1974
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1975
 *
1976
 * The cdm_ws_debug block will display the debug information.
1977
 *
1978
 * @param $uri
1979
 *    The CDM REST URI to which the request has been send
1980
 * @param string $method
1981
 *    The HTTP request method, either 'GET' or 'POST'
1982
 * @param string $post_data
1983
 *    The datastring send with a post request
1984
 * @param $duration_fetch
1985
 *    The time in seconds it took to fetch the data from the web service
1986
 * @param $duration_parse
1987
 *    Time in seconds which was needed to parse the json response
1988
 * @param $datasize
1989
 *    Size of the data received from the server
1990
 * @param $status
1991
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1992
 * @return bool
1993
 *    TRUE if adding the debug information was successful
1994
 */
1995
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1996

    
1997
  static $initial_time = NULL;
1998
  if(!$initial_time) {
1999
    $initial_time = microtime(TRUE);
2000
  }
2001
  $time = microtime(TRUE) - $initial_time;
2002

    
2003
  // Decompose uri into path and query element.
2004
  $uri_parts = explode("?", $uri);
2005
  $query = array();
2006
  if (count($uri_parts) == 2) {
2007
    $path = $uri_parts[0];
2008
  }
2009
  else {
2010
    $path = $uri;
2011
  }
2012

    
2013
  if(strpos($uri, '?') > 0){
2014
    $json_uri = str_replace('?', '.json?', $uri);
2015
    $xml_uri = str_replace('?', '.xml?', $uri);
2016
  } else {
2017
    $json_uri = $uri . '.json';
2018
    $xml_uri = $json_uri . '.xml';
2019
  }
2020

    
2021
  // data links to make data accecsible as json and xml
2022
  $data_links = '';
2023
  if (_is_cdm_ws_uri($path)) {
2024

    
2025
    // see ./js/http-method-link.js
2026

    
2027
    if($method == 'GET'){
2028
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2029
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2030
      $data_links .= '<br/>';
2031
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2032
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2033
    } else {
2034
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2035
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2036
      $data_links .= '<br/>';
2037
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2038
    }
2039
  }
2040
  else {
2041
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2042
  }
2043

    
2044
  //
2045
  $data = array(
2046
      'ws_uri' => $uri,
2047
      'method' => $method,
2048
      'post_data' => $post_data,
2049
      'time' => sprintf('%3.3f', $time),
2050
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2051
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2052
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2053
      'status' => $status,
2054
      'data_links' => $data_links
2055
  );
2056
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2057
    $_SESSION['cdm']['ws_debug'] = array();
2058
  }
2059
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2060

    
2061
  // Mark this page as being uncacheable.
2062
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2063
  drupal_page_is_cacheable(FALSE);
2064

    
2065
  // Messages not set when DB connection fails.
2066
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2067
}
2068

    
2069
/**
2070
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2071
 * the visibility depends on whether
2072
 *  - the block is enabled
2073
 *  - the visibility restrictions in the block settings are satisfied
2074
 */
2075
function cdm_debug_block_visible() {
2076
  static $is_visible = null;
2077

    
2078
  if($is_visible === null){
2079
      $block = block_load('cdm_api', 'cdm_ws_debug');
2080
      $is_visible = isset($block->status) && $block->status == 1;
2081
      if($is_visible){
2082
        $blocks = array($block);
2083
        // Checks the page, user role, and user-specific visibilty settings.
2084
        block_block_list_alter($blocks);
2085
        $is_visible = count($blocks) > 0;
2086
      }
2087
  }
2088
  return $is_visible;
2089
}
2090

    
2091
/**
2092
 * @todo Please document this function.
2093
 * @see http://drupal.org/node/1354
2094
 */
2095
function cdm_load_obj($response_body) {
2096
  $obj = json_decode($response_body);
2097

    
2098
  if (!(is_object($obj) || is_array($obj))) {
2099
    ob_start();
2100
    $obj_dump = ob_get_contents();
2101
    ob_clean();
2102
    return FALSE;
2103
  }
2104

    
2105
  return $obj;
2106
}
2107

    
2108
/**
2109
 * Do a http request to a CDM RESTful web service.
2110
 *
2111
 * @param string $uri
2112
 *   The webservice url.
2113
 * @param string $method
2114
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2115
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2116
 * @param $data: A string containing the request body, formatted as
2117
 *     'param=value&param=value&...'. Defaults to NULL.
2118
 *
2119
 * @return object
2120
 *   The object as returned by drupal_http_request():
2121
 *   An object that can have one or more of the following components:
2122
 *   - request: A string containing the request body that was sent.
2123
 *   - code: An integer containing the response status code, or the error code
2124
 *     if an error occurred.
2125
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2126
 *   - status_message: The status message from the response, if a response was
2127
 *     received.
2128
 *   - redirect_code: If redirected, an integer containing the initial response
2129
 *     status code.
2130
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2131
 *     target.
2132
 *   - error: If an error occurred, the error message. Otherwise not set.
2133
 *   - headers: An array containing the response headers as name/value pairs.
2134
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2135
 *     easy access the array keys are returned in lower case.
2136
 *   - data: A string containing the response body that was received.
2137
 */
2138
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2139
  static $acceptLanguage = NULL;
2140
  $header = array();
2141
  
2142
  if(!$acceptLanguage && module_exists('i18n')){
2143
    $acceptLanguage = i18n_language_content()->language;
2144
  }
2145

    
2146
  if (!$acceptLanguage) {
2147
    if (function_exists('apache_request_headers')) {
2148
      $headers = apache_request_headers();
2149
      if (isset($headers['Accept-Language'])) {
2150
        $acceptLanguage = $headers['Accept-Language'];
2151
      }
2152
    }
2153
  }
2154

    
2155
  if ($method != "GET" && $method != "POST") {
2156
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2157
  }
2158

    
2159
  if (_is_cdm_ws_uri($uri)) {
2160
    $header['Accept'] = 'application/json';
2161
    $header['Accept-Language'] = $acceptLanguage;
2162
    $header['Accept-Charset'] = 'UTF-8';
2163
  }
2164

    
2165
  if($method == "POST") {
2166
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2167
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2168
  }
2169

    
2170

    
2171
  cdm_dd($uri);
2172
  return drupal_http_request($uri, array(
2173
      'headers' => $header,
2174
      'method' => $method,
2175
      'data' => $data,
2176
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2177
      )
2178
   );
2179
}
2180

    
2181
/**
2182
 * Concatenates recursively the fields of all features contained in the given
2183
 * CDM FeatureTree root node.
2184
 *
2185
 * @param $rootNode
2186
 *     A CDM FeatureTree node
2187
 * @param
2188
 *     The character to be used as glue for concatenation, default is ', '
2189
 * @param $field_name
2190
 *     The field name of the CDM Features
2191
 * @param $excludes
2192
 *     Allows defining a set of values to be excluded. This refers to the values
2193
 *     in the field denoted by the $field_name parameter
2194
 *
2195
 */
2196
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2197
  $out = '';
2198

    
2199
  $pre_child_separator = $separator;
2200
  $post_child_separator = '';
2201

    
2202
  foreach ($root_node->childNodes as $feature_node) {
2203
    $out .= ($out ? $separator : '');
2204
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2205
      $out .= $feature_node->feature->$field_name;
2206
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2207
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2208
        if (strlen($childlabels)) {
2209
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2210
        }
2211
      }
2212
    }
2213
  }
2214
  return $out;
2215
}
2216

    
2217
/**
2218
 * Create a one-dimensional form options array.
2219
 *
2220
 * Creates an array of all features in the feature tree of feature nodes,
2221
 * the node labels are indented by $node_char and $childIndent depending on the
2222
 * hierachy level.
2223
 *
2224
 * @param - $rootNode
2225
 * @param - $node_char
2226
 * @param - $childIndentStr
2227
 * @param - $childIndent
2228
 *   ONLY USED INTERNALLY!
2229
 *
2230
 * @return array
2231
 *   A one dimensional Drupal form options array.
2232
 */
2233
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2234
  $options = array();
2235
  foreach ($rootNode->childNodes as $featureNode) {
2236
    $indent_prefix = '';
2237
    if ($childIndent) {
2238
      $indent_prefix = $childIndent . $node_char . " ";
2239
    }
2240
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2241
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2242
      // Foreach ($featureNode->childNodes as $childNode){
2243
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2244
      $options = array_merge_recursive($options, $childList);
2245
      // }
2246
    }
2247
  }
2248
  return $options;
2249
}
2250

    
2251
/**
2252
 * Returns an array with all available FeatureTrees and the representations of the selected
2253
 * FeatureTree as a detail view.
2254
 *
2255
 * @param boolean $add_default_feature_free
2256
 * @return array
2257
 *  associative array with following keys:
2258
 *  -options: Returns an array with all available Feature Trees
2259
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2260
 *
2261
 */
2262
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2263

    
2264
  $options = array();
2265
  $tree_representations = array();
2266
  $feature_trees = array();
2267

    
2268
  // Set tree that contains all features.
2269
  if ($add_default_feature_free) {
2270
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2271
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2272
  }
2273

    
2274
  // Get feature trees from database.
2275
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2276
  if (is_array($persited_trees)) {
2277
    $feature_trees = array_merge($feature_trees, $persited_trees);
2278
  }
2279

    
2280
  foreach ($feature_trees as $featureTree) {
2281

    
2282
    if(!is_object($featureTree)){
2283
      continue;
2284
    }
2285
    // Do not add the DEFAULT_FEATURETREE again,
2286
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2287
      $options[$featureTree->uuid] = $featureTree->titleCache;
2288
    }
2289

    
2290
    // Render the hierarchic tree structure
2291
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2292

    
2293
      // Render the hierarchic tree structure.
2294
      $treeDetails = '<div class="featuretree_structure">'
2295
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2296
        . '</div>';
2297

    
2298
      $form = array();
2299
      $form['featureTree-' .  $featureTree->uuid] = array(
2300
        '#type' => 'fieldset',
2301
        '#title' => 'Show details',
2302
        '#attributes' => array('class' => array('collapsible collapsed')),
2303
        // '#collapsible' => TRUE,
2304
        // '#collapsed' => TRUE,
2305
      );
2306
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2307
        '#markup' => $treeDetails,
2308
      );
2309

    
2310
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2311
    }
2312

    
2313
  } // END loop over feature trees
2314

    
2315
  // return $options;
2316
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2317
}
2318

    
2319
/**
2320
 * Provides the list of available classifications in form of an options array.
2321
 *
2322
 * The options array is suitable for drupal form API elements that allow multiple choices.
2323
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2324
 *
2325
 * The classifications are ordered alphabetically whereas the classification
2326
 * chosen as default will always appear on top of the array, followed by a
2327
 * blank line below.
2328
 *
2329
 * @param bool $add_none_option
2330
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2331
 *
2332
 * @return array
2333
 *   classifications in an array as options for a form element that allows multiple choices.
2334
 */
2335
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2336

    
2337
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2338

    
2339
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2340
  $default_classification_label = '';
2341

    
2342
  // add all classifications
2343
  $taxonomic_tree_options = array();
2344
  if ($add_none_option) {
2345
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2346
  }
2347
  if ($taxonTrees) {
2348
    foreach ($taxonTrees as $tree) {
2349
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2350
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2351
      } else {
2352
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2353
        $default_classification_label = $tree->titleCache;
2354
      }
2355
    }
2356
  }
2357
  // oder alphabetically the space
2358
  asort($taxonomic_tree_options);
2359

    
2360
  // now set the labels
2361
  //   for none
2362
  if ($add_none_option) {
2363
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2364
  }
2365

    
2366
  //   for default_classification
2367
  if (is_uuid($default_classification_uuid)) {
2368
    $taxonomic_tree_options[$default_classification_uuid] =
2369
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2370
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2371
  }
2372

    
2373
  return $taxonomic_tree_options;
2374
}
2375

    
2376
/**
2377
 * @todo Please document this function.
2378
 * @see http://drupal.org/node/1354
2379
 */
2380
function cdm_api_secref_cache_prefetch(&$secUuids) {
2381
  // Comment @WA: global variables should start with a single underscore
2382
  // followed by the module and another underscore.
2383
  global $_cdm_api_secref_cache;
2384
  if (!is_array($_cdm_api_secref_cache)) {
2385
    $_cdm_api_secref_cache = array();
2386
  }
2387
  $uniqueUuids = array_unique($secUuids);
2388
  $i = 0;
2389
  $param = '';
2390
  while ($i++ < count($uniqueUuids)) {
2391
    $param .= $secUuids[$i] . ',';
2392
    if (strlen($param) + 37 > 2000) {
2393
      _cdm_api_secref_cache_add($param);
2394
      $param = '';
2395
    }
2396
  }
2397
  if ($param) {
2398
    _cdm_api_secref_cache_add($param);
2399
  }
2400
}
2401

    
2402
/**
2403
 * @todo Please document this function.
2404
 * @see http://drupal.org/node/1354
2405
 */
2406
function cdm_api_secref_cache_get($secUuid) {
2407
  global $_cdm_api_secref_cache;
2408
  if (!is_array($_cdm_api_secref_cache)) {
2409
    $_cdm_api_secref_cache = array();
2410
  }
2411
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2412
    _cdm_api_secref_cache_add($secUuid);
2413
  }
2414
  return $_cdm_api_secref_cache[$secUuid];
2415
}
2416

    
2417
/**
2418
 * @todo Please document this function.
2419
 * @see http://drupal.org/node/1354
2420
 */
2421
function cdm_api_secref_cache_clear() {
2422
  global $_cdm_api_secref_cache;
2423
  $_cdm_api_secref_cache = array();
2424
}
2425

    
2426

    
2427
/**
2428
 * Validates if the given string is a uuid.
2429
 *
2430
 * @param string $str
2431
 *   The string to validate.
2432
 *
2433
 * return bool
2434
 *   TRUE if the string is a UUID.
2435
 */
2436
function is_uuid($str) {
2437
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2438
}
2439

    
2440
/**
2441
 * Checks if the given $object is a valid cdm entity.
2442
 *
2443
 * An object is considered a cdm entity if it has a string field $object->class
2444
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2445
 * The function is null save.
2446
 *
2447
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2448
 *
2449
 * @param mixed $object
2450
 *   The object to validate
2451
 *
2452
 * @return bool
2453
 *   True if the object is a cdm entity.
2454
 */
2455
function is_cdm_entity($object) {
2456
  return
2457
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2458
    && is_string($object->uuid) && is_uuid($object->uuid);
2459
}
2460

    
2461
/**
2462
 * @todo Please document this function.
2463
 * @see http://drupal.org/node/1354
2464
 */
2465
function _cdm_api_secref_cache_add($secUuidsStr) {
2466
  global $_cdm_api_secref_cache;
2467
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2468
  // Batch fetching not jet reimplemented thus:
2469
  /*
2470
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2471
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2472
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2473
  */
2474
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2475
}
2476

    
2477
/**
2478
 * Checks if the given uri starts with a cdm webservice url.
2479
 *
2480
 * Checks if the uri starts with the cdm webservice url stored in the
2481
 * Drupal variable 'cdm_webservice_url'.
2482
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2483
 *
2484
 * @param string $uri
2485
 *   The URI to test.
2486
 *
2487
 * @return bool
2488
 *   True if the uri starts with a cdm webservice url.
2489
 */
2490
function _is_cdm_ws_uri($uri) {
2491
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2492
}
2493

    
2494
/**
2495
 * @todo Please document this function.
2496
 * @see http://drupal.org/node/1354
2497
 */
2498
function queryString($elements) {
2499
  $query = '';
2500
  foreach ($elements as $key => $value) {
2501
    if (is_array($value)) {
2502
      foreach ($value as $v) {
2503
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2504
      }
2505
    }
2506
    else {
2507
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2508
    }
2509
  }
2510
  return $query;
2511
}
2512

    
2513
/**
2514
 * Implementation of the magic method __clone to allow deep cloning of objects
2515
 * and arrays.
2516
 */
2517
function __clone() {
2518
  foreach ($this as $name => $value) {
2519
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2520
      $this->$name = clone($this->$name);
2521
    }
2522
  }
2523
}
2524

    
2525
/**
2526
 * Compares the given CDM Term instances by the  representationL10n.
2527
 *
2528
 * Can also be used with TermDTOs. To be used in usort()
2529
 *
2530
 * @see http://php.net/manual/en/function.usort.php
2531
 *
2532
 * @param $term1
2533
 *   The first CDM Term instance
2534
 * @param $term2
2535
 *   The second CDM Term instance
2536
 * @return int
2537
 *   The result of the comparison
2538
 */
2539
function compare_terms_by_representationL10n($term1, $term2) {
2540

    
2541
  if (!isset($term1->representation_L10n)) {
2542
    $term1->representationL10n = '';
2543
  }
2544
  if (!isset($term2->representation_L10n)) {
2545
    $term2->representationL10n = '';
2546
  }
2547

    
2548
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2549
}
2550

    
2551
function compare_terms_by_order_index($term1, $term2) {
2552

    
2553

    
2554
  if (!isset($term1->orderIndex)) {
2555
    $a = 0;
2556
  } else {
2557
    $a = $term1->orderIndex;
2558
  }
2559
  if (!isset($term2->orderIndex)) {
2560
    $b = 0;
2561
  } else {
2562
    $b = $term2->orderIndex;
2563
  }
2564

    
2565
  if ($a == $b) {
2566
    return 0;
2567
  }
2568
  return ($a < $b) ? -1 : 1;
2569

    
2570
}
2571

    
2572

    
2573
/**
2574
 * Make a 'deep copy' of an array.
2575
 *
2576
 * Make a complete deep copy of an array replacing
2577
 * references with deep copies until a certain depth is reached
2578
 * ($maxdepth) whereupon references are copied as-is...
2579
 *
2580
 * @see http://us3.php.net/manual/en/ref.array.php
2581
 *
2582
 * @param array $array
2583
 * @param array $copy passed by reference
2584
 * @param int $maxdepth
2585
 * @param int $depth
2586
 */
2587
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2588
  if ($depth > $maxdepth) {
2589
    $copy = $array;
2590
    return;
2591
  }
2592
  if (!is_array($copy)) {
2593
    $copy = array();
2594
  }
2595
  foreach ($array as $k => &$v) {
2596
    if (is_array($v)) {
2597
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2598
    }
2599
    else {
2600
      $copy[$k] = $v;
2601
    }
2602
  }
2603
}
2604

    
2605
/**
2606
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2607
 *
2608
 */
2609
function _add_js_ws_debug() {
2610

    
2611
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2612
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2613
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2614
    // use the developer versions of js libs
2615
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2616
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2617
  }
2618
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2619
    array(
2620
      'type' => 'file',
2621
      'weight' => JS_LIBRARY,
2622
      'cache' => TRUE)
2623
    );
2624

    
2625
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2626
    array(
2627
      'type' => 'file',
2628
      'weight' => JS_LIBRARY,
2629
      'cache' => TRUE)
2630
    );
2631
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2632
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2633

    
2634
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2635
    array(
2636
      'type' => 'file',
2637
      'weight' => JS_LIBRARY,
2638
      'cache' => TRUE)
2639
    );
2640
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2641
    array(
2642
    'type' => 'file',
2643
    'weight' => JS_LIBRARY,
2644
    'cache' => TRUE)
2645
    );
2646

    
2647
}
2648

    
2649
/**
2650
 * @todo Please document this function.
2651
 * @see http://drupal.org/node/1354
2652
 */
2653
function _no_classfication_uuid_message() {
2654
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2655
    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.');
2656
  }
2657
  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.');
2658
}
2659

    
2660
/**
2661
 * Implementation of hook flush_caches
2662
 *
2663
 * Add custom cache tables to the list of cache tables that
2664
 * will be cleared by the Clear button on the Performance page or whenever
2665
 * drupal_flush_all_caches is invoked.
2666
 *
2667
 * @author W.Addink <waddink@eti.uva.nl>
2668
 *
2669
 * @return array
2670
 *   An array with custom cache tables to include.
2671
 */
2672
function cdm_api_flush_caches() {
2673
  return array('cache_cdm_ws');
2674
}
2675

    
2676
/**
2677
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2678
 *
2679
 * @param $data
2680
 *   The variable to log to the drupal_debug.txt log file.
2681
 * @param $label
2682
 *   (optional) If set, a label to output before $data in the log file.
2683
 *
2684
 * @return
2685
 *   No return value if successful, FALSE if the log file could not be written
2686
 *   to.
2687
 *
2688
 * @see cdm_dataportal_init() where the log file is reset on each requests
2689
 * @see dd()
2690
 * @see http://drupal.org/node/314112
2691
 *
2692
 */
2693
function cdm_dd($data, $label = NULL) {
2694
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2695
    return dd($data, $label);
2696
  }
2697
}
2698

    
(5-5/11)