Project

General

Profile

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

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

    
31
  /**
32
   * Timeout used to override the default of 30 seconds
33
   * in @see drupal_http_request()
34
   *
35
   * @var CDM_HTTP_REQUEST_TIMEOUT: A float representing the maximum number of seconds the function
36
   *     call may take
37
   */
38
  define('CDM_HTTP_REQUEST_TIMEOUT', 90.0);
39

    
40

    
41

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

    
47
/**
48
 * orderBy webservice query parameter value
49
 */
50
define('CDM_ORDER_BY_ID_DESC', 'BY_ID_DESC');
51
/**
52
 * orderBy webservice query parameter value
53
 */
54
define('CDM_ORDER_BY_TITLE_CACHE_ASC', 'BY_TITLE_CACHE_ASC');
55
/**
56
 * orderBy webservice query parameter value
57
 */
58
define('CDM_ORDER_BY_TITLE_CACHE_DESC', 'BY_TITLE_CACHE_DESC');
59
/**
60
 * orderBy webservice query parameter value
61
 */
62
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_ASC', 'BY_NOMENCLATURAL_ORDER_ASC');
63
/**
64
 * orderBy webservice query parameter value
65
 */
66
define('CDM_ORDER_BY_NOMENCLATURAL_ORDER_DESC', 'BY_NOMENCLATURAL_ORDER_DESC');
67
/**
68
 * orderBy webservice query parameter value
69
 */
70
define('CDM_ORDER_BY_ORDER_INDEX_ASC', 'BY_ORDER_INDEX_ASC');
71
/**
72
 * orderBy webservice query parameter value
73
 */
74
define('CDM_ORDER_BY_ORDER_INDEX_DESC', 'BY_ORDER_INDEX_DESC');
75

    
76

    
77
/**
78
 * Implements hook_menu().
79
 */
80
function cdm_api_menu() {
81
  $items = array();
82

    
83
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
84
  $items['cdm_api/proxy'] = array(
85
    'page callback' => 'proxy_content',
86
    'access arguments' => array(
87
      'access 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
        // also get the microfererence which could be in $tagged_text[$i + 3]
314
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
315
          $extracted_tt[2] = $tagged_text[$i + 2];
316
          $extracted_tt[3] = $tagged_text[$i + 3];
317
        }
318
        break;
319
      }
320
    }
321
  }
322
  return $extracted_tt;
323
}
324

    
325

    
326
function split_nomstatus_from_tagged_text(&$tagged_text) {
327

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

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

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

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

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

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

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

    
401
  return $profile_featureTree;
402
}
403

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

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

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

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

    
459

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

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

    
481
/**
482
 * @todo Improve the documentation of this function.
483
 *
484
 * media Array [4]
485
 * representations Array [3]
486
 * mimeType image/jpeg
487
 * representationParts Array [1]
488
 * duration 0
489
 * heigth 0
490
 * size 0
491
 * uri
492
 * http://wp5.e-taxonomy.eu/dataportal/cichorieae/media/protolog/jpeg/Acanthocephalus_p1.jpg
493
 * uuid 15c687f1-f79d-4b79-992f-7ba0f55e610b
494
 * width 0
495
 * suffix jpg
496
 * uuid 930b7d51-e7b6-4350-b21e-8124b14fe29b
497
 * title
498
 * uuid 17e514f1-7a8e-4daa-87ea-8f13f8742cf9
499
 *
500
 * @param object $media
501
 * @param array $mimeTypes
502
 * @param int $width
503
 * @param int $height
504
 *
505
 * @return array
506
 *   An array with preferred media representations or else an empty array.
507
 */
508
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
509
  $prefRepr = array();
510
  if (!isset($media->representations[0])) {
511
    return $prefRepr;
512
  }
513

    
514
  while (count($mimeTypes) > 0) {
515
    // getRepresentationByMimeType
516
    $mimeType = array_shift($mimeTypes);
517

    
518
    foreach ($media->representations as &$representation) {
519
      // If the mimetype is not known, try inferring it.
520
      if (!$representation->mimeType) {
521
        if (isset($representation->parts[0])) {
522
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
523
        }
524
      }
525

    
526
      if ($representation->mimeType == $mimeType) {
527
        // Preferred mimetype found -> erase all remaining mimetypes
528
        // to end loop.
529
        $mimeTypes = array();
530
        $dwa = 0;
531
        $dw = 0;
532
        // Look for part with the best matching size.
533
        foreach ($representation->parts as $part) {
534
          if (isset($part->width) && isset($part->height)) {
535
            $dw = $part->width * $part->height - $height * $width;
536
          }
537
          if ($dw < 0) {
538
            $dw *= -1;
539
          }
540
          $dwa += $dw;
541
        }
542
        $dwa = (count($representation->parts) > 0) ? $dwa / count($representation->parts) : 0;
543
        $prefRepr[$dwa . '_'] = $representation;
544
      }
545
    }
546
  }
547
  // Sort the array.
548
  krsort($prefRepr);
549
  return $prefRepr;
550
}
551

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

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

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

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

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

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

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

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

    
701
  $date = '';
702

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

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

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

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

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

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

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

    
814
  $i = 0;
815
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
816
    if (count($pathParameters) <= $i) {
817
        drupal_set_message(t('cdm_compose_url(): missing pathParameter ' . $i .  ' for ' . $uri_pattern), 'error');
818
      break;
819
    }
820
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
821
    ++$i;
822
  }
823

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

    
838
  // (3)
839
  // Append the query string supplied by $query.
840
  if (isset($query)) {
841
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
842
  }
843

    
844
  $path = $uri_pattern;
845

    
846
  $uri = variable_get('cdm_webservice_url', '') . $path;
847
  return $uri;
848
}
849

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

    
869
  $args = func_get_args();
870
  $do_gzip = function_exists('gzencode');
871
  $uriEncoded = array_shift($args);
872
  $uri = urldecode($uriEncoded);
873
  $hook = array_shift($args);
874
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
875

    
876
  $post_data = null;
877

    
878
  if ($request_method == "POST" || $request_method == "PUT") {
879
    // read response body via inputstream module
880
    $post_data = file_get_contents("php://input");
881
  }
882

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

    
892
  // In all these cases perform a simple get request.
893
  // TODO reconsider caching logic in this function.
894

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

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

    
927
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
928
    } else {
929
      $obj = NULL;
930
    }
931

    
932
    $reponse_data = NULL;
933

    
934
    if (function_exists('compose_' . $hook)){
935
      // call compose hook
936

    
937
      $elements =  call_user_func('compose_' . $hook, $obj);
938
      // pass the render array to drupal_render()
939
      $reponse_data = drupal_render($elements);
940
    } else {
941
      // call theme hook
942

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

    
957
        case 'cdm_list_of_taxa':
958
            $variables = array(
959
              'records' => $obj,
960
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
961
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
962
            $reponse_data = theme($hook, $variables);
963
            break;
964

    
965
        case 'cdm_media_caption':
966
          $variables = array(
967
          'media' => $obj,
968
          // $args[0] is set in taxon_image_gallery_default in
969
          // cdm_dataportal.page.theme.
970
          'elements' => isset($args[0]) ? $args[0] : array(
971
          'title',
972
          'description',
973
          'artist',
974
          'location',
975
          'rights',
976
          ),
977
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
978
          );
979
          $reponse_data = theme($hook, $variables);
980
          break;
981

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

    
992

    
993
    if($do_gzip){
994
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
995
      drupal_add_http_header('Content-Encoding', 'gzip');
996
    }
997
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
998
    drupal_add_http_header('Content-Length', strlen($reponse_data));
999

    
1000
    print $reponse_data;
1001
  } // END of handle $hook either as compose ot theme hook
1002

    
1003
}
1004

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

    
1019
  // Prevent from malicous tags.
1020
  $val = strip_tags($val);
1021

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

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

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

    
1060
  $ws_base_uri = NULL;
1061
  switch ($cdmBase->class) {
1062
    case 'TaxonBase':
1063
    case 'Taxon':
1064
    case 'Synonym':
1065
      $ws_base_uri = CDM_WS_TAXON;
1066
      break;
1067

    
1068
    case 'TaxonNameBase':
1069
    case 'NonViralName':
1070
    case 'BacterialName':
1071
    case 'BotanicalName':
1072
    case 'CultivarPlantName':
1073
    case 'ZoologicalName':
1074
    case 'ViralName':
1075
      $ws_base_uri = CDM_WS_NAME;
1076
      break;
1077

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1250
    $response = NULL;
1251

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

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

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

    
1285
  return $response;
1286
}
1287

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

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

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

    
1335
  return $response;
1336
}
1337

    
1338

    
1339
// =============================Terms and Vocabularies ========================================= //
1340

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

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

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

    
1406
  return $options;
1407
}
1408

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

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

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

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

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

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

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

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

    
1562

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

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

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

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

    
1599
  return $feature_tree;
1600
}
1601

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

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

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

    
1639
}
1640

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

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

    
1673
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1674
  if(is_array($microreference) || is_object($microreference)) {
1675
    return '';
1676
  }
1677

    
1678
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1679
    $referenceUuid,
1680
  ), "microReference=" . urlencode($microreference));
1681

    
1682
  if ($obj) {
1683
    return $obj->String;
1684
  }
1685
  else {
1686
    return NULL;
1687
  }
1688
}
1689

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

    
1701
  // 1. scan this level
1702
  foreach ($feature_tree_nodes as $node){
1703
    if($node->feature->uuid == $feature_uuid){
1704
      return $node;
1705
    }
1706
  }
1707

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

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

    
1745
  foreach ($featureNodes as &$node) {
1746
    // since the $featureNodes array is reused for each description
1747
    // it is necessary to clear the custom node fields in advance
1748
    if(isset($node->descriptionElements)){
1749
      unset($node->descriptionElements);
1750
    }
1751

    
1752
    // Append corresponding elements to an additional node field:
1753
    // $node->descriptionElements.
1754
    foreach ($descriptionElements as $element) {
1755
      if ($element->feature->uuid == $node->feature->uuid) {
1756
        if (!isset($node->descriptionElements)) {
1757
          $node->descriptionElements = array();
1758
        }
1759
        $node->descriptionElements[] = $element;
1760
      }
1761
    }
1762

    
1763
    // Recurse into node children.
1764
    if (isset($node->childNodes[0])) {
1765
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1766
      $node->childNodes = $mergedChildNodes;
1767
    }
1768

    
1769
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1770
      unset($node);
1771
    }
1772

    
1773
  }
1774

    
1775
  return $featureNodes;
1776
}
1777

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

    
1814
  static $cacheL1 = array();
1815

    
1816
  $data = NULL;
1817
  // store query string in $data and clear the query, $data will be set as HTTP request body
1818
  if($method == 'POST'){
1819
    $data = $query;
1820
    $query = NULL;
1821
  }
1822

    
1823
  // Transform the given uri path or pattern into a proper webservice uri.
1824
  if (!$absoluteURI) {
1825
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1826
  }
1827

    
1828
  // read request parameter 'cacheL2_refresh'
1829
  // which allows refreshing the level 2 cache
1830
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1831

    
1832
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1833
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1834

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

    
1843
  if (array_key_exists($cache_key, $cacheL1)) {
1844
    $cacheL1_obj = $cacheL1[$uri];
1845
  }
1846

    
1847
  $set_cacheL1 = FALSE;
1848
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1849
    $set_cacheL1 = TRUE;
1850
  }
1851

    
1852
  // Only cache cdm webservice URIs.
1853
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1854
  $cacheL2_entry = FALSE;
1855

    
1856
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1857
    // Try to get object from cacheL2.
1858
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1859
  }
1860

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

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

    
1896
    // Parse data and create object.
1897
    $obj = cdm_load_obj($response_body);
1898

    
1899
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1900

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

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

    
1950
  static $initial_time = NULL;
1951
  if(!$initial_time) {
1952
    $initial_time = microtime(TRUE);
1953
  }
1954
  $time = microtime(TRUE) - $initial_time;
1955

    
1956
  // Decompose uri into path and query element.
1957
  $uri_parts = explode("?", $uri);
1958
  $query = array();
1959
  if (count($uri_parts) == 2) {
1960
    $path = $uri_parts[0];
1961
  }
1962
  else {
1963
    $path = $uri;
1964
  }
1965

    
1966
  if(strpos($uri, '?') > 0){
1967
    $json_uri = str_replace('?', '.json?', $uri);
1968
    $xml_uri = str_replace('?', '.xml?', $uri);
1969
  } else {
1970
    $json_uri = $uri . '.json';
1971
    $xml_uri = $json_uri . '.xml';
1972
  }
1973

    
1974
  // data links to make data accecsible as json and xml
1975
  $data_links = '';
1976
  if (_is_cdm_ws_uri($path)) {
1977

    
1978
    // see ./js/http-method-link.js
1979

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

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

    
2014
  // Mark this page as being uncacheable.
2015
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2016
  drupal_page_is_cacheable(FALSE);
2017

    
2018
  // Messages not set when DB connection fails.
2019
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2020
}
2021

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

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

    
2044
/**
2045
 * @todo Please document this function.
2046
 * @see http://drupal.org/node/1354
2047
 */
2048
function cdm_load_obj($response_body) {
2049
  $obj = json_decode($response_body);
2050

    
2051
  if (!(is_object($obj) || is_array($obj))) {
2052
    ob_start();
2053
    $obj_dump = ob_get_contents();
2054
    ob_clean();
2055
    return FALSE;
2056
  }
2057

    
2058
  return $obj;
2059
}
2060

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

    
2099
  if (!$acceptLanguage) {
2100
    if (function_exists('apache_request_headers')) {
2101
      $headers = apache_request_headers();
2102
      if (isset($headers['Accept-Language'])) {
2103
        $acceptLanguage = $headers['Accept-Language'];
2104
      }
2105
    }
2106
  }
2107

    
2108
  if ($method != "GET" && $method != "POST") {
2109
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2110
  }
2111

    
2112
  if (_is_cdm_ws_uri($uri)) {
2113
    $header['Accept'] = 'application/json';
2114
    $header['Accept-Language'] = $acceptLanguage;
2115
    $header['Accept-Charset'] = 'UTF-8';
2116
  }
2117

    
2118
  if($method == "POST") {
2119
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2120
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2121
  }
2122

    
2123

    
2124
  cdm_dd($uri);
2125
  return drupal_http_request($uri, array(
2126
      'headers' => $header,
2127
      'method' => $method,
2128
      'data' => $data,
2129
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2130
      )
2131
   );
2132
}
2133

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

    
2152
  $pre_child_separator = $separator;
2153
  $post_child_separator = '';
2154

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

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

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

    
2217
  $options = array();
2218
  $tree_representations = array();
2219
  $feature_trees = array();
2220

    
2221
  // Set tree that contains all features.
2222
  if ($add_default_feature_free) {
2223
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2224
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2225
  }
2226

    
2227
  // Get feature trees from database.
2228
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2229
  if (is_array($persited_trees)) {
2230
    $feature_trees = array_merge($feature_trees, $persited_trees);
2231
  }
2232

    
2233
  foreach ($feature_trees as $featureTree) {
2234

    
2235
    if(!is_object($featureTree)){
2236
      continue;
2237
    }
2238
    // Do not add the DEFAULT_FEATURETREE again,
2239
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2240
      $options[$featureTree->uuid] = $featureTree->titleCache;
2241
    }
2242

    
2243
    // Render the hierarchic tree structure
2244
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2245

    
2246
      // Render the hierarchic tree structure.
2247
      $treeDetails = '<div class="featuretree_structure">'
2248
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2249
        . '</div>';
2250

    
2251
      $form = array();
2252
      $form['featureTree-' .  $featureTree->uuid] = array(
2253
        '#type' => 'fieldset',
2254
        '#title' => 'Show details',
2255
        '#attributes' => array('class' => array('collapsible collapsed')),
2256
        // '#collapsible' => TRUE,
2257
        // '#collapsed' => TRUE,
2258
      );
2259
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2260
        '#markup' => $treeDetails,
2261
      );
2262

    
2263
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2264
    }
2265

    
2266
  } // END loop over feature trees
2267

    
2268
  // return $options;
2269
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2270
}
2271

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

    
2290
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2291

    
2292
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2293
  $default_classification_label = '';
2294

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

    
2313
  // now set the labels
2314
  //   for none
2315
  if ($add_none_option) {
2316
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2317
  }
2318

    
2319
  //   for default_classification
2320
  if (is_uuid($default_classification_uuid)) {
2321
    $taxonomic_tree_options[$default_classification_uuid] =
2322
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2323
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2324
  }
2325

    
2326
  return $taxonomic_tree_options;
2327
}
2328

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

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

    
2370
/**
2371
 * @todo Please document this function.
2372
 * @see http://drupal.org/node/1354
2373
 */
2374
function cdm_api_secref_cache_clear() {
2375
  global $_cdm_api_secref_cache;
2376
  $_cdm_api_secref_cache = array();
2377
}
2378

    
2379

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

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

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

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

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

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

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

    
2492
  if (!isset($term1->representation_L10n)) {
2493
    $term1->representationL10n = '';
2494
  }
2495
  if (!isset($term2->representation_L10n)) {
2496
    $term2->representationL10n = '';
2497
  }
2498

    
2499
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2500
}
2501

    
2502

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

    
2535
/**
2536
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2537
 *
2538
 */
2539
function _add_js_ws_debug() {
2540

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

    
2555
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2556
    array(
2557
      'type' => 'file',
2558
      'weight' => JS_LIBRARY,
2559
      'cache' => TRUE)
2560
    );
2561
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2562
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2563

    
2564
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2565
    array(
2566
      'type' => 'file',
2567
      'weight' => JS_LIBRARY,
2568
      'cache' => TRUE)
2569
    );
2570
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2571
    array(
2572
    'type' => 'file',
2573
    'weight' => JS_LIBRARY,
2574
    'cache' => TRUE)
2575
    );
2576

    
2577
}
2578

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

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

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

    
(5-5/11)