Project

General

Profile

Download (77.7 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', 'ORDER_BY_ID_ASC');
46

    
47
/**
48
 * orderBy webservice query parameter value
49
 */
50
define('CDM_ORDER_BY_ID_DESC', 'ORDER_BY_ID_DESC');
51
/**
52
 * orderBy webservice query parameter value
53
 */
54
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'ORDER_BY_TITLE_CACHE_ASC');
55
/**
56
 * orderBy webservice query parameter value
57
 */
58
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'ORDER_BY_TITLE_CACHE_DESC');
59
/**
60
 * orderBy webservice query parameter value
61
 */
62
define('CDM_NOMENCLATURAL_SORT_ORDER_ASC', 'NOMENCLATURAL_SORT_ORDER_ASC');
63
/**
64
 * orderBy webservice query parameter value
65
 */
66
define('CDM_NOMENCLATURAL_SORT_DESC', 'NOMENCLATURAL_SORT_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 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 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'] =
167
        '<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

    
175
    return $block;
176
  }
177
}
178

    
179
/**
180
 * Implements hook_cron().
181
 *
182
 * Expire outdated cache entries.
183
 */
184
function cdm_api_cron() {
185
  cache_clear_all(NULL, 'cache_cdm_ws');
186
}
187

    
188
/**
189
 * @todo Please document this function.
190
 * @see http://drupal.org/node/1354
191
 */
192
function cdm_api_permission() {
193
  return array(
194
    'administer cdm_api' => array(
195
      'title' => t('administer cdm_api'),
196
      'description' => t("TODO Add a description for 'administer cdm_api'"),
197
    ),
198
  );
199
}
200

    
201
// ===================== Tagged Text functions ================== //
202

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

    
231

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

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

    
272
  if (is_array($taggedTextList)) {
273

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

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

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

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

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

    
303
function split_secref_from_tagged_text(&$tagged_text) {
304

    
305
  $extracted_tt = array();
306
  if (is_array($tagged_text)) {
307
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
308
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
309
        $extracted_tt[0] = $tagged_text[$i];
310
        $extracted_tt[1] = $tagged_text[$i + 1];
311
        unset($tagged_text[$i]);
312
        unset($tagged_text[$i + 1]);
313
        break;
314
      }
315
    }
316
  }
317
  return $extracted_tt;
318
}
319

    
320

    
321
function split_nomstatus_from_tagged_text(&$tagged_text) {
322

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

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

    
356
// ===================== END of Tagged Text functions ================== //
357

    
358
/**
359
 * Returns the currently classification tree in use.
360
 */
361
function get_current_classification_uuid() {
362
  if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
363
    return $_SESSION['cdm']['taxonomictree_uuid'];
364
  }
365
  else {
366
    return variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
367
  }
368
}
369

    
370
/**
371
 * Lists the classifications a taxon belongs to
372
 *
373
 * @param CDM type Taxon $taxon
374
 *   the taxon
375
 *
376
 * @return array
377
 *   aray of CDM instances of Type Classification
378
 */
379
function get_classifications_for_taxon($taxon) {
380

    
381
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
382
}
383

    
384
/**
385
 * Returns the chosen FeatureTree for the taxon profile.
386
 *
387
 * The FeatureTree profile returned is the one that has been set in the
388
 * dataportal settings (layout->taxon:profile).
389
 * When the chosen FeatureTree is not found in the database,
390
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
391
 *
392
 * @return mixed
393
 *   A cdm FeatureTree object.
394
 */
395
function get_profile_feature_tree() {
396
  static $profile_featureTree;
397

    
398
  if($profile_featureTree == NULL) {
399
    $profile_featureTree = cdm_ws_get(
400
      CDM_WS_FEATURETREE,
401
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
402
    );
403
    if (!$profile_featureTree) {
404
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
405
    }
406
  }
407

    
408
  return $profile_featureTree;
409
}
410

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

    
425
  if($occurrence_featureTree == NULL) {
426
    $occurrence_featureTree = cdm_ws_get(
427
      CDM_WS_FEATURETREE,
428
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
429
    );
430
    if (!$occurrence_featureTree) {
431
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
432
    }
433
  }
434
  return $occurrence_featureTree;
435
}
436

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

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

    
466
/**
467
 * @todo Please document this function.
468
 * @see http://drupal.org/node/1354
469
 */
470
function switch_to_taxonomictree_uuid($taxonomictree_uuid) {
471
  $_SESSION['cdm']['taxonomictree_uuid'] = $taxonomictree_uuid;
472
}
473

    
474
/**
475
 * @todo Please document this function.
476
 * @see http://drupal.org/node/1354
477
 */
478
function reset_taxonomictree_uuid($taxonomictree_uuid) {
479
  unset($_SESSION['cdm']['taxonomictree_uuid']);
480
}
481

    
482
/**
483
 * @todo Please document this function.
484
 * @see http://drupal.org/node/1354
485
 */
486
function set_last_taxon_page_tab($taxonPageTab) {
487
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
488
}
489

    
490
/**
491
 * @todo Please document this function.
492
 * @see http://drupal.org/node/1354
493
 */
494
function get_last_taxon_page_tab() {
495
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
496
    return $_SESSION['cdm']['taxon_page_tab'];
497
  }
498
  else {
499
    return FALSE;
500
  }
501
}
502

    
503
/**
504
 * @todo Improve the documentation of this function.
505
 *
506
 * media Array [4]
507
 * representations Array [3]
508
 * mimeType image/jpeg
509
 * representationParts Array [1]
510
 * duration 0
511
 * heigth 0
512
 * size 0
513
 * uri
514
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
515
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
516
 * width 0
517
 * suffix jpg
518
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
519
 * title
520
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
521
 *
522
 * @param object $media
523
 * @param array $mimeTypes
524
 * @param int $width
525
 * @param int $height
526
 *
527
 * @return array
528
 *   An array with preferred media representations or else an empty array.
529
 */
530
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
531
  $prefRepr = array();
532
  if (!isset($media->representations[0])) {
533
    return $prefRepr;
534
  }
535

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

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

    
548
      if ($representation->mimeType == $mimeType) {
549
        // Preferred mimetype found -> erase all remaining mimetypes
550
        // to end loop.
551
        $mimeTypes = array();
552
        $dwa = 0;
553
        $dw = 0;
554
        // Look for part with the best matching size.
555
        foreach ($representation->parts as $part) {
556
          if (isset($part->width) && isset($part->height)) {
557
            $dw = $part->width * $part->height - $height * $width;
558
          }
559
          if ($dw < 0) {
560
            $dw *= -1;
561
          }
562
          $dwa += $dw;
563
        }
564
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
565
        $prefRepr[$dwa . '_'] = $representation;
566
      }
567
    }
568
  }
569
  // Sort the array.
570
  krsort($prefRepr);
571
  return $prefRepr;
572
}
573

    
574
/**
575
 * Infers the mime type of a file using the filename extension.
576
 *
577
 * The filename extension is used to infer the mime type.
578
 *
579
 * @param string $filepath
580
 *   The path to the respective file.
581
 *
582
 * @return string
583
 *   The mimetype for the file or FALSE if the according mime type could
584
 *   not be found.
585
 */
586
function infer_mime_type($filepath) {
587
  static $mimemap = NULL;
588
  if (!$mimemap) {
589
    $mimemap = array(
590
      'jpg' => 'image/jpeg',
591
      'jpeg' => 'image/jpeg',
592
      'png' => 'image/png',
593
      'gif' => 'image/gif',
594
      'giff' => 'image/gif',
595
      'tif' => 'image/tif',
596
      'tiff' => 'image/tif',
597
      'pdf' => 'application/pdf',
598
      'html' => 'text/html',
599
      'htm' => 'text/html',
600
    );
601
  }
602
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
603
  if (isset($mimemap[$extension])) {
604
    return $mimemap[$extension];
605
  }
606
  else {
607
    // FIXME remove this hack just return FALSE;
608
    return 'text/html';
609
  }
610
}
611

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

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

    
657
/**
658
 * Converts an ISO 8601 org.joda.time.Partial to a day.
659
 *
660
 * This function expects an ISO 8601 time representation of a
661
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
662
 * In case the day is unknown (= ???) NULL is returned.
663
 *
664
 * @param string $partial
665
 *   ISO 8601 time representation of a org.joda.time.Partial.
666
 *
667
 * @return string
668
 *   A day.
669
 */
670
function partialToDay($partial) {
671
  if (is_string($partial)) {
672
    $day = substr($partial, 8, 2);
673
    if (preg_match("/[0-9][0-9]/", $day)) {
674
      return $day;
675
    }
676
  }
677
  return;
678
}
679

    
680
/**
681
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
682
 *
683
 * This function expects an ISO 8601 time representations of a
684
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
685
 * four digit year, month and day with dashes:
686
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
687
 *
688
 * The partial may contain question marks eg: "1973-??-??",
689
 * these are turned in to '00' or are stripped depending of the $stripZeros
690
 * parameter.
691
 *
692
 * @param string $partial
693
 *   org.joda.time.Partial.
694
 * @param bool $stripZeros
695
 *   If set to TRUE the zero (00) month and days will be hidden:
696
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
697
 * @param string @format
698
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
699
 *    - "YYYY": Year only
700
 *    - "YYYY-MM-DD": this is the default
701
 *
702
 * @return string
703
 *   YYYY-MM-DD formatted year, month, day.
704
 */
705
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
706

    
707
  $y = NULL; $m = NULL; $d = NULL;
708

    
709
  if(strpos($format, 'YY') !== FALSE){
710
    $y = partialToYear($partial);
711
  }
712
  if(strpos($format, 'MM') !== FALSE){
713
    $m = partialToMonth($partial);
714
  }
715
  if(strpos($format, 'DD') !== FALSE){
716
    $d = partialToDay($partial);
717
  }
718

    
719
  $y = $y ? $y : '00';
720
  $m = $m ? $m : '00';
721
  $d = $d ? $d : '00';
722

    
723
  $date = '';
724

    
725
  if ($y == '00' && $stripZeros) {
726
    return;
727
  }
728
  else {
729
    $date = $y;
730
  }
731

    
732
  if ($m == '00' && $stripZeros) {
733
    return $date;
734
  }
735
  else {
736
    $date .= "-" . $m;
737
  }
738

    
739
  if ($d == '00' && $stripZeros) {
740
    return $date;
741
  }
742
  else {
743
    $date .= "-" . $d;
744
  }
745
  return $date;
746
}
747

    
748
/**
749
 * Converts a time period to a string.
750
 *
751
 * See also partialToDate($partial, $stripZeros).
752
 *
753
 * @param object $period
754
 *   An JodaTime org.joda.time.Period object.
755
 * @param bool $stripZeros
756
 *   If set to True, the zero (00) month and days will be hidden:
757
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
758
 * @param string @format
759
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
760
 *    - "YYYY": Year only
761
 *    - "YYYY-MM-DD": this is the default
762
 *
763
 * @return string
764
 *   Returns a date in the form of a string.
765
 */
766
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
767
  $dateString = '';
768
  if ($period->start) {
769
    $dateString = partialToDate($period->start, $stripZeros, $format);
770
  }
771
  if ($period->end) {
772
    $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
773
  }
774
  return $dateString;
775
}
776

    
777
/**
778
 * returns the earliest date available in the $period in a normalized
779
 * form suitable for sorting, e.g.:
780
 *
781
 *  - 1956-00-00
782
 *  - 0000-00-00
783
 *  - 1957-03-00
784
 *
785
 * that is either the start date is returned if set otherwise the
786
 * end date
787
 *
788
 * @param  $period
789
 *    An JodaTime org.joda.time.Period object.
790
 * @return string normalized form of the date
791
 *   suitable for sorting
792
 */
793
function timePeriodAsOrderKey($period) {
794
  $dateString = '';
795
  if ($period->start) {
796
    $dateString = partialToDate($period->start, false);
797
  }
798
  if ($period->end) {
799
    $dateString .= partialToDate($period->end, false);
800
  }
801
  return $dateString;
802
}
803

    
804
/**
805
 * Composes a absolute CDM web service URI with parameters and querystring.
806
 *
807
 * @param string $uri_pattern
808
 *   String with place holders ($0, $1, ..) that should be replaced by the
809
 *   according element of the $pathParameters array.
810
 * @param array $pathParameters
811
 *   An array of path elements, or a single element.
812
 * @param string $query
813
 *   A query string to append to the URL.
814
 *
815
 * @return string
816
 *   A complete URL with parameters to a CDM webservice.
817
 */
818
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
819
  if (empty($pathParameters)) {
820
    $pathParameters = array();
821
  }
822

    
823
  // (1)
824
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
825
  // according element of the $pathParameters array.
826
  static $helperArray = array();
827
  if (isset($pathParameters) && !is_array($pathParameters)) {
828
    $helperArray[0] = $pathParameters;
829
    $pathParameters = $helperArray;
830
  }
831

    
832
  $i = 0;
833
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
834
    if (count($pathParameters) <= $i) {
835
        drupal_set_message(t('cdm_compose_url(): missing pathParameter ' . $i .  ' for ' . $uri_pattern), 'error');
836
      break;
837
    }
838
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
839
    ++$i;
840
  }
841

    
842
  // (2)
843
  // Append all remaining element of the $pathParameters array as path
844
  // elements.
845
  if (count($pathParameters) > $i) {
846
    // Strip trailing slashes.
847
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
848
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
849
    }
850
    while (count($pathParameters) > $i) {
851
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
852
      ++$i;
853
    }
854
  }
855

    
856
  // (3)
857
  // Append the query string supplied by $query.
858
  if (isset($query)) {
859
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
860
  }
861

    
862
  $path = $uri_pattern;
863

    
864
  $uri = variable_get('cdm_webservice_url', '') . $path;
865
  return $uri;
866
}
867

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

    
887
  $args = func_get_args();
888
  $do_gzip = function_exists('gzencode');
889
  $uriEncoded = array_shift($args);
890
  $uri = urldecode($uriEncoded);
891
  $hook = array_shift($args);
892
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
893

    
894
  $post_data = null;
895

    
896
  if ($request_method == "POST" || $request_method == "PUT") {
897
    // read response body via inputstream module
898
    $post_data = file_get_contents("php://input");
899
  }
900

    
901
  // Find and deserialize arrays.
902
  foreach ($args as &$arg) {
903
    // FIXME use regex to find serialized arrays.
904
    //       or should we accept json instead of php serializations?
905
    if (strpos($arg, "a:") === 0) {
906
      $arg = unserialize($arg);
907
    }
908
  }
909

    
910
  // In all these cases perform a simple get request.
911
  // TODO reconsider caching logic in this function.
912

    
913
  if (empty($hook)) {
914
    // simply return the webservice response
915
    // Print out JSON, the cache cannot be used since it contains objects.
916
    $http_response = cdm_http_request($uri, $request_method, $post_data);
917
    if (isset($http_response->headers)) {
918
      foreach ($http_response->headers as $hname => $hvalue) {
919
        drupal_add_http_header($hname, $hvalue);
920
      }
921
    }
922
    if (isset($http_response->data)) {
923
      print $http_response->data;
924
      flush();
925
    }
926
    exit(); // leave drupal here
927
  } else {
928
    // $hook has been supplied
929
    // handle $hook either as compose ot theme hook
930
    // pass through theme or comose hook
931

    
932
    // do a security check since the $uri will be passed
933
    // as absolute URI to cdm_ws_get()
934
    if( !_is_cdm_ws_uri($uri)) {
935
      drupal_set_message(
936
      'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
937
      'error'
938
          );
939
          return '';
940
    }
941

    
942
    $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
943

    
944
    $reponse_data = NULL;
945

    
946
    if (function_exists('compose_' . $hook)){
947
      // call compose hook
948

    
949
      $elements =  call_user_func('compose_' . $hook, $obj);
950
      // pass the render array to drupal_render()
951
      $reponse_data = drupal_render($elements);
952
    } else {
953
      // call theme hook
954

    
955
      // TODO use theme registry to get the registered hook info and
956
      //    use these defaults
957
      switch($hook) {
958
        case 'cdm_taxontree':
959
          $variables = array(
960
            'tree' => $obj,
961
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
962
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
963
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
964
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
965
            );
966
          $reponse_data = theme($hook, $variables);
967
          break;
968

    
969
        case 'cdm_list_of_taxa':
970
            $variables = array(
971
              'records' => $obj,
972
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
973
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
974
            $reponse_data = theme($hook, $variables);
975
            break;
976

    
977
        case 'cdm_media_caption':
978
          $variables = array(
979
          'media' => $obj,
980
          // $args[0] is set in taxon_image_gallery_default in
981
          // cdm_dataportal.page.theme.
982
          'elements' => isset($args[0]) ? $args[0] : array(
983
          'title',
984
          'description',
985
          'artist',
986
          'location',
987
          'rights',
988
          ),
989
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
990
          );
991
          $reponse_data = theme($hook, $variables);
992
          break;
993

    
994
        default:
995
          drupal_set_message(t(
996
          'Theme !theme is not yet supported by the function !function.', array(
997
          '!theme' => $hook,
998
          '!function' => __FUNCTION__,
999
          )), 'error');
1000
          break;
1001
      } // END of theme hook switch
1002
    } // END of tread as theme hook
1003

    
1004

    
1005
    if($do_gzip){
1006
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1007
      drupal_add_http_header('Content-Encoding', 'gzip');
1008
    }
1009
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1010
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1011

    
1012
    print $reponse_data;
1013
  } // END of handle $hook either as compose ot theme hook
1014

    
1015
}
1016

    
1017
/**
1018
 * @todo Please document this function.
1019
 * @see http://drupal.org/node/1354
1020
 */
1021
function setvalue_session() {
1022
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1023
    $keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1024
    $keys = explode('][', $keys);
1025
  }
1026
  else {
1027
    return;
1028
  }
1029
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1030

    
1031
  // Prevent from malicous tags.
1032
  $val = strip_tags($val);
1033

    
1034
  $var = &$_SESSION;
1035
  $i = 0;
1036
  foreach ($keys as $key) {
1037
    $hasMoreKeys = ++$i < count($var);
1038
    if ($hasMoreKeys && (!isset($var[$key]) || !is_array($var[$key]))) {
1039
      $var[$key] = array();
1040
    }
1041
    $var = &$var[$key];
1042
  }
1043
  $var = $val;
1044
  if (isset($_REQUEST['destination'])) {
1045
    drupal_goto($_REQUEST['destination']);
1046
  }
1047
}
1048

    
1049
/**
1050
 * @todo Please document this function.
1051
 * @see http://drupal.org/node/1354
1052
 */
1053
function uri_uriByProxy($uri, $theme = FALSE) {
1054
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1055
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1056
}
1057

    
1058
/**
1059
 * Composes the the absolute REST service URI to the annotations pager
1060
 * for the given CDM entity.
1061
 *
1062
 * NOTE: Not all CDM Base types are yet supported.
1063
 *
1064
 * @param $cdmBase
1065
 *   The CDM entity to construct the annotations pager uri for
1066
 */
1067
function cdm_compose_annotations_uri($cdmBase) {
1068
  if (!$cdmBase->uuid) {
1069
    return;
1070
  }
1071

    
1072
  $ws_base_uri = NULL;
1073
  switch ($cdmBase->class) {
1074
    case 'TaxonBase':
1075
    case 'Taxon':
1076
    case 'Synonym':
1077
      $ws_base_uri = CDM_WS_TAXON;
1078
      break;
1079

    
1080
    case 'TaxonNameBase':
1081
    case 'NonViralName':
1082
    case 'BacterialName':
1083
    case 'BotanicalName':
1084
    case 'CultivarPlantName':
1085
    case 'ZoologicalName':
1086
    case 'ViralName':
1087
      $ws_base_uri = CDM_WS_NAME;
1088
      break;
1089

    
1090
    case 'Media':
1091
      $ws_base_uri = CDM_WS_MEDIA;
1092
      break;
1093

    
1094
    case 'Reference':
1095
      $ws_base_uri = CDM_WS_REFERENCE;
1096
      break;
1097

    
1098
    case 'Distribution':
1099
    case 'TextData':
1100
    case 'TaxonInteraction':
1101
    case 'QuantitativeData':
1102
    case 'IndividualsAssociation':
1103
    case 'Distribution':
1104
    case 'CommonTaxonName':
1105
    case 'CategoricalData':
1106
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1107
      break;
1108

    
1109
    case 'PolytomousKey':
1110
    case 'MediaKey':
1111
    case 'MultiAccessKey':
1112
      $ws_base_uri = $cdmBase->class;
1113
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1114
      break;
1115

    
1116
    default:
1117
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1118
      return;
1119
  }
1120
  return cdm_compose_url($ws_base_uri, array(
1121
    $cdmBase->uuid,
1122
    'annotations',
1123
  ));
1124
}
1125

    
1126
/**
1127
 * Enter description here...
1128
 *
1129
 * @param string $resourceURI
1130
 * @param int $pageSize
1131
 *   The maximum number of entities returned per page.
1132
 *   The default page size as configured in the cdm server
1133
 *   will be used if set to NULL
1134
 *   to return all entities in a single page).
1135
 * @param int $pageNumber
1136
 *   The number of the page to be returned, the first page has the
1137
 *   pageNumber = 0
1138
 * @param array $query
1139
 *   A array holding the HTTP request query parameters for the request
1140
 * @param string $method
1141
 *   The HTTP method to use, valid values are "GET" or "POST"
1142
 * @param bool $absoluteURI
1143
 *   TRUE when the URL should be treated as absolute URL.
1144
 *
1145
 * @return the a CDM Pager object
1146
 *
1147
 */
1148
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1149

    
1150
  $query['pageNumber'] = $pageNumber;
1151
  $query['pageSize'] = $pageSize;
1152

    
1153
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1154
}
1155

    
1156
/**
1157
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1158
 *
1159
 * @param string $resourceURI
1160
 * @param array $query
1161
 *   A array holding the HTTP request query parameters for the request
1162
 * @param string $method
1163
 *   The HTTP method to use, valid values are "GET" or "POST";
1164
 * @param bool $absoluteURI
1165
 *   TRUE when the URL should be treated as absolute URL.
1166
 *
1167
 * @return array
1168
 *     A list of CDM entitites
1169
 *
1170
 */
1171
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1172
  $page_index = 0;
1173
  // using a bigger page size to avoid to many multiple requests
1174
  $page_size = 500;
1175
  $entities = array();
1176

    
1177
  while ($page_index !== FALSE){
1178
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1179
    if(isset($pager->records) && is_array($pager->records)) {
1180
      $entities = $pager->records;
1181
      if(!empty($pager->nextIndex)){
1182
        $page_index = $pager->nextIndex;
1183
      } else {
1184
        $page_index = FALSE;
1185
      }
1186
    } else {
1187
      $page_index = FALSE;
1188
    }
1189
  }
1190
  return $entities;
1191
}
1192

    
1193
/*
1194
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1195
  $viewrank = _cdm_taxonomy_compose_viewrank();
1196
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1197
  ? '/' . $path : '') ;
1198
}
1199
*/
1200

    
1201
/**
1202
 * @todo Enter description here...
1203
 *
1204
 * @param string $taxon_uuid
1205
 *  The UUID of a cdm taxon instance
1206
 * @param string $ignore_rank_limit
1207
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1208
 *
1209
 * @return A cdm REST service URL path to a Classification
1210
 */
1211
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1212

    
1213
  $view_uuid = get_current_classification_uuid();
1214
  $rank_uuid = NULL;
1215
  if (!$ignore_rank_limit) {
1216
    $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1217
  }
1218

    
1219
  if (!empty($taxon_uuid)) {
1220
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1221
      $view_uuid,
1222
      $taxon_uuid,
1223
    ));
1224
  }
1225
  else {
1226
    if (!empty($rank_uuid)) {
1227
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1228
        $view_uuid,
1229
        $rank_uuid,
1230
      ));
1231
    }
1232
    else {
1233
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1234
        $view_uuid,
1235
      ));
1236
    }
1237
  }
1238
}
1239

    
1240
/**
1241
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1242
 *
1243
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1244
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1245
 *
1246
 * Operates in two modes depending on whether the parameter
1247
 * $taxon_uuid is set or NULL.
1248
 *
1249
 * A) $taxon_uuid = NULL:
1250
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1251
 *  2. otherwise return the default classification as defined by the admin via the settings
1252
 *
1253
 * b) $taxon_uuid is set:
1254
 *   return the classification to whcih the taxon belongs to.
1255
 *
1256
 * @param UUID $taxon_uuid
1257
 *   The UUID of a cdm taxon instance
1258
 */
1259
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1260

    
1261
    $response = NULL;
1262

    
1263
    // 1st try
1264
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1265

    
1266
    if ($response == NULL) {
1267
      // 2dn try by ignoring the rank limit
1268
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1269
    }
1270

    
1271
    if ($response == NULL) {
1272
      // 3rd try, last fallback:
1273
      //    return the default classification
1274
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1275
        // Delete the session value and try again with the default.
1276
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1277
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1278
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1279
      }
1280
      else {
1281
        // Check if taxonomictree_uuid is valid.
1282
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1283
        if ($test == NULL) {
1284
          // The default set by the admin seems to be invalid or is not even set.
1285
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1286
        }
1287
      }
1288
    }
1289

    
1290
  return $response;
1291
}
1292

    
1293
/**
1294
 * @todo Enter description here...
1295
 *
1296
 * @param string $taxon_uuid
1297
 *
1298
 * @return unknown
1299
 */
1300
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1301
  $view_uuid = get_current_classification_uuid();
1302
  $rank_uuid = variable_get('taxontree_ranklimit', DEFAULT_TAXONTREE_RANKLIMIT);
1303

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

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

    
1336
  return $response;
1337
}
1338

    
1339

    
1340
// =============================Terms and Vocabularies ========================================= //
1341

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

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

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

    
1407
  return $options;
1408
}
1409

    
1410
/**
1411
 * Creates and array of options for drupal select form elements.
1412
 *
1413
 * @param $vocabulary_uuid
1414
 *   The UUID of the CDM Term Vocabulary
1415
 * @param $term_label_callback
1416
 *   An optional call back function which can be used to modify the term label
1417
 * @param $default_option
1418
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1419
 *   In order to put an empty element the begining of the options pass an " " as argument.
1420
 * @param $order_by
1421
 *   One of the order by constants defined in this file
1422
 */
1423
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $default_option = FALSE, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1424
  static $vocabularyOptions = array();
1425

    
1426
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1427
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1428
      array(
1429
        'orderBy' => $order_by
1430
      )
1431
    );
1432
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1433
  }
1434

    
1435
  $options = $vocabularyOptions[$vocabulary_uuid];
1436
  if($default_option !== FALSE){
1437
    array_unshift ($options, "");
1438
  }
1439
  return $options;
1440
}
1441

    
1442
/**
1443
 * @param $term_type one of
1444
 *  - Unknown
1445
 *  - Language
1446
 *  - NamedArea
1447
 *  - Rank
1448
 *  - Feature
1449
 *  - AnnotationType
1450
 *  - MarkerType
1451
 *  - ExtensionType
1452
 *  - DerivationEventType
1453
 *  - PresenceAbsenceTerm
1454
 *  - NomenclaturalStatusType
1455
 *  - NameRelationshipType
1456
 *  - HybridRelationshipType
1457
 *  - SynonymRelationshipType
1458
 *  - TaxonRelationshipType
1459
 *  - NameTypeDesignationStatus
1460
 *  - SpecimenTypeDesignationStatus
1461
 *  - InstitutionType
1462
 *  - NamedAreaType
1463
 *  - NamedAreaLevel
1464
 *  - RightsType
1465
 *  - MeasurementUnit
1466
 *  - StatisticalMeasure
1467
 *  - MaterialOrMethod
1468
 *  - Material
1469
 *  - Method
1470
 *  - Modifier
1471
 *  - Scope
1472
 *  - Stage
1473
 *  - KindOfUnit
1474
 *  - Sex
1475
 *  - ReferenceSystem
1476
 *  - State
1477
 *  - NaturalLanguageTerm
1478
 *  - TextFormat
1479
 *  - DeterminationModifier
1480
 *  - DnaMarker
1481
 *
1482
 * @param  $order_by
1483
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1484
 *  possible values:
1485
 *    - CDM_ORDER_BY_ID_ASC
1486
 *    - CDM_ORDER_BY_ID_DESC
1487
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1488
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1489
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1490
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1491
 */
1492
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL){
1493
  $terms = cdm_ws_fetch_all(
1494
    CDM_WS_TERM,
1495
    array(
1496
      'class' => $term_type,
1497
      'orderBy' => $order_by
1498
    )
1499
  );
1500
  return cdm_terms_as_options($terms, $term_label_callback);
1501
}
1502

    
1503
/**
1504
 * @todo Please document this function.
1505
 * @see http://drupal.org/node/1354
1506
 */
1507
function cdm_rankVocabulary_as_option() {
1508
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, "");
1509
  return $options;
1510
}
1511

    
1512
/**
1513
 * @todo Please document this function.
1514
 * @see http://drupal.org/node/1354
1515
 */
1516
function _cdm_relationship_type_term_label_callback($term) {
1517
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1518
    return $term->representation_L10n_abbreviatedLabel . ' : ' . t($term->representation_L10n);
1519
  }
1520
else {
1521
    return t($term->representation_L10n);
1522
  }
1523
}
1524

    
1525
// ========================================================================================== //
1526
/**
1527
 * @todo Improve documentation of this function.
1528
 *
1529
 * eu.etaxonomy.cdm.model.description.
1530
 * CategoricalData
1531
 * CommonTaxonName
1532
 * Distribution
1533
 * IndividualsAssociation
1534
 * QuantitativeData
1535
 * TaxonInteraction
1536
 * TextData
1537
 */
1538
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1539
  static $types = array(
1540
    "CategoricalData",
1541
    "CommonTaxonName",
1542
    "Distribution",
1543
    "IndividualsAssociation",
1544
    "QuantitativeData",
1545
    "TaxonInteraction",
1546
    "TextData",
1547
  );
1548

    
1549
  static $options = NULL;
1550
  if ($options == NULL) {
1551
    $options = array();
1552
    if ($prependEmptyElement) {
1553
      $options[' '] = '';
1554
    }
1555
    foreach ($types as $type) {
1556
      // No internatianalization here since these are purely technical terms.
1557
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1558
    }
1559
  }
1560
  return $options;
1561
}
1562

    
1563

    
1564
/**
1565
 * Fetches all TaxonDescription descriptions elements which are associated to the
1566
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1567
 * feature tree.
1568
 * @param $feature_tree
1569
 *     The CDM FeatureTree to be used as template
1570
 * @param $taxon_uuid
1571
 *     The UUID of the taxon
1572
 * @param $excludes
1573
 *     UUIDs of features to be excluded
1574
 * @return$feature_tree
1575
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1576
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1577
 *     witch will hold the according $descriptionElements.
1578
 */
1579
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1580

    
1581
  if (!$feature_tree) {
1582
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1583
      In order to see the species profiles of your taxa, please select a
1584
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1585
    return FALSE;
1586
  }
1587

    
1588
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1589
      array(
1590
      'taxon' => $taxon_uuid,
1591
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1592
      ),
1593
      'POST'
1594
  );
1595

    
1596
  // Combine all descriptions into one feature tree.
1597
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1598
  $feature_tree->root->childNodes = $merged_nodes;
1599

    
1600
  return $feature_tree;
1601
}
1602

    
1603
/**
1604
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1605
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1606
 * be requested for the annotations.
1607
 *
1608
 * @param string $cdmBase
1609
 *   An annotatable cdm entity.
1610
 * @param array $includeTypes
1611
 *   If an array of annotation type uuids is supplied by this parameter the
1612
 *   list of annotations is resticted to those which belong to this type.
1613
 *
1614
 * @return array
1615
 *   An array of Annotation objects or an empty array.
1616
 */
1617
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1618

    
1619
  if(!isset($cdmBase->annotations)){
1620
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1621
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1622
  }
1623

    
1624
  $annotations = array();
1625
  foreach ($cdmBase->annotations as $annotation) {
1626
    if ($includeTypes) {
1627
      if (
1628
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1629
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1630
      ) {
1631
        $annotations[] = $annotation;
1632
      }
1633
    }
1634
    else {
1635
      $annotations[] = $annotation;
1636
    }
1637
  }
1638
  return $annotations;
1639

    
1640
}
1641

    
1642
/**
1643
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1644
 *
1645
 * @param object $annotatable_entity
1646
 *   The CDM AnnotatableEntity to load annotations for
1647
 */
1648
function cdm_load_annotations(&$annotatable_entity) {
1649
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1650
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1651
    if (is_array($annotations)) {
1652
      $annotatable_entity->annotations = $annotations;
1653
    }
1654
  }
1655
}
1656

    
1657
/**
1658
 * Get a NomenclaturalReference string.
1659
 *
1660
 * Returns the NomenclaturalReference string with correctly placed
1661
 * microreference (= reference detail) e.g.
1662
 * in Phytotaxa 43: 1-48. 2012.
1663
 *
1664
 * @param string $referenceUuid
1665
 *   UUID of the reference.
1666
 * @param string $microreference
1667
 *   Reference detail.
1668
 *
1669
 * @return string
1670
 *   a NomenclaturalReference.
1671
 */
1672
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1673
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1674
    $referenceUuid,
1675
  ), "microReference=" . urlencode($microreference));
1676

    
1677
  if ($obj) {
1678
    return $obj->String;
1679
  }
1680
  else {
1681
    return NULL;
1682
  }
1683
}
1684

    
1685
/**
1686
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1687
 *
1688
 * @param $feature_tree_nodes
1689
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1690
 * @param $feature_uuid
1691
 *    The UUID of the Feature
1692
 * @return returns the FeatureNode or null
1693
 */
1694
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1695

    
1696
  // 1. scan this level
1697
  foreach ($feature_tree_nodes as $node){
1698
    if($node->feature->uuid == $feature_uuid){
1699
      return $node;
1700
    }
1701
  }
1702

    
1703
  // 2. descend into childen
1704
  foreach ($feature_tree_nodes as $node){
1705
    if(is_array($node->childNodes)){
1706
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1707
      if($node) {
1708
        return $node;
1709
      }
1710
    }
1711
  }
1712
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1713
  return $null_var;
1714
}
1715

    
1716
/**
1717
 * Merges the given featureNodes structure with the descriptionElements.
1718
 *
1719
 * This method is used in preparation for rendering the descriptionElements.
1720
 * The descriptionElements which belong to a specific feature node are appended
1721
 * to a the feature node by creating a new field:
1722
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1723
 * The descriptionElements will be cleared in advance in order to allow reusing the
1724
 * same feature tree without the risk of mixing sets of description elements.
1725
 *
1726
 * which originally is not existing in the cdm.
1727
 *
1728
 *
1729
 *
1730
 * @param array $featureNodes
1731
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1732
 *    may have children.
1733
 * @param array $descriptionElements
1734
 *    An flat array of cdm DescriptionElements
1735
 * @return array
1736
 *    The $featureNodes structure enriched with the according $descriptionElements
1737
 */
1738
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1739

    
1740
  foreach ($featureNodes as &$node) {
1741
    // since the $featureNodes array is reused for each description
1742
    // it is necessary to clear the custom node fields in advance
1743
    if(isset($node->descriptionElements)){
1744
      unset($node->descriptionElements);
1745
    }
1746

    
1747
    // Append corresponding elements to an additional node field:
1748
    // $node->descriptionElements.
1749
    foreach ($descriptionElements as $element) {
1750
      if ($element->feature->uuid == $node->feature->uuid) {
1751
        if (!isset($node->descriptionElements)) {
1752
          $node->descriptionElements = array();
1753
        }
1754
        $node->descriptionElements[] = $element;
1755
      }
1756
    }
1757

    
1758
    // Recurse into node children.
1759
    if (isset($node->childNodes[0])) {
1760
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1761
      $node->childNodes = $mergedChildNodes;
1762
    }
1763

    
1764
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1765
      unset($node);
1766
    }
1767

    
1768
  }
1769

    
1770
  return $featureNodes;
1771
}
1772

    
1773
/**
1774
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1775
 *
1776
 * The response from the HTTP GET request is returned as object.
1777
 * The response objects coming from the webservice configured in the
1778
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1779
 *  in a level 2 (L2) cache.
1780
 *
1781
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1782
 * function, this cache persists only per each single page execution.
1783
 * Any object coming from the webservice is stored into it by default.
1784
 * In contrast to this default caching mechanism the L2 cache only is used if
1785
 * the 'cdm_webservice_cache' variable is set to TRUE,
1786
 * which can be set using the modules administrative settings section.
1787
 * Objects stored in this L2 cache are serialized and stored
1788
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1789
 * objects that are stored in the database will persist as
1790
 * long as the drupal cache is not being cleared and are available across
1791
 * multiple script executions.
1792
 *
1793
 * @param string $uri
1794
 *   URL to the webservice.
1795
 * @param array $pathParameters
1796
 *   An array of path parameters.
1797
 * @param string $query
1798
 *   A query string to be appended to the URL.
1799
 * @param string $method
1800
 *   The HTTP method to use, valid values are "GET" or "POST";
1801
 * @param bool $absoluteURI
1802
 *   TRUE when the URL should be treated as absolute URL.
1803
 *
1804
 * @return object| array
1805
 *   The de-serialized webservice response object.
1806
 */
1807
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1808

    
1809
  static $cacheL1 = array();
1810

    
1811
  $data = NULL;
1812
  // store query string in $data and clear the query, $data will be set as HTTP request body
1813
  if($method == 'POST'){
1814
    $data = $query;
1815
    $query = NULL;
1816
  }
1817

    
1818
  // Transform the given uri path or pattern into a proper webservice uri.
1819
  if (!$absoluteURI) {
1820
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1821
  }
1822

    
1823
  // read request parameter 'cacheL2_refresh'
1824
  // which allows refreshing the level 2 cache
1825
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1826

    
1827
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1828
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1829

    
1830
  if($method == 'GET'){
1831
    $cache_key = $uri;
1832
  } else {
1833
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1834
    // crc32 is faster but creates much shorter hashes
1835
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1836
  }
1837

    
1838
  if (array_key_exists($cache_key, $cacheL1)) {
1839
    $cacheL1_obj = $cacheL1[$uri];
1840
  }
1841

    
1842
  $set_cacheL1 = FALSE;
1843
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1844
    $set_cacheL1 = TRUE;
1845
  }
1846

    
1847
  // Only cache cdm webservice URIs.
1848
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1849
  $cacheL2_entry = FALSE;
1850

    
1851
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1852
    // Try to get object from cacheL2.
1853
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1854
  }
1855

    
1856
  if (isset($cacheL1_obj)) {
1857
    //
1858
    // The object has been found in the L1 cache.
1859
    //
1860
    $obj = $cacheL1_obj;
1861
    if (cdm_debug_block_visible()) {
1862
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1863
    }
1864
  }
1865
  elseif ($cacheL2_entry) {
1866
    //
1867
    // The object has been found in the L2 cache.
1868
    //
1869
    $duration_parse_start = microtime(TRUE);
1870
    $obj = unserialize($cacheL2_entry->data);
1871
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1872

    
1873
    if (cdm_debug_block_visible()) {
1874
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1875
    }
1876
  }
1877
  else {
1878
    //
1879
    // Get the object from the webservice and cache it.
1880
    //
1881
    $duration_fetch_start = microtime(TRUE);
1882
    // Request data from webservice JSON or XML.
1883
    $response = cdm_http_request($uri, $method, $data);
1884
    $response_body = NULL;
1885
    if (isset($response->data)) {
1886
      $response_body = $response->data;
1887
    }
1888
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1889
    $duration_parse_start = microtime(TRUE);
1890

    
1891
    // Parse data and create object.
1892
    $obj = cdm_load_obj($response_body);
1893

    
1894
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1895

    
1896
    if (cdm_debug_block_visible()) {
1897
      if ($obj || $response_body == "[]") {
1898
        $status = 'valid';
1899
      }
1900
      else {
1901
        $status = 'invalid';
1902
      }
1903
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1904
    }
1905
    if ($set_cacheL2) {
1906
      // Store the object in cache L2.
1907
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1908
      // flag serialized is set properly in the cache table.
1909
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1910
    }
1911
  }
1912
  if ($obj) {
1913
    // Store the object in cache L1.
1914
    if ($set_cacheL1) {
1915
      $cacheL1[$cache_key] = $obj;
1916
    }
1917
  }
1918
  return $obj;
1919
}
1920

    
1921
/**
1922
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1923
 *
1924
 * The cdm_ws_debug block will display the debug information.
1925
 *
1926
 * @param $uri
1927
 *    The CDM REST URI to which the request has been send
1928
 * @param string $method
1929
 *    The HTTP request method, either 'GET' or 'POST'
1930
 * @param string $post_data
1931
 *    The datastring send with a post request
1932
 * @param $duration_fetch
1933
 *    The time in seconds it took to fetch the data from the web service
1934
 * @param $duration_parse
1935
 *    Time in seconds which was needed to parse the json response
1936
 * @param $datasize
1937
 *    Size of the data received from the server
1938
 * @param $status
1939
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1940
 * @return bool
1941
 *    TRUE if adding the debug information was successful
1942
 */
1943
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1944

    
1945
  static $initial_time = NULL;
1946
  if(!$initial_time) {
1947
    $initial_time = microtime(TRUE);
1948
  }
1949
  $time = microtime(TRUE) - $initial_time;
1950

    
1951
  // Decompose uri into path and query element.
1952
  $uri_parts = explode("?", $uri);
1953
  $query = array();
1954
  if (count($uri_parts) == 2) {
1955
    $path = $uri_parts[0];
1956
  }
1957
  else {
1958
    $path = $uri;
1959
  }
1960

    
1961
  if(strpos($uri, '?') > 0){
1962
    $json_uri = str_replace('?', '.json?', $uri);
1963
    $xml_uri = str_replace('?', '.xml?', $uri);
1964
  } else {
1965
    $json_uri = $uri . '.json';
1966
    $xml_uri = $json_uri . '.xml';
1967
  }
1968

    
1969
  // data links to make data accecsible as json and xml
1970
  $data_links = '';
1971
  if (_is_cdm_ws_uri($path)) {
1972

    
1973
    // see ./js/http-method-link.js
1974

    
1975
    if($method == 'GET'){
1976
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
1977
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
1978
      $data_links .= '<br/>';
1979
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
1980
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
1981
    } else {
1982
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
1983
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
1984
      $data_links .= '<br/>';
1985
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
1986
    }
1987
  }
1988
  else {
1989
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
1990
  }
1991

    
1992
  //
1993
  $data = array(
1994
      'ws_uri' => $uri,
1995
      'method' => $method,
1996
      'post_data' => $post_data,
1997
      'time' => sprintf('%3.3f', $time),
1998
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
1999
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2000
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2001
      'status' => $status,
2002
      'data_links' => $data_links
2003
  );
2004
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2005
    $_SESSION['cdm']['ws_debug'] = array();
2006
  }
2007
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2008

    
2009
  // Mark this page as being uncacheable.
2010
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2011
  drupal_page_is_cacheable(FALSE);
2012

    
2013
  // Messages not set when DB connection fails.
2014
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2015
}
2016

    
2017
/**
2018
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2019
 * the visibility depends on whether
2020
 *  - the block is enabled
2021
 *  - the visibility restrictions in the block settings are satisfied
2022
 */
2023
function cdm_debug_block_visible() {
2024
  static $is_visible = null;
2025

    
2026
  if($is_visible === null){
2027
      $block = block_load('cdm_api', 'cdm_ws_debug');
2028
      $is_visible = isset($block->status) && $block->status == 1;
2029
      if($is_visible){
2030
        $blocks = array($block);
2031
        // Checks the page, user role, and user-specific visibilty settings.
2032
        block_block_list_alter($blocks);
2033
        $is_visible = count($blocks) > 0;
2034
      }
2035
  }
2036
  return $is_visible;
2037
}
2038

    
2039
/**
2040
 * @todo Please document this function.
2041
 * @see http://drupal.org/node/1354
2042
 */
2043
function cdm_load_obj($response_body) {
2044
  $obj = json_decode($response_body);
2045

    
2046
  if (!(is_object($obj) || is_array($obj))) {
2047
    ob_start();
2048
    $obj_dump = ob_get_contents();
2049
    ob_clean();
2050
    return FALSE;
2051
  }
2052

    
2053
  return $obj;
2054
}
2055

    
2056
/**
2057
 * Do a http request to a CDM RESTful web service.
2058
 *
2059
 * @param string $uri
2060
 *   The webservice url.
2061
 * @param string $method
2062
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2063
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2064
 * @param $data: A string containing the request body, formatted as
2065
 *     'param=value&param=value&...'. Defaults to NULL.
2066
 *
2067
 * @return object
2068
 *   The object as returned by drupal_http_request():
2069
 *   An object that can have one or more of the following components:
2070
 *   - request: A string containing the request body that was sent.
2071
 *   - code: An integer containing the response status code, or the error code
2072
 *     if an error occurred.
2073
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2074
 *   - status_message: The status message from the response, if a response was
2075
 *     received.
2076
 *   - redirect_code: If redirected, an integer containing the initial response
2077
 *     status code.
2078
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2079
 *     target.
2080
 *   - error: If an error occurred, the error message. Otherwise not set.
2081
 *   - headers: An array containing the response headers as name/value pairs.
2082
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2083
 *     easy access the array keys are returned in lower case.
2084
 *   - data: A string containing the response body that was received.
2085
 */
2086
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2087
  static $acceptLanguage = NULL;
2088
  $header = array();
2089
  
2090
  if(!$acceptLanguage && module_exists('i18n')){
2091
    $acceptLanguage = i18n_language_content()->language;
2092
  }
2093

    
2094
  if (!$acceptLanguage) {
2095
    if (function_exists('apache_request_headers')) {
2096
      $headers = apache_request_headers();
2097
      if (isset($headers['Accept-Language'])) {
2098
        $acceptLanguage = $headers['Accept-Language'];
2099
      }
2100
    }
2101
  }
2102

    
2103
  if ($method != "GET" && $method != "POST") {
2104
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2105
  }
2106

    
2107
  if (_is_cdm_ws_uri($uri)) {
2108
    $header['Accept'] = 'application/json';
2109
    $header['Accept-Language'] = $acceptLanguage;
2110
    $header['Accept-Charset'] = 'UTF-8';
2111
  }
2112

    
2113
  if($method == "POST") {
2114
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2115
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2116
  }
2117

    
2118

    
2119
  cdm_dd($uri);
2120
  return drupal_http_request($uri, array(
2121
      'headers' => $header,
2122
      'method' => $method,
2123
      'data' => $data,
2124
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2125
      )
2126
   );
2127
}
2128

    
2129
/**
2130
 * Concatenates recursively the fields of all features contained in the given
2131
 * CDM FeatureTree root node.
2132
 *
2133
 * @param $rootNode
2134
 *     A CDM FeatureTree node
2135
 * @param
2136
 *     The character to be used as glue for concatenation, default is ', '
2137
 * @param $field_name
2138
 *     The field name of the CDM Features
2139
 * @param $excludes
2140
 *     Allows defining a set of values to be excluded. This refers to the values
2141
 *     in the field denoted by the $field_name parameter
2142
 *
2143
 */
2144
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2145
  $out = '';
2146

    
2147
  $pre_child_separator = $separator;
2148
  $post_child_separator = '';
2149

    
2150
  foreach ($root_node->childNodes as $feature_node) {
2151
    $out .= ($out ? $separator : '');
2152
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2153
      $out .= $feature_node->feature->$field_name;
2154
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2155
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2156
        if (strlen($childlabels)) {
2157
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2158
        }
2159
      }
2160
    }
2161
  }
2162
  return $out;
2163
}
2164

    
2165
/**
2166
 * Create a one-dimensional form options array.
2167
 *
2168
 * Creates an array of all features in the feature tree of feature nodes,
2169
 * the node labels are indented by $node_char and $childIndent depending on the
2170
 * hierachy level.
2171
 *
2172
 * @param - $rootNode
2173
 * @param - $node_char
2174
 * @param - $childIndentStr
2175
 * @param - $childIndent
2176
 *   ONLY USED INTERNALLY!
2177
 *
2178
 * @return array
2179
 *   A one dimensional Drupal form options array.
2180
 */
2181
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2182
  $options = array();
2183
  foreach ($rootNode->childNodes as $featureNode) {
2184
    $indent_prefix = '';
2185
    if ($childIndent) {
2186
      $indent_prefix = $childIndent . $node_char . " ";
2187
    }
2188
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2189
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2190
      // Foreach ($featureNode->childNodes as $childNode){
2191
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2192
      $options = array_merge_recursive($options, $childList);
2193
      // }
2194
    }
2195
  }
2196
  return $options;
2197
}
2198

    
2199
/**
2200
 * Returns an array with all available FeatureTrees and the representations of the selected
2201
 * FeatureTree as a detail view.
2202
 *
2203
 * @param boolean $add_default_feature_free
2204
 * @return array
2205
 *  associative array with following keys:
2206
 *  -options: Returns an array with all available Feature Trees
2207
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2208
 *
2209
 */
2210
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2211

    
2212
  $options = array();
2213
  $tree_representations = array();
2214
  $feature_trees = array();
2215

    
2216
  // Set tree that contains all features.
2217
  if ($add_default_feature_free) {
2218
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2219
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2220
  }
2221

    
2222
  // Get feature trees from database.
2223
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2224
  if (is_array($persited_trees)) {
2225
    $feature_trees = array_merge($feature_trees, $persited_trees);
2226
  }
2227

    
2228
  foreach ($feature_trees as $featureTree) {
2229

    
2230
    if(!is_object($featureTree)){
2231
      continue;
2232
    }
2233
    // Do not add the DEFAULT_FEATURETREE again,
2234
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2235
      $options[$featureTree->uuid] = $featureTree->titleCache;
2236
    }
2237

    
2238
    // Render the hierarchic tree structure
2239
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2240

    
2241
      // Render the hierarchic tree structure.
2242
      $treeDetails = '<div class="featuretree_structure">'
2243
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2244
        . '</div>';
2245

    
2246
      $form = array();
2247
      $form['featureTree-' .  $featureTree->uuid] = array(
2248
        '#type' => 'fieldset',
2249
        '#title' => 'Show details',
2250
        '#attributes' => array('class' => array('collapsible collapsed')),
2251
        // '#collapsible' => TRUE,
2252
        // '#collapsed' => TRUE,
2253
      );
2254
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2255
        '#markup' => $treeDetails,
2256
      );
2257

    
2258
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2259
    }
2260

    
2261
  } // END loop over feature trees
2262

    
2263
  // return $options;
2264
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2265
}
2266

    
2267
/**
2268
 * Provides the list of availbale classifications in form of an options array.
2269
 *
2270
 * The options array is suitable for drupal form API elements that allow multiple choices.
2271
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2272
 *
2273
 * The classifications are ordered alphabetically whereas the classification
2274
 * chosen as default will always appear on top of the array, followed by a
2275
 * blank line below.
2276
 *
2277
 * @param bool $add_none_option
2278
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2279
 *
2280
 * @return array
2281
 *   classifications in an array as options for a form element that allows multiple choices.
2282
 */
2283
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2284

    
2285
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2286

    
2287
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2288
  $default_classification_label = '';
2289

    
2290
  // add all classifications
2291
  $taxonomic_tree_options = array();
2292
  if ($add_none_option) {
2293
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2294
  }
2295
  if ($taxonTrees) {
2296
    foreach ($taxonTrees as $tree) {
2297
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2298
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2299
      } else {
2300
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2301
        $default_classification_label = $tree->titleCache;
2302
      }
2303
    }
2304
  }
2305
  // oder alphabetically the space
2306
  asort($taxonomic_tree_options);
2307

    
2308
  // now set the labels
2309
  //   for none
2310
  if ($add_none_option) {
2311
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2312
  }
2313

    
2314
  //   for default_classification
2315
  if (is_uuid($default_classification_uuid)) {
2316
    $taxonomic_tree_options[$default_classification_uuid] =
2317
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2318
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2319
  }
2320

    
2321
  return $taxonomic_tree_options;
2322
}
2323

    
2324
/**
2325
 * @todo Please document this function.
2326
 * @see http://drupal.org/node/1354
2327
 */
2328
function cdm_api_secref_cache_prefetch(&$secUuids) {
2329
  // Comment @WA: global variables should start with a single underscore
2330
  // followed by the module and another underscore.
2331
  global $_cdm_api_secref_cache;
2332
  if (!is_array($_cdm_api_secref_cache)) {
2333
    $_cdm_api_secref_cache = array();
2334
  }
2335
  $uniqueUuids = array_unique($secUuids);
2336
  $i = 0;
2337
  $param = '';
2338
  while ($i++ < count($uniqueUuids)) {
2339
    $param .= $secUuids[$i] . ',';
2340
    if (strlen($param) + 37 > 2000) {
2341
      _cdm_api_secref_cache_add($param);
2342
      $param = '';
2343
    }
2344
  }
2345
  if ($param) {
2346
    _cdm_api_secref_cache_add($param);
2347
  }
2348
}
2349

    
2350
/**
2351
 * @todo Please document this function.
2352
 * @see http://drupal.org/node/1354
2353
 */
2354
function cdm_api_secref_cache_get($secUuid) {
2355
  global $_cdm_api_secref_cache;
2356
  if (!is_array($_cdm_api_secref_cache)) {
2357
    $_cdm_api_secref_cache = array();
2358
  }
2359
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2360
    _cdm_api_secref_cache_add($secUuid);
2361
  }
2362
  return $_cdm_api_secref_cache[$secUuid];
2363
}
2364

    
2365
/**
2366
 * @todo Please document this function.
2367
 * @see http://drupal.org/node/1354
2368
 */
2369
function cdm_api_secref_cache_clear() {
2370
  global $_cdm_api_secref_cache;
2371
  $_cdm_api_secref_cache = array();
2372
}
2373

    
2374

    
2375
/**
2376
 * Validates if the given string is a uuid.
2377
 *
2378
 * @param string $str
2379
 *   The string to validate.
2380
 *
2381
 * return bool
2382
 *   TRUE if the string is a UUID.
2383
 */
2384
function is_uuid($str) {
2385
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2386
}
2387

    
2388
/**
2389
 * Checks if the given $object is a valid cdm entity.
2390
 *
2391
 * An object is considered a cdm entity if it has a string field $object->class
2392
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2393
 * The function is null save.
2394
 *
2395
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2396
 *
2397
 * @param mixed $object
2398
 *   The object to validate
2399
 *
2400
 * @return bool
2401
 *   True if the object is a cdm entity.
2402
 */
2403
function is_cdm_entity($object) {
2404
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2405
}
2406

    
2407
/**
2408
 * @todo Please document this function.
2409
 * @see http://drupal.org/node/1354
2410
 */
2411
function _cdm_api_secref_cache_add($secUuidsStr) {
2412
  global $_cdm_api_secref_cache;
2413
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2414
  // Batch fetching not jet reimplemented thus:
2415
  /*
2416
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2417
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2418
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2419
  */
2420
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2421
}
2422

    
2423
/**
2424
 * Checks if the given uri starts with a cdm webservice url.
2425
 *
2426
 * Checks if the uri starts with the cdm webservice url stored in the
2427
 * Drupal variable 'cdm_webservice_url'.
2428
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2429
 *
2430
 * @param string $uri
2431
 *   The URI to test.
2432
 *
2433
 * @return bool
2434
 *   True if the uri starts with a cdm webservice url.
2435
 */
2436
function _is_cdm_ws_uri($uri) {
2437
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2438
}
2439

    
2440
/**
2441
 * @todo Please document this function.
2442
 * @see http://drupal.org/node/1354
2443
 */
2444
function queryString($elements) {
2445
  $query = '';
2446
  foreach ($elements as $key => $value) {
2447
    if (is_array($value)) {
2448
      foreach ($value as $v) {
2449
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2450
      }
2451
    }
2452
    else {
2453
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2454
    }
2455
  }
2456
  return $query;
2457
}
2458

    
2459
/**
2460
 * Implementation of the magic method __clone to allow deep cloning of objects
2461
 * and arrays.
2462
 */
2463
function __clone() {
2464
  foreach ($this as $name => $value) {
2465
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2466
      $this->$name = clone($this->$name);
2467
    }
2468
  }
2469
}
2470

    
2471
/**
2472
 * Compares the given CDM Term instances by the  representationL10n.
2473
 *
2474
 * Can also be used with TermDTOs. To be used in usort()
2475
 *
2476
 * @see http://php.net/manual/en/function.usort.php
2477
 *
2478
 * @param $term1
2479
 *   The first CDM Term instance
2480
 * @param $term2
2481
 *   The second CDM Term instance
2482
 * @return int
2483
 *   The result of the comparison
2484
 */
2485
function compare_terms_by_representationL10n($term1, $term2) {
2486

    
2487
  if (!isset($term1->representation_L10n)) {
2488
    $term1->representationL10n = '';
2489
  }
2490
  if (!isset($term2->representation_L10n)) {
2491
    $term2->representationL10n = '';
2492
  }
2493

    
2494
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2495
}
2496

    
2497

    
2498
/**
2499
 * Make a 'deep copy' of an array.
2500
 *
2501
 * Make a complete deep copy of an array replacing
2502
 * references with deep copies until a certain depth is reached
2503
 * ($maxdepth) whereupon references are copied as-is...
2504
 *
2505
 * @see http://us3.php.net/manual/en/ref.array.php
2506
 *
2507
 * @param array $array
2508
 * @param array $copy passed by reference
2509
 * @param int $maxdepth
2510
 * @param int $depth
2511
 */
2512
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2513
  if ($depth > $maxdepth) {
2514
    $copy = $array;
2515
    return;
2516
  }
2517
  if (!is_array($copy)) {
2518
    $copy = array();
2519
  }
2520
  foreach ($array as $k => &$v) {
2521
    if (is_array($v)) {
2522
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2523
    }
2524
    else {
2525
      $copy[$k] = $v;
2526
    }
2527
  }
2528
}
2529

    
2530
/**
2531
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2532
 *
2533
 */
2534
function _add_js_ws_debug() {
2535

    
2536
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2537
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2538
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2539
    // use the developer versions of js libs
2540
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2541
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2542
  }
2543
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2544
    array(
2545
      'type' => 'file',
2546
      'weight' => JS_LIBRARY,
2547
      'cache' => TRUE)
2548
    );
2549

    
2550
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2551
    array(
2552
      'type' => 'file',
2553
      'weight' => JS_LIBRARY,
2554
      'cache' => TRUE)
2555
    );
2556
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2557
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2558

    
2559
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2560
    array(
2561
      'type' => 'file',
2562
      'weight' => JS_LIBRARY,
2563
      'cache' => TRUE)
2564
    );
2565
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2566
    array(
2567
    'type' => 'file',
2568
    'weight' => JS_LIBRARY,
2569
    'cache' => TRUE)
2570
    );
2571

    
2572
}
2573

    
2574
/**
2575
 * @todo Please document this function.
2576
 * @see http://drupal.org/node/1354
2577
 */
2578
function _no_classfication_uuid_message() {
2579
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2580
    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.');
2581
  }
2582
  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.');
2583
}
2584

    
2585
/**
2586
 * Implementation of hook flush_caches
2587
 *
2588
 * Add custom cache tables to the list of cache tables that
2589
 * will be cleared by the Clear button on the Performance page or whenever
2590
 * drupal_flush_all_caches is invoked.
2591
 *
2592
 * @author W.Addink <waddink@eti.uva.nl>
2593
 *
2594
 * @return array
2595
 *   An array with custom cache tables to include.
2596
 */
2597
function cdm_api_flush_caches() {
2598
  return array('cache_cdm_ws');
2599
}
2600

    
2601
/**
2602
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2603
 *
2604
 * @param $data
2605
 *   The variable to log to the drupal_debug.txt log file.
2606
 * @param $label
2607
 *   (optional) If set, a label to output before $data in the log file.
2608
 *
2609
 * @return
2610
 *   No return value if successful, FALSE if the log file could not be written
2611
 *   to.
2612
 *
2613
 * @see cdm_dataportal_init() where the log file is reset on each requests
2614
 * @see dd()
2615
 * @see http://drupal.org/node/314112
2616
 *
2617
 */
2618
function cdm_dd($data, $label = NULL) {
2619
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2620
    return dd($data, $label);
2621
  }
2622
}
2623

    
(5-5/11)