Project

General

Profile

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

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

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

    
40

    
41

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

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

    
76

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

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

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

    
100
  return $items;
101
}
102

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

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

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

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

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

    
134

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

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

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

    
145
      $data = unserialize($data);
146

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

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

    
162
    _add_js_ws_debug();
163

    
164
    $block['subject'] = ''; // no subject, title in content for having a defined element id
165
    // otherwise it would depend on the theme
166
    $block['content'] =
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
// ===================== Tagged Text functions ================== //
189

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

    
221

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

    
248
/**
249
 * Preprocess the taggedTitle arrays.
250
 *
251
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
252
 * into tag type "name"
253
 *
254
 * Step 2: Two taggedTexts which have the same type and which have
255
 * a separator between them are merged together.
256
 *
257
 * @param array $taggedTextList
258
 *    An array of TaggedText objects
259
 */
260
function normalize_tagged_text(&$taggedTextList) {
261

    
262
  if (is_array($taggedTextList)) {
263

    
264
    // First pass: rename.
265
    for ($i = 0; $i < count($taggedTextList); $i++) {
266

    
267
      if ($taggedTextList[$i]->type == "hybridSign") {
268
        $taggedTextList[$i]->type = "name";
269
      }
270
    }
271

    
272
    // Second pass: resolve separators.
273
    $taggedNameListNew = array();
274
    for ($i = 0; $i < count($taggedTextList); $i++) {
275

    
276
      // elements of the same type concatenated by a separator should be merged together
277
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
278
        $taggedName = clone $taggedTextList[$i];
279
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
280
        $taggedNameListNew[] = $taggedName;
281
        ++$i;
282
        ++$i;
283
        continue;
284
      }
285
      // no special handling
286
      $taggedNameListNew[] = $taggedTextList[$i];
287

    
288
    }
289
    $taggedTextList = $taggedNameListNew;
290
  }
291
}
292

    
293
function split_secref_from_tagged_text(&$tagged_text) {
294

    
295
  $extracted_tt = array();
296
  if (is_array($tagged_text)) {
297
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
298
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
299
        $extracted_tt[0] = $tagged_text[$i];
300
        $extracted_tt[1] = $tagged_text[$i + 1];
301
        unset($tagged_text[$i]);
302
        unset($tagged_text[$i + 1]);
303
        // also get the microfererence which could be in $tagged_text[$i + 3]
304
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
305
          $extracted_tt[2] = $tagged_text[$i + 2];
306
          $extracted_tt[3] = $tagged_text[$i + 3];
307
        }
308
        break;
309
      }
310
    }
311
  }
312
  return $extracted_tt;
313
}
314

    
315

    
316
function split_nomstatus_from_tagged_text(&$tagged_text) {
317

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

    
339
function find_tagged_text_elements($taggedTextList, $type){
340
  $matching_elements = array();
341
  if (is_array($taggedTextList)) {
342
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
343
      if($taggedTextList[$i]->type == $type){
344
        $matching_elements[] = $taggedTextList[$i];
345
      }
346
    }
347
  }
348
  return $matching_elements;
349
}
350

    
351
// ===================== END of Tagged Text functions ================== //
352

    
353
/**
354
 * Lists the classifications a taxon belongs to
355
 *
356
 * @param CDM type Taxon $taxon
357
 *   the taxon
358
 *
359
 * @return array
360
 *   aray of CDM instances of Type Classification
361
 */
362
function get_classifications_for_taxon($taxon) {
363

    
364
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
365
}
366

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

    
381
  if($profile_featureTree == NULL) {
382
    $profile_featureTree = cdm_ws_get(
383
      CDM_WS_FEATURETREE,
384
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
385
    );
386
    if (!$profile_featureTree) {
387
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
388
    }
389
  }
390

    
391
  return $profile_featureTree;
392
}
393

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

    
408
  if($occurrence_featureTree == NULL) {
409
    $occurrence_featureTree = cdm_ws_get(
410
      CDM_WS_FEATURETREE,
411
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
412
    );
413
    if (!$occurrence_featureTree) {
414
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
415
    }
416
  }
417
  return $occurrence_featureTree;
418
}
419

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

    
434
  if($structured_description_featureTree == NULL) {
435
    $structured_description_featureTree = cdm_ws_get(
436
        CDM_WS_FEATURETREE,
437
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
438
    );
439
    if (!$structured_description_featureTree) {
440
      $structured_description_featureTree = cdm_ws_get(
441
          CDM_WS_FEATURETREE,
442
          UUID_DEFAULT_FEATURETREE
443
      );
444
    }
445
  }
446
  return $structured_description_featureTree;
447
}
448

    
449

    
450
/**
451
 * @todo Please document this function.
452
 * @see http://drupal.org/node/1354
453
 */
454
function set_last_taxon_page_tab($taxonPageTab) {
455
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
456
}
457

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

    
471
/**
472
 *
473
 * @param object $media
474
 * @param array $mimeTypes
475
 * @param int $width
476
 * @param int $height
477
 *
478
 * @return array
479
 *   An array with preferred media representations or else an empty array.
480
 */
481
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
482
  $prefRepr = array();
483
  if (!isset($media->representations[0])) {
484
    return $prefRepr;
485
  }
486

    
487
  while (count($mimeTypes) > 0) {
488
    // getRepresentationByMimeType
489
    $mimeType = array_shift($mimeTypes);
490

    
491
    foreach ($media->representations as &$representation) {
492
      // If the mimetype is not known, try inferring it.
493
      if (!$representation->mimeType) {
494
        if (isset($representation->parts[0])) {
495
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
496
        }
497
      }
498

    
499
      if ($representation->mimeType == $mimeType) {
500
        // Preferred mimetype found -> erase all remaining mimetypes
501
        // to end loop.
502
        $mimeTypes = array();
503
        $dwa = 0;
504
        $dw = 0;
505
        $valid_parts_cnt = 0;
506
        // Look for part with the best matching size.
507
        foreach ($representation->parts as $part) {
508
          if(empty($part->uri)){
509
            // skip part if URI is missing
510
            continue;
511
          }
512
          $valid_parts_cnt++;
513
          if (isset($part->width) && isset($part->height)) {
514
            $dw = $part->width * $part->height - $height * $width;
515
          }
516
          if ($dw < 0) {
517
            $dw *= -1;
518
          }
519
          $dwa += $dw;
520
        }
521
        if($valid_parts_cnt > 0){
522
          $dwa = $dwa / $valid_parts_cnt;
523
          $prefRepr[$dwa . '_'] = $representation;
524
        }
525
      }
526
    }
527
  }
528
  // Sort the array.
529
  krsort($prefRepr);
530
  return $prefRepr;
531
}
532

    
533
/**
534
 * Infers the mime type of a file using the filename extension.
535
 *
536
 * The filename extension is used to infer the mime type.
537
 *
538
 * @param string $filepath
539
 *   The path to the respective file.
540
 *
541
 * @return string
542
 *   The mimetype for the file or FALSE if the according mime type could
543
 *   not be found.
544
 */
545
function infer_mime_type($filepath) {
546
  static $mimemap = NULL;
547
  if (!$mimemap) {
548
    $mimemap = array(
549
      'jpg' => 'image/jpeg',
550
      'jpeg' => 'image/jpeg',
551
      'png' => 'image/png',
552
      'gif' => 'image/gif',
553
      'giff' => 'image/gif',
554
      'tif' => 'image/tif',
555
      'tiff' => 'image/tif',
556
      'pdf' => 'application/pdf',
557
      'html' => 'text/html',
558
      'htm' => 'text/html',
559
    );
560
  }
561
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
562
  if (isset($mimemap[$extension])) {
563
    return $mimemap[$extension];
564
  }
565
  else {
566
    // FIXME remove this hack just return FALSE;
567
    return 'text/html';
568
  }
569
}
570

    
571
/**
572
 * Converts an ISO 8601 org.joda.time.Partial to a year.
573
 *
574
 * The function expects an ISO 8601 time representation of a
575
 * org.joda.time.Partial of the form yyyy-MM-dd.
576
 *
577
 * @param string $partial
578
 *   ISO 8601 time representation of a org.joda.time.Partial.
579
 *
580
 * @return string
581
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
582
 */
583
function partialToYear($partial) {
584
  if (is_string($partial)) {
585
    $year = substr($partial, 0, 4);
586
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
587
      return $year;
588
    }
589
  }
590
  return '';
591
}
592

    
593
/**
594
 * Converts an ISO 8601 org.joda.time.Partial to a month.
595
 *
596
 * This function expects an ISO 8601 time representation of a
597
 * org.joda.time.Partial of the form yyyy-MM-dd.
598
 * In case the month is unknown (= ???) NULL is returned.
599
 *
600
 * @param string $partial
601
 *   ISO 8601 time representation of a org.joda.time.Partial.
602
 *
603
 * @return string
604
 *   A month.
605
 */
606
function partialToMonth($partial) {
607
  if (is_string($partial)) {
608
    $month = substr($partial, 5, 2);
609
    if (preg_match("/[0-9][0-9]/", $month)) {
610
      return $month;
611
    }
612
  }
613
  return '';
614
}
615

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

    
639
/**
640
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
641
 *
642
 * This function expects an ISO 8601 time representations of a
643
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
644
 * four digit year, month and day with dashes:
645
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
646
 *
647
 * The partial may contain question marks eg: "1973-??-??",
648
 * these are turned in to '00' or are stripped depending of the $stripZeros
649
 * parameter.
650
 *
651
 * @param string $partial
652
 *   org.joda.time.Partial.
653
 * @param bool $stripZeros
654
 *   If set to TRUE the zero (00) month and days will be hidden:
655
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
656
 * @param string @format
657
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
658
 *    - "YYYY": Year only
659
 *    - "YYYY-MM-DD": this is the default
660
 *
661
 * @return string
662
 *   YYYY-MM-DD formatted year, month, day.
663
 */
664
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
665

    
666
  $y = NULL; $m = NULL; $d = NULL;
667

    
668
  if(strpos($format, 'YY') !== FALSE){
669
    $y = partialToYear($partial);
670
  }
671
  if(strpos($format, 'MM') !== FALSE){
672
    $m = partialToMonth($partial);
673
  }
674
  if(strpos($format, 'DD') !== FALSE){
675
    $d = partialToDay($partial);
676
  }
677

    
678
  $y = $y ? $y : '00';
679
  $m = $m ? $m : '00';
680
  $d = $d ? $d : '00';
681

    
682
  $date = '';
683

    
684
  if ($y == '00' && $stripZeros) {
685
    return '';
686
  }
687
  else {
688
    $date = $y;
689
  }
690

    
691
  if ($m == '00' && $stripZeros) {
692
    return $date;
693
  }
694
  else {
695
    $date .= "-" . $m;
696
  }
697

    
698
  if ($d == '00' && $stripZeros) {
699
    return $date;
700
  }
701
  else {
702
    $date .= "-" . $d;
703
  }
704
  return $date;
705
}
706

    
707
/**
708
 * Converts a time period to a string.
709
 *
710
 * See also partialToDate($partial, $stripZeros).
711
 *
712
 * @param object $period
713
 *   An JodaTime org.joda.time.Period object.
714
 * @param bool $stripZeros
715
 *   If set to True, the zero (00) month and days will be hidden:
716
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
717
 * @param string @format
718
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
719
 *    - "YYYY": Year only
720
 *    - "YYYY-MM-DD": this is the default
721
 *
722
 * @return string
723
 *   Returns a date in the form of a string.
724
 */
725
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
726
  $dateString = '';
727
  if($period->freeText){
728
    $dateString = $period->freeText;
729
  } else {
730
    if ($period->start) {
731
      $dateString = partialToDate($period->start, $stripZeros, $format);
732
    }
733
    if ($period->end) {
734
      $dateString .= (strlen($dateString) > 0 ? ' ' . t('to') . ' ' : '') . partialToDate($period->end, $stripZeros, $format);
735
    }
736
  }
737
  return $dateString;
738
}
739

    
740
/**
741
 * returns the earliest date available in the $period in a normalized
742
 * form suitable for sorting, e.g.:
743
 *
744
 *  - 1956-00-00
745
 *  - 0000-00-00
746
 *  - 1957-03-00
747
 *
748
 * that is either the start date is returned if set otherwise the
749
 * end date
750
 *
751
 * @param  $period
752
 *    An JodaTime org.joda.time.Period object.
753
 * @return string normalized form of the date
754
 *   suitable for sorting
755
 */
756
function timePeriodAsOrderKey($period) {
757
  $dateString = '';
758
  if ($period->start) {
759
    $dateString = partialToDate($period->start, false);
760
  }
761
  if ($period->end) {
762
    $dateString .= partialToDate($period->end, false);
763
  }
764
  return $dateString;
765
}
766

    
767
/**
768
 * Composes a absolute CDM web service URI with parameters and querystring.
769
 *
770
 * @param string $uri_pattern
771
 *   String with place holders ($0, $1, ..) that should be replaced by the
772
 *   according element of the $pathParameters array.
773
 * @param array $pathParameters
774
 *   An array of path elements, or a single element.
775
 * @param string $query
776
 *   A query string to append to the URL.
777
 *
778
 * @return string
779
 *   A complete URL with parameters to a CDM webservice.
780
 */
781
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
782
  if (empty($pathParameters)) {
783
    $pathParameters = array();
784
  }
785

    
786
  // (1)
787
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
788
  // according element of the $pathParameters array.
789
  static $helperArray = array();
790
  if (isset($pathParameters) && !is_array($pathParameters)) {
791
    $helperArray[0] = $pathParameters;
792
    $pathParameters = $helperArray;
793
  }
794

    
795
  $i = 0;
796
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
797
    if (count($pathParameters) <= $i) {
798
        drupal_set_message(
799
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
800
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
801
          'error');
802
      break;
803
    }
804
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
805
    ++$i;
806
  }
807

    
808
  // (2)
809
  // Append all remaining element of the $pathParameters array as path
810
  // elements.
811
  if (count($pathParameters) > $i) {
812
    // Strip trailing slashes.
813
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
814
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
815
    }
816
    while (count($pathParameters) > $i) {
817
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
818
      ++$i;
819
    }
820
  }
821

    
822
  // (3)
823
  // Append the query string supplied by $query.
824
  if (isset($query)) {
825
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
826
  }
827

    
828
  $path = $uri_pattern;
829

    
830
  $uri = variable_get('cdm_webservice_url', '') . $path;
831
  return $uri;
832
}
833

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

    
853
  $args = func_get_args();
854
  $do_gzip = function_exists('gzencode');
855
  $uriEncoded = array_shift($args);
856
  $uri = urldecode($uriEncoded);
857
  $hook = array_shift($args);
858
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
859

    
860
  $post_data = null;
861

    
862
  if ($request_method == "POST" || $request_method == "PUT") {
863
    // read response body via inputstream module
864
    $post_data = file_get_contents("php://input");
865
  }
866

    
867
  // Find and deserialize arrays.
868
  foreach ($args as &$arg) {
869
    // FIXME use regex to find serialized arrays.
870
    //       or should we accept json instead of php serializations?
871
    if (strpos($arg, "a:") === 0) {
872
      $arg = unserialize($arg);
873
    }
874
  }
875

    
876
  // In all these cases perform a simple get request.
877
  // TODO reconsider caching logic in this function.
878

    
879
  if (empty($hook)) {
880
    // simply return the webservice response
881
    // Print out JSON, the cache cannot be used since it contains objects.
882
    $http_response = cdm_http_request($uri, $request_method, $post_data);
883
    if (isset($http_response->headers)) {
884
      foreach ($http_response->headers as $hname => $hvalue) {
885
        drupal_add_http_header($hname, $hvalue);
886
      }
887
    }
888
    if (isset($http_response->data)) {
889
      print $http_response->data;
890
      flush();
891
    }
892
    exit(); // leave drupal here
893
  } else {
894
    // $hook has been supplied
895
    // handle $hook either as compose ot theme hook
896
    // pass through theme or comose hook
897
    // compose hooks can be called without data, therefore
898
    // passing the $uri in this case is not always a requirement
899

    
900
    if($uri && $uri != 'NULL') {
901
    // do a security check since the $uri will be passed
902
    // as absolute URI to cdm_ws_get()
903
      if (!_is_cdm_ws_uri($uri)) {
904
        drupal_set_message(
905
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
906
          'error'
907
        );
908
        return '';
909
      }
910

    
911
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
912
    } else {
913
      $obj = NULL;
914
    }
915

    
916
    $reponse_data = NULL;
917

    
918
    if (function_exists('compose_' . $hook)){
919
      // call compose hook
920

    
921
      $elements =  call_user_func('compose_' . $hook, $obj);
922
      // pass the render array to drupal_render()
923
      $reponse_data = drupal_render($elements);
924
    } else {
925
      // call theme hook
926

    
927
      // TODO use theme registry to get the registered hook info and
928
      //    use these defaults
929
      switch($hook) {
930
        case 'cdm_taxontree':
931
          $variables = array(
932
            'tree' => $obj,
933
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
934
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
935
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
936
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
937
            );
938
          $reponse_data = theme($hook, $variables);
939
          break;
940

    
941
        case 'cdm_list_of_taxa':
942
            $variables = array(
943
              'records' => $obj,
944
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
945
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
946
            $reponse_data = theme($hook, $variables);
947
            break;
948

    
949
        case 'cdm_media_caption':
950
          $variables = array(
951
          'media' => $obj,
952
          // $args[0] is set in taxon_image_gallery_default in
953
          // cdm_dataportal.page.theme.
954
          'elements' => isset($args[0]) ? $args[0] : array(
955
          'title',
956
          'description',
957
          'artist',
958
          'location',
959
          'rights',
960
          ),
961
          'fileUri' => isset($args[1]) ? $args[1] : NULL,
962
          );
963
          $reponse_data = theme($hook, $variables);
964
          break;
965

    
966
        default:
967
          drupal_set_message(t(
968
          'Theme !theme is not yet supported by the function !function.', array(
969
          '!theme' => $hook,
970
          '!function' => __FUNCTION__,
971
          )), 'error');
972
          break;
973
      } // END of theme hook switch
974
    } // END of tread as theme hook
975

    
976

    
977
    if($do_gzip){
978
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
979
      drupal_add_http_header('Content-Encoding', 'gzip');
980
    }
981
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
982
    drupal_add_http_header('Content-Length', strlen($reponse_data));
983

    
984
    print $reponse_data;
985
  } // END of handle $hook either as compose ot theme hook
986

    
987
}
988

    
989
/**
990
 * @todo Please document this function.
991
 * @see http://drupal.org/node/1354
992
 */
993
function setvalue_session() {
994
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
995
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
996
    $var_keys = explode('][', $var_keys);
997
  }
998
  else {
999
    return;
1000
  }
1001
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1002

    
1003
  // Prevent from malicous tags.
1004
  $val = strip_tags($val);
1005

    
1006
  $session_var = &$_SESSION;
1007
  //$i = 0;
1008
  foreach ($var_keys as $key) {
1009
    // $hasMoreKeys = ++$i < count($session);
1010
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1011
      $session_var[$key] = array();
1012
    }
1013
    $session_var = &$session_var[$key];
1014
  }
1015
  $session_var = $val;
1016
  if (isset($_REQUEST['destination'])) {
1017
    drupal_goto($_REQUEST['destination']);
1018
  }
1019
}
1020

    
1021
/**
1022
 * @todo Please document this function.
1023
 * @see http://drupal.org/node/1354
1024
 */
1025
function uri_uriByProxy($uri, $theme = FALSE) {
1026
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1027
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1028
}
1029

    
1030
/**
1031
 * Composes the the absolute REST service URI to the annotations pager
1032
 * for the given CDM entity.
1033
 *
1034
 * NOTE: Not all CDM Base types are yet supported.
1035
 *
1036
 * @param $cdmBase
1037
 *   The CDM entity to construct the annotations pager uri for
1038
 */
1039
function cdm_compose_annotations_uri($cdmBase) {
1040
  if (!$cdmBase->uuid) {
1041
    return;
1042
  }
1043

    
1044
  $ws_base_uri = NULL;
1045
  switch ($cdmBase->class) {
1046
    case 'TaxonBase':
1047
    case 'Taxon':
1048
    case 'Synonym':
1049
      $ws_base_uri = CDM_WS_TAXON;
1050
      break;
1051

    
1052
    case 'TaxonNameBase':
1053
    case 'NonViralName':
1054
    case 'BacterialName':
1055
    case 'BotanicalName':
1056
    case 'CultivarPlantName':
1057
    case 'ZoologicalName':
1058
    case 'ViralName':
1059
      $ws_base_uri = CDM_WS_NAME;
1060
      break;
1061

    
1062
    case 'Media':
1063
      $ws_base_uri = CDM_WS_MEDIA;
1064
      break;
1065

    
1066
    case 'Reference':
1067
      $ws_base_uri = CDM_WS_REFERENCE;
1068
      break;
1069

    
1070
    case 'Distribution':
1071
    case 'TextData':
1072
    case 'TaxonInteraction':
1073
    case 'QuantitativeData':
1074
    case 'IndividualsAssociation':
1075
    case 'Distribution':
1076
    case 'CommonTaxonName':
1077
    case 'CategoricalData':
1078
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1079
      break;
1080

    
1081
    case 'PolytomousKey':
1082
    case 'MediaKey':
1083
    case 'MultiAccessKey':
1084
      $ws_base_uri = $cdmBase->class;
1085
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1086
      break;
1087

    
1088
    default:
1089
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1090
      return;
1091
  }
1092
  return cdm_compose_url($ws_base_uri, array(
1093
    $cdmBase->uuid,
1094
    'annotations',
1095
  ));
1096
}
1097

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

    
1122
  $query['pageNumber'] = $pageNumber;
1123
  $query['pageSize'] = $pageSize;
1124

    
1125
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1126
}
1127

    
1128
/**
1129
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1130
 *
1131
 * @param string $resourceURI
1132
 * @param array $query
1133
 *   A array holding the HTTP request query parameters for the request
1134
 * @param string $method
1135
 *   The HTTP method to use, valid values are "GET" or "POST";
1136
 * @param bool $absoluteURI
1137
 *   TRUE when the URL should be treated as absolute URL.
1138
 *
1139
 * @return array
1140
 *     A list of CDM entitites
1141
 *
1142
 */
1143
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1144
  $page_index = 0;
1145
  // using a bigger page size to avoid to many multiple requests
1146
  $page_size = 500;
1147
  $entities = array();
1148

    
1149
  while ($page_index !== FALSE){
1150
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1151
    if(isset($pager->records) && is_array($pager->records)) {
1152
      $entities = array_merge($entities, $pager->records);
1153
      if(!empty($pager->nextIndex)){
1154
        $page_index = $pager->nextIndex;
1155
      } else {
1156
        $page_index = FALSE;
1157
      }
1158
    } else {
1159
      $page_index = FALSE;
1160
    }
1161
  }
1162
  return $entities;
1163
}
1164

    
1165
/*
1166
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1167
  $viewrank = _cdm_taxonomy_compose_viewrank();
1168
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1169
  ? '/' . $path : '') ;
1170
}
1171
*/
1172

    
1173
/**
1174
 * @todo Enter description here...
1175
 *
1176
 * @param string $taxon_uuid
1177
 *  The UUID of a cdm taxon instance
1178
 * @param string $ignore_rank_limit
1179
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1180
 *
1181
 * @return string
1182
 *   A cdm REST service URL path to a Classification
1183
 */
1184
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1185

    
1186
  $view_uuid = get_current_classification_uuid();
1187
  $rank_uuid = NULL;
1188
  if (!$ignore_rank_limit) {
1189
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1190
  }
1191

    
1192
  if (!empty($taxon_uuid)) {
1193
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1194
      $view_uuid,
1195
      $taxon_uuid,
1196
    ));
1197
  }
1198
  else {
1199
    if (is_uuid($rank_uuid)) {
1200
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1201
        $view_uuid,
1202
        $rank_uuid,
1203
      ));
1204
    }
1205
    else {
1206
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1207
        $view_uuid,
1208
      ));
1209
    }
1210
  }
1211
}
1212

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

    
1234
    $response = NULL;
1235

    
1236
    // 1st try
1237
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1238

    
1239
    if ($response == NULL) {
1240
      // 2dn try by ignoring the rank limit
1241
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1242
    }
1243

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

    
1269
  return $response;
1270
}
1271

    
1272
/**
1273
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1274
 * 
1275
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1276
 * variable is set.
1277
 *
1278
 * @param string $taxon_uuid
1279
 *
1280
 * @return array
1281
 *   An array of CDM TaxonNodeDTO objects
1282
 */
1283
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1284
  $view_uuid = get_current_classification_uuid();
1285
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1286

    
1287
  $response = NULL;
1288
  if (is_uuid($rank_uuid)) {
1289
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1290
      $view_uuid,
1291
      $taxon_uuid,
1292
      $rank_uuid,
1293
    ));
1294
  }
1295
  else {
1296
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1297
      $view_uuid,
1298
      $taxon_uuid,
1299
    ));
1300
  }
1301

    
1302
  if ($response == NULL) {
1303
    // Error handing.
1304
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1305
//      // Delete the session value and try again with the default.
1306
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1307
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1308
//    }
1309
//    else {
1310
      // Check if taxonomictree_uuid is valid.
1311
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1312
      if ($test == NULL) {
1313
        // The default set by the admin seems to be invalid or is not even set.
1314
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1315
      }
1316
//    }
1317
  }
1318

    
1319
  return $response;
1320
}
1321

    
1322

    
1323
// =============================Terms and Vocabularies ========================================= //
1324

    
1325
/**
1326
 * Returns the localized representation for the given term.
1327
 *
1328
 * @param Object $definedTermBase
1329
 * 	  of cdm type DefinedTermBase
1330
 * @return string
1331
 * 	  the localized representation_L10n of the term,
1332
 *    otherwise the titleCache as fall back,
1333
 *    otherwise the default_representation which defaults to an empty string
1334
 */
1335
function cdm_term_representation($definedTermBase, $default_representation = '') {
1336
  if ( isset($definedTermBase->representation_L10n) ) {
1337
    return $definedTermBase->representation_L10n;
1338
  } elseif ( isset($definedTermBase->titleCache)) {
1339
    return $definedTermBase->titleCache;
1340
  }
1341
  return $default_representation;
1342
}
1343

    
1344
/**
1345
 * Returns the abbreviated localized representation for the given term.
1346
 *
1347
 * @param Object $definedTermBase
1348
 * 	  of cdm type DefinedTermBase
1349
 * @return string
1350
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1351
 *    if this representation is not available the function delegates the
1352
 *    call to cdm_term_representation()
1353
 */
1354
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1355
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1356
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1357
  } else {
1358
    cdm_term_representation($definedTermBase, $default_representation);
1359
  }
1360
}
1361

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

    
1390
  return $options;
1391
}
1392

    
1393
/**
1394
 * Creates and array of options for drupal select form elements.
1395
 *
1396
 * @param $vocabulary_uuid
1397
 *   The UUID of the CDM Term Vocabulary
1398
 * @param $term_label_callback
1399
 *   An optional call back function which can be used to modify the term label
1400
 * @param bool $default_option
1401
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1402
 *   In order to put an empty element the beginning of the options pass an " " as argument.
1403
 * @param array $include_filter
1404
 *   An associative array consisting of a field name an regular expression. All term matching
1405
 *   these filter are included. The value of the field is converted to a String by var_export()
1406
 *   so a boolean 'true' can be matched by '/true/'
1407
 * @param string $order_by
1408
 *   One of the order by constants defined in this file
1409
 * @return mixed
1410
 */
1411
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $default_option = FALSE,
1412
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1413

    
1414
  static $vocabularyOptions = array();
1415

    
1416
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1417
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1418
      array(
1419
        'orderBy' => $order_by
1420
      )
1421
    );
1422

    
1423
    // apply the include filter
1424
    if($include_filter != null){
1425
      $included_terms = array();
1426

    
1427
      foreach ($terms as $term){
1428
        $include = true;
1429
        foreach ($include_filter as $field=>$regex){
1430
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1431
          if(!$include){
1432
            break;
1433
          }
1434
        }
1435
        if($include){
1436
          $included_terms[] = $term;
1437
        }
1438
      }
1439

    
1440
      $terms = $included_terms;
1441
    }
1442

    
1443
    // make options list
1444
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1445
  }
1446

    
1447
  $options = $vocabularyOptions[$vocabulary_uuid];
1448
  if($default_option !== FALSE){
1449
    array_unshift ($options, "");
1450
  }
1451
  return $options;
1452
}
1453

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

    
1515
/**
1516
 * @todo Please document this function.
1517
 * @see http://drupal.org/node/1354
1518
 */
1519
function cdm_rankVocabulary_as_option() {
1520
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, false);
1521
  return $options;
1522
}
1523

    
1524
/**
1525
 * @todo Please document this function.
1526
 * @see http://drupal.org/node/1354
1527
 */
1528
function _cdm_relationship_type_term_label_callback($term) {
1529
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1530
    return $term->representation_L10n_abbreviatedLabel . ' : '
1531
    . t('@term', array('@term' => $term->representation_L10n));
1532
  }
1533
else {
1534
    return t('@term', array('@term' => $term->representation_L10n));
1535
  }
1536
}
1537

    
1538
// ========================================================================================== //
1539
/**
1540
 * @todo Improve documentation of this function.
1541
 *
1542
 * eu.etaxonomy.cdm.model.description.
1543
 * CategoricalData
1544
 * CommonTaxonName
1545
 * Distribution
1546
 * IndividualsAssociation
1547
 * QuantitativeData
1548
 * TaxonInteraction
1549
 * TextData
1550
 */
1551
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1552
  static $types = array(
1553
    "CategoricalData",
1554
    "CommonTaxonName",
1555
    "Distribution",
1556
    "IndividualsAssociation",
1557
    "QuantitativeData",
1558
    "TaxonInteraction",
1559
    "TextData",
1560
  );
1561

    
1562
  static $options = NULL;
1563
  if ($options == NULL) {
1564
    $options = array();
1565
    if ($prependEmptyElement) {
1566
      $options[' '] = '';
1567
    }
1568
    foreach ($types as $type) {
1569
      // No internatianalization here since these are purely technical terms.
1570
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1571
    }
1572
  }
1573
  return $options;
1574
}
1575

    
1576

    
1577
/**
1578
 * Fetches all TaxonDescription descriptions elements which are associated to the
1579
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1580
 * feature tree.
1581
 * @param $feature_tree
1582
 *     The CDM FeatureTree to be used as template
1583
 * @param $taxon_uuid
1584
 *     The UUID of the taxon
1585
 * @param $excludes
1586
 *     UUIDs of features to be excluded
1587
 * @return$feature_tree
1588
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1589
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1590
 *     witch will hold the according $descriptionElements.
1591
 */
1592
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1593

    
1594
  if (!$feature_tree) {
1595
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1596
      In order to see the species profiles of your taxa, please select a
1597
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1598
    return FALSE;
1599
  }
1600

    
1601
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1602
      array(
1603
      'taxon' => $taxon_uuid,
1604
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1605
      ),
1606
      'POST'
1607
  );
1608

    
1609
  // Combine all descriptions into one feature tree.
1610
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1611
  $feature_tree->root->childNodes = $merged_nodes;
1612

    
1613
  return $feature_tree;
1614
}
1615

    
1616
/**
1617
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1618
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1619
 * be requested for the annotations.
1620
 *
1621
 * @param string $cdmBase
1622
 *   An annotatable cdm entity.
1623
 * @param array $includeTypes
1624
 *   If an array of annotation type uuids is supplied by this parameter the
1625
 *   list of annotations is resticted to those which belong to this type.
1626
 *
1627
 * @return array
1628
 *   An array of Annotation objects or an empty array.
1629
 */
1630
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1631

    
1632
  if(!isset($cdmBase->annotations)){
1633
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1634
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1635
  }
1636

    
1637
  $annotations = array();
1638
  foreach ($cdmBase->annotations as $annotation) {
1639
    if ($includeTypes) {
1640
      if (
1641
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1642
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1643
      ) {
1644
        $annotations[] = $annotation;
1645
      }
1646
    }
1647
    else {
1648
      $annotations[] = $annotation;
1649
    }
1650
  }
1651
  return $annotations;
1652

    
1653
}
1654

    
1655
/**
1656
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1657
 *
1658
 * @param object $annotatable_entity
1659
 *   The CDM AnnotatableEntity to load annotations for
1660
 */
1661
function cdm_load_annotations(&$annotatable_entity) {
1662
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1663
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1664
    if (is_array($annotations)) {
1665
      $annotatable_entity->annotations = $annotations;
1666
    }
1667
  }
1668
}
1669

    
1670
/**
1671
 * Extends the $cdm_entity object by the field if it is not already existing.
1672
 *
1673
 * This function can only be used for fields with 1 to many relations.
1674
  *
1675
 * @param $cdm_base_type
1676
 * @param $field_name
1677
 * @param $cdm_entity
1678
 */
1679
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1680
{
1681
  if (!isset($cdm_entity->$field_name)) {
1682
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1683
    $cdm_entity->$field_name = $items;
1684
  }
1685
}
1686

    
1687

    
1688
/**
1689
 * Get a NomenclaturalReference string.
1690
 *
1691
 * Returns the NomenclaturalReference string with correctly placed
1692
 * microreference (= reference detail) e.g.
1693
 * in Phytotaxa 43: 1-48. 2012.
1694
 *
1695
 * @param string $referenceUuid
1696
 *   UUID of the reference.
1697
 * @param string $microreference
1698
 *   Reference detail.
1699
 *
1700
 * @return string
1701
 *   a NomenclaturalReference.
1702
 */
1703
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1704

    
1705
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1706
  if(is_array($microreference) || is_object($microreference)) {
1707
    return '';
1708
  }
1709

    
1710
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1711
    $referenceUuid,
1712
  ), "microReference=" . urlencode($microreference));
1713

    
1714
  if ($obj) {
1715
    return $obj->String;
1716
  }
1717
  else {
1718
    return NULL;
1719
  }
1720
}
1721

    
1722
/**
1723
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1724
 *
1725
 * @param $feature_tree_nodes
1726
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1727
 * @param $feature_uuid
1728
 *    The UUID of the Feature
1729
 * @return returns the FeatureNode or null
1730
 */
1731
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1732

    
1733
  // 1. scan this level
1734
  foreach ($feature_tree_nodes as $node){
1735
    if($node->feature->uuid == $feature_uuid){
1736
      return $node;
1737
    }
1738
  }
1739

    
1740
  // 2. descend into childen
1741
  foreach ($feature_tree_nodes as $node){
1742
    if(is_array($node->childNodes)){
1743
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1744
      if($node) {
1745
        return $node;
1746
      }
1747
    }
1748
  }
1749
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1750
  return $null_var;
1751
}
1752

    
1753
/**
1754
 * Merges the given featureNodes structure with the descriptionElements.
1755
 *
1756
 * This method is used in preparation for rendering the descriptionElements.
1757
 * The descriptionElements which belong to a specific feature node are appended
1758
 * to a the feature node by creating a new field:
1759
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1760
 * The descriptionElements will be cleared in advance in order to allow reusing the
1761
 * same feature tree without the risk of mixing sets of description elements.
1762
 *
1763
 * which originally is not existing in the cdm.
1764
 *
1765
 *
1766
 *
1767
 * @param array $featureNodes
1768
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1769
 *    may have children.
1770
 * @param array $descriptionElements
1771
 *    An flat array of cdm DescriptionElements
1772
 * @return array
1773
 *    The $featureNodes structure enriched with the according $descriptionElements
1774
 */
1775
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1776

    
1777
  foreach ($featureNodes as &$node) {
1778
    // since the $featureNodes array is reused for each description
1779
    // it is necessary to clear the custom node fields in advance
1780
    if(isset($node->descriptionElements)){
1781
      unset($node->descriptionElements);
1782
    }
1783

    
1784
    // Append corresponding elements to an additional node field:
1785
    // $node->descriptionElements.
1786
    foreach ($descriptionElements as $element) {
1787
      if ($element->feature->uuid == $node->feature->uuid) {
1788
        if (!isset($node->descriptionElements)) {
1789
          $node->descriptionElements = array();
1790
        }
1791
        $node->descriptionElements[] = $element;
1792
      }
1793
    }
1794

    
1795
    // Recurse into node children.
1796
    if (isset($node->childNodes[0])) {
1797
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1798
      $node->childNodes = $mergedChildNodes;
1799
    }
1800

    
1801
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1802
      unset($node);
1803
    }
1804

    
1805
  }
1806

    
1807
  return $featureNodes;
1808
}
1809

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

    
1846
  static $cacheL1 = array();
1847

    
1848
  $data = NULL;
1849
  // store query string in $data and clear the query, $data will be set as HTTP request body
1850
  if($method == 'POST'){
1851
    $data = $query;
1852
    $query = NULL;
1853
  }
1854

    
1855
  // Transform the given uri path or pattern into a proper webservice uri.
1856
  if (!$absoluteURI) {
1857
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1858
  }
1859

    
1860
  // read request parameter 'cacheL2_refresh'
1861
  // which allows refreshing the level 2 cache
1862
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1863

    
1864
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1865
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1866

    
1867
  if($method == 'GET'){
1868
    $cache_key = $uri;
1869
  } else {
1870
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1871
    // crc32 is faster but creates much shorter hashes
1872
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1873
  }
1874

    
1875
  if (array_key_exists($cache_key, $cacheL1)) {
1876
    $cacheL1_obj = $cacheL1[$uri];
1877
  }
1878

    
1879
  $set_cacheL1 = FALSE;
1880
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1881
    $set_cacheL1 = TRUE;
1882
  }
1883

    
1884
  // Only cache cdm webservice URIs.
1885
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1886
  $cacheL2_entry = FALSE;
1887

    
1888
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1889
    // Try to get object from cacheL2.
1890
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1891
  }
1892

    
1893
  if (isset($cacheL1_obj)) {
1894
    //
1895
    // The object has been found in the L1 cache.
1896
    //
1897
    $obj = $cacheL1_obj;
1898
    if (cdm_debug_block_visible()) {
1899
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1900
    }
1901
  }
1902
  elseif ($cacheL2_entry) {
1903
    //
1904
    // The object has been found in the L2 cache.
1905
    //
1906
    $duration_parse_start = microtime(TRUE);
1907
    $obj = unserialize($cacheL2_entry->data);
1908
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1909

    
1910
    if (cdm_debug_block_visible()) {
1911
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1912
    }
1913
  }
1914
  else {
1915
    //
1916
    // Get the object from the webservice and cache it.
1917
    //
1918
    $duration_fetch_start = microtime(TRUE);
1919
    // Request data from webservice JSON or XML.
1920
    $response = cdm_http_request($uri, $method, $data);
1921
    $response_body = NULL;
1922
    if (isset($response->data)) {
1923
      $response_body = $response->data;
1924
    }
1925
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1926
    $duration_parse_start = microtime(TRUE);
1927

    
1928
    // Parse data and create object.
1929
    $obj = cdm_load_obj($response_body);
1930

    
1931
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1932

    
1933
    if (cdm_debug_block_visible()) {
1934
      if ($obj || $response_body == "[]") {
1935
        $status = 'valid';
1936
      }
1937
      else {
1938
        $status = 'invalid';
1939
      }
1940
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
1941
    }
1942
    if ($set_cacheL2) {
1943
      // Store the object in cache L2.
1944
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
1945
      // flag serialized is set properly in the cache table.
1946
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
1947
    }
1948
  }
1949
  if ($obj) {
1950
    // Store the object in cache L1.
1951
    if ($set_cacheL1) {
1952
      $cacheL1[$cache_key] = $obj;
1953
    }
1954
  }
1955
  return $obj;
1956
}
1957

    
1958
/**
1959
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
1960
 *
1961
 * The cdm_ws_debug block will display the debug information.
1962
 *
1963
 * @param $uri
1964
 *    The CDM REST URI to which the request has been send
1965
 * @param string $method
1966
 *    The HTTP request method, either 'GET' or 'POST'
1967
 * @param string $post_data
1968
 *    The datastring send with a post request
1969
 * @param $duration_fetch
1970
 *    The time in seconds it took to fetch the data from the web service
1971
 * @param $duration_parse
1972
 *    Time in seconds which was needed to parse the json response
1973
 * @param $datasize
1974
 *    Size of the data received from the server
1975
 * @param $status
1976
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
1977
 * @return bool
1978
 *    TRUE if adding the debug information was successful
1979
 */
1980
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
1981

    
1982
  static $initial_time = NULL;
1983
  if(!$initial_time) {
1984
    $initial_time = microtime(TRUE);
1985
  }
1986
  $time = microtime(TRUE) - $initial_time;
1987

    
1988
  // Decompose uri into path and query element.
1989
  $uri_parts = explode("?", $uri);
1990
  $query = array();
1991
  if (count($uri_parts) == 2) {
1992
    $path = $uri_parts[0];
1993
  }
1994
  else {
1995
    $path = $uri;
1996
  }
1997

    
1998
  if(strpos($uri, '?') > 0){
1999
    $json_uri = str_replace('?', '.json?', $uri);
2000
    $xml_uri = str_replace('?', '.xml?', $uri);
2001
  } else {
2002
    $json_uri = $uri . '.json';
2003
    $xml_uri = $json_uri . '.xml';
2004
  }
2005

    
2006
  // data links to make data accecsible as json and xml
2007
  $data_links = '';
2008
  if (_is_cdm_ws_uri($path)) {
2009

    
2010
    // see ./js/http-method-link.js
2011

    
2012
    if($method == 'GET'){
2013
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2014
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2015
      $data_links .= '<br/>';
2016
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2017
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2018
    } else {
2019
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2020
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2021
      $data_links .= '<br/>';
2022
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2023
    }
2024
  }
2025
  else {
2026
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2027
  }
2028

    
2029
  //
2030
  $data = array(
2031
      'ws_uri' => $uri,
2032
      'method' => $method,
2033
      'post_data' => $post_data,
2034
      'time' => sprintf('%3.3f', $time),
2035
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2036
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2037
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2038
      'status' => $status,
2039
      'data_links' => $data_links
2040
  );
2041
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2042
    $_SESSION['cdm']['ws_debug'] = array();
2043
  }
2044
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2045

    
2046
  // Mark this page as being uncacheable.
2047
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2048
  drupal_page_is_cacheable(FALSE);
2049

    
2050
  // Messages not set when DB connection fails.
2051
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2052
}
2053

    
2054
/**
2055
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2056
 * the visibility depends on whether
2057
 *  - the block is enabled
2058
 *  - the visibility restrictions in the block settings are satisfied
2059
 */
2060
function cdm_debug_block_visible() {
2061
  static $is_visible = null;
2062

    
2063
  if($is_visible === null){
2064
      $block = block_load('cdm_api', 'cdm_ws_debug');
2065
      $is_visible = isset($block->status) && $block->status == 1;
2066
      if($is_visible){
2067
        $blocks = array($block);
2068
        // Checks the page, user role, and user-specific visibilty settings.
2069
        block_block_list_alter($blocks);
2070
        $is_visible = count($blocks) > 0;
2071
      }
2072
  }
2073
  return $is_visible;
2074
}
2075

    
2076
/**
2077
 * @todo Please document this function.
2078
 * @see http://drupal.org/node/1354
2079
 */
2080
function cdm_load_obj($response_body) {
2081
  $obj = json_decode($response_body);
2082

    
2083
  if (!(is_object($obj) || is_array($obj))) {
2084
    ob_start();
2085
    $obj_dump = ob_get_contents();
2086
    ob_clean();
2087
    return FALSE;
2088
  }
2089

    
2090
  return $obj;
2091
}
2092

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

    
2131
  if (!$acceptLanguage) {
2132
    if (function_exists('apache_request_headers')) {
2133
      $headers = apache_request_headers();
2134
      if (isset($headers['Accept-Language'])) {
2135
        $acceptLanguage = $headers['Accept-Language'];
2136
      }
2137
    }
2138
  }
2139

    
2140
  if ($method != "GET" && $method != "POST") {
2141
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2142
  }
2143

    
2144
  if (_is_cdm_ws_uri($uri)) {
2145
    $header['Accept'] = 'application/json';
2146
    $header['Accept-Language'] = $acceptLanguage;
2147
    $header['Accept-Charset'] = 'UTF-8';
2148
  }
2149

    
2150
  if($method == "POST") {
2151
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2152
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2153
  }
2154

    
2155

    
2156
  cdm_dd($uri);
2157
  return drupal_http_request($uri, array(
2158
      'headers' => $header,
2159
      'method' => $method,
2160
      'data' => $data,
2161
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2162
      )
2163
   );
2164
}
2165

    
2166
/**
2167
 * Concatenates recursively the fields of all features contained in the given
2168
 * CDM FeatureTree root node.
2169
 *
2170
 * @param $rootNode
2171
 *     A CDM FeatureTree node
2172
 * @param
2173
 *     The character to be used as glue for concatenation, default is ', '
2174
 * @param $field_name
2175
 *     The field name of the CDM Features
2176
 * @param $excludes
2177
 *     Allows defining a set of values to be excluded. This refers to the values
2178
 *     in the field denoted by the $field_name parameter
2179
 *
2180
 */
2181
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2182
  $out = '';
2183

    
2184
  $pre_child_separator = $separator;
2185
  $post_child_separator = '';
2186

    
2187
  foreach ($root_node->childNodes as $feature_node) {
2188
    $out .= ($out ? $separator : '');
2189
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2190
      $out .= $feature_node->feature->$field_name;
2191
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2192
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2193
        if (strlen($childlabels)) {
2194
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2195
        }
2196
      }
2197
    }
2198
  }
2199
  return $out;
2200
}
2201

    
2202
/**
2203
 * Create a one-dimensional form options array.
2204
 *
2205
 * Creates an array of all features in the feature tree of feature nodes,
2206
 * the node labels are indented by $node_char and $childIndent depending on the
2207
 * hierachy level.
2208
 *
2209
 * @param - $rootNode
2210
 * @param - $node_char
2211
 * @param - $childIndentStr
2212
 * @param - $childIndent
2213
 *   ONLY USED INTERNALLY!
2214
 *
2215
 * @return array
2216
 *   A one dimensional Drupal form options array.
2217
 */
2218
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2219
  $options = array();
2220
  foreach ($rootNode->childNodes as $featureNode) {
2221
    $indent_prefix = '';
2222
    if ($childIndent) {
2223
      $indent_prefix = $childIndent . $node_char . " ";
2224
    }
2225
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2226
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2227
      // Foreach ($featureNode->childNodes as $childNode){
2228
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2229
      $options = array_merge_recursive($options, $childList);
2230
      // }
2231
    }
2232
  }
2233
  return $options;
2234
}
2235

    
2236
/**
2237
 * Returns an array with all available FeatureTrees and the representations of the selected
2238
 * FeatureTree as a detail view.
2239
 *
2240
 * @param boolean $add_default_feature_free
2241
 * @return array
2242
 *  associative array with following keys:
2243
 *  -options: Returns an array with all available Feature Trees
2244
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2245
 *
2246
 */
2247
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2248

    
2249
  $options = array();
2250
  $tree_representations = array();
2251
  $feature_trees = array();
2252

    
2253
  // Set tree that contains all features.
2254
  if ($add_default_feature_free) {
2255
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2256
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2257
  }
2258

    
2259
  // Get feature trees from database.
2260
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2261
  if (is_array($persited_trees)) {
2262
    $feature_trees = array_merge($feature_trees, $persited_trees);
2263
  }
2264

    
2265
  foreach ($feature_trees as $featureTree) {
2266

    
2267
    if(!is_object($featureTree)){
2268
      continue;
2269
    }
2270
    // Do not add the DEFAULT_FEATURETREE again,
2271
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2272
      $options[$featureTree->uuid] = $featureTree->titleCache;
2273
    }
2274

    
2275
    // Render the hierarchic tree structure
2276
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2277

    
2278
      // Render the hierarchic tree structure.
2279
      $treeDetails = '<div class="featuretree_structure">'
2280
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2281
        . '</div>';
2282

    
2283
      $form = array();
2284
      $form['featureTree-' .  $featureTree->uuid] = array(
2285
        '#type' => 'fieldset',
2286
        '#title' => 'Show details',
2287
        '#attributes' => array('class' => array('collapsible collapsed')),
2288
        // '#collapsible' => TRUE,
2289
        // '#collapsed' => TRUE,
2290
      );
2291
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2292
        '#markup' => $treeDetails,
2293
      );
2294

    
2295
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2296
    }
2297

    
2298
  } // END loop over feature trees
2299

    
2300
  // return $options;
2301
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2302
}
2303

    
2304
/**
2305
 * Provides the list of available classifications in form of an options array.
2306
 *
2307
 * The options array is suitable for drupal form API elements that allow multiple choices.
2308
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2309
 *
2310
 * The classifications are ordered alphabetically whereas the classification
2311
 * chosen as default will always appear on top of the array, followed by a
2312
 * blank line below.
2313
 *
2314
 * @param bool $add_none_option
2315
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2316
 *
2317
 * @return array
2318
 *   classifications in an array as options for a form element that allows multiple choices.
2319
 */
2320
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2321

    
2322
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2323

    
2324
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2325
  $default_classification_label = '';
2326

    
2327
  // add all classifications
2328
  $taxonomic_tree_options = array();
2329
  if ($add_none_option) {
2330
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2331
  }
2332
  if ($taxonTrees) {
2333
    foreach ($taxonTrees as $tree) {
2334
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2335
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2336
      } else {
2337
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2338
        $default_classification_label = $tree->titleCache;
2339
      }
2340
    }
2341
  }
2342
  // oder alphabetically the space
2343
  asort($taxonomic_tree_options);
2344

    
2345
  // now set the labels
2346
  //   for none
2347
  if ($add_none_option) {
2348
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2349
  }
2350

    
2351
  //   for default_classification
2352
  if (is_uuid($default_classification_uuid)) {
2353
    $taxonomic_tree_options[$default_classification_uuid] =
2354
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2355
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2356
  }
2357

    
2358
  return $taxonomic_tree_options;
2359
}
2360

    
2361
/**
2362
 * @todo Please document this function.
2363
 * @see http://drupal.org/node/1354
2364
 */
2365
function cdm_api_secref_cache_prefetch(&$secUuids) {
2366
  // Comment @WA: global variables should start with a single underscore
2367
  // followed by the module and another underscore.
2368
  global $_cdm_api_secref_cache;
2369
  if (!is_array($_cdm_api_secref_cache)) {
2370
    $_cdm_api_secref_cache = array();
2371
  }
2372
  $uniqueUuids = array_unique($secUuids);
2373
  $i = 0;
2374
  $param = '';
2375
  while ($i++ < count($uniqueUuids)) {
2376
    $param .= $secUuids[$i] . ',';
2377
    if (strlen($param) + 37 > 2000) {
2378
      _cdm_api_secref_cache_add($param);
2379
      $param = '';
2380
    }
2381
  }
2382
  if ($param) {
2383
    _cdm_api_secref_cache_add($param);
2384
  }
2385
}
2386

    
2387
/**
2388
 * @todo Please document this function.
2389
 * @see http://drupal.org/node/1354
2390
 */
2391
function cdm_api_secref_cache_get($secUuid) {
2392
  global $_cdm_api_secref_cache;
2393
  if (!is_array($_cdm_api_secref_cache)) {
2394
    $_cdm_api_secref_cache = array();
2395
  }
2396
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2397
    _cdm_api_secref_cache_add($secUuid);
2398
  }
2399
  return $_cdm_api_secref_cache[$secUuid];
2400
}
2401

    
2402
/**
2403
 * @todo Please document this function.
2404
 * @see http://drupal.org/node/1354
2405
 */
2406
function cdm_api_secref_cache_clear() {
2407
  global $_cdm_api_secref_cache;
2408
  $_cdm_api_secref_cache = array();
2409
}
2410

    
2411

    
2412
/**
2413
 * Validates if the given string is a uuid.
2414
 *
2415
 * @param string $str
2416
 *   The string to validate.
2417
 *
2418
 * return bool
2419
 *   TRUE if the string is a UUID.
2420
 */
2421
function is_uuid($str) {
2422
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2423
}
2424

    
2425
/**
2426
 * Checks if the given $object is a valid cdm entity.
2427
 *
2428
 * An object is considered a cdm entity if it has a string field $object->class
2429
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2430
 * The function is null save.
2431
 *
2432
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2433
 *
2434
 * @param mixed $object
2435
 *   The object to validate
2436
 *
2437
 * @return bool
2438
 *   True if the object is a cdm entity.
2439
 */
2440
function is_cdm_entity($object) {
2441
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2442
}
2443

    
2444
/**
2445
 * @todo Please document this function.
2446
 * @see http://drupal.org/node/1354
2447
 */
2448
function _cdm_api_secref_cache_add($secUuidsStr) {
2449
  global $_cdm_api_secref_cache;
2450
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2451
  // Batch fetching not jet reimplemented thus:
2452
  /*
2453
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2454
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2455
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2456
  */
2457
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2458
}
2459

    
2460
/**
2461
 * Checks if the given uri starts with a cdm webservice url.
2462
 *
2463
 * Checks if the uri starts with the cdm webservice url stored in the
2464
 * Drupal variable 'cdm_webservice_url'.
2465
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2466
 *
2467
 * @param string $uri
2468
 *   The URI to test.
2469
 *
2470
 * @return bool
2471
 *   True if the uri starts with a cdm webservice url.
2472
 */
2473
function _is_cdm_ws_uri($uri) {
2474
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2475
}
2476

    
2477
/**
2478
 * @todo Please document this function.
2479
 * @see http://drupal.org/node/1354
2480
 */
2481
function queryString($elements) {
2482
  $query = '';
2483
  foreach ($elements as $key => $value) {
2484
    if (is_array($value)) {
2485
      foreach ($value as $v) {
2486
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2487
      }
2488
    }
2489
    else {
2490
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2491
    }
2492
  }
2493
  return $query;
2494
}
2495

    
2496
/**
2497
 * Implementation of the magic method __clone to allow deep cloning of objects
2498
 * and arrays.
2499
 */
2500
function __clone() {
2501
  foreach ($this as $name => $value) {
2502
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2503
      $this->$name = clone($this->$name);
2504
    }
2505
  }
2506
}
2507

    
2508
/**
2509
 * Compares the given CDM Term instances by the  representationL10n.
2510
 *
2511
 * Can also be used with TermDTOs. To be used in usort()
2512
 *
2513
 * @see http://php.net/manual/en/function.usort.php
2514
 *
2515
 * @param $term1
2516
 *   The first CDM Term instance
2517
 * @param $term2
2518
 *   The second CDM Term instance
2519
 * @return int
2520
 *   The result of the comparison
2521
 */
2522
function compare_terms_by_representationL10n($term1, $term2) {
2523

    
2524
  if (!isset($term1->representation_L10n)) {
2525
    $term1->representationL10n = '';
2526
  }
2527
  if (!isset($term2->representation_L10n)) {
2528
    $term2->representationL10n = '';
2529
  }
2530

    
2531
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2532
}
2533

    
2534
function compare_terms_by_order_index($term1, $term2) {
2535

    
2536

    
2537
  if (!isset($term1->orderIndex)) {
2538
    $a = 0;
2539
  } else {
2540
    $a = $term1->orderIndex;
2541
  }
2542
  if (!isset($term2->orderIndex)) {
2543
    $b = 0;
2544
  } else {
2545
    $b = $term2->orderIndex;
2546
  }
2547

    
2548
  if ($a == $b) {
2549
    return 0;
2550
  }
2551
  return ($a < $b) ? -1 : 1;
2552

    
2553
}
2554

    
2555

    
2556
/**
2557
 * Make a 'deep copy' of an array.
2558
 *
2559
 * Make a complete deep copy of an array replacing
2560
 * references with deep copies until a certain depth is reached
2561
 * ($maxdepth) whereupon references are copied as-is...
2562
 *
2563
 * @see http://us3.php.net/manual/en/ref.array.php
2564
 *
2565
 * @param array $array
2566
 * @param array $copy passed by reference
2567
 * @param int $maxdepth
2568
 * @param int $depth
2569
 */
2570
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2571
  if ($depth > $maxdepth) {
2572
    $copy = $array;
2573
    return;
2574
  }
2575
  if (!is_array($copy)) {
2576
    $copy = array();
2577
  }
2578
  foreach ($array as $k => &$v) {
2579
    if (is_array($v)) {
2580
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2581
    }
2582
    else {
2583
      $copy[$k] = $v;
2584
    }
2585
  }
2586
}
2587

    
2588
/**
2589
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2590
 *
2591
 */
2592
function _add_js_ws_debug() {
2593

    
2594
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2595
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2596
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2597
    // use the developer versions of js libs
2598
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2599
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2600
  }
2601
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2602
    array(
2603
      'type' => 'file',
2604
      'weight' => JS_LIBRARY,
2605
      'cache' => TRUE)
2606
    );
2607

    
2608
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2609
    array(
2610
      'type' => 'file',
2611
      'weight' => JS_LIBRARY,
2612
      'cache' => TRUE)
2613
    );
2614
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2615
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2616

    
2617
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2618
    array(
2619
      'type' => 'file',
2620
      'weight' => JS_LIBRARY,
2621
      'cache' => TRUE)
2622
    );
2623
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2624
    array(
2625
    'type' => 'file',
2626
    'weight' => JS_LIBRARY,
2627
    'cache' => TRUE)
2628
    );
2629

    
2630
}
2631

    
2632
/**
2633
 * @todo Please document this function.
2634
 * @see http://drupal.org/node/1354
2635
 */
2636
function _no_classfication_uuid_message() {
2637
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2638
    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.');
2639
  }
2640
  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.');
2641
}
2642

    
2643
/**
2644
 * Implementation of hook flush_caches
2645
 *
2646
 * Add custom cache tables to the list of cache tables that
2647
 * will be cleared by the Clear button on the Performance page or whenever
2648
 * drupal_flush_all_caches is invoked.
2649
 *
2650
 * @author W.Addink <waddink@eti.uva.nl>
2651
 *
2652
 * @return array
2653
 *   An array with custom cache tables to include.
2654
 */
2655
function cdm_api_flush_caches() {
2656
  return array('cache_cdm_ws');
2657
}
2658

    
2659
/**
2660
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2661
 *
2662
 * @param $data
2663
 *   The variable to log to the drupal_debug.txt log file.
2664
 * @param $label
2665
 *   (optional) If set, a label to output before $data in the log file.
2666
 *
2667
 * @return
2668
 *   No return value if successful, FALSE if the log file could not be written
2669
 *   to.
2670
 *
2671
 * @see cdm_dataportal_init() where the log file is reset on each requests
2672
 * @see dd()
2673
 * @see http://drupal.org/node/314112
2674
 *
2675
 */
2676
function cdm_dd($data, $label = NULL) {
2677
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2678
    return dd($data, $label);
2679
  }
2680
}
2681

    
(5-5/11)