Project

General

Profile

Download (79.9 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'] = array(
167
      '#markup' => '<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
      '#attached' => array(
175
        'css' => array(
176
          drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_ws_debug.css'
177
        )
178
      )
179
    );
180
    return $block;
181
  }
182
}
183

    
184
/**
185
 * Implements hook_cron().
186
 *
187
 * Expire outdated cache entries.
188
 */
189
function cdm_api_cron() {
190
  cache_clear_all(NULL, 'cache_cdm_ws');
191
}
192

    
193
// ===================== Tagged Text functions ================== //
194

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

    
226

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

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

    
267
  if (is_array($taggedTextList)) {
268

    
269
    // First pass: rename.
270
    for ($i = 0; $i < count($taggedTextList); $i++) {
271

    
272
      if ($taggedTextList[$i]->type == "hybridSign") {
273
        $taggedTextList[$i]->type = "name";
274
      }
275
    }
276

    
277
    // Second pass: resolve separators.
278
    $taggedNameListNew = array();
279
    for ($i = 0; $i < count($taggedTextList); $i++) {
280

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

    
293
    }
294
    $taggedTextList = $taggedNameListNew;
295
  }
296
}
297

    
298
function split_secref_from_tagged_text(&$tagged_text) {
299

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

    
320

    
321
function split_nomstatus_from_tagged_text(&$tagged_text) {
322

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

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

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

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

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

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

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

    
396
  return $profile_featureTree;
397
}
398

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

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

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

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

    
454

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

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

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

    
492
  while (count($mimeTypes) > 0) {
493
    // getRepresentationByMimeType
494
    $mimeType = array_shift($mimeTypes);
495

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

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

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

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

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

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

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

    
671
  $y = NULL; $m = NULL; $d = NULL;
672

    
673
  if(strpos($format, 'YY') !== FALSE){
674
    $y = partialToYear($partial);
675
  }
676
  if(strpos($format, 'MM') !== FALSE){
677
    $m = partialToMonth($partial);
678
  }
679
  if(strpos($format, 'DD') !== FALSE){
680
    $d = partialToDay($partial);
681
  }
682

    
683
  $y = $y ? $y : '00';
684
  $m = $m ? $m : '00';
685
  $d = $d ? $d : '00';
686

    
687
  $date = '';
688

    
689
  if ($y == '00' && $stripZeros) {
690
    return '';
691
  }
692
  else {
693
    $date = $y;
694
  }
695

    
696
  if ($m == '00' && $stripZeros) {
697
    return $date;
698
  }
699
  else {
700
    $date .= "-" . $m;
701
  }
702

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

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

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

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

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

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

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

    
827
  // (3)
828
  // Append the query string supplied by $query.
829
  if (isset($query)) {
830
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
831
  }
832

    
833
  $path = $uri_pattern;
834

    
835
  $uri = variable_get('cdm_webservice_url', '') . $path;
836
  return $uri;
837
}
838

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

    
858
  $args = func_get_args();
859
  $do_gzip = function_exists('gzencode');
860
  $uriEncoded = array_shift($args);
861
  $uri = urldecode($uriEncoded);
862
  $hook = array_shift($args);
863
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
864

    
865
  $post_data = null;
866

    
867
  if ($request_method == "POST" || $request_method == "PUT") {
868
    // read response body via inputstream module
869
    $post_data = file_get_contents("php://input");
870
  }
871

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

    
881
  // In all these cases perform a simple get request.
882
  // TODO reconsider caching logic in this function.
883

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

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

    
916
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
917
    } else {
918
      $obj = NULL;
919
    }
920

    
921
    $reponse_data = NULL;
922

    
923
    if (function_exists('compose_' . $hook)){
924
      // call compose hook
925

    
926
      $elements =  call_user_func('compose_' . $hook, $obj);
927
      // pass the render array to drupal_render()
928
      $reponse_data = drupal_render($elements);
929
    } else {
930
      // call theme hook
931

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

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

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

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

    
981

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

    
989
    print $reponse_data;
990
  } // END of handle $hook either as compose ot theme hook
991

    
992
}
993

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

    
1008
  // Prevent from malicous tags.
1009
  $val = strip_tags($val);
1010

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

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

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

    
1049
  $ws_base_uri = NULL;
1050
  switch ($cdmBase->class) {
1051
    case 'TaxonBase':
1052
    case 'Taxon':
1053
    case 'Synonym':
1054
      $ws_base_uri = CDM_WS_TAXON;
1055
      break;
1056

    
1057
    case 'TaxonNameBase':
1058
    case 'NonViralName':
1059
    case 'BacterialName':
1060
    case 'BotanicalName':
1061
    case 'CultivarPlantName':
1062
    case 'ZoologicalName':
1063
    case 'ViralName':
1064
      $ws_base_uri = CDM_WS_NAME;
1065
      break;
1066

    
1067
    case 'Media':
1068
      $ws_base_uri = CDM_WS_MEDIA;
1069
      break;
1070

    
1071
    case 'Reference':
1072
      $ws_base_uri = CDM_WS_REFERENCE;
1073
      break;
1074

    
1075
    case 'Distribution':
1076
    case 'TextData':
1077
    case 'TaxonInteraction':
1078
    case 'QuantitativeData':
1079
    case 'IndividualsAssociation':
1080
    case 'Distribution':
1081
    case 'CommonTaxonName':
1082
    case 'CategoricalData':
1083
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1084
      break;
1085

    
1086
    case 'PolytomousKey':
1087
    case 'MediaKey':
1088
    case 'MultiAccessKey':
1089
      $ws_base_uri = $cdmBase->class;
1090
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1091
      break;
1092

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

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

    
1127
  $query['pageNumber'] = $pageNumber;
1128
  $query['pageSize'] = $pageSize;
1129

    
1130
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1131
}
1132

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

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

    
1170
/*
1171
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1172
  $viewrank = _cdm_taxonomy_compose_viewrank();
1173
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1174
  ? '/' . $path : '') ;
1175
}
1176
*/
1177

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

    
1191
  $view_uuid = get_current_classification_uuid();
1192
  $rank_uuid = NULL;
1193
  if (!$ignore_rank_limit) {
1194
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1195
  }
1196

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

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

    
1239
    $response = NULL;
1240

    
1241
    // 1st try
1242
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1243

    
1244
    if ($response == NULL) {
1245
      // 2dn try by ignoring the rank limit
1246
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1247
    }
1248

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

    
1274
  return $response;
1275
}
1276

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

    
1292
  $response = NULL;
1293
  if (is_uuid($rank_uuid)) {
1294
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1295
      $view_uuid,
1296
      $taxon_uuid,
1297
      $rank_uuid,
1298
    ));
1299
  }
1300
  else {
1301
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1302
      $view_uuid,
1303
      $taxon_uuid,
1304
    ));
1305
  }
1306

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

    
1324
  return $response;
1325
}
1326

    
1327

    
1328
// =============================Terms and Vocabularies ========================================= //
1329

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

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

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

    
1395
  return $options;
1396
}
1397

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

    
1419
  static $vocabularyOptions = array();
1420

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

    
1428
    // apply the include filter
1429
    if($include_filter != null){
1430
      $included_terms = array();
1431

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

    
1445
      $terms = $included_terms;
1446
    }
1447

    
1448
    // make options list
1449
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1450
  }
1451

    
1452
  $options = $vocabularyOptions[$vocabulary_uuid];
1453
  if($default_option !== FALSE){
1454
    array_unshift ($options, "");
1455
  }
1456
  return $options;
1457
}
1458

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

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

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

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

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

    
1581

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

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

    
1606
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1607
      array(
1608
      'taxon' => $taxon_uuid,
1609
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1610
      ),
1611
      'POST'
1612
  );
1613

    
1614
  // Combine all descriptions into one feature tree.
1615
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1616
  $feature_tree->root->childNodes = $merged_nodes;
1617

    
1618
  return $feature_tree;
1619
}
1620

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

    
1637
  if(!isset($cdmBase->annotations)){
1638
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1639
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1640
  }
1641

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

    
1658
}
1659

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

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

    
1692

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

    
1710
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1711
  if(is_array($microreference) || is_object($microreference)) {
1712
    return '';
1713
  }
1714

    
1715
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1716
    $referenceUuid,
1717
  ), "microReference=" . urlencode($microreference));
1718

    
1719
  if ($obj) {
1720
    return $obj->String;
1721
  }
1722
  else {
1723
    return NULL;
1724
  }
1725
}
1726

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

    
1738
  // 1. scan this level
1739
  foreach ($feature_tree_nodes as $node){
1740
    if($node->feature->uuid == $feature_uuid){
1741
      return $node;
1742
    }
1743
  }
1744

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

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

    
1782
  foreach ($featureNodes as &$node) {
1783
    // since the $featureNodes array is reused for each description
1784
    // it is necessary to clear the custom node fields in advance
1785
    if(isset($node->descriptionElements)){
1786
      unset($node->descriptionElements);
1787
    }
1788

    
1789
    // Append corresponding elements to an additional node field:
1790
    // $node->descriptionElements.
1791
    foreach ($descriptionElements as $element) {
1792
      if ($element->feature->uuid == $node->feature->uuid) {
1793
        if (!isset($node->descriptionElements)) {
1794
          $node->descriptionElements = array();
1795
        }
1796
        $node->descriptionElements[] = $element;
1797
      }
1798
    }
1799

    
1800
    // Recurse into node children.
1801
    if (isset($node->childNodes[0])) {
1802
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1803
      $node->childNodes = $mergedChildNodes;
1804
    }
1805

    
1806
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1807
      unset($node);
1808
    }
1809

    
1810
  }
1811

    
1812
  return $featureNodes;
1813
}
1814

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

    
1851
  static $cacheL1 = array();
1852

    
1853
  $data = NULL;
1854
  // store query string in $data and clear the query, $data will be set as HTTP request body
1855
  if($method == 'POST'){
1856
    $data = $query;
1857
    $query = NULL;
1858
  }
1859

    
1860
  // Transform the given uri path or pattern into a proper webservice uri.
1861
  if (!$absoluteURI) {
1862
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1863
  }
1864

    
1865
  // read request parameter 'cacheL2_refresh'
1866
  // which allows refreshing the level 2 cache
1867
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1868

    
1869
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1870
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1871

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

    
1880
  if (array_key_exists($cache_key, $cacheL1)) {
1881
    $cacheL1_obj = $cacheL1[$uri];
1882
  }
1883

    
1884
  $set_cacheL1 = FALSE;
1885
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1886
    $set_cacheL1 = TRUE;
1887
  }
1888

    
1889
  // Only cache cdm webservice URIs.
1890
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1891
  $cacheL2_entry = FALSE;
1892

    
1893
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1894
    // Try to get object from cacheL2.
1895
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1896
  }
1897

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

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

    
1933
    // Parse data and create object.
1934
    $obj = cdm_load_obj($response_body);
1935

    
1936
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1937

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

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

    
1987
  static $initial_time = NULL;
1988
  if(!$initial_time) {
1989
    $initial_time = microtime(TRUE);
1990
  }
1991
  $time = microtime(TRUE) - $initial_time;
1992

    
1993
  // Decompose uri into path and query element.
1994
  $uri_parts = explode("?", $uri);
1995
  $query = array();
1996
  if (count($uri_parts) == 2) {
1997
    $path = $uri_parts[0];
1998
  }
1999
  else {
2000
    $path = $uri;
2001
  }
2002

    
2003
  if(strpos($uri, '?') > 0){
2004
    $json_uri = str_replace('?', '.json?', $uri);
2005
    $xml_uri = str_replace('?', '.xml?', $uri);
2006
  } else {
2007
    $json_uri = $uri . '.json';
2008
    $xml_uri = $json_uri . '.xml';
2009
  }
2010

    
2011
  // data links to make data accecsible as json and xml
2012
  $data_links = '';
2013
  if (_is_cdm_ws_uri($path)) {
2014

    
2015
    // see ./js/http-method-link.js
2016

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

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

    
2051
  // Mark this page as being uncacheable.
2052
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2053
  drupal_page_is_cacheable(FALSE);
2054

    
2055
  // Messages not set when DB connection fails.
2056
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2057
}
2058

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

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

    
2081
/**
2082
 * @todo Please document this function.
2083
 * @see http://drupal.org/node/1354
2084
 */
2085
function cdm_load_obj($response_body) {
2086
  $obj = json_decode($response_body);
2087

    
2088
  if (!(is_object($obj) || is_array($obj))) {
2089
    ob_start();
2090
    $obj_dump = ob_get_contents();
2091
    ob_clean();
2092
    return FALSE;
2093
  }
2094

    
2095
  return $obj;
2096
}
2097

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

    
2136
  if (!$acceptLanguage) {
2137
    if (function_exists('apache_request_headers')) {
2138
      $headers = apache_request_headers();
2139
      if (isset($headers['Accept-Language'])) {
2140
        $acceptLanguage = $headers['Accept-Language'];
2141
      }
2142
    }
2143
  }
2144

    
2145
  if ($method != "GET" && $method != "POST") {
2146
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2147
  }
2148

    
2149
  if (_is_cdm_ws_uri($uri)) {
2150
    $header['Accept'] = 'application/json';
2151
    $header['Accept-Language'] = $acceptLanguage;
2152
    $header['Accept-Charset'] = 'UTF-8';
2153
  }
2154

    
2155
  if($method == "POST") {
2156
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2157
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2158
  }
2159

    
2160

    
2161
  cdm_dd($uri);
2162
  return drupal_http_request($uri, array(
2163
      'headers' => $header,
2164
      'method' => $method,
2165
      'data' => $data,
2166
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2167
      )
2168
   );
2169
}
2170

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

    
2189
  $pre_child_separator = $separator;
2190
  $post_child_separator = '';
2191

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

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

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

    
2254
  $options = array();
2255
  $tree_representations = array();
2256
  $feature_trees = array();
2257

    
2258
  // Set tree that contains all features.
2259
  if ($add_default_feature_free) {
2260
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2261
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2262
  }
2263

    
2264
  // Get feature trees from database.
2265
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2266
  if (is_array($persited_trees)) {
2267
    $feature_trees = array_merge($feature_trees, $persited_trees);
2268
  }
2269

    
2270
  foreach ($feature_trees as $featureTree) {
2271

    
2272
    if(!is_object($featureTree)){
2273
      continue;
2274
    }
2275
    // Do not add the DEFAULT_FEATURETREE again,
2276
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2277
      $options[$featureTree->uuid] = $featureTree->titleCache;
2278
    }
2279

    
2280
    // Render the hierarchic tree structure
2281
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2282

    
2283
      // Render the hierarchic tree structure.
2284
      $treeDetails = '<div class="featuretree_structure">'
2285
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2286
        . '</div>';
2287

    
2288
      $form = array();
2289
      $form['featureTree-' .  $featureTree->uuid] = array(
2290
        '#type' => 'fieldset',
2291
        '#title' => 'Show details',
2292
        '#attributes' => array('class' => array('collapsible collapsed')),
2293
        // '#collapsible' => TRUE,
2294
        // '#collapsed' => TRUE,
2295
      );
2296
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2297
        '#markup' => $treeDetails,
2298
      );
2299

    
2300
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2301
    }
2302

    
2303
  } // END loop over feature trees
2304

    
2305
  // return $options;
2306
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2307
}
2308

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

    
2327
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2328

    
2329
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2330
  $default_classification_label = '';
2331

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

    
2350
  // now set the labels
2351
  //   for none
2352
  if ($add_none_option) {
2353
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2354
  }
2355

    
2356
  //   for default_classification
2357
  if (is_uuid($default_classification_uuid)) {
2358
    $taxonomic_tree_options[$default_classification_uuid] =
2359
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2360
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2361
  }
2362

    
2363
  return $taxonomic_tree_options;
2364
}
2365

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

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

    
2407
/**
2408
 * @todo Please document this function.
2409
 * @see http://drupal.org/node/1354
2410
 */
2411
function cdm_api_secref_cache_clear() {
2412
  global $_cdm_api_secref_cache;
2413
  $_cdm_api_secref_cache = array();
2414
}
2415

    
2416

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

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

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

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

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

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

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

    
2529
  if (!isset($term1->representation_L10n)) {
2530
    $term1->representationL10n = '';
2531
  }
2532
  if (!isset($term2->representation_L10n)) {
2533
    $term2->representationL10n = '';
2534
  }
2535

    
2536
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2537
}
2538

    
2539
function compare_terms_by_order_index($term1, $term2) {
2540

    
2541

    
2542
  if (!isset($term1->orderIndex)) {
2543
    $a = 0;
2544
  } else {
2545
    $a = $term1->orderIndex;
2546
  }
2547
  if (!isset($term2->orderIndex)) {
2548
    $b = 0;
2549
  } else {
2550
    $b = $term2->orderIndex;
2551
  }
2552

    
2553
  if ($a == $b) {
2554
    return 0;
2555
  }
2556
  return ($a < $b) ? -1 : 1;
2557

    
2558
}
2559

    
2560

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

    
2593
/**
2594
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2595
 *
2596
 */
2597
function _add_js_ws_debug() {
2598

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

    
2613
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2614
    array(
2615
      'type' => 'file',
2616
      'weight' => JS_LIBRARY,
2617
      'cache' => TRUE)
2618
    );
2619
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2620
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2621

    
2622
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2623
    array(
2624
      'type' => 'file',
2625
      'weight' => JS_LIBRARY,
2626
      'cache' => TRUE)
2627
    );
2628
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2629
    array(
2630
    'type' => 'file',
2631
    'weight' => JS_LIBRARY,
2632
    'cache' => TRUE)
2633
    );
2634

    
2635
}
2636

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

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

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

    
(5-5/11)