Project

General

Profile

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

    
504
  while (count($mimeTypes) > 0) {
505
    // getRepresentationByMimeType
506
    $mimeType = array_shift($mimeTypes);
507

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

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

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

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

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

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

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

    
675
  $y = NULL; $m = NULL; $d = NULL;
676

    
677
  if(strpos($format, 'YY') !== FALSE){
678
    $y = partialToYear($partial);
679
  }
680
  if(strpos($format, 'MM') !== FALSE){
681
    $m = partialToMonth($partial);
682
  }
683
  if(strpos($format, 'DD') !== FALSE){
684
    $d = partialToDay($partial);
685
  }
686

    
687
  $y = $y ? $y : '00';
688
  $m = $m ? $m : '00';
689
  $d = $d ? $d : '00';
690

    
691
  $date = '';
692

    
693
  if ($y == '00' && $stripZeros) {
694
    return;
695
  }
696
  else {
697
    $date = $y;
698
  }
699

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

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

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

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

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

    
795
  // (1)
796
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
797
  // according element of the $pathParameters array.
798
  static $helperArray = array();
799
  if (isset($pathParameters) && !is_array($pathParameters)) {
800
    $helperArray[0] = $pathParameters;
801
    $pathParameters = $helperArray;
802
  }
803

    
804
  $i = 0;
805
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
806
    if (count($pathParameters) <= $i) {
807
        drupal_set_message(
808
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
809
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
810
          'error');
811
      break;
812
    }
813
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
814
    ++$i;
815
  }
816

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

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

    
837
  $path = $uri_pattern;
838

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

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

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

    
869
  $post_data = null;
870

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

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

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

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

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

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

    
925
    $reponse_data = NULL;
926

    
927
    if (function_exists('compose_' . $hook)){
928
      // call compose hook
929

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

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

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

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

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

    
985

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

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

    
996
}
997

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

    
1012
  // Prevent from malicous tags.
1013
  $val = strip_tags($val);
1014

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

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

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

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

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

    
1071
    case 'Media':
1072
      $ws_base_uri = CDM_WS_MEDIA;
1073
      break;
1074

    
1075
    case 'Reference':
1076
      $ws_base_uri = CDM_WS_REFERENCE;
1077
      break;
1078

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

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

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

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

    
1131
  $query['pageNumber'] = $pageNumber;
1132
  $query['pageSize'] = $pageSize;
1133

    
1134
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1135
}
1136

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

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

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

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

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

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

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

    
1243
    $response = NULL;
1244

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

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

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

    
1278
  return $response;
1279
}
1280

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

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

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

    
1328
  return $response;
1329
}
1330

    
1331

    
1332
// =============================Terms and Vocabularies ========================================= //
1333

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

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

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

    
1399
  return $options;
1400
}
1401

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

    
1423
  static $vocabularyOptions = array();
1424

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

    
1432
    // apply the include filter
1433
    if($include_filter != null){
1434
      $included_terms = array();
1435

    
1436
      foreach ($terms as $term){
1437
        $include = true;
1438
        foreach ($include_filter as $field=>$regex){
1439
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1440
          if(!$include){
1441
            break;
1442
          }
1443
        }
1444
        if($include){
1445
          $included_terms[] = $term;
1446
        }
1447
      }
1448

    
1449
      $terms = $included_terms;
1450
    }
1451

    
1452
    // make options list
1453
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1454
  }
1455

    
1456
  $options = $vocabularyOptions[$vocabulary_uuid];
1457
  if($default_option !== FALSE){
1458
    array_unshift ($options, "");
1459
  }
1460
  return $options;
1461
}
1462

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

    
1524
/**
1525
 * @todo Please document this function.
1526
 * @see http://drupal.org/node/1354
1527
 */
1528
function cdm_rankVocabulary_as_option() {
1529
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, false);
1530
  return $options;
1531
}
1532

    
1533
/**
1534
 * @todo Please document this function.
1535
 * @see http://drupal.org/node/1354
1536
 */
1537
function _cdm_relationship_type_term_label_callback($term) {
1538
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1539
    return $term->representation_L10n_abbreviatedLabel . ' : '
1540
    . t('@term', array('@term' => $term->representation_L10n));
1541
  }
1542
else {
1543
    return t('@term', array('@term' => $term->representation_L10n));
1544
  }
1545
}
1546

    
1547
// ========================================================================================== //
1548
/**
1549
 * @todo Improve documentation of this function.
1550
 *
1551
 * eu.etaxonomy.cdm.model.description.
1552
 * CategoricalData
1553
 * CommonTaxonName
1554
 * Distribution
1555
 * IndividualsAssociation
1556
 * QuantitativeData
1557
 * TaxonInteraction
1558
 * TextData
1559
 */
1560
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1561
  static $types = array(
1562
    "CategoricalData",
1563
    "CommonTaxonName",
1564
    "Distribution",
1565
    "IndividualsAssociation",
1566
    "QuantitativeData",
1567
    "TaxonInteraction",
1568
    "TextData",
1569
  );
1570

    
1571
  static $options = NULL;
1572
  if ($options == NULL) {
1573
    $options = array();
1574
    if ($prependEmptyElement) {
1575
      $options[' '] = '';
1576
    }
1577
    foreach ($types as $type) {
1578
      // No internatianalization here since these are purely technical terms.
1579
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1580
    }
1581
  }
1582
  return $options;
1583
}
1584

    
1585

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

    
1603
  if (!$feature_tree) {
1604
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1605
      In order to see the species profiles of your taxa, please select a
1606
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1607
    return FALSE;
1608
  }
1609

    
1610
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1611
      array(
1612
      'taxon' => $taxon_uuid,
1613
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1614
      ),
1615
      'POST'
1616
  );
1617

    
1618
  // Combine all descriptions into one feature tree.
1619
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1620
  $feature_tree->root->childNodes = $merged_nodes;
1621

    
1622
  return $feature_tree;
1623
}
1624

    
1625
/**
1626
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1627
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1628
 * be requested for the annotations.
1629
 *
1630
 * @param string $cdmBase
1631
 *   An annotatable cdm entity.
1632
 * @param array $includeTypes
1633
 *   If an array of annotation type uuids is supplied by this parameter the
1634
 *   list of annotations is resticted to those which belong to this type.
1635
 *
1636
 * @return array
1637
 *   An array of Annotation objects or an empty array.
1638
 */
1639
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1640

    
1641
  if(!isset($cdmBase->annotations)){
1642
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1643
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1644
  }
1645

    
1646
  $annotations = array();
1647
  foreach ($cdmBase->annotations as $annotation) {
1648
    if ($includeTypes) {
1649
      if (
1650
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1651
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1652
      ) {
1653
        $annotations[] = $annotation;
1654
      }
1655
    }
1656
    else {
1657
      $annotations[] = $annotation;
1658
    }
1659
  }
1660
  return $annotations;
1661

    
1662
}
1663

    
1664
/**
1665
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1666
 *
1667
 * @param object $annotatable_entity
1668
 *   The CDM AnnotatableEntity to load annotations for
1669
 */
1670
function cdm_load_annotations(&$annotatable_entity) {
1671
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1672
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1673
    if (is_array($annotations)) {
1674
      $annotatable_entity->annotations = $annotations;
1675
    }
1676
  }
1677
}
1678

    
1679
/**
1680
 * Get a NomenclaturalReference string.
1681
 *
1682
 * Returns the NomenclaturalReference string with correctly placed
1683
 * microreference (= reference detail) e.g.
1684
 * in Phytotaxa 43: 1-48. 2012.
1685
 *
1686
 * @param string $referenceUuid
1687
 *   UUID of the reference.
1688
 * @param string $microreference
1689
 *   Reference detail.
1690
 *
1691
 * @return string
1692
 *   a NomenclaturalReference.
1693
 */
1694
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1695

    
1696
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1697
  if(is_array($microreference) || is_object($microreference)) {
1698
    return '';
1699
  }
1700

    
1701
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1702
    $referenceUuid,
1703
  ), "microReference=" . urlencode($microreference));
1704

    
1705
  if ($obj) {
1706
    return $obj->String;
1707
  }
1708
  else {
1709
    return NULL;
1710
  }
1711
}
1712

    
1713
/**
1714
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1715
 *
1716
 * @param $feature_tree_nodes
1717
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1718
 * @param $feature_uuid
1719
 *    The UUID of the Feature
1720
 * @return returns the FeatureNode or null
1721
 */
1722
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1723

    
1724
  // 1. scan this level
1725
  foreach ($feature_tree_nodes as $node){
1726
    if($node->feature->uuid == $feature_uuid){
1727
      return $node;
1728
    }
1729
  }
1730

    
1731
  // 2. descend into childen
1732
  foreach ($feature_tree_nodes as $node){
1733
    if(is_array($node->childNodes)){
1734
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1735
      if($node) {
1736
        return $node;
1737
      }
1738
    }
1739
  }
1740
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1741
  return $null_var;
1742
}
1743

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

    
1768
  foreach ($featureNodes as &$node) {
1769
    // since the $featureNodes array is reused for each description
1770
    // it is necessary to clear the custom node fields in advance
1771
    if(isset($node->descriptionElements)){
1772
      unset($node->descriptionElements);
1773
    }
1774

    
1775
    // Append corresponding elements to an additional node field:
1776
    // $node->descriptionElements.
1777
    foreach ($descriptionElements as $element) {
1778
      if ($element->feature->uuid == $node->feature->uuid) {
1779
        if (!isset($node->descriptionElements)) {
1780
          $node->descriptionElements = array();
1781
        }
1782
        $node->descriptionElements[] = $element;
1783
      }
1784
    }
1785

    
1786
    // Recurse into node children.
1787
    if (isset($node->childNodes[0])) {
1788
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1789
      $node->childNodes = $mergedChildNodes;
1790
    }
1791

    
1792
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1793
      unset($node);
1794
    }
1795

    
1796
  }
1797

    
1798
  return $featureNodes;
1799
}
1800

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

    
1837
  static $cacheL1 = array();
1838

    
1839
  $data = NULL;
1840
  // store query string in $data and clear the query, $data will be set as HTTP request body
1841
  if($method == 'POST'){
1842
    $data = $query;
1843
    $query = NULL;
1844
  }
1845

    
1846
  // Transform the given uri path or pattern into a proper webservice uri.
1847
  if (!$absoluteURI) {
1848
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1849
  }
1850

    
1851
  // read request parameter 'cacheL2_refresh'
1852
  // which allows refreshing the level 2 cache
1853
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1854

    
1855
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1856
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1857

    
1858
  if($method == 'GET'){
1859
    $cache_key = $uri;
1860
  } else {
1861
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1862
    // crc32 is faster but creates much shorter hashes
1863
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1864
  }
1865

    
1866
  if (array_key_exists($cache_key, $cacheL1)) {
1867
    $cacheL1_obj = $cacheL1[$uri];
1868
  }
1869

    
1870
  $set_cacheL1 = FALSE;
1871
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1872
    $set_cacheL1 = TRUE;
1873
  }
1874

    
1875
  // Only cache cdm webservice URIs.
1876
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1877
  $cacheL2_entry = FALSE;
1878

    
1879
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1880
    // Try to get object from cacheL2.
1881
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1882
  }
1883

    
1884
  if (isset($cacheL1_obj)) {
1885
    //
1886
    // The object has been found in the L1 cache.
1887
    //
1888
    $obj = $cacheL1_obj;
1889
    if (cdm_debug_block_visible()) {
1890
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1891
    }
1892
  }
1893
  elseif ($cacheL2_entry) {
1894
    //
1895
    // The object has been found in the L2 cache.
1896
    //
1897
    $duration_parse_start = microtime(TRUE);
1898
    $obj = unserialize($cacheL2_entry->data);
1899
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1900

    
1901
    if (cdm_debug_block_visible()) {
1902
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1903
    }
1904
  }
1905
  else {
1906
    //
1907
    // Get the object from the webservice and cache it.
1908
    //
1909
    $duration_fetch_start = microtime(TRUE);
1910
    // Request data from webservice JSON or XML.
1911
    $response = cdm_http_request($uri, $method, $data);
1912
    $response_body = NULL;
1913
    if (isset($response->data)) {
1914
      $response_body = $response->data;
1915
    }
1916
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
1917
    $duration_parse_start = microtime(TRUE);
1918

    
1919
    // Parse data and create object.
1920
    $obj = cdm_load_obj($response_body);
1921

    
1922
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1923

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

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

    
1973
  static $initial_time = NULL;
1974
  if(!$initial_time) {
1975
    $initial_time = microtime(TRUE);
1976
  }
1977
  $time = microtime(TRUE) - $initial_time;
1978

    
1979
  // Decompose uri into path and query element.
1980
  $uri_parts = explode("?", $uri);
1981
  $query = array();
1982
  if (count($uri_parts) == 2) {
1983
    $path = $uri_parts[0];
1984
  }
1985
  else {
1986
    $path = $uri;
1987
  }
1988

    
1989
  if(strpos($uri, '?') > 0){
1990
    $json_uri = str_replace('?', '.json?', $uri);
1991
    $xml_uri = str_replace('?', '.xml?', $uri);
1992
  } else {
1993
    $json_uri = $uri . '.json';
1994
    $xml_uri = $json_uri . '.xml';
1995
  }
1996

    
1997
  // data links to make data accecsible as json and xml
1998
  $data_links = '';
1999
  if (_is_cdm_ws_uri($path)) {
2000

    
2001
    // see ./js/http-method-link.js
2002

    
2003
    if($method == 'GET'){
2004
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2005
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2006
      $data_links .= '<br/>';
2007
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2008
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2009
    } else {
2010
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2011
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2012
      $data_links .= '<br/>';
2013
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2014
    }
2015
  }
2016
  else {
2017
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2018
  }
2019

    
2020
  //
2021
  $data = array(
2022
      'ws_uri' => $uri,
2023
      'method' => $method,
2024
      'post_data' => $post_data,
2025
      'time' => sprintf('%3.3f', $time),
2026
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2027
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2028
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2029
      'status' => $status,
2030
      'data_links' => $data_links
2031
  );
2032
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2033
    $_SESSION['cdm']['ws_debug'] = array();
2034
  }
2035
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2036

    
2037
  // Mark this page as being uncacheable.
2038
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2039
  drupal_page_is_cacheable(FALSE);
2040

    
2041
  // Messages not set when DB connection fails.
2042
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2043
}
2044

    
2045
/**
2046
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2047
 * the visibility depends on whether
2048
 *  - the block is enabled
2049
 *  - the visibility restrictions in the block settings are satisfied
2050
 */
2051
function cdm_debug_block_visible() {
2052
  static $is_visible = null;
2053

    
2054
  if($is_visible === null){
2055
      $block = block_load('cdm_api', 'cdm_ws_debug');
2056
      $is_visible = isset($block->status) && $block->status == 1;
2057
      if($is_visible){
2058
        $blocks = array($block);
2059
        // Checks the page, user role, and user-specific visibilty settings.
2060
        block_block_list_alter($blocks);
2061
        $is_visible = count($blocks) > 0;
2062
      }
2063
  }
2064
  return $is_visible;
2065
}
2066

    
2067
/**
2068
 * @todo Please document this function.
2069
 * @see http://drupal.org/node/1354
2070
 */
2071
function cdm_load_obj($response_body) {
2072
  $obj = json_decode($response_body);
2073

    
2074
  if (!(is_object($obj) || is_array($obj))) {
2075
    ob_start();
2076
    $obj_dump = ob_get_contents();
2077
    ob_clean();
2078
    return FALSE;
2079
  }
2080

    
2081
  return $obj;
2082
}
2083

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

    
2122
  if (!$acceptLanguage) {
2123
    if (function_exists('apache_request_headers')) {
2124
      $headers = apache_request_headers();
2125
      if (isset($headers['Accept-Language'])) {
2126
        $acceptLanguage = $headers['Accept-Language'];
2127
      }
2128
    }
2129
  }
2130

    
2131
  if ($method != "GET" && $method != "POST") {
2132
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2133
  }
2134

    
2135
  if (_is_cdm_ws_uri($uri)) {
2136
    $header['Accept'] = 'application/json';
2137
    $header['Accept-Language'] = $acceptLanguage;
2138
    $header['Accept-Charset'] = 'UTF-8';
2139
  }
2140

    
2141
  if($method == "POST") {
2142
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2143
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2144
  }
2145

    
2146

    
2147
  cdm_dd($uri);
2148
  return drupal_http_request($uri, array(
2149
      'headers' => $header,
2150
      'method' => $method,
2151
      'data' => $data,
2152
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2153
      )
2154
   );
2155
}
2156

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

    
2175
  $pre_child_separator = $separator;
2176
  $post_child_separator = '';
2177

    
2178
  foreach ($root_node->childNodes as $feature_node) {
2179
    $out .= ($out ? $separator : '');
2180
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2181
      $out .= $feature_node->feature->$field_name;
2182
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2183
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2184
        if (strlen($childlabels)) {
2185
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2186
        }
2187
      }
2188
    }
2189
  }
2190
  return $out;
2191
}
2192

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

    
2227
/**
2228
 * Returns an array with all available FeatureTrees and the representations of the selected
2229
 * FeatureTree as a detail view.
2230
 *
2231
 * @param boolean $add_default_feature_free
2232
 * @return array
2233
 *  associative array with following keys:
2234
 *  -options: Returns an array with all available Feature Trees
2235
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2236
 *
2237
 */
2238
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2239

    
2240
  $options = array();
2241
  $tree_representations = array();
2242
  $feature_trees = array();
2243

    
2244
  // Set tree that contains all features.
2245
  if ($add_default_feature_free) {
2246
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2247
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2248
  }
2249

    
2250
  // Get feature trees from database.
2251
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2252
  if (is_array($persited_trees)) {
2253
    $feature_trees = array_merge($feature_trees, $persited_trees);
2254
  }
2255

    
2256
  foreach ($feature_trees as $featureTree) {
2257

    
2258
    if(!is_object($featureTree)){
2259
      continue;
2260
    }
2261
    // Do not add the DEFAULT_FEATURETREE again,
2262
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2263
      $options[$featureTree->uuid] = $featureTree->titleCache;
2264
    }
2265

    
2266
    // Render the hierarchic tree structure
2267
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2268

    
2269
      // Render the hierarchic tree structure.
2270
      $treeDetails = '<div class="featuretree_structure">'
2271
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2272
        . '</div>';
2273

    
2274
      $form = array();
2275
      $form['featureTree-' .  $featureTree->uuid] = array(
2276
        '#type' => 'fieldset',
2277
        '#title' => 'Show details',
2278
        '#attributes' => array('class' => array('collapsible collapsed')),
2279
        // '#collapsible' => TRUE,
2280
        // '#collapsed' => TRUE,
2281
      );
2282
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2283
        '#markup' => $treeDetails,
2284
      );
2285

    
2286
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2287
    }
2288

    
2289
  } // END loop over feature trees
2290

    
2291
  // return $options;
2292
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2293
}
2294

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

    
2313
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2314

    
2315
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2316
  $default_classification_label = '';
2317

    
2318
  // add all classifications
2319
  $taxonomic_tree_options = array();
2320
  if ($add_none_option) {
2321
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2322
  }
2323
  if ($taxonTrees) {
2324
    foreach ($taxonTrees as $tree) {
2325
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2326
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2327
      } else {
2328
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2329
        $default_classification_label = $tree->titleCache;
2330
      }
2331
    }
2332
  }
2333
  // oder alphabetically the space
2334
  asort($taxonomic_tree_options);
2335

    
2336
  // now set the labels
2337
  //   for none
2338
  if ($add_none_option) {
2339
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2340
  }
2341

    
2342
  //   for default_classification
2343
  if (is_uuid($default_classification_uuid)) {
2344
    $taxonomic_tree_options[$default_classification_uuid] =
2345
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2346
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2347
  }
2348

    
2349
  return $taxonomic_tree_options;
2350
}
2351

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

    
2378
/**
2379
 * @todo Please document this function.
2380
 * @see http://drupal.org/node/1354
2381
 */
2382
function cdm_api_secref_cache_get($secUuid) {
2383
  global $_cdm_api_secref_cache;
2384
  if (!is_array($_cdm_api_secref_cache)) {
2385
    $_cdm_api_secref_cache = array();
2386
  }
2387
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2388
    _cdm_api_secref_cache_add($secUuid);
2389
  }
2390
  return $_cdm_api_secref_cache[$secUuid];
2391
}
2392

    
2393
/**
2394
 * @todo Please document this function.
2395
 * @see http://drupal.org/node/1354
2396
 */
2397
function cdm_api_secref_cache_clear() {
2398
  global $_cdm_api_secref_cache;
2399
  $_cdm_api_secref_cache = array();
2400
}
2401

    
2402

    
2403
/**
2404
 * Validates if the given string is a uuid.
2405
 *
2406
 * @param string $str
2407
 *   The string to validate.
2408
 *
2409
 * return bool
2410
 *   TRUE if the string is a UUID.
2411
 */
2412
function is_uuid($str) {
2413
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2414
}
2415

    
2416
/**
2417
 * Checks if the given $object is a valid cdm entity.
2418
 *
2419
 * An object is considered a cdm entity if it has a string field $object->class
2420
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2421
 * The function is null save.
2422
 *
2423
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2424
 *
2425
 * @param mixed $object
2426
 *   The object to validate
2427
 *
2428
 * @return bool
2429
 *   True if the object is a cdm entity.
2430
 */
2431
function is_cdm_entity($object) {
2432
  return isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && is_string($object->uuid) && is_uuid($object->uuid);
2433
}
2434

    
2435
/**
2436
 * @todo Please document this function.
2437
 * @see http://drupal.org/node/1354
2438
 */
2439
function _cdm_api_secref_cache_add($secUuidsStr) {
2440
  global $_cdm_api_secref_cache;
2441
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2442
  // Batch fetching not jet reimplemented thus:
2443
  /*
2444
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2445
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2446
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2447
  */
2448
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2449
}
2450

    
2451
/**
2452
 * Checks if the given uri starts with a cdm webservice url.
2453
 *
2454
 * Checks if the uri starts with the cdm webservice url stored in the
2455
 * Drupal variable 'cdm_webservice_url'.
2456
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2457
 *
2458
 * @param string $uri
2459
 *   The URI to test.
2460
 *
2461
 * @return bool
2462
 *   True if the uri starts with a cdm webservice url.
2463
 */
2464
function _is_cdm_ws_uri($uri) {
2465
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2466
}
2467

    
2468
/**
2469
 * @todo Please document this function.
2470
 * @see http://drupal.org/node/1354
2471
 */
2472
function queryString($elements) {
2473
  $query = '';
2474
  foreach ($elements as $key => $value) {
2475
    if (is_array($value)) {
2476
      foreach ($value as $v) {
2477
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2478
      }
2479
    }
2480
    else {
2481
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2482
    }
2483
  }
2484
  return $query;
2485
}
2486

    
2487
/**
2488
 * Implementation of the magic method __clone to allow deep cloning of objects
2489
 * and arrays.
2490
 */
2491
function __clone() {
2492
  foreach ($this as $name => $value) {
2493
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2494
      $this->$name = clone($this->$name);
2495
    }
2496
  }
2497
}
2498

    
2499
/**
2500
 * Compares the given CDM Term instances by the  representationL10n.
2501
 *
2502
 * Can also be used with TermDTOs. To be used in usort()
2503
 *
2504
 * @see http://php.net/manual/en/function.usort.php
2505
 *
2506
 * @param $term1
2507
 *   The first CDM Term instance
2508
 * @param $term2
2509
 *   The second CDM Term instance
2510
 * @return int
2511
 *   The result of the comparison
2512
 */
2513
function compare_terms_by_representationL10n($term1, $term2) {
2514

    
2515
  if (!isset($term1->representation_L10n)) {
2516
    $term1->representationL10n = '';
2517
  }
2518
  if (!isset($term2->representation_L10n)) {
2519
    $term2->representationL10n = '';
2520
  }
2521

    
2522
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2523
}
2524

    
2525
function compare_terms_by_order_index($term1, $term2) {
2526

    
2527

    
2528
  if (!isset($term1->orderIndex)) {
2529
    $a = 0;
2530
  } else {
2531
    $a = $term1->orderIndex;
2532
  }
2533
  if (!isset($term2->orderIndex)) {
2534
    $b = 0;
2535
  } else {
2536
    $b = $term2->orderIndex;
2537
  }
2538

    
2539
  if ($a == $b) {
2540
    return 0;
2541
  }
2542
  return ($a < $b) ? -1 : 1;
2543

    
2544
}
2545

    
2546

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

    
2579
/**
2580
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2581
 *
2582
 */
2583
function _add_js_ws_debug() {
2584

    
2585
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2586
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2587
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2588
    // use the developer versions of js libs
2589
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2590
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2591
  }
2592
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2593
    array(
2594
      'type' => 'file',
2595
      'weight' => JS_LIBRARY,
2596
      'cache' => TRUE)
2597
    );
2598

    
2599
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2600
    array(
2601
      'type' => 'file',
2602
      'weight' => JS_LIBRARY,
2603
      'cache' => TRUE)
2604
    );
2605
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2606
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2607

    
2608
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2609
    array(
2610
      'type' => 'file',
2611
      'weight' => JS_LIBRARY,
2612
      'cache' => TRUE)
2613
    );
2614
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2615
    array(
2616
    'type' => 'file',
2617
    'weight' => JS_LIBRARY,
2618
    'cache' => TRUE)
2619
    );
2620

    
2621
}
2622

    
2623
/**
2624
 * @todo Please document this function.
2625
 * @see http://drupal.org/node/1354
2626
 */
2627
function _no_classfication_uuid_message() {
2628
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2629
    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.');
2630
  }
2631
  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.');
2632
}
2633

    
2634
/**
2635
 * Implementation of hook flush_caches
2636
 *
2637
 * Add custom cache tables to the list of cache tables that
2638
 * will be cleared by the Clear button on the Performance page or whenever
2639
 * drupal_flush_all_caches is invoked.
2640
 *
2641
 * @author W.Addink <waddink@eti.uva.nl>
2642
 *
2643
 * @return array
2644
 *   An array with custom cache tables to include.
2645
 */
2646
function cdm_api_flush_caches() {
2647
  return array('cache_cdm_ws');
2648
}
2649

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

    
(5-5/11)