Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / 7.x / modules / cdm_dataportal / cdm_api / cdm_api.module @ 42f2e1e0

History | View | Annotate | Download (63.4 KB)

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', 'webservice_uris');
28
module_load_include('php', 'cdm_api', 'cdm_node');
29

    
30

    
31
/**
32
 * Tiemout 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
 * Implements hook_menu().
42
 */
43
function cdm_api_menu() {
44
  $items = array();
45

    
46
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
47
  $items['cdm_api/proxy'] = array(
48
    'page callback' => 'proxy_content',
49
    'access arguments' => array(
50
      'access content',
51
    ),
52
    'type' => MENU_CALLBACK,
53
  );
54

    
55
  $items['cdm_api/setvalue/session'] = array(
56
    'page callback' => 'setvalue_session',
57
    'access arguments' => array(
58
      'access content',
59
    ),
60
    'type' => MENU_CALLBACK,
61
  );
62

    
63
  return $items;
64
}
65

    
66
/**
67
 * Implements hook_block_info().
68
 */
69
function cdm_api_block_info() {
70

    
71
  $block['cdm_ws_debug'] = array(
72
      "info" => t("CDM web service debug"),
73
      "cache" => DRUPAL_NO_CACHE
74
  );
75
  return $block;
76
}
77

    
78
/**
79
 * Implements hook_block_view().
80
 */
81
function cdm_api_block_view($delta) {
82
  switch ($delta) {
83
    case 'cdm_ws_debug':
84

    
85
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
86

    
87
    $field_map = array(
88
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
89
        'time' => t('Time'),
90
        'fetch_seconds' => t('Fetching [s]'),
91
        'parse_seconds' => t('Parsing [s]'),
92
        'size_kb' => t('Size [kb]'),
93
        'status' => t('Status'),
94
        'data_links' =>  t('Links'),
95
    );
96

    
97

    
98
    if (!isset($_SESSION['cdm']['ws_debug'])) {
99
      $_SESSION['cdm']['ws_debug'] = array();
100
    }
101

    
102
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
103
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
104
    $rows = array();
105

    
106
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
107

    
108
      $data = unserialize($data);
109

    
110
      // stip of webservice base url
111
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
112

    
113
      $cells = array();
114
      foreach ($field_map as $field => $label){
115
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
116
      }
117
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
118
    }
119
    // clear session again
120
    $_SESSION['cdm']['ws_debug'] = array();
121

    
122
    _add_js_ws_debug();
123

    
124
    $block['subject'] = ''; // no subject, title in content for having a defined element id
125
    // otherwise it would depend on the theme
126
    $block['content'] =
127
        '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
128
          // cannot use theme_table() since table footer is not jet supported in D7
129
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
130
        . $header
131
        . '<tbody>' . join('', $rows) . '</tbody>'
132
        . $footer
133
        . '</table></div>';
134

    
135
    return $block;
136
  }
137
}
138

    
139
/**
140
 * Implements hook_cron().
141
 *
142
 * Expire outdated cache entries.
143
 */
144
function cdm_api_cron() {
145
  cache_clear_all(NULL, 'cache_cdm_ws');
146
}
147

    
148
/**
149
 * @todo Please document this function.
150
 * @see http://drupal.org/node/1354
151
 */
152
function cdm_api_permission() {
153
  return array(
154
    'administer cdm_api' => array(
155
      'title' => t('administer cdm_api'),
156
      'description' => t("TODO Add a description for 'administer cdm_api'"),
157
    ),
158
  );
159
}
160

    
161
/**
162
 * Converts an array of TaggedText items into corresponding html tags.
163
 *
164
 * Each item is provided with a class attribute which is set to the key of the
165
 * TaggedText item.
166
 *
167
 * @param array $taggedtxt
168
 *   Array with text items to convert.
169
 * @param string $tag
170
 *   Html tag name to convert the items into, default is 'span'.
171
 * @param string $glue
172
 *   The string by which the chained text tokens are concatenated together.
173
 *   Default is a blank character.
174
 *
175
 * @return string
176
 *   A string with HTML.
177
 */
178
function cdm_taggedtext2html(array $taggedtxt, $tag = 'span', $glue = ' ', $skiptags = array()) {
179
  $out = '';
180
  $i = 0;
181
  foreach ($taggedtxt as $tt) {
182
    if (!in_array($tt->type, $skiptags) && strlen($tt->text) > 0) {
183
      $out .= (strlen($out) > 0 && ++$i < count($taggedtxt) ? $glue : '') . '<' . $tag . ' class="' . $tt->type . '">' . t($tt->text) . '</' . $tag . '>';
184
    }
185
  }
186
  return $out;
187
}
188

    
189
/**
190
 * Finds the text tagged with $tag_type in an array of taggedText instances.
191
 *
192
 * Comment @WA: this function seems unused.
193
 *
194
 * @param array $taggedtxt
195
 *   Array with text items.
196
 * @param string $tag_type
197
 *   The type of tag for which to find text items in the $taggedtxt array.
198
 *
199
 * @return array
200
 *   An array with the texts mapped by $tag_type.
201
 */
202
function cdm_taggedtext_values(array $taggedtxt, $tag_type) {
203
  $tokens = array();
204
  if (!empty($taggedtxt)) {
205
    foreach ($taggedtxt as $tagtxt) {
206
      if ($tagtxt->type == $tag_type) {
207
        $tokens[] = $tagtxt->text;
208
      }
209
    }
210
  }
211
  return $tokens;
212
}
213

    
214
/**
215
 * Returns the currently classification tree in use.
216
 */
217
function get_taxonomictree_uuid_selected() {
218
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
219
    return $_SESSION['cdm']['taxonomictree_uuid'];
220
  }
221
  else {
222
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
223
  }
224
}
225

    
226
/**
227
 * Lists the classifications a taxon belongs to
228
 *
229
 * @param CDM type Taxon $taxon
230
 *   the taxon
231
 *
232
 * @return array
233
 *   aray of CDM instances of Type Classification
234
 */
235
function get_classifications_for_taxon($taxon) {
236

    
237
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
238
}
239

    
240
/**
241
 * Returns the chosen FeatureTree for the taxon profile.
242
 *
243
 * The FeatureTree profile returned is the one that has been set in the
244
 * dataportal settings (layout->taxon:profile).
245
 * When the chosen FeatureTree is not found in the database,
246
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
247
 *
248
 * @return mixed
249
 *   A cdm FeatureTree object.
250
 */
251
function get_profile_featureTree() {
252
  static $profile_featureTree;
253

    
254
  if($profile_featureTree == NULL) {
255
    $profile_featureTree = cdm_ws_get(
256
      CDM_WS_FEATURETREE,
257
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
258
    );
259
    if (!$profile_featureTree) {
260
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
261
    }
262
  }
263
  return $profile_featureTree;
264
}
265

    
266
/**
267
 * Returns the chosen FeatureTree for SpecimenDescriptions.
268
 *
269
 * The FeatureTree returned is the one that has been set in the
270
 * dataportal settings (layout->taxon:specimen).
271
 * When the chosen FeatureTree is not found in the database,
272
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
273
 *
274
 * @return mixed
275
 *   A cdm FeatureTree object.
276
 */
277
function cdm_get_occurrence_featureTree() {
278
  static $occurrence_featureTree;
279

    
280
  if($occurrence_featureTree == NULL) {
281
    $occurrence_featureTree = cdm_ws_get(
282
      CDM_WS_FEATURETREE,
283
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
284
    );
285
    if (!$occurrence_featureTree) {
286
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
287
    }
288
  }
289
  return $occurrence_featureTree;
290
}
291

    
292
/**
293
 * Returns the FeatureTree for structured descriptions
294
 *
295
 * The FeatureTree returned is the one that has been set in the
296
 * dataportal settings (layout->taxon:profile).
297
 * When the chosen FeatureTree is not found in the database,
298
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
299
 *
300
 * @return mixed
301
 *   A cdm FeatureTree object.
302
 */
303
function get_structured_description_featureTree() {
304
  static $structured_description_featureTree;
305

    
306
  if($structured_description_featureTree == NULL) {
307
    $structured_description_featureTree = cdm_ws_get(
308
        CDM_WS_FEATURETREE,
309
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
310
    );
311
    if (!$structured_description_featureTree) {
312
      $structured_description_featureTree = cdm_ws_get(
313
          CDM_WS_FEATURETREE,
314
          UUID_DEFAULT_FEATURETREE
315
      );
316
    }
317
  }
318
  return $structured_description_featureTree;
319
}
320

    
321
/**
322
 * @todo Please document this function.
323
 * @see http://drupal.org/node/1354
324
 */
325
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
326
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
327
}
328

    
329
/**
330
 * @todo Please document this function.
331
 * @see http://drupal.org/node/1354
332
 */
333
function reset_taxonomictree_uuid($taxonomictree_uuid) {
334
  unset($_SESSION['cdm']['taxonomictree_uuid']);
335
}
336

    
337
/**
338
 * @todo Please document this function.
339
 * @see http://drupal.org/node/1354
340
 */
341
function set_last_taxon_page_tab($taxonPageTab) {
342
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
343
}
344

    
345
/**
346
 * @todo Please document this function.
347
 * @see http://drupal.org/node/1354
348
 */
349
function get_last_taxon_page_tab() {
350
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
351
    return $_SESSION['cdm']['taxon_page_tab'];
352
  }
353
  else {
354
    return FALSE;
355
  }
356
}
357

    
358
/**
359
 * @todo Improve the documentation of this function.
360
 *
361
 * media Array [4]
362
 * representations Array [3]
363
 * mimeType image/jpeg
364
 * representationParts Array [1]
365
 * duration 0
366
 * heigth 0
367
 * size 0
368
 * uri
369
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
370
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
371
 * width 0
372
 * suffix jpg
373
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
374
 * title
375
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
376
 *
377
 * @param object $media
378
 * @param array $mimeTypes
379
 * @param int $width
380
 * @param int $height
381
 *
382
 * @return array
383
 *   An array with preferred media representations or else an empty array.
384
 */
385
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
386
  $prefRepr = array();
387
  if (!isset($media->representations[0])) {
388
    return $prefRepr;
389
  }
390

    
391
  while (count($mimeTypes) > 0) {
392
    // getRepresentationByMimeType
393
    $mimeType = array_shift($mimeTypes);
394

    
395
    foreach ($media->representations as &$representation) {
396
      // If the mimetype is not known, try inferring it.
397
      if (!$representation->mimeType) {
398
        if (isset($representation->parts[0])) {
399
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
400
        }
401
      }
402

    
403
      if ($representation->mimeType == $mimeType) {
404
        // Preferred mimetype found -> erase all remaining mimetypes
405
        // to end loop.
406
        $mimeTypes = array();
407
        $dwa = 0;
408
        $dw = 0;
409
        // Look for part with the best matching size.
410
        foreach ($representation->parts as $part) {
411
          if (isset($part->width) && isset($part->height)) {
412
            $dw = $part->width * $part->height - $height * $width;
413
          }
414
          if ($dw < 0) {
415
            $dw *= -1;
416
          }
417
          $dwa += $dw;
418
        }
419
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
420
        $prefRepr[$dwa . '_'] = $representation;
421
      }
422
    }
423
  }
424
  // Sort the array.
425
  krsort($prefRepr);
426
  return $prefRepr;
427
}
428

    
429
/**
430
 * Infers the mime type of a file using the filename extension.
431
 *
432
 * The filename extension is used to infer the mime type.
433
 *
434
 * @param string $filepath
435
 *   The path to the respective file.
436
 *
437
 * @return string
438
 *   The mimetype for the file or FALSE if the according mime type could
439
 *   not be found.
440
 */
441
function infer_mime_type($filepath) {
442
  static $mimemap = NULL;
443
  if (!$mimemap) {
444
    $mimemap = array(
445
      'jpg' => 'image/jpeg',
446
      'jpeg' => 'image/jpeg',
447
      'png' => 'image/png',
448
      'gif' => 'image/gif',
449
      'giff' => 'image/gif',
450
      'tif' => 'image/tif',
451
      'tiff' => 'image/tif',
452
      'pdf' => 'application/pdf',
453
      'html' => 'text/html',
454
      'htm' => 'text/html',
455
    );
456
  }
457
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
458
  if (isset($mimemap[$extension])) {
459
    return $mimemap[$extension];
460
  }
461
  else {
462
    // FIXME remove this hack just return FALSE;
463
    return 'text/html';
464
  }
465
}
466

    
467
/**
468
 * Converts an ISO 8601 org.joda.time.Partial to a year.
469
 *
470
 * The function expects an ISO 8601 time representation of a
471
 * org.joda.time.Partial of the form yyyy-MM-dd.
472
 *
473
 * @param string $partial
474
 *   ISO 8601 time representation of a org.joda.time.Partial.
475
 *
476
 * @return string
477
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
478
 */
479
function partialToYear($partial) {
480
  if (is_string($partial)) {
481
    $year = substr($partial, 0, 4);
482
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
483
      return $year;
484
    }
485
  }
486
  return;
487
}
488

    
489
/**
490
 * Converts an ISO 8601 org.joda.time.Partial to a month.
491
 *
492
 * This function expects an ISO 8601 time representation of a
493
 * org.joda.time.Partial of the form yyyy-MM-dd.
494
 * In case the month is unknown (= ???) NULL is returned.
495
 *
496
 * @param string $partial
497
 *   ISO 8601 time representation of a org.joda.time.Partial.
498
 *
499
 * @return string
500
 *   A month.
501
 */
502
function partialToMonth($partial) {
503
  if (is_string($partial)) {
504
    $month = substr($partial, 5, 2);
505
    if (preg_match("/[0-9][0-9]/", $month)) {
506
      return $month;
507
    }
508
  }
509
  return;
510
}
511

    
512
/**
513
 * Converts an ISO 8601 org.joda.time.Partial to a day.
514
 *
515
 * This function expects an ISO 8601 time representation of a
516
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
517
 * In case the day is unknown (= ???) NULL is returned.
518
 *
519
 * @param string $partial
520
 *   ISO 8601 time representation of a org.joda.time.Partial.
521
 *
522
 * @return string
523
 *   A day.
524
 */
525
function partialToDay($partial) {
526
  if (is_string($partial)) {
527
    $day = substr($partial, 8, 2);
528
    if (preg_match("/[0-9][0-9]/", $day)) {
529
      return $day;
530
    }
531
  }
532
  return;
533
}
534

    
535
/**
536
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
537
 *
538
 * This function expects an ISO 8601 time representations of a
539
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
540
 * four digit year, month and day with dashes:
541
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
542
 *
543
 * The partial may contain question marks eg: "1973-??-??",
544
 * these are turned in to '00' or are stripped depending of the $stripZeros
545
 * parameter.
546
 *
547
 * @param string $partial
548
 *   org.joda.time.Partial.
549
 * @param bool $stripZeros
550
 *   If set to TRUE the zero (00) month and days will be hidden:
551
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
552
 *
553
 * @return string
554
 *   YYYY-MM-DD formatted year, month, day.
555
 */
556
function partialToDate($partial, $stripZeros = TRUE) {
557
  $y = partialToYear($partial);
558
  $m = partialToMonth($partial);
559
  $d = partialToDay($partial);
560

    
561
  $y = $y ? $y : '00';
562
  $m = $m ? $m : '00';
563
  $d = $d ? $d : '00';
564

    
565
  $date = '';
566

    
567
  if ($y == '00' && $stripZeros) {
568
    return;
569
  }
570
  else {
571
    $date = $y;
572
  }
573

    
574
  if ($m == '00' && $stripZeros) {
575
    return $date;
576
  }
577
  else {
578
    $date .= "-" . $m;
579
  }
580

    
581
  if ($d == '00' && $stripZeros) {
582
    return $date;
583
  }
584
  else {
585
    $date .= "-" . $d;
586
  }
587
  return $date;
588
}
589

    
590
/**
591
 * Converts a time period to a string.
592
 *
593
 * See also partialToDate($partial, $stripZeros).
594
 *
595
 * @param object $period
596
 *   An JodaTime org.joda.time.Period object.
597
 * @param bool $stripZeros
598
 *   If set to True, the zero (00) month and days will be hidden:
599
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
600
 *
601
 * @return string
602
 *   Returns a date in the form of a string.
603
 */
604
function timePeriodToString($period, $stripZeros = TRUE) {
605
  $dateString = '';
606
  if ($period->start) {
607
    $dateString = partialToDate($period->start, $stripZeros);
608
  }
609
  if ($period->end) {
610
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros);
611
  }
612
  return $dateString;
613
}
614
/**
615
 * returns the earliest date available in the $period in a normalized
616
 * form suitable for sorting, e.g.:
617
 *
618
 *  - 1956-00-00
619
 *  - 0000-00-00
620
 *  - 1957-03-00
621
 *
622
 * that is either the start date is returned if set otherwise the
623
 * end date
624
 *
625
 * @param  $period
626
 *    An JodaTime org.joda.time.Period object.
627
 * @return string normalized form of the date
628
 *   suitable for sorting
629
 */
630
function timePeriodAsOrderKey($period) {
631
  $dateString = '';
632
  if ($period->start) {
633
    $dateString = partialToDate($period->start, false);
634
  }
635
  if ($period->end) {
636
    $dateString .= partialToDate($period->end, false);
637
  }
638
  return $dateString;
639
}
640

    
641
/**
642
 * Composes a absolute CDM web service URI with parameters and querystring.
643
 *
644
 * @param string $uri_pattern
645
 *   String with place holders ($0, $1, ..) that should be replaced by the
646
 *   according element of the $pathParameters array.
647
 * @param array $pathParameters
648
 *   An array of path elements, or a single element.
649
 * @param string $query
650
 *   A query string to append to the URL.
651
 *
652
 * @return string
653
 *   A complete URL with parameters to a CDM webservice.
654
 */
655
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
656
  if (empty($pathParameters)) {
657
    $pathParameters = array();
658
  }
659

    
660
  $request_params = '';
661
  $path_params = '';
662

    
663
  // (1)
664
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
665
  // according element of the $pathParameters array.
666
  static $helperArray = array();
667
  if (isset($pathParameters) && !is_array($pathParameters)) {
668
    $helperArray[0] = $pathParameters;
669
    $pathParameters = $helperArray;
670
  }
671

    
672
  $i = 0;
673
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
674
    if (count($pathParameters) <= $i) {
675
      if (module_exists("user") && user_access('administer')) {
676
        drupal_set_message(t('cdm_compose_url(): missing pathParameters'), 'debug');
677
      }
678
      break;
679
    }
680
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
681
    ++$i;
682
  }
683

    
684
  // (2)
685
  // Append all remaining element of the $pathParameters array as path
686
  // elements.
687
  if (count($pathParameters) > $i) {
688
    // Strip trailing slashes.
689
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
690
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
691
    }
692
    while (count($pathParameters) > $i) {
693
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
694
      ++$i;
695
    }
696
  }
697

    
698
  // (3)
699
  // Append the query string supplied by $query.
700
  if (isset($query)) {
701
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
702
  }
703

    
704
  $path = $uri_pattern;
705

    
706
  $uri = variable_get('cdm_webservice_url', '') . $path;
707
  return $uri;
708
}
709

    
710
/**
711
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
712
 *     together with a theme name to such a proxy function?
713
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
714
 *     Maybe we want to have two different proxy functions, one with theming and one without?
715
 *
716
 * @param string $uri
717
 *     A URI to a CDM Rest service from which to retrieve an object
718
 * @param string|null $hook
719
 *     (optional) The hook name to which the retrieved object should be passed.
720
 *     Hooks can either be a theme_hook() or compose_hook() implementation
721
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
722
 *     suitable for drupal_render()
723
 *
724
 * @todo Please document this function.
725
 * @see http://drupal.org/node/1354
726
 */
727
function proxy_content($uri, $hook = NULL) {
728
  $args = func_get_args();
729
  $do_gzip = function_exists('gzencode');
730
  $uriEncoded = array_shift($args);
731
  $uri = urldecode($uriEncoded);
732
  $hook = array_shift($args);
733

    
734
  // Find and deserialize arrays.
735
  foreach ($args as &$arg) {
736
    // FIXME use regex to find serialized arrays.
737
    //       or should we accept json instead pf php serializations?
738
    if (strpos($arg, "a:") === 0) {
739
      $arg = unserialize($arg);
740
    }
741
  }
742

    
743
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
744
  if ($request_method == "POST") {
745
    // this is an experimental feature which will allow to
746
    // write data inot the cdm via the RESTfull web service
747
    $parameters = $_POST;
748
    $post_data = array();
749

    
750
    foreach ($parameters as $k => $v) {
751
      $post_data[] = "$k=" . utf8_encode($v);
752
    }
753
    $post_data = implode(',', $post_data);
754

    
755
    // For testing.
756
    // TODO use cdm_http_request(..) instead; ( CDM_HTTP_REQUEST_TIMEOUT is already set in there )
757
    $data = drupal_http_request($uri, array('headers' => "POST", 'method' => $post_data, 'timeout' => CDM_HTTP_REQUEST_TIMEOUT));
758
    // print $data;
759
  } else {
760
    // Not a "POST" request
761
    // In all these cases perform a simple get request.
762
    // TODO reconsider caching logic in this function.
763

    
764
    if (empty($hook)) {
765
      // simply return the webservice response
766
      // Print out JSON, the cache cannot be used since it contains objects.
767
      $http_response = cdm_http_request($uri);
768
      if (isset($http_response->headers)) {
769
        foreach ($http_response->headers as $hname => $hvalue) {
770
          drupal_add_http_header($hname, $hvalue);
771
        }
772
      }
773
      if (isset($http_response->data)) {
774
        print $http_response->data;
775
        flush();
776
      }
777
      exit(); // leave drupal here
778
    } else {
779
      // $hook has been supplied
780
      // handle $hook either as compose ot theme hook
781
      // pass through theme or comose hook
782

    
783
      // do a security check since the $uri will be passed
784
      // as absolute URI to cdm_ws_get()
785
      if( !_is_cdm_ws_uri($uri)) {
786
        drupal_set_message(
787
            'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
788
            'error'
789
        );
790
        return '';
791
      }
792

    
793
      $obj = cdm_ws_get($uri, NULL, NULL, NULL, TRUE);
794

    
795
      $reponse_data = NULL;
796

    
797
      if (function_exists('compose_' . $hook)){
798
        // call compose hook
799

    
800
        $elements =  call_user_func('compose_' . $hook, $obj);
801
        // pass the render array to drupal_render()
802
        $reponse_data = drupal_render($elements);
803
      } else {
804
        // call theme hook
805

    
806
        // TODO use theme registry to get the registered hook info and
807
        //    use these defaults
808
        switch($hook) {
809
          case 'cdm_taxontree':
810
            $variables = array(
811
              'tree' => $obj,
812
              'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
813
              'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
814
              'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
815
              'element_name'=> isset($args[3]) ? $args[3] : FALSE,
816
            );
817
            $reponse_data = theme($hook, $variables);
818
            break;
819

    
820
          case 'cdm_media_caption':
821
            $variables = array(
822
              'media' => $obj,
823
              // $args[0] is set in taxon_image_gallery_default in
824
              // cdm_dataportal.page.theme.
825
              'elements' => isset($args[0]) ? $args[0] : array(
826
                'title',
827
                'description',
828
                'artist',
829
                'location',
830
                'rights',
831
              ),
832
              'fileUri' => isset($args[1]) ? $args[1] : NULL,
833
            );
834
            $reponse_data = theme($hook, $variables);
835
            break;
836

    
837
          default:
838
            drupal_set_message(t(
839
            'Theme !theme is not supported yet by function !function.', array(
840
            '!theme' => $hook,
841
            '!function' => __FUNCTION__,
842
            )), 'error');
843
            break;
844
        } // END of theme hook switch
845
      } // END of tread as theme hook
846
      if($do_gzip){
847
        $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
848
        drupal_add_http_header('Content-Encoding', 'gzip');
849
      }
850
      drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
851
      drupal_add_http_header('Content-Length', strlen($reponse_data));
852
      print $reponse_data;
853
    } // END of handle $hook either as compose ot theme hook
854
  }
855
}
856

    
857
/**
858
 * @todo Please document this function.
859
 * @see http://drupal.org/node/1354
860
 */
861
function setvalue_session() {
862
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
863
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
864
    $keys = explode('][', $keys);
865
  }
866
  else {
867
    return;
868
  }
869
  $val = $_REQUEST['val'] ? $_REQUEST['val'] : NULL;
870

    
871
  // Prevent from malicous tags.
872
  $val = strip_tags($val);
873

    
874
  $var = &$_SESSION;
875
  $i = 0;
876
  foreach ($keys as $key) {
877
    $hasMoreKeys = ++$i < count($var);
878
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
879
      $var[$key] = array();
880
    }
881
    $var = &$var[$key];
882
  }
883
  $var = $val;
884
  if (isset($_REQUEST['destination'])) {
885
    drupal_goto($_REQUEST['destination']);
886
  }
887
}
888

    
889
/**
890
 * @todo Please document this function.
891
 * @see http://drupal.org/node/1354
892
 */
893
function uri_uriByProxy($uri, $theme = FALSE) {
894
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
895
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
896
}
897

    
898
/**
899
 * Composes the the absolute REST service URI to the annotations pager
900
 * for the given CDM entity.
901
 *
902
 * NOTE: Not all CDM Base types are yet supported.
903
 *
904
 * @param $cdmBase
905
 *   The CDM entity to construct the annotations pager uri for
906
 */
907
function cdm_compose_annotations_uri($cdmBase) {
908
  if (!$cdmBase->uuid) {
909
    return;
910
  }
911

    
912
  $ws_base_uri = NULL;
913
  switch ($cdmBase->class) {
914
    case 'TaxonBase':
915
    case 'Taxon':
916
    case 'Synonym':
917
      $ws_base_uri = CDM_WS_TAXON;
918
      break;
919

    
920
    case 'TaxonNameBase':
921
    case 'NonViralName':
922
    case 'BacterialName':
923
    case 'BotanicalName':
924
    case 'CultivarPlantName':
925
    case 'ZoologicalName':
926
    case 'ViralName':
927
      $ws_base_uri = CDM_WS_NAME;
928
      break;
929

    
930
    case 'Media':
931
      $ws_base_uri = CDM_WS_MEDIA;
932
      break;
933

    
934
    case 'Reference':
935
      $ws_base_uri = CDM_WS_REFERENCE;
936
      break;
937

    
938
    case 'Distribution':
939
    case 'TextData':
940
    case 'TaxonInteraction':
941
    case 'QuantitativeData':
942
    case 'IndividualsAssociation':
943
    case 'Distribution':
944
    case 'CommonTaxonName':
945
    case 'CategoricalData':
946
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
947
      break;
948

    
949
    case 'PolytomousKey':
950
    case 'MediaKey':
951
    case 'MultiAccessKey':
952
      $ws_base_uri = $cdmBase->class;
953
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
954
      break;
955

    
956
    default:
957
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
958
      return;
959
  }
960
  return cdm_compose_url($ws_base_uri, array(
961
    $cdmBase->uuid,
962
    'annotations',
963
  ));
964
}
965

    
966
/**
967
 * Enter description here...
968
 *
969
 * @param string $resourceURI
970
 * @param int $pageSize
971
 *   The maximum number of entities returned per page.
972
 *   The default page size as configured in the cdm server
973
 *   will be used if set to NULL
974
 *   to return all entities in a single page).
975
 * @param int $pageNumber
976
 *   The number of the page to be returned, the first page has the
977
 *   pageNumber = 0
978
 * @param bool $absoluteURI
979
 *   TRUE when the URL should be treated as absolute URL.
980
 * @return the a CDM Pager object
981
 *
982
 */
983
function cdm_ws_page($resourceURI, $pageSize, $pageNumber,  $absoluteURI = FALSE) {
984
  return cdm_ws_get($resourceURI, NULL, queryString(array(
985
      "pageNumber" => $pageNumber,
986
      'pageSize' => $pageSize,
987
    )),
988
    'GET',
989
    $absoluteURI);
990
}
991

    
992
/**
993
 * Fetches all entities from the given REST endpoint using the pager mechanism.
994
 *
995
 * @param string $resourceURI
996
 * @param bool $absoluteURI
997
 *   TRUE when the URL should be treated as absolute URL.
998
 *
999
 * @return array
1000
 *     A list of CDM entitites
1001
 *
1002
 */
1003
function cdm_ws_fetch_all($resourceURI, $absoluteURI = FALSE) {
1004
  $page_index = 0;
1005
  // using a bigger page size to avoid to many multiple requests
1006
  $page_size = 200;
1007
  $entities = array();
1008

    
1009
  while ($page_index !== FALSE){
1010
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $absoluteURI);
1011
    if(isset($pager->records) && is_array($pager->records)) {
1012
      $entities = $pager->records;
1013
      if(!empty($pager->nextIndex)){
1014
        $page_index = $pager->nextIndex;
1015
      } else {
1016
        $page_index = FALSE;
1017
      }
1018
    } else {
1019
      $page_index = FALSE;
1020
    }
1021
  }
1022
  return $entities;
1023
}
1024

    
1025
/*
1026
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1027
  $viewrank = _cdm_taxonomy_compose_viewrank();
1028
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1029
  ? '/' . $path : '') ;
1030
}
1031
*/
1032

    
1033
/**
1034
 * @todo Enter description here...
1035
 *
1036
 * @param string $taxon_uuid
1037
 *  The UUID of a cdm taxon instance
1038
 * @param string $ignore_rank_limit
1039
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1040
 *
1041
 * @return A cdm REST service URL path to a Classification
1042
 */
1043
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1044

    
1045
  $view_uuid = get_taxonomictree_uuid_selected();
1046
  $rank_uuid = NULL;
1047
  if (!$ignore_rank_limit) {
1048
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1049
  }
1050

    
1051
  if (!empty($taxon_uuid)) {
1052
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1053
      $view_uuid,
1054
      $taxon_uuid,
1055
    ));
1056
  }
1057
  else {
1058
    if (!empty($rank_uuid)) {
1059
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1060
        $view_uuid,
1061
        $rank_uuid,
1062
      ));
1063
    }
1064
    else {
1065
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1066
        $view_uuid,
1067
      ));
1068
    }
1069
  }
1070
}
1071

    
1072
/**
1073
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1074
 *
1075
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1076
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1077
 *
1078
 * Operates in two modes depending on whether the parameter
1079
 * $taxon_uuid is set or NULL.
1080
 *
1081
 * A) $taxon_uuid = NULL:
1082
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1083
 *  2. otherwise return the default classification as defined by the admin via the settings
1084
 *
1085
 * b) $taxon_uuid is set:
1086
 *   return the classification to whcih the taxon belongs to.
1087
 *
1088
 * @param UUID $taxon_uuid
1089
 *   The UUID of a cdm taxon instance
1090
 */
1091
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1092

    
1093
    $response = NULL;
1094

    
1095
    // 1st try
1096
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, NULL, TRUE);
1097

    
1098
    if ($response == NULL) {
1099
      // 2dn try by ignoring the rank limit
1100
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, NULL, TRUE);
1101
    }
1102

    
1103
    if ($response == NULL) {
1104
      // 3rd try, last fallback:
1105
      //    return the default classification
1106
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1107
        // Delete the session value and try again with the default.
1108
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1109
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1110
      }
1111
      else {
1112
        // Check if taxonomictree_uuid is valid.
1113
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1114
        if ($test == NULL) {
1115
          // The default set by the admin seems to be invalid or is not even set.
1116
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1117
        }
1118
      }
1119
    }
1120

    
1121
  return $response;
1122
}
1123

    
1124
/**
1125
 * @todo Enter description here...
1126
 *
1127
 * @param string $taxon_uuid
1128
 *
1129
 * @return unknown
1130
 */
1131
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1132
  $view_uuid = get_taxonomictree_uuid_selected();
1133
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1134

    
1135
  $response = NULL;
1136
  if ($rank_uuid) {
1137
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1138
      $view_uuid,
1139
      $taxon_uuid,
1140
      $rank_uuid,
1141
    ));
1142
  }
1143
  else {
1144
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1145
      $view_uuid,
1146
      $taxon_uuid,
1147
    ));
1148
  }
1149

    
1150
  if ($response == NULL) {
1151
    // Error handing.
1152
    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1153
      // Delete the session value and try again with the default.
1154
      unset($_SESSION['cdm']['taxonomictree_uuid']);
1155
      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1156
    }
1157
    else {
1158
      // Check if taxonomictree_uuid is valid.
1159
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, NULL, TRUE);
1160
      if ($test == NULL) {
1161
        // The default set by the admin seems to be invalid or is not even set.
1162
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1163
      }
1164
    }
1165
  }
1166

    
1167
  return $response;
1168
}
1169

    
1170
/**
1171
 * @todo Please document this function.
1172
 * @see http://drupal.org/node/1354
1173
 */
1174
function cdm_rankVocabulary_as_option() {
1175
  $options = cdm_Vocabulary_as_option(UUID_RANK);
1176
  array_unshift ($options, "");
1177
  return $options;
1178
}
1179

    
1180
/**
1181
 *
1182
 * @param Object $definedTermBase
1183
 * 	  of cdm type DefinedTermBase
1184
 * @return string
1185
 * 	  the localized representation_L10n of the term,
1186
 *    otherwise the titleCache as fall back,
1187
 *    otherwise an empty string
1188
 */
1189
function cdm_term_representation($definedTermBase) {
1190
  if ( isset($definedTermBase->representation_L10n) ) {
1191
    return $definedTermBase->representation_L10n;
1192
  } elseif ( isset($definedTermBase->titleCache)) {
1193
    return $definedTermBase->titleCache;
1194
  }
1195
  return '';
1196
}
1197

    
1198
/**
1199
 * @todo Improve documentation of this function.
1200
 *
1201
 * eu.etaxonomy.cdm.model.description.
1202
 * CategoricalData
1203
 * CommonTaxonName
1204
 * Distribution
1205
 * IndividualsAssociation
1206
 * QuantitativeData
1207
 * TaxonInteraction
1208
 * TextData
1209
 */
1210
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1211
  static $types = array(
1212
    "CategoricalData",
1213
    "CommonTaxonName",
1214
    "Distribution",
1215
    "IndividualsAssociation",
1216
    "QuantitativeData",
1217
    "TaxonInteraction",
1218
    "TextData",
1219
  );
1220

    
1221
  static $options = NULL;
1222
  if ($options == NULL) {
1223
    $options = array();
1224
    if ($prependEmptyElement) {
1225
      $options[' '] = '';
1226
    }
1227
    foreach ($types as $type) {
1228
      // No internatianalization here since these are purely technical terms.
1229
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1230
    }
1231
  }
1232
  return $options;
1233
}
1234

    
1235
/**
1236
 * @todo Please document this function.
1237
 * @see http://drupal.org/node/1354
1238
 */
1239
function cdm_Vocabulary_as_option($vocabularyUuid, $term_label_callback = NULL) {
1240
  static $vocabularyOptions = array();
1241

    
1242
  if (!isset($vocabularyOptions[$vocabularyUuid])) {
1243
    $vocab = cdm_ws_get(CDM_WS_TERMVOCABULARY, $vocabularyUuid);
1244
    $vocabularyOptions[$vocabularyUuid] = array();
1245

    
1246
    if ($vocab) {
1247
      foreach ($vocab->terms as $term) {
1248
        if ($term_label_callback && function_exists($term_label_callback)) {
1249
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = call_user_func($term_label_callback, $term);
1250
        }
1251
        else {
1252
          $vocabularyOptions[$vocabularyUuid][$term->uuid] = t($term->representation_L10n);
1253
        }
1254
      }
1255
      array_reverse($vocabularyOptions[$vocabularyUuid]);
1256
    }
1257
  }
1258
  return $vocabularyOptions[$vocabularyUuid];
1259
}
1260

    
1261
/**
1262
 * @todo Please document this function.
1263
 * @see http://drupal.org/node/1354
1264
 */
1265
function _cdm_relationship_type_term_label_callback($term) {
1266
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1267
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1268
  }
1269
  else {
1270
    return t($term->representation_L10n);
1271
  }
1272
}
1273

    
1274
/**
1275
 * @todo Please document this function.
1276
 * @see http://drupal.org/node/1354
1277
 */
1278
function cdm_ws_descriptions_by_featuretree($featureTree, $descriptions, $isDescriptionsSeparated = FALSE) {
1279
  if (!$featureTree) {
1280
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1281
      In order to see the species profiles of your taxa, please select a
1282
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1283
    return FALSE;
1284
  }
1285

    
1286
  $mergedTrees = array();
1287

    
1288
  if ($isDescriptionsSeparated) {
1289
    // Merge any description into a separate feature tree.
1290
    foreach ($descriptions as $desc) {
1291
      $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $desc->elements);
1292

    
1293
      $mergedTree = clone $featureTree;
1294
      $mergedTree->root->children = $mergedNodes;
1295
      $mergedTrees[] = $mergedTree;
1296
    }
1297
  }
1298
  else {
1299
    // Combine all descripions into one feature tree.
1300
    $descriptionElemens = array();
1301
    foreach ($descriptions as $desc) {
1302
      $descriptionElemens = array_merge($descriptionElemens, $desc->elements);
1303
    }
1304
    $mergedNodes = _mergeFeatureTreeDescriptions($featureTree->root->children, $descriptionElemens);
1305
    $featureTree->root->children = $mergedNodes;
1306
    $mergedTrees[] = $featureTree;
1307
  }
1308

    
1309
  return $mergedTrees;
1310
}
1311

    
1312
/**
1313
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1314
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1315
 * be requested for the annotations.
1316
 *
1317
 * @param string $cdmBase
1318
 *   An annotatable cdm entity.
1319
 * @param array $includeTypes
1320
 *   If an array of annotation type uuids is supplied by this parameter the
1321
 *   list of annotations is resticted to those which belong to this type.
1322
 *
1323
 * @return array
1324
 *   An array of Annotation objects or an empty array.
1325
 */
1326
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1327

    
1328
  if(!isset($cdmBase->annotations)){
1329
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1330
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, TRUE);
1331
  }
1332

    
1333
  $annotations = array();
1334
  foreach ($cdmBase->annotations as $annotation) {
1335
    if ($includeTypes) {
1336
      if ((isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE)) || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))) {
1337
        $annotations[] = $annotation;
1338
      }
1339
    }
1340
    else {
1341
      $annotations[] = $annotation;
1342
    }
1343
  }
1344
  return $annotations;
1345

    
1346
}
1347

    
1348
/**
1349
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1350
 *
1351
 * @param object $annotatable_entity
1352
 *   The CDM AnnotatableEntity to load annotations for
1353
 */
1354
function cdm_load_annotations(&$annotatable_entity) {
1355
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1356
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1357
    if (is_array($annotations)) {
1358
      $annotatable_entity->annotations = $annotations;
1359
    }
1360
  }
1361
}
1362

    
1363
/**
1364
 * Get a NomenclaturalReference string.
1365
 *
1366
 * Returns the NomenclaturalReference string with correctly placed
1367
 * microreference (= reference detail) e.g.
1368
 * in Phytotaxa 43: 1-48. 2012.
1369
 *
1370
 * @param string $referenceUuid
1371
 *   UUID of the reference.
1372
 * @param string $microreference
1373
 *   Reference detail.
1374
 *
1375
 * @return string
1376
 *   a NomenclaturalReference.
1377
 */
1378
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1379
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1380
    $referenceUuid,
1381
  ), "microReference=" . urlencode($microreference));
1382

    
1383
  if ($obj) {
1384
    return $obj->String;
1385
  }
1386
  else {
1387
    return NULL;
1388
  }
1389
}
1390

    
1391
/**
1392
 * Merges the given featureNodes structure with the descriptionElements.
1393
 *
1394
 * This method is used in preparation for rendering the descriptionElements.
1395
 * The descriptionElements wich belong to a specific feature node are appended
1396
 * to a the feature node by creating a new fields:
1397
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1398
 * The descriptionElements will be cleared in advance in order to allow reusing the
1399
 * same feature tree without the risk of mixing sets of descrition elemens.
1400
 *
1401
 * which originally is not existing in the cdm.
1402
 *
1403
 *
1404
 *
1405
 * @param array $featureNodes
1406
 *    An array of cdm FeatureNodes which may be hierachical since feature nodes
1407
 *    may have children.
1408
 * @param array $descriptionElements
1409
 *    An flat array of cdm DescriptionElements
1410
 * @return array
1411
 *    The $featureNodes structure enriched with the accoding $descriptionElements
1412
 */
1413
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1414

    
1415
  foreach ($featureNodes as &$node) {
1416
    // since the $featureNodes array is reused for each description
1417
    // it is nessecary to clear the custom node fields in advance
1418
    if(isset($node->descriptionElements)){
1419
      unset($node->descriptionElements);
1420
    }
1421

    
1422
    // Append corresponding elements to an additional node field:
1423
    // $node->descriptionElements.
1424
    foreach ($descriptionElements as $element) {
1425
      if ($element->feature->uuid == $node->feature->uuid) {
1426
        if (!isset($node->descriptionElements)) {
1427
          $node->descriptionElements = array();
1428
        }
1429
        $node->descriptionElements[] = $element;
1430
      }
1431
    }
1432

    
1433
    // Recurse into node children.
1434
    if (isset($node->children[0])) {
1435
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->children, $descriptionElements);
1436
      $node->children = $mergedChildNodes;
1437
    }
1438

    
1439
    if(!isset($node->descriptionElements) && !isset($node->children[0])){
1440
      unset($node);
1441
    }
1442

    
1443
  }
1444

    
1445
  return $featureNodes;
1446
}
1447

    
1448
/**
1449
 * Sends a GET request to a CDM RESTService and returns a deserialized object.
1450
 *
1451
 * The response from the HTTP GET request is returned as object.
1452
 * The response objects coming from the webservice configured in the
1453
 * 'cdm_webservice_url' variable are beeing cached in a level 1 (L1) and / or
1454
 *  in a level 2 (L2) cache.
1455
 *
1456
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1457
 * function, this cache persists only per each single page execution.
1458
 * Any object coming from the webservice is stored into it by default.
1459
 * In contrast to this default caching mechanism the L2 cache only is used if
1460
 * the 'cdm_webservice_cache' variable is set to TRUE,
1461
 * which can be set using the modules administrative settings section.
1462
 * Objects stored in this L2 cache are serialized and stored
1463
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1464
 * objects that are stored in the database will persist as
1465
 * long as the drupal cache is not beeing cleared and are available across
1466
 * multiple script executions.
1467
 *
1468
 * @param string $uri
1469
 *   URL to the webservice.
1470
 * @param array $pathParameters
1471
 *   An array of path parameters.
1472
 * @param string $query
1473
 *   A query string to be appended to the URL.
1474
 * @param string $method
1475
 *   The HTTP method to use, valid values are "GET" or "POST";
1476
 * @param bool $absoluteURI
1477
 *   TRUE when the URL should be treated as absolute URL.
1478
 *
1479
 * @return object
1480
 *   The deserialized webservice response object.
1481
 */
1482
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1483

    
1484
  static $cacheL1 = array();
1485

    
1486
  // Transform the given uri path or pattern into a proper webservice uri.
1487
  if (!$absoluteURI) {
1488
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1489
  }
1490

    
1491
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1492
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1493

    
1494
  if (array_key_exists($uri, $cacheL1)) {
1495
    $cacheL1_obj = $cacheL1[$uri];
1496
  }
1497

    
1498
  $set_cacheL1 = FALSE;
1499
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1500
    $set_cacheL1 = TRUE;
1501
  }
1502

    
1503
  // Only cache cdm webservice URIs.
1504
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1505
  $cacheL2_entry = FALSE;
1506

    
1507
  if ($use_cacheL2) {
1508
    // Try to get object from cacheL2.
1509
    $cacheL2_entry = cache_get($uri, 'cache_cdm_ws');
1510
  }
1511

    
1512
  if (isset($cacheL1_obj)) {
1513
    //
1514
    // The object has been found in the L1 cache.
1515
    //
1516
    $obj = $cacheL1_obj;
1517
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1518
      cdm_ws_debug_add($uri, 0, 0, NULL, 'cacheL1');
1519
    }
1520
  }
1521
  elseif ($cacheL2_entry) {
1522
    //
1523
    // The object has been found in the L2 cache.
1524
    //
1525
    $duration_parse_start = microtime(TRUE);
1526
    $obj = unserialize($cacheL2_entry->data);
1527
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1528

    
1529
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1530
      cdm_ws_debug_add($uri, 0, $duration_parse, NULL, 'cacheL2');
1531
    }
1532
  }
1533
  else {
1534
    //
1535
    // Get the object from the webservice and cache it.
1536
    //
1537
    $duration_fetch_start = microtime(TRUE);
1538
    // Request data from webservice JSON or XML.
1539
    $response = cdm_http_request($uri, $method);
1540
    $datastr = NULL;
1541
    if (isset($response->data)) {
1542
      $datastr = $response->data;
1543
    }
1544
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1545
    $duration_parse_start = microtime(TRUE);
1546

    
1547
    // Parse data and create object.
1548
    $obj = cdm_load_obj($datastr);
1549

    
1550
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1551
    if (variable_get('cdm_webservice_debug', 1) && user_access('administer')) {
1552
      if ($obj || $datastr == "[]") {
1553
        $status = 'valid';
1554
      }
1555
      else {
1556
        $status = 'invalid';
1557
      }
1558
      cdm_ws_debug_add($uri, $duration_fetch, $duration_parse, strlen($datastr), $status);
1559
    }
1560
    if ($set_cacheL2) {
1561
      // Store the object in cache L2.
1562
      // Comment @WA perhaps better if Drupal serializes here? Then the
1563
      // flag serialized is set properly in the cache table.
1564
      cache_set($uri, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1565
    }
1566
  }
1567
  if ($obj) {
1568
    // Store the object in cache L1.
1569
    if ($set_cacheL1) {
1570
      $cacheL1[$uri] = $obj;
1571
    }
1572
  }
1573
  return $obj;
1574
}
1575

    
1576
/**
1577
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1578
 *
1579
 * The cdm_ws_debug block will display the debug information.
1580
 *
1581
 * @param $uri
1582
 *    The CDM REST URI to which the request has been send
1583
 * @param $duration_fetch
1584
 *    The time in seconds it took to fetch the data from the web service
1585
 * @param $duration_parse
1586
 *    Time in seconds which was needed to parse the json response
1587
 * @param $datasize
1588
 *    Size of the data received from the server
1589
 * @param $status
1590
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1591
 * @return bool
1592
 *    TRUE if adding the debug information was successful
1593
 */
1594
function cdm_ws_debug_add($uri, $duration_fetch, $duration_parse, $datasize, $status) {
1595

    
1596
  static $initial_time = NULL;
1597
  if(!$initial_time) {
1598
    $initial_time = microtime(TRUE);
1599
  }
1600
  $time = microtime(TRUE) - $initial_time;
1601

    
1602
  // Decompose uri into path and query element.
1603
  // URI query elements are stored in an array
1604
  // suitable for drupal_http_build_query()
1605
  $uri_parts = explode("?", $uri);
1606
  $query = array();
1607
  if (count($uri_parts) == 2) {
1608
    $path = $uri_parts[0];
1609
    $queryparts = explode("&", $uri_parts[1]);
1610
    foreach ($queryparts as $querypart) {
1611
      $querypart = explode("=", $querypart);
1612
      if(count($querypart) == 2){
1613
        $query[$querypart[0]] = $querypart[1];
1614
      } else {
1615
        $query[$querypart[0]] = null;
1616
      }
1617
    }
1618
  }
1619
  else {
1620
    $path = $uri;
1621
  }
1622

    
1623
  // data links to make data accecsible as json and xml
1624
  $data_links = '';
1625
  if (_is_cdm_ws_uri($path)) {
1626
    $data_links .= '<a href="'
1627
        . url($path . '.xml', array('query' => $query, 'absolute' => TRUE))
1628
        . '" target="data">xml</a>-';
1629
    $data_links .= '<a href="'
1630
        . url('cdm_api/proxy/' . urlencode(url($path . '.xml', array('query' => $query))))
1631
        . '" target="data">proxied</a>';
1632
    $data_links .= '<br/>';
1633
    $data_links .= '<a href="'
1634
        . url($path . '.json', array('query' => $query, 'absolute' => TRUE))
1635
        . '" target="data">json</a>-';
1636
    $data_links .= '<a href="'
1637
        . url('cdm_api/proxy/' . urlencode(url($path . '.json', array('query' => $query))))
1638
        . '" target="data">proxied</a>';
1639
  }
1640
  else {
1641
    $data_links .= '<a href="' . url($path, array(
1642
        'query' => $query)) . '" target="data">open</a>';
1643
  }
1644

    
1645
  //
1646
  $data = array(
1647
      'ws_uri' => $uri,
1648
      'time' => sprintf('%3.3f', $time),
1649
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1650
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
1651
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
1652
      'status' => $status,
1653
      'data_links' => $data_links
1654
  );
1655
  if (!isset($_SESSION['cdm']['ws_debug'])) {
1656
    $_SESSION['cdm']['ws_debug'] = array();
1657
  }
1658
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
1659

    
1660
  // Mark this page as being uncacheable.
1661
  // taken over from drupal_get_messages() but it is unsure if we really need this here
1662
  drupal_page_is_cacheable(FALSE);
1663

    
1664
  // Messages not set when DB connection fails.
1665
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
1666
}
1667

    
1668
/**
1669
 * @todo Please document this function.
1670
 * @see http://drupal.org/node/1354
1671
 */
1672
function cdm_load_obj($datastr) {
1673
  $obj = json_decode($datastr);
1674

    
1675
  if (!(is_object($obj) || is_array($obj))) {
1676
    ob_start();
1677
    $obj_dump = ob_get_contents();
1678
    ob_clean();
1679
    return FALSE;
1680
  }
1681

    
1682
  return $obj;
1683
}
1684

    
1685
/**
1686
 * Do a http request to a CDM RESTful web service.
1687
 *
1688
 * @param string $uri
1689
 *   The webservice url.
1690
 * @param string $method
1691
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
1692
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
1693
 * @param array $parameters
1694
 *   Parameters to use in the request.
1695
 * @param array $header
1696
 *   The header to include in the request.
1697
 *
1698
 * @return object
1699
 *   The object as returned by drupal_http_request():
1700
 *   An object that can have one or more of the following components:
1701
 *   - request: A string containing the request body that was sent.
1702
 *   - code: An integer containing the response status code, or the error code
1703
 *     if an error occurred.
1704
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
1705
 *   - status_message: The status message from the response, if a response was
1706
 *     received.
1707
 *   - redirect_code: If redirected, an integer containing the initial response
1708
 *     status code.
1709
 *   - redirect_url: If redirected, a string containing the URL of the redirect
1710
 *     target.
1711
 *   - error: If an error occurred, the error message. Otherwise not set.
1712
 *   - headers: An array containing the response headers as name/value pairs.
1713
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
1714
 *     easy access the array keys are returned in lower case.
1715
 *   - data: A string containing the response body that was received.
1716
 */
1717
function cdm_http_request($uri, $method = "GET", $parameters = array(), $header = array(), $options = NULL) {
1718
  static $acceptLanguage = NULL;
1719

    
1720
  if (!$acceptLanguage) {
1721
    if (function_exists('apache_request_headers')) {
1722
      $headers = apache_request_headers();
1723
      if (isset($headers['Accept-Language'])) {
1724
        $acceptLanguage = $headers['Accept-Language'];
1725
      }
1726
    }
1727
    if (!$acceptLanguage) {
1728
      // DEFAULT TODO make configurable.
1729
      $acceptLanguage = "en";
1730
    }
1731
  }
1732

    
1733
  if ($method != "GET" && $method != "POST") {
1734
    $method = "GET";
1735
  }
1736

    
1737
  if (empty($header) && _is_cdm_ws_uri($uri)) {
1738
    $header['Accept'] = 'application/json';
1739
    $header['Accept-Language'] = $acceptLanguage;
1740
    $header['Accept-Charset'] = 'UTF-8';
1741
  }
1742

    
1743
  return drupal_http_request($uri, array(
1744
      'headers' => $header,
1745
      'method' => $method,
1746
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
1747
      )
1748
   );
1749
}
1750

    
1751
/**
1752
 * @todo Please document this function.
1753
 * @see http://drupal.org/node/1354
1754
 */
1755
function _featureTree_elements_toString($rootNode, $separator = ', ') {
1756
  $out = '';
1757

    
1758
  foreach ($rootNode->children as $featureNode) {
1759
    $out .= ($out ? $separator : '');
1760
    $out .= $featureNode->feature->representation_L10n;
1761
    if (is_array($featureNode->children)) {
1762
      $childlabels = '';
1763
      foreach ($featureNode->children as $childNode) {
1764
        $childlabels .= ($childlabels ? $separator : '');
1765
      }
1766
      $childlabels .= _featureTree_elements_toString($childNode);
1767
    }
1768
    if ($childlabels) {
1769
      $out .= '[' . $childlabels . ' ]';
1770
    }
1771
  }
1772
  return $out;
1773
}
1774

    
1775
/**
1776
 * Create a one-dimensional form options array.
1777
 *
1778
 * Creates an array of all features in the feature tree of feature nodes,
1779
 * the node labels are indented by $node_char and $childIndent depending on the
1780
 * hierachy level.
1781
 *
1782
 * @param - $rootNode
1783
 * @param - $node_char
1784
 * @param - $childIndentStr
1785
 * @param - $childIndent
1786
 *   ONLY USED INTERNALLY!
1787
 *
1788
 * @return array
1789
 *   A one dimensional Drupal form options array.
1790
 */
1791
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
1792
  $options = array();
1793
  foreach ($rootNode->children as $featureNode) {
1794
    $indent_prefix = '';
1795
    if ($childIndent) {
1796
      $indent_prefix = $childIndent . $node_char . " ";
1797
    }
1798
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
1799
    if (isset($featureNode->children) && is_array($featureNode->children)) {
1800
      // Foreach ($featureNode->children as $childNode){
1801
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
1802
      $options = array_merge_recursive($options, $childList);
1803
      // }
1804
    }
1805
  }
1806
  return $options;
1807
}
1808

    
1809
/**
1810
 * Returns an array with all available FeatureTrees and the representations of the selected
1811
 * FeatureTree as a detail view.
1812
 *
1813
 * @param boolean $add_default_feature_free
1814
 * @return array
1815
 *  associative array with following keys:
1816
 *  -options: Returns an array with all available Feature Trees
1817
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
1818
 *
1819
 */
1820
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
1821

    
1822
  $options = array();
1823
  $tree_representations = array();
1824
  $feature_trees = array();
1825

    
1826
  // Set tree that contains all features.
1827
  if ($add_default_feature_free) {
1828
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
1829
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
1830
  }
1831

    
1832
  // Get feature trees from database.
1833
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
1834
  if (is_array($persited_trees)) {
1835
    $feature_trees = array_merge($feature_trees, $persited_trees);
1836
  }
1837

    
1838
  foreach ($feature_trees as $featureTree) {
1839

    
1840
    // Do not add the DEFAULT_FEATURETREE again,
1841
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
1842
      $options[$featureTree->uuid] = $featureTree->titleCache;
1843
    }
1844

    
1845
    // Render the hierarchic tree structure
1846
    if (is_array( $featureTree->root->children) && count( $featureTree->root->children) > 0) {
1847

    
1848
      // Render the hierarchic tree structure.
1849
      $treeDetails = '<div class="featuretree_structure">'
1850
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
1851
        . '</div>';
1852

    
1853
      $form = array();
1854
      $form['featureTree-' .  $featureTree->uuid] = array(
1855
        '#type' => 'fieldset',
1856
        '#title' => 'Show details',
1857
        '#attributes' => array('class' => array('collapsible collapsed')),
1858
        // '#collapsible' => TRUE,
1859
        // '#collapsed' => TRUE,
1860
      );
1861
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
1862
        '#markup' => $treeDetails,
1863
      );
1864

    
1865
      $tree_representations[$featureTree->uuid] = drupal_render($form);
1866
    }
1867

    
1868
  } // END loop over feature trees
1869

    
1870
  // return $options;
1871
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
1872
}
1873

    
1874
/**
1875
 * Provides the list of availbale classifications in form of an options array.
1876
 *
1877
 * The options array is suitable for drupal form API elements that allow multiple choices.
1878
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1879
 *
1880
 * The classifications are ordered alphabetically whereas the classification
1881
 * chosen as default will always appear on top of the array, followed by a
1882
 * blank line below.
1883
 *
1884
 * @param bool $add_none_option
1885
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
1886
 *
1887
 * @return array
1888
 *   classifications in an array as options for a form element that allows multiple choices.
1889
 */
1890
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
1891

    
1892
  $taxonTrees = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY);
1893

    
1894
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
1895
  $default_classification_label = '';
1896

    
1897
  // add all classifications
1898
  $taxonomic_tree_options = array();
1899
  if ($add_none_option) {
1900
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
1901
  }
1902
  if ($taxonTrees) {
1903
    foreach ($taxonTrees as $tree) {
1904
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
1905
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
1906
      } else {
1907
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
1908
        if (count($taxonTrees) > 1) {
1909
          $taxonomic_tree_options[''] = '   '; // three Space characters for an empy line below
1910
        }
1911
        $default_classification_label = $tree->titleCache;
1912
      }
1913
    }
1914
  }
1915
  // oder alphabetically the space
1916
  asort($taxonomic_tree_options);
1917

    
1918
  // now set the labels
1919
  //   for none
1920
  if ($add_none_option) {
1921
    $taxonomic_tree_options['NONE'] = t('-- None --');
1922
  }
1923

    
1924
  //   for default_classification
1925
  if (is_uuid($default_classification_uuid)) {
1926
    $taxonomic_tree_options[$default_classification_uuid] =
1927
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
1928
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
1929
  }
1930

    
1931
  return $taxonomic_tree_options;
1932
}
1933

    
1934
/**
1935
 * @todo Please document this function.
1936
 * @see http://drupal.org/node/1354
1937
 */
1938
function cdm_api_secref_cache_prefetch(&$secUuids) {
1939
  // Comment @WA: global variables should start with a single underscore
1940
  // followed by the module and another underscore.
1941
  global $_cdm_api_secref_cache;
1942
  if (!is_array($_cdm_api_secref_cache)) {
1943
    $_cdm_api_secref_cache = array();
1944
  }
1945
  $uniqueUuids = array_unique($secUuids);
1946
  $i = 0;
1947
  $param = '';
1948
  while ($i++ < count($uniqueUuids)) {
1949
    $param .= $secUuids[$i] . ',';
1950
    if (strlen($param) + 37 > 2000) {
1951
      _cdm_api_secref_cache_add($param);
1952
      $param = '';
1953
    }
1954
  }
1955
  if ($param) {
1956
    _cdm_api_secref_cache_add($param);
1957
  }
1958
}
1959

    
1960
/**
1961
 * @todo Please document this function.
1962
 * @see http://drupal.org/node/1354
1963
 */
1964
function cdm_api_secref_cache_get($secUuid) {
1965
  global $_cdm_api_secref_cache;
1966
  if (!is_array($_cdm_api_secref_cache)) {
1967
    $_cdm_api_secref_cache = array();
1968
  }
1969
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
1970
    _cdm_api_secref_cache_add($secUuid);
1971
  }
1972
  return $_cdm_api_secref_cache[$secUuid];
1973
}
1974

    
1975
/**
1976
 * @todo Please document this function.
1977
 * @see http://drupal.org/node/1354
1978
 */
1979
function cdm_api_secref_cache_clear() {
1980
  global $_cdm_api_secref_cache;
1981
  $_cdm_api_secref_cache = array();
1982
}
1983

    
1984
/**
1985
 * Validates if the given string is a uuid.
1986
 *
1987
 * @param string $str
1988
 *   The string to validate.
1989
 *
1990
 * return bool
1991
 *   TRUE if the string is a UUID.
1992
 */
1993
function is_uuid($str) {
1994
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
1995
}
1996

    
1997
/**
1998
 * Checks if the given $object is a valid cdm entity.
1999
 *
2000
 * An object is considered a cdm entity if it has a string field $object->class
2001
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2002
 *
2003
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2004
 *
2005
 * @param mixed $object
2006
 *   The object to validate
2007
 *
2008
 * @return bool
2009
 *   True if the object is a cdm entity.
2010
 */
2011
function is_cdm_entity($object) {
2012
  return is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2013
}
2014

    
2015
/**
2016
 * @todo Please document this function.
2017
 * @see http://drupal.org/node/1354
2018
 */
2019
function _cdm_api_secref_cache_add($secUuidsStr) {
2020
  global $_cdm_api_secref_cache;
2021
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2022
  // Batch fetching not jet reimplemented thus:
2023
  /*
2024
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2025
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2026
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2027
  */
2028
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2029
}
2030

    
2031
/**
2032
 * Checks if the given uri starts with a cdm webservice url.
2033
 *
2034
 * Checks if the uri starts with the cdm webservice url stored in the
2035
 * Drupal variable 'cdm_webservice_url'.
2036
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2037
 *
2038
 * @param string $uri
2039
 *   The URI to test.
2040
 *
2041
 * @return bool
2042
 *   True if the uri starts with a cdm webservice url.
2043
 */
2044
function _is_cdm_ws_uri($uri) {
2045
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2046
}
2047

    
2048
/**
2049
 * @todo Please document this function.
2050
 * @see http://drupal.org/node/1354
2051
 */
2052
function queryString($elements) {
2053
  $query = '';
2054
  foreach ($elements as $key => $value) {
2055
    if (is_array($value)) {
2056
      foreach ($value as $v) {
2057
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2058
      }
2059
    }
2060
    else {
2061
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2062
    }
2063
  }
2064
  return $query;
2065
}
2066

    
2067
/**
2068
 * Implementation of the magic method __clone to allow deep cloning of objects
2069
 * and arrays.
2070
 */
2071
function __clone() {
2072
  foreach ($this as $name => $value) {
2073
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2074
      $this->$name = clone($this->$name);
2075
    }
2076
  }
2077
}
2078

    
2079
/**
2080
 * Make a 'deep copy' of an array.
2081
 *
2082
 * Make a complete deep copy of an array replacing
2083
 * references with deep copies until a certain depth is reached
2084
 * ($maxdepth) whereupon references are copied as-is...
2085
 *
2086
 * @see http://us3.php.net/manual/en/ref.array.php
2087
 *
2088
 * @param array $array
2089
 * @param array $copy
2090
 * @param int $maxdepth
2091
 * @param int $depth
2092
 *
2093
 * @return void
2094
 */
2095
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2096
  if ($depth > $maxdepth) {
2097
    $copy = $array;
2098
    return;
2099
  }
2100
  if (!is_array($copy)) {
2101
    $copy = array();
2102
  }
2103
  foreach ($array as $k => &$v) {
2104
    if (is_array($v)) {
2105
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2106
    }
2107
    else {
2108
      $copy[$k] = $v;
2109
    }
2110
  }
2111
}
2112

    
2113
/**
2114
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2115
 *
2116
 */
2117
function _add_js_ws_debug() {
2118

    
2119
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js',
2120
    array(
2121
      'type' => 'file',
2122
      'weight' => JS_LIBRARY,
2123
      'cache' => TRUE)
2124
    );
2125

    
2126
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/jquery.colorbox-min.js',
2127
    array(
2128
      'type' => 'file',
2129
      'weight' => JS_LIBRARY,
2130
      'cache' => TRUE)
2131
    );
2132
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2133
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2134

    
2135
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2136
    array(
2137
      'type' => 'file',
2138
      'weight' => JS_LIBRARY,
2139
      'cache' => TRUE)
2140
    );
2141

    
2142
}
2143

    
2144
/**
2145
 * @todo Please document this function.
2146
 * @see http://drupal.org/node/1354
2147
 */
2148
function _no_classfication_uuid_message() {
2149
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2150
    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.');
2151
  }
2152
  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.');
2153
}
2154

    
2155
/**
2156
 * Implementation of hook flush_caches
2157
 *
2158
 * Add custom cache tables to the list of cache tables that
2159
 * will be cleared by the Clear button on the Performance page or whenever
2160
 * drupal_flush_all_caches is invoked.
2161
 *
2162
 * @author W.Addink <waddink@eti.uva.nl>
2163
 *
2164
 * @return array
2165
 *   An array with custom cache tables to include.
2166
 */
2167
function cdm_api_flush_caches() {
2168
  return array('cache_cdm_ws');
2169
}
Add picture from clipboard (Maximum size: 40 MB)