Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_api / cdm_api.module @ c079337e

History | View | Annotate | Download (79.7 KB)

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

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

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

    
40

    
41

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

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

    
76

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

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

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

    
100
  return $items;
101
}
102

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

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

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

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

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

    
134

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

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

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

    
145
      $data = unserialize($data);
146

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

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

    
162
    _add_js_ws_debug();
163

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

    
175
    return $block;
176
  }
177
}
178

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

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

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

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

    
234

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

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

    
275
  if (is_array($taggedTextList)) {
276

    
277
    // First pass: rename.
278
    for ($i = 0; $i < count($taggedTextList); $i++) {
279

    
280
      if ($taggedTextList[$i]->type == "hybridSign") {
281
        $taggedTextList[$i]->type = "name";
282
      }
283
    }
284

    
285
    // Second pass: resolve separators.
286
    $taggedNameListNew = array();
287
    for ($i = 0; $i < count($taggedTextList); $i++) {
288

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

    
301
    }
302
    $taggedTextList = $taggedNameListNew;
303
  }
304
}
305

    
306
function split_secref_from_tagged_text(&$tagged_text) {
307

    
308
  $extracted_tt = array();
309
  if (is_array($tagged_text)) {
310
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
311
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
312
        $extracted_tt[0] = $tagged_text[$i];
313
        $extracted_tt[1] = $tagged_text[$i + 1];
314
        unset($tagged_text[$i]);
315
        unset($tagged_text[$i + 1]);
316
        // also get the microfererence which could be in $tagged_text[$i + 3]
317
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
318
          $extracted_tt[2] = $tagged_text[$i + 2];
319
          $extracted_tt[3] = $tagged_text[$i + 3];
320
        }
321
        break;
322
      }
323
    }
324
  }
325
  return $extracted_tt;
326
}
327

    
328

    
329
function split_nomstatus_from_tagged_text(&$tagged_text) {
330

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

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

    
364
// ===================== END of Tagged Text functions ================== //
365

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

    
377
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
378
}
379

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

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

    
404
  return $profile_featureTree;
405
}
406

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

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

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

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

    
462

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

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

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

    
517
  while (count($mimeTypes) > 0) {
518
    // getRepresentationByMimeType
519
    $mimeType = array_shift($mimeTypes);
520

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

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

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

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

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

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

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

    
688
  $y = NULL; $m = NULL; $d = NULL;
689

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

    
700
  $y = $y ? $y : '00';
701
  $m = $m ? $m : '00';
702
  $d = $d ? $d : '00';
703

    
704
  $date = '';
705

    
706
  if ($y == '00' && $stripZeros) {
707
    return;
708
  }
709
  else {
710
    $date = $y;
711
  }
712

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

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

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

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

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

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

    
817
  $i = 0;
818
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
819
    if (count($pathParameters) <= $i) {
820
        drupal_set_message(
821
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
822
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
823
          'error');
824
      break;
825
    }
826
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
827
    ++$i;
828
  }
829

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

    
844
  // (3)
845
  // Append the query string supplied by $query.
846
  if (isset($query)) {
847
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
848
  }
849

    
850
  $path = $uri_pattern;
851

    
852
  $uri = variable_get('cdm_webservice_url', '') . $path;
853
  return $uri;
854
}
855

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

    
875
  $args = func_get_args();
876
  $do_gzip = function_exists('gzencode');
877
  $uriEncoded = array_shift($args);
878
  $uri = urldecode($uriEncoded);
879
  $hook = array_shift($args);
880
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
881

    
882
  $post_data = null;
883

    
884
  if ($request_method == "POST" || $request_method == "PUT") {
885
    // read response body via inputstream module
886
    $post_data = file_get_contents("php://input");
887
  }
888

    
889
  // Find and deserialize arrays.
890
  foreach ($args as &$arg) {
891
    // FIXME use regex to find serialized arrays.
892
    //       or should we accept json instead of php serializations?
893
    if (strpos($arg, "a:") === 0) {
894
      $arg = unserialize($arg);
895
    }
896
  }
897

    
898
  // In all these cases perform a simple get request.
899
  // TODO reconsider caching logic in this function.
900

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

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

    
933
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
934
    } else {
935
      $obj = NULL;
936
    }
937

    
938
    $reponse_data = NULL;
939

    
940
    if (function_exists('compose_' . $hook)){
941
      // call compose hook
942

    
943
      $elements =  call_user_func('compose_' . $hook, $obj);
944
      // pass the render array to drupal_render()
945
      $reponse_data = drupal_render($elements);
946
    } else {
947
      // call theme hook
948

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

    
963
        case 'cdm_list_of_taxa':
964
            $variables = array(
965
              'records' => $obj,
966
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
967
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
968
            $reponse_data = theme($hook, $variables);
969
            break;
970

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

    
988
        default:
989
          drupal_set_message(t(
990
          'Theme !theme is not yet supported by the function !function.', array(
991
          '!theme' => $hook,
992
          '!function' => __FUNCTION__,
993
          )), 'error');
994
          break;
995
      } // END of theme hook switch
996
    } // END of tread as theme hook
997

    
998

    
999
    if($do_gzip){
1000
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1001
      drupal_add_http_header('Content-Encoding', 'gzip');
1002
    }
1003
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1004
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1005

    
1006
    print $reponse_data;
1007
  } // END of handle $hook either as compose ot theme hook
1008

    
1009
}
1010

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

    
1025
  // Prevent from malicous tags.
1026
  $val = strip_tags($val);
1027

    
1028
  $session_var = &$_SESSION;
1029
  //$i = 0;
1030
  foreach ($var_keys as $key) {
1031
    // $hasMoreKeys = ++$i < count($session);
1032
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1033
      $session_var[$key] = array();
1034
    }
1035
    $session_var = &$session_var[$key];
1036
  }
1037
  $session_var = $val;
1038
  if (isset($_REQUEST['destination'])) {
1039
    drupal_goto($_REQUEST['destination']);
1040
  }
1041
}
1042

    
1043
/**
1044
 * @todo Please document this function.
1045
 * @see http://drupal.org/node/1354
1046
 */
1047
function uri_uriByProxy($uri, $theme = FALSE) {
1048
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1049
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1050
}
1051

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

    
1066
  $ws_base_uri = NULL;
1067
  switch ($cdmBase->class) {
1068
    case 'TaxonBase':
1069
    case 'Taxon':
1070
    case 'Synonym':
1071
      $ws_base_uri = CDM_WS_TAXON;
1072
      break;
1073

    
1074
    case 'TaxonNameBase':
1075
    case 'NonViralName':
1076
    case 'BacterialName':
1077
    case 'BotanicalName':
1078
    case 'CultivarPlantName':
1079
    case 'ZoologicalName':
1080
    case 'ViralName':
1081
      $ws_base_uri = CDM_WS_NAME;
1082
      break;
1083

    
1084
    case 'Media':
1085
      $ws_base_uri = CDM_WS_MEDIA;
1086
      break;
1087

    
1088
    case 'Reference':
1089
      $ws_base_uri = CDM_WS_REFERENCE;
1090
      break;
1091

    
1092
    case 'Distribution':
1093
    case 'TextData':
1094
    case 'TaxonInteraction':
1095
    case 'QuantitativeData':
1096
    case 'IndividualsAssociation':
1097
    case 'Distribution':
1098
    case 'CommonTaxonName':
1099
    case 'CategoricalData':
1100
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1101
      break;
1102

    
1103
    case 'PolytomousKey':
1104
    case 'MediaKey':
1105
    case 'MultiAccessKey':
1106
      $ws_base_uri = $cdmBase->class;
1107
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1108
      break;
1109

    
1110
    default:
1111
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1112
      return;
1113
  }
1114
  return cdm_compose_url($ws_base_uri, array(
1115
    $cdmBase->uuid,
1116
    'annotations',
1117
  ));
1118
}
1119

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

    
1144
  $query['pageNumber'] = $pageNumber;
1145
  $query['pageSize'] = $pageSize;
1146

    
1147
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1148
}
1149

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

    
1171
  while ($page_index !== FALSE){
1172
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1173
    if(isset($pager->records) && is_array($pager->records)) {
1174
      $entities = array_merge($entities, $pager->records);
1175
      if(!empty($pager->nextIndex)){
1176
        $page_index = $pager->nextIndex;
1177
      } else {
1178
        $page_index = FALSE;
1179
      }
1180
    } else {
1181
      $page_index = FALSE;
1182
    }
1183
  }
1184
  return $entities;
1185
}
1186

    
1187
/*
1188
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1189
  $viewrank = _cdm_taxonomy_compose_viewrank();
1190
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1191
  ? '/' . $path : '') ;
1192
}
1193
*/
1194

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

    
1208
  $view_uuid = get_current_classification_uuid();
1209
  $rank_uuid = NULL;
1210
  if (!$ignore_rank_limit) {
1211
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1212
  }
1213

    
1214
  if (!empty($taxon_uuid)) {
1215
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1216
      $view_uuid,
1217
      $taxon_uuid,
1218
    ));
1219
  }
1220
  else {
1221
    if (is_uuid($rank_uuid)) {
1222
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1223
        $view_uuid,
1224
        $rank_uuid,
1225
      ));
1226
    }
1227
    else {
1228
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1229
        $view_uuid,
1230
      ));
1231
    }
1232
  }
1233
}
1234

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

    
1256
    $response = NULL;
1257

    
1258
    // 1st try
1259
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1260

    
1261
    if ($response == NULL) {
1262
      // 2dn try by ignoring the rank limit
1263
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1264
    }
1265

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

    
1291
  return $response;
1292
}
1293

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

    
1309
  $response = NULL;
1310
  if (is_uuid($rank_uuid)) {
1311
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1312
      $view_uuid,
1313
      $taxon_uuid,
1314
      $rank_uuid,
1315
    ));
1316
  }
1317
  else {
1318
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1319
      $view_uuid,
1320
      $taxon_uuid,
1321
    ));
1322
  }
1323

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

    
1341
  return $response;
1342
}
1343

    
1344

    
1345
// =============================Terms and Vocabularies ========================================= //
1346

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

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

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

    
1412
  return $options;
1413
}
1414

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

    
1436
  static $vocabularyOptions = array();
1437

    
1438
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1439
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1440
      array(
1441
        'orderBy' => $order_by
1442
      )
1443
    );
1444

    
1445
    // apply the include filter
1446
    if($include_filter != null){
1447
      $included_terms = array();
1448

    
1449
      foreach ($terms as $term){
1450
        $include = true;
1451
        foreach ($include_filter as $field=>$regex){
1452
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1453
          if(!$include){
1454
            break;
1455
          }
1456
        }
1457
        if($include){
1458
          $included_terms[] = $term;
1459
        }
1460
      }
1461

    
1462
      $terms = $included_terms;
1463
    }
1464

    
1465
    // make options list
1466
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback);
1467
  }
1468

    
1469
  $options = $vocabularyOptions[$vocabulary_uuid];
1470
  if($default_option !== FALSE){
1471
    array_unshift ($options, "");
1472
  }
1473
  return $options;
1474
}
1475

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

    
1537
/**
1538
 * @todo Please document this function.
1539
 * @see http://drupal.org/node/1354
1540
 */
1541
function cdm_rankVocabulary_as_option() {
1542
  $options = cdm_vocabulary_as_option(UUID_RANK, NULL, "");
1543
  return $options;
1544
}
1545

    
1546
/**
1547
 * @todo Please document this function.
1548
 * @see http://drupal.org/node/1354
1549
 */
1550
function _cdm_relationship_type_term_label_callback($term) {
1551
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1552
    return $term->representation_L10n_abbreviatedLabel . ' : '
1553
    . t('@term', array('@term' => $term->representation_L10n));
1554
  }
1555
else {
1556
    return t('@term', array('@term' => $term->representation_L10n));
1557
  }
1558
}
1559

    
1560
// ========================================================================================== //
1561
/**
1562
 * @todo Improve documentation of this function.
1563
 *
1564
 * eu.etaxonomy.cdm.model.description.
1565
 * CategoricalData
1566
 * CommonTaxonName
1567
 * Distribution
1568
 * IndividualsAssociation
1569
 * QuantitativeData
1570
 * TaxonInteraction
1571
 * TextData
1572
 */
1573
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1574
  static $types = array(
1575
    "CategoricalData",
1576
    "CommonTaxonName",
1577
    "Distribution",
1578
    "IndividualsAssociation",
1579
    "QuantitativeData",
1580
    "TaxonInteraction",
1581
    "TextData",
1582
  );
1583

    
1584
  static $options = NULL;
1585
  if ($options == NULL) {
1586
    $options = array();
1587
    if ($prependEmptyElement) {
1588
      $options[' '] = '';
1589
    }
1590
    foreach ($types as $type) {
1591
      // No internatianalization here since these are purely technical terms.
1592
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1593
    }
1594
  }
1595
  return $options;
1596
}
1597

    
1598

    
1599
/**
1600
 * Fetches all TaxonDescription descriptions elements which are associated to the
1601
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1602
 * feature tree.
1603
 * @param $feature_tree
1604
 *     The CDM FeatureTree to be used as template
1605
 * @param $taxon_uuid
1606
 *     The UUID of the taxon
1607
 * @param $excludes
1608
 *     UUIDs of features to be excluded
1609
 * @return$feature_tree
1610
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1611
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1612
 *     witch will hold the according $descriptionElements.
1613
 */
1614
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1615

    
1616
  if (!$feature_tree) {
1617
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1618
      In order to see the species profiles of your taxa, please select a
1619
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1620
    return FALSE;
1621
  }
1622

    
1623
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1624
      array(
1625
      'taxon' => $taxon_uuid,
1626
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1627
      ),
1628
      'POST'
1629
  );
1630

    
1631
  // Combine all descriptions into one feature tree.
1632
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1633
  $feature_tree->root->childNodes = $merged_nodes;
1634

    
1635
  return $feature_tree;
1636
}
1637

    
1638
/**
1639
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1640
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1641
 * be requested for the annotations.
1642
 *
1643
 * @param string $cdmBase
1644
 *   An annotatable cdm entity.
1645
 * @param array $includeTypes
1646
 *   If an array of annotation type uuids is supplied by this parameter the
1647
 *   list of annotations is resticted to those which belong to this type.
1648
 *
1649
 * @return array
1650
 *   An array of Annotation objects or an empty array.
1651
 */
1652
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1653

    
1654
  if(!isset($cdmBase->annotations)){
1655
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1656
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1657
  }
1658

    
1659
  $annotations = array();
1660
  foreach ($cdmBase->annotations as $annotation) {
1661
    if ($includeTypes) {
1662
      if (
1663
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1664
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1665
      ) {
1666
        $annotations[] = $annotation;
1667
      }
1668
    }
1669
    else {
1670
      $annotations[] = $annotation;
1671
    }
1672
  }
1673
  return $annotations;
1674

    
1675
}
1676

    
1677
/**
1678
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1679
 *
1680
 * @param object $annotatable_entity
1681
 *   The CDM AnnotatableEntity to load annotations for
1682
 */
1683
function cdm_load_annotations(&$annotatable_entity) {
1684
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1685
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1686
    if (is_array($annotations)) {
1687
      $annotatable_entity->annotations = $annotations;
1688
    }
1689
  }
1690
}
1691

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

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

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

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

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

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

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

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

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

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

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

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

    
1809
  }
1810

    
1811
  return $featureNodes;
1812
}
1813

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

    
1850
  static $cacheL1 = array();
1851

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
2094
  return $obj;
2095
}
2096

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

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

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

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

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

    
2159

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

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

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

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

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

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

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

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

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

    
2269
  foreach ($feature_trees as $featureTree) {
2270

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

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

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

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

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

    
2302
  } // END loop over feature trees
2303

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

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

    
2326
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2327

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

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

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

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

    
2362
  return $taxonomic_tree_options;
2363
}
2364

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

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

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

    
2415

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

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

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

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

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

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

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

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

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

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

    
2540

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

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

    
2557
}
2558

    
2559

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

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

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

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

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

    
2634
}
2635

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

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

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

    
Add picture from clipboard (Maximum size: 40 MB)