Project

General

Profile

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

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

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

    
40

    
41

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

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

    
76

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

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

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

    
100
  return $items;
101
}
102

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

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

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

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

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

    
134

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

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

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

    
145
      $data = unserialize($data);
146

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

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

    
162
    _add_js_ws_debug();
163

    
164
    $block['subject'] = ''; // no subject, title in content for having a defined element id
165
    // otherwise it would depend on the theme
166
    $block['content'] = array(
167
      '#markup' => '<h4 id="cdm-ws-debug-button">' . t('CDM Debug') . '</h4>'
168
        // cannot use theme_table() since table footer is not jet supported in D7
169
        . '<div id="cdm-ws-debug-table-container"><table id="cdm-ws-debug-table">'
170
        . $header
171
        . '<tbody>' . join('', $rows) . '</tbody>'
172
        . $footer
173
        . '</table></div>',
174
      '#attached' => array(
175
        'css' => array(
176
          drupal_get_path('module', 'cdm_dataportal') . '/cdm_dataportal_ws_debug.css'
177
        )
178
      )
179
    );
180
    return $block;
181
  }
182
}
183

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

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

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

    
226

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

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

    
267
  if (is_array($taggedTextList)) {
268

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

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

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

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

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

    
298
function split_secref_from_tagged_text(&$tagged_text) {
299

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

    
320

    
321
function split_nomstatus_from_tagged_text(&$tagged_text) {
322

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

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

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

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

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

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

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

    
396
  return $profile_featureTree;
397
}
398

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

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

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

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

    
454

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

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

    
476
/**
477
 *
478
 * @param object $media
479
 * @param array $mimeTypes
480
 *    an array of mimetypes in their order of preference. e.g:
481
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
482
 * @param int $width
483
 *    The width of the optimal image. If null, the method will return the representation with the biggest expanse
484
 * @param int $height
485
 *    The height of the optimal image. If null, the method will return the representation with the biggest expanse
486
 *
487
 * @return array
488
 *   An array with preferred media representations or else an empty array.
489
 */
490
function cdm_preferred_media_representations($media, array $mimeTypes, $width = 400, $height = 300) {
491
  $prefRepr = array();
492
  if (!isset($media->representations[0])) {
493
    return $prefRepr;
494
  }
495

    
496
  while (count($mimeTypes) > 0) {
497
    // getRepresentationByMimeType
498
    $mimeType = array_shift($mimeTypes);
499

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

    
508
      if ($representation->mimeType == $mimeType) {
509
        // Preferred mimetype found -> erase all remaining mimetypes
510
        // to end loop.
511
        $mimeTypes = array();
512
        $expanseDeltaSum = 0;
513
        $valid_parts_cnt = 0;
514
        // Look for part with the best matching size.
515
        foreach ($representation->parts as $part) {
516
          if (empty($part->uri)) {
517
            // skip part if URI is missing
518
            continue;
519
          }
520
          $valid_parts_cnt++;
521
          $expanseDelta = PHP_INT_MAX; // biggest delta for unkown sizes
522

    
523
          // determine the optimal size
524
          if (isset($part->width) && isset($part->height)) {
525
            $expanse = $part->width * $part->height;
526
            if ($width != null && $height != null) {
527
              $optimalExpanse = $height * $width;
528
            } else {
529
              $optimalExpanse = PHP_INT_MAX;
530
            }
531
            // determine the difference
532
            $expanseDelta = $expanse > $optimalExpanse ? $expanse - $optimalExpanse : $optimalExpanse - $expanse;
533
          }
534
          // sum up the expanseDeltas of all parts contained in the representation
535
          $expanseDeltaSum += $expanseDelta;
536
        }
537
        if($valid_parts_cnt > 0){
538
          $expanseDeltaSum = $expanseDeltaSum / $valid_parts_cnt;
539
          $prefRepr[$expanseDeltaSum . '_'] = $representation;
540
        }
541
      }
542
    }
543
  }
544
  // Sort the array so that the smallest key value is the first in the array
545
  ksort($prefRepr);
546
  return $prefRepr;
547
}
548

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

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

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

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

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

    
682
  $y = NULL; $m = NULL; $d = NULL;
683

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

    
694
  $y = $y ? $y : '00';
695
  $m = $m ? $m : '00';
696
  $d = $d ? $d : '00';
697

    
698
  $date = '';
699

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

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

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

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

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

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

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

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

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

    
838
  // (3)
839
  // Append the query string supplied by $query.
840
  if (isset($query)) {
841
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
842
  }
843

    
844
  $path = $uri_pattern;
845

    
846
  $uri = variable_get('cdm_webservice_url', '') . $path;
847
  return $uri;
848
}
849

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

    
869
  $args = func_get_args();
870
  $do_gzip = function_exists('gzencode');
871
  $uriEncoded = array_shift($args);
872
  $uri = urldecode($uriEncoded);
873
  $hook = array_shift($args);
874
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
875

    
876
  $post_data = null;
877

    
878
  if ($request_method == "POST" || $request_method == "PUT") {
879
    // read response body via inputstream module
880
    $post_data = file_get_contents("php://input");
881
  }
882

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

    
892
  // In all these cases perform a simple get request.
893
  // TODO reconsider caching logic in this function.
894

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

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

    
927
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
928
    } else {
929
      $obj = NULL;
930
    }
931

    
932
    $reponse_data = NULL;
933

    
934
    if (function_exists('compose_' . $hook)){
935
      // call compose hook
936

    
937
      $elements =  call_user_func('compose_' . $hook, $obj);
938
      // pass the render array to drupal_render()
939
      $reponse_data = drupal_render($elements);
940
    } else {
941
      // call theme hook
942

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

    
957
        case 'cdm_list_of_taxa':
958
            $variables = array(
959
              'records' => $obj,
960
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
961
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
962
            $reponse_data = theme($hook, $variables);
963
            break;
964

    
965
        case 'cdm_media_caption':
966
          $variables = array(
967
            'media' => $obj,
968
            // $args[0] is set in taxon_image_gallery_default in
969
            // cdm_dataportal.page.theme.
970
            'elements' => isset($args[0]) ? $args[0] : array(
971
            'title',
972
            'description',
973
            'artist',
974
            'location',
975
            'rights',
976
          ),
977
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
978
          );
979
          $reponse_data = theme($hook, $variables);
980
          break;
981

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

    
992

    
993
    if($do_gzip){
994
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
995
      drupal_add_http_header('Content-Encoding', 'gzip');
996
    }
997
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
998
    drupal_add_http_header('Content-Length', strlen($reponse_data));
999

    
1000
    print $reponse_data;
1001
  } // END of handle $hook either as compose ot theme hook
1002

    
1003
}
1004

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

    
1019
  // Prevent from malicous tags.
1020
  $val = strip_tags($val);
1021

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

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

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

    
1060
  $ws_base_uri = NULL;
1061
  switch ($cdmBase->class) {
1062
    case 'TaxonBase':
1063
    case 'Taxon':
1064
    case 'Synonym':
1065
      $ws_base_uri = CDM_WS_TAXON;
1066
      break;
1067

    
1068
    case 'TaxonName':
1069
      $ws_base_uri = CDM_WS_NAME;
1070
      break;
1071

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1244
    $response = NULL;
1245

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

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

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

    
1279
  return $response;
1280
}
1281

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

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

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

    
1329
  return $response;
1330
}
1331

    
1332

    
1333
// =============================Terms and Vocabularies ========================================= //
1334

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

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

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

    
1400
  return $options;
1401
}
1402

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

    
1424
  static $vocabularyOptions = array();
1425

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

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

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

    
1450
      $terms = $included_terms;
1451
    }
1452

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

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

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

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

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

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

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

    
1586

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

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

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

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

    
1623
  return $feature_tree;
1624
}
1625

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

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

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

    
1663
}
1664

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

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

    
1697

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

    
1715
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1716
  if(is_array($microreference) || is_object($microreference)) {
1717
    return '';
1718
  }
1719

    
1720
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1721
    $referenceUuid,
1722
  ), "microReference=" . urlencode($microreference));
1723

    
1724
  if ($obj) {
1725
    return $obj->String;
1726
  }
1727
  else {
1728
    return NULL;
1729
  }
1730
}
1731

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

    
1743
  // 1. scan this level
1744
  foreach ($feature_tree_nodes as $node){
1745
    if($node->feature->uuid == $feature_uuid){
1746
      return $node;
1747
    }
1748
  }
1749

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

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

    
1787
  foreach ($featureNodes as &$node) {
1788
    // since the $featureNodes array is reused for each description
1789
    // it is necessary to clear the custom node fields in advance
1790
    if(isset($node->descriptionElements)){
1791
      unset($node->descriptionElements);
1792
    }
1793

    
1794
    // Append corresponding elements to an additional node field:
1795
    // $node->descriptionElements.
1796
    foreach ($descriptionElements as $element) {
1797
      if ($element->feature->uuid == $node->feature->uuid) {
1798
        if (!isset($node->descriptionElements)) {
1799
          $node->descriptionElements = array();
1800
        }
1801
        $node->descriptionElements[] = $element;
1802
      }
1803
    }
1804

    
1805
    // Recurse into node children.
1806
    if (isset($node->childNodes[0])) {
1807
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1808
      $node->childNodes = $mergedChildNodes;
1809
    }
1810

    
1811
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1812
      unset($node);
1813
    }
1814

    
1815
  }
1816

    
1817
  return $featureNodes;
1818
}
1819

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

    
1856
  static $cacheL1 = array();
1857

    
1858
  $data = NULL;
1859
  // store query string in $data and clear the query, $data will be set as HTTP request body
1860
  if($method == 'POST'){
1861
    $data = $query;
1862
    $query = NULL;
1863
  }
1864

    
1865
  // Transform the given uri path or pattern into a proper webservice uri.
1866
  if (!$absoluteURI) {
1867
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1868
  }
1869

    
1870
  // read request parameter 'cacheL2_refresh'
1871
  // which allows refreshing the level 2 cache
1872
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1873

    
1874
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1875
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1876

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

    
1885
  if (array_key_exists($cache_key, $cacheL1)) {
1886
    $cacheL1_obj = $cacheL1[$uri];
1887
  }
1888

    
1889
  $set_cacheL1 = FALSE;
1890
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1891
    $set_cacheL1 = TRUE;
1892
  }
1893

    
1894
  // Only cache cdm webservice URIs.
1895
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1896
  $cacheL2_entry = FALSE;
1897

    
1898
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1899
    // Try to get object from cacheL2.
1900
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1901
  }
1902

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

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

    
1938
    // Parse data and create object.
1939
    $obj = cdm_load_obj($response_body);
1940

    
1941
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1942

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

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

    
1992
  static $initial_time = NULL;
1993
  if(!$initial_time) {
1994
    $initial_time = microtime(TRUE);
1995
  }
1996
  $time = microtime(TRUE) - $initial_time;
1997

    
1998
  // Decompose uri into path and query element.
1999
  $uri_parts = explode("?", $uri);
2000
  $query = array();
2001
  if (count($uri_parts) == 2) {
2002
    $path = $uri_parts[0];
2003
  }
2004
  else {
2005
    $path = $uri;
2006
  }
2007

    
2008
  if(strpos($uri, '?') > 0){
2009
    $json_uri = str_replace('?', '.json?', $uri);
2010
    $xml_uri = str_replace('?', '.xml?', $uri);
2011
  } else {
2012
    $json_uri = $uri . '.json';
2013
    $xml_uri = $json_uri . '.xml';
2014
  }
2015

    
2016
  // data links to make data accecsible as json and xml
2017
  $data_links = '';
2018
  if (_is_cdm_ws_uri($path)) {
2019

    
2020
    // see ./js/http-method-link.js
2021

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

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

    
2056
  // Mark this page as being uncacheable.
2057
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2058
  drupal_page_is_cacheable(FALSE);
2059

    
2060
  // Messages not set when DB connection fails.
2061
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2062
}
2063

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

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

    
2086
/**
2087
 * @todo Please document this function.
2088
 * @see http://drupal.org/node/1354
2089
 */
2090
function cdm_load_obj($response_body) {
2091
  $obj = json_decode($response_body);
2092

    
2093
  if (!(is_object($obj) || is_array($obj))) {
2094
    ob_start();
2095
    $obj_dump = ob_get_contents();
2096
    ob_clean();
2097
    return FALSE;
2098
  }
2099

    
2100
  return $obj;
2101
}
2102

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

    
2141
  if (!$acceptLanguage) {
2142
    if (function_exists('apache_request_headers')) {
2143
      $headers = apache_request_headers();
2144
      if (isset($headers['Accept-Language'])) {
2145
        $acceptLanguage = $headers['Accept-Language'];
2146
      }
2147
    }
2148
  }
2149

    
2150
  if ($method != "GET" && $method != "POST") {
2151
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2152
  }
2153

    
2154
  if (_is_cdm_ws_uri($uri)) {
2155
    $header['Accept'] = 'application/json';
2156
    $header['Accept-Language'] = $acceptLanguage;
2157
    $header['Accept-Charset'] = 'UTF-8';
2158
  }
2159

    
2160
  if($method == "POST") {
2161
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2162
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2163
  }
2164

    
2165

    
2166
  cdm_dd($uri);
2167
  return drupal_http_request($uri, array(
2168
      'headers' => $header,
2169
      'method' => $method,
2170
      'data' => $data,
2171
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2172
      )
2173
   );
2174
}
2175

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

    
2194
  $pre_child_separator = $separator;
2195
  $post_child_separator = '';
2196

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

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

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

    
2259
  $options = array();
2260
  $tree_representations = array();
2261
  $feature_trees = array();
2262

    
2263
  // Set tree that contains all features.
2264
  if ($add_default_feature_free) {
2265
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2266
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2267
  }
2268

    
2269
  // Get feature trees from database.
2270
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2271
  if (is_array($persited_trees)) {
2272
    $feature_trees = array_merge($feature_trees, $persited_trees);
2273
  }
2274

    
2275
  foreach ($feature_trees as $featureTree) {
2276

    
2277
    if(!is_object($featureTree)){
2278
      continue;
2279
    }
2280
    // Do not add the DEFAULT_FEATURETREE again,
2281
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2282
      $options[$featureTree->uuid] = $featureTree->titleCache;
2283
    }
2284

    
2285
    // Render the hierarchic tree structure
2286
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2287

    
2288
      // Render the hierarchic tree structure.
2289
      $treeDetails = '<div class="featuretree_structure">'
2290
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2291
        . '</div>';
2292

    
2293
      $form = array();
2294
      $form['featureTree-' .  $featureTree->uuid] = array(
2295
        '#type' => 'fieldset',
2296
        '#title' => 'Show details',
2297
        '#attributes' => array('class' => array('collapsible collapsed')),
2298
        // '#collapsible' => TRUE,
2299
        // '#collapsed' => TRUE,
2300
      );
2301
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2302
        '#markup' => $treeDetails,
2303
      );
2304

    
2305
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2306
    }
2307

    
2308
  } // END loop over feature trees
2309

    
2310
  // return $options;
2311
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2312
}
2313

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

    
2332
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2333

    
2334
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2335
  $default_classification_label = '';
2336

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

    
2355
  // now set the labels
2356
  //   for none
2357
  if ($add_none_option) {
2358
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2359
  }
2360

    
2361
  //   for default_classification
2362
  if (is_uuid($default_classification_uuid)) {
2363
    $taxonomic_tree_options[$default_classification_uuid] =
2364
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2365
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2366
  }
2367

    
2368
  return $taxonomic_tree_options;
2369
}
2370

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

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

    
2412
/**
2413
 * @todo Please document this function.
2414
 * @see http://drupal.org/node/1354
2415
 */
2416
function cdm_api_secref_cache_clear() {
2417
  global $_cdm_api_secref_cache;
2418
  $_cdm_api_secref_cache = array();
2419
}
2420

    
2421

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

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

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

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

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

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

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

    
2534
  if (!isset($term1->representation_L10n)) {
2535
    $term1->representationL10n = '';
2536
  }
2537
  if (!isset($term2->representation_L10n)) {
2538
    $term2->representationL10n = '';
2539
  }
2540

    
2541
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2542
}
2543

    
2544
function compare_terms_by_order_index($term1, $term2) {
2545

    
2546

    
2547
  if (!isset($term1->orderIndex)) {
2548
    $a = 0;
2549
  } else {
2550
    $a = $term1->orderIndex;
2551
  }
2552
  if (!isset($term2->orderIndex)) {
2553
    $b = 0;
2554
  } else {
2555
    $b = $term2->orderIndex;
2556
  }
2557

    
2558
  if ($a == $b) {
2559
    return 0;
2560
  }
2561
  return ($a < $b) ? -1 : 1;
2562

    
2563
}
2564

    
2565

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

    
2598
/**
2599
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2600
 *
2601
 */
2602
function _add_js_ws_debug() {
2603

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

    
2618
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2619
    array(
2620
      'type' => 'file',
2621
      'weight' => JS_LIBRARY,
2622
      'cache' => TRUE)
2623
    );
2624
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2625
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2626

    
2627
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2628
    array(
2629
      'type' => 'file',
2630
      'weight' => JS_LIBRARY,
2631
      'cache' => TRUE)
2632
    );
2633
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2634
    array(
2635
    'type' => 'file',
2636
    'weight' => JS_LIBRARY,
2637
    'cache' => TRUE)
2638
    );
2639

    
2640
}
2641

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

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

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

    
(5-5/11)