Project

General

Profile

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

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

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

    
40

    
41

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

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

    
76

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

    
83
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
84
  $items['cdm_api/proxy'] = array(
85
    'page callback' => 'proxy_content',
86
    'access arguments' => array(
87
      'access content',
88
    ),
89
    'type' => MENU_CALLBACK,
90
  );
91

    
92
  $items['cdm_api/setvalue/session'] = array(
93
    'page callback' => 'setvalue_session',
94
    'access arguments' => array(
95
      'access content',
96
    ),
97
    'type' => MENU_CALLBACK,
98
  );
99

    
100
  return $items;
101
}
102

    
103
/**
104
 * Implements hook_block_info().
105
 */
106
function cdm_api_block_info() {
107

    
108
  $block['cdm_ws_debug'] = array(
109
      "info" => t("CDM web service debug"),
110
      "cache" => DRUPAL_NO_CACHE
111
  );
112
  return $block;
113
}
114

    
115
/**
116
 * Implements hook_block_view().
117
 */
118
function cdm_api_block_view($delta) {
119
  switch ($delta) {
120
    case 'cdm_ws_debug':
121

    
122
    $cdm_ws_url = variable_get('cdm_webservice_url', '');
123

    
124
    $field_map = array(
125
        'ws_uri' => t('URI') . ' <code>(' . $cdm_ws_url .'...)</code>',
126
        'time' => t('Time'),
127
        'fetch_seconds' => t('Fetching [s]'),
128
        'parse_seconds' => t('Parsing [s]'),
129
        'size_kb' => t('Size [kb]'),
130
        'status' => t('Status'),
131
        'data_links' =>  t('Links'),
132
    );
133

    
134

    
135
    if (!isset($_SESSION['cdm']['ws_debug'])) {
136
      $_SESSION['cdm']['ws_debug'] = array();
137
    }
138

    
139
    $header = '<thead><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></thead>';
140
    $footer = '<tfoot><tr><th>' . join('</th><th>' , array_values($field_map)) . '</th></tfoot>';
141
    $rows = array();
142

    
143
    foreach ($_SESSION['cdm']['ws_debug'] as $data){
144

    
145
      $data = unserialize($data);
146

    
147
      // stip of webservice base url
148
      $data['ws_uri'] = str_replace($cdm_ws_url, '', $data['ws_uri']);
149
      if($data['method'] == 'POST'){
150
        $data['ws_uri'] = 'POST: ' . $data['ws_uri'] . '?' . $data['post_data'];
151
      }
152

    
153
      $cells = array();
154
      foreach ($field_map as $field => $label){
155
        $cells[] = '<td class="' . $field . '">' .  $data[$field] . '</td>';
156
      }
157
      $rows[] = '<tr class="' . $data['status']  . '">' . join('' , $cells). '</tr>';
158
    }
159
    // clear session again
160
    $_SESSION['cdm']['ws_debug'] = array();
161

    
162
    _add_js_ws_debug();
163

    
164
    $block['subject'] = ''; // no subject, title in content for having a defined element id
165
    // otherwise it would depend on the theme
166
    $block['content'] =
167
        '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
168
          // cannot use theme_table() since table footer is not jet supported in D7
169
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
170
        . $header
171
        . '<tbody>' . join('', $rows) . '</tbody>'
172
        . $footer
173
        . '</table></div>';
174

    
175
    return $block;
176
  }
177
}
178

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

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

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

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

    
231

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

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

    
272
  if (is_array($taggedTextList)) {
273

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

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

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

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

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

    
303
function split_secref_from_tagged_text(&$tagged_text) {
304

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

    
320

    
321
function split_nomstatus_from_tagged_text(&$tagged_text) {
322

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

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

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

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

    
369
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
370
}
371

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

    
386
  if($profile_featureTree == NULL) {
387
    $profile_featureTree = cdm_ws_get(
388
      CDM_WS_FEATURETREE,
389
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
390
    );
391
    if (!$profile_featureTree) {
392
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
393
    }
394
  }
395

    
396
  return $profile_featureTree;
397
}
398

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

    
413
  if($occurrence_featureTree == NULL) {
414
    $occurrence_featureTree = cdm_ws_get(
415
      CDM_WS_FEATURETREE,
416
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
417
    );
418
    if (!$occurrence_featureTree) {
419
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
420
    }
421
  }
422
  return $occurrence_featureTree;
423
}
424

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

    
439
  if($structured_description_featureTree == NULL) {
440
    $structured_description_featureTree = cdm_ws_get(
441
        CDM_WS_FEATURETREE,
442
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
443
    );
444
    if (!$structured_description_featureTree) {
445
      $structured_description_featureTree = cdm_ws_get(
446
          CDM_WS_FEATURETREE,
447
          UUID_DEFAULT_FEATURETREE
448
      );
449
    }
450
  }
451
  return $structured_description_featureTree;
452
}
453

    
454

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

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

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

    
509
  while (count($mimeTypes) > 0) {
510
    // getRepresentationByMimeType
511
    $mimeType = array_shift($mimeTypes);
512

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

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

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

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

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

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

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

    
680
  $y = NULL; $m = NULL; $d = NULL;
681

    
682
  if(strpos($format, 'YY') !== FALSE){
683
    $y = partialToYear($partial);
684
  }
685
  if(strpos($format, 'MM') !== FALSE){
686
    $m = partialToMonth($partial);
687
  }
688
  if(strpos($format, 'DD') !== FALSE){
689
    $d = partialToDay($partial);
690
  }
691

    
692
  $y = $y ? $y : '00';
693
  $m = $m ? $m : '00';
694
  $d = $d ? $d : '00';
695

    
696
  $date = '';
697

    
698
  if ($y == '00' && $stripZeros) {
699
    return;
700
  }
701
  else {
702
    $date = $y;
703
  }
704

    
705
  if ($m == '00' && $stripZeros) {
706
    return $date;
707
  }
708
  else {
709
    $date .= "-" . $m;
710
  }
711

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

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

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

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

    
800
  // (1)
801
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
802
  // according element of the $pathParameters array.
803
  static $helperArray = array();
804
  if (isset($pathParameters) && !is_array($pathParameters)) {
805
    $helperArray[0] = $pathParameters;
806
    $pathParameters = $helperArray;
807
  }
808

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

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

    
833
  // (3)
834
  // Append the query string supplied by $query.
835
  if (isset($query)) {
836
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
837
  }
838

    
839
  $path = $uri_pattern;
840

    
841
  $uri = variable_get('cdm_webservice_url', '') . $path;
842
  return $uri;
843
}
844

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

    
864
  $args = func_get_args();
865
  $do_gzip = function_exists('gzencode');
866
  $uriEncoded = array_shift($args);
867
  $uri = urldecode($uriEncoded);
868
  $hook = array_shift($args);
869
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
870

    
871
  $post_data = null;
872

    
873
  if ($request_method == "POST" || $request_method == "PUT") {
874
    // read response body via inputstream module
875
    $post_data = file_get_contents("php://input");
876
  }
877

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

    
887
  // In all these cases perform a simple get request.
888
  // TODO reconsider caching logic in this function.
889

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

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

    
922
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
923
    } else {
924
      $obj = NULL;
925
    }
926

    
927
    $reponse_data = NULL;
928

    
929
    if (function_exists('compose_' . $hook)){
930
      // call compose hook
931

    
932
      $elements =  call_user_func('compose_' . $hook, $obj);
933
      // pass the render array to drupal_render()
934
      $reponse_data = drupal_render($elements);
935
    } else {
936
      // call theme hook
937

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

    
952
        case 'cdm_list_of_taxa':
953
            $variables = array(
954
              'records' => $obj,
955
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
956
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
957
            $reponse_data = theme($hook, $variables);
958
            break;
959

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

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

    
987

    
988
    if($do_gzip){
989
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
990
      drupal_add_http_header('Content-Encoding', 'gzip');
991
    }
992
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
993
    drupal_add_http_header('Content-Length', strlen($reponse_data));
994

    
995
    print $reponse_data;
996
  } // END of handle $hook either as compose ot theme hook
997

    
998
}
999

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

    
1014
  // Prevent from malicous tags.
1015
  $val = strip_tags($val);
1016

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

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

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

    
1055
  $ws_base_uri = NULL;
1056
  switch ($cdmBase->class) {
1057
    case 'TaxonBase':
1058
    case 'Taxon':
1059
    case 'Synonym':
1060
      $ws_base_uri = CDM_WS_TAXON;
1061
      break;
1062

    
1063
    case 'TaxonNameBase':
1064
    case 'NonViralName':
1065
    case 'BacterialName':
1066
    case 'BotanicalName':
1067
    case 'CultivarPlantName':
1068
    case 'ZoologicalName':
1069
    case 'ViralName':
1070
      $ws_base_uri = CDM_WS_NAME;
1071
      break;
1072

    
1073
    case 'Media':
1074
      $ws_base_uri = CDM_WS_MEDIA;
1075
      break;
1076

    
1077
    case 'Reference':
1078
      $ws_base_uri = CDM_WS_REFERENCE;
1079
      break;
1080

    
1081
    case 'Distribution':
1082
    case 'TextData':
1083
    case 'TaxonInteraction':
1084
    case 'QuantitativeData':
1085
    case 'IndividualsAssociation':
1086
    case 'Distribution':
1087
    case 'CommonTaxonName':
1088
    case 'CategoricalData':
1089
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1090
      break;
1091

    
1092
    case 'PolytomousKey':
1093
    case 'MediaKey':
1094
    case 'MultiAccessKey':
1095
      $ws_base_uri = $cdmBase->class;
1096
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1097
      break;
1098

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

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

    
1133
  $query['pageNumber'] = $pageNumber;
1134
  $query['pageSize'] = $pageSize;
1135

    
1136
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1137
}
1138

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

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

    
1176
/*
1177
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1178
  $viewrank = _cdm_taxonomy_compose_viewrank();
1179
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1180
  ? '/' . $path : '') ;
1181
}
1182
*/
1183

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

    
1197
  $view_uuid = get_current_classification_uuid();
1198
  $rank_uuid = NULL;
1199
  if (!$ignore_rank_limit) {
1200
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1201
  }
1202

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

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

    
1245
    $response = NULL;
1246

    
1247
    // 1st try
1248
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1249

    
1250
    if ($response == NULL) {
1251
      // 2dn try by ignoring the rank limit
1252
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1253
    }
1254

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

    
1280
  return $response;
1281
}
1282

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

    
1298
  $response = NULL;
1299
  if (is_uuid($rank_uuid)) {
1300
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1301
      $view_uuid,
1302
      $taxon_uuid,
1303
      $rank_uuid,
1304
    ));
1305
  }
1306
  else {
1307
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1308
      $view_uuid,
1309
      $taxon_uuid,
1310
    ));
1311
  }
1312

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

    
1330
  return $response;
1331
}
1332

    
1333

    
1334
// =============================Terms and Vocabularies ========================================= //
1335

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

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

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

    
1401
  return $options;
1402
}
1403

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

    
1420
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1421
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1422
      array(
1423
        'orderBy' => $order_by
1424
      )
1425
    );
1426
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1427
  }
1428

    
1429
  $options = $vocabularyOptions[$vocabulary_uuid];
1430
  if($default_option !== FALSE){
1431
    array_unshift ($options, "");
1432
  }
1433
  return $options;
1434
}
1435

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

    
1497
/**
1498
 * @todo Please document this function.
1499
 * @see http://drupal.org/node/1354
1500
 */
1501
function cdm_rankVocabulary_as_option() {
1502
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, "");
1503
  return $options;
1504
}
1505

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

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

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

    
1557

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

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

    
1582
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1583
      array(
1584
      'taxon' => $taxon_uuid,
1585
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1586
      ),
1587
      'POST'
1588
  );
1589

    
1590
  // Combine all descriptions into one feature tree.
1591
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1592
  $feature_tree->root->childNodes = $merged_nodes;
1593

    
1594
  return $feature_tree;
1595
}
1596

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

    
1613
  if(!isset($cdmBase->annotations)){
1614
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1615
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1616
  }
1617

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

    
1634
}
1635

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

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

    
1668
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1669
  if(is_array($microreference) || is_object($microreference)) {
1670
    return '';
1671
  }
1672

    
1673
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1674
    $referenceUuid,
1675
  ), "microReference=" . urlencode($microreference));
1676

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

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

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

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

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

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

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

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

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

    
1768
  }
1769

    
1770
  return $featureNodes;
1771
}
1772

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

    
1809
  static $cacheL1 = array();
1810

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2053
  return $obj;
2054
}
2055

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

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

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

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

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

    
2118

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

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

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

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

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

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

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

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

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

    
2228
  foreach ($feature_trees as $featureTree) {
2229

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

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

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

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

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

    
2261
  } // END loop over feature trees
2262

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

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

    
2285
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2286

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

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

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

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

    
2321
  return $taxonomic_tree_options;
2322
}
2323

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

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

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

    
2374

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

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

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

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

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

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

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

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

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

    
2497

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

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

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

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

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

    
2572
}
2573

    
2574
/**
2575
 * @todo Please document this function.
2576
 * @see http://drupal.org/node/1354
2577
 */
2578
function _no_classfication_uuid_message() {
2579
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2580
    return t('This DataPortal is not configured properly or the CDM-Server may be absent.') . ' Please check the ' . l(t('CDM web service URL'), 'admin/config/cdm_dataportal/settings/general') . t(', or contact the maintainer of this DataPortal.');
2581
  }
2582
  return t('This DataPortal is not configured properly.') . l(t('Please choose a valid classification'), 'admin/config/cdm_dataportal/settings/general') . t(', or contact the maintainer of this DataPortal.');
2583
}
2584

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

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

    
(5-5/11)