Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_api / cdm_api.module @ 109968f7

History | View | Annotate | Download (83.1 KB)

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

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

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

    
40

    
41

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

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

    
76

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

    
83
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");
84
  $items['cdm_api/proxy'] = array(
85
    'page callback' => 'proxy_content',
86
    'access arguments' => array(
87
      'access 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
 * Walks the passed TaggedText array to find all elements which have a
197
 * TaggedText->entityReference. For each of these the taggedTexts is loaded
198
 * from the webservice and the original enty in the TaggedText array will be
199
 * replaced by the newly loaded array.
200
 *
201
 * @param array $taggedtxt
202
 *    The original TaggedText array
203
 * @param array $skiptags
204
 *    Optional list of tag names to skip
205
 * @return array
206
 *    The new tagged text with all TaggedText->entityReference objects expanded
207
 */
208
function cdm_tagged_text_expand_entity_references(array $taggedtxt, $skiptags = array()) {
209
  $tagged_text_expanded = array();
210
  foreach ($taggedtxt as $tt) {
211
    if (isset($tt->entityReference) && !in_array($tt->type, $skiptags)) {
212
      $base_uri = cdm_ws_base_uri($tt->entityReference->type);
213
      if($base_uri){
214
        $tagged_text_method = "/taggedText";
215
        if($base_uri == CDM_WS_NAME){
216
          $tagged_text_method = "/taggedName";
217
        }
218
        $referenced_tt = cdm_ws_get($base_uri . "/" . $tt->entityReference->uuid . $tagged_text_method);
219
        if($referenced_tt){
220
          $tagged_text_expanded = array_merge($tagged_text_expanded, $referenced_tt);
221
          continue;
222
        }
223
      }
224
    }
225
    // default case
226
    $tagged_text_expanded[] = $tt;
227
  }
228
  return $tagged_text_expanded;
229
}
230

    
231
/**
232
 * Converts an array of TaggedText items into corresponding html tags.
233
 *
234
 * Each item is provided with a class attribute which is set to the key of the
235
 * TaggedText item.
236
 *
237
 * @param array $taggedtxt
238
 *   Array with text items to convert.
239
 * @param array $skiptags
240
 *   Array of tag names to skip
241
 *
242
 * @return string
243
 *   A string with HTML.
244
 */
245
function cdm_tagged_text_to_markup(array $taggedtxt, $skiptags = array()) {
246

    
247
  $tag = 'span';
248
  $out = '';
249
  $was_separator = false;
250
  $i = 0;
251
  foreach ($taggedtxt as $tt) {
252
    if (!in_array($tt->type, $skiptags) && $tt->text) {
253
      $class_attr = $tt->type;
254

    
255
      if(isset($tt->entityReference)){
256
        $class_attr .= " " . html_class_attribute_ref($tt->entityReference);
257
      }
258
      $is_last = $i + 1 == count($taggedtxt);
259
      $is_separator = is_tagged_text_sepatator_type($tt->type);
260
      $glue = !$is_separator && !$was_separator && !$is_last ? ' ' : '';
261
      $out .= '<' . $tag . ' class="' . $class_attr . '">'
262
        . t('@text', array('@text' => $tt->text))
263
        . '</' . $tag . '>'
264
        . $glue;
265
      $was_separator = $is_separator;
266
    }
267
    $i++;
268
  }
269
  return $out;
270
}
271

    
272
/**
273
 * See cdmlib: boolean eu.etaxonomy.cdm.strategy.cache.TagEnum.isSeparator();
274
 *
275
 * @return bool
276
 */
277
function is_tagged_text_sepatator_type($tagged_text_type){
278
    static $separator_names = array('separator', 'postSeparator');
279
		$result = array_search($tagged_text_type, $separator_names) !== false;
280
    return $result;
281
}
282

    
283

    
284
/**
285
 * Finds the text tagged with $tag_type in an array of taggedText instances.
286
 *
287
 * Note: This function is currently unused.
288
 *
289
 * @param array $taggedtxt
290
 *   Array with text items.
291
 * @param string $tag_type
292
 *   The type of tag for which to find text items in the $taggedtxt array, or NULL
293
 *   to return all texts.
294
 *
295
 * @return array
296
 *   An array with the texts mapped by $tag_type.
297
 */
298
function cdm_tagged_text_values(array $taggedtxt, $tag_type = NULL) {
299
  $tokens = array();
300
  if (!empty($taggedtxt)) {
301
    foreach ($taggedtxt as $tagtxt) {
302
      if ($tag_type === NULL || $tagtxt->type == $tag_type) {
303
        $tokens[] = $tagtxt->text;
304
      }
305
    }
306
  }
307
  return $tokens;
308
}
309

    
310
/**
311
 * Preprocess the taggedTitle arrays.
312
 *
313
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
314
 * into tag type "name"
315
 *
316
 * Step 2: Two taggedTexts which have the same type and which have
317
 * a separator between them are merged together.
318
 *
319
 * @param array $taggedTextList
320
 *    An array of TaggedText objects
321
 */
322
function normalize_tagged_text(&$taggedTextList) {
323

    
324
  if (is_array($taggedTextList)) {
325

    
326
    // First pass: rename.
327
    for ($i = 0; $i < count($taggedTextList); $i++) {
328

    
329
      if ($taggedTextList[$i]->type == "hybridSign") {
330
        $taggedTextList[$i]->type = "name";
331
      }
332
    }
333

    
334
    // Second pass: resolve separators.
335
    $taggedNameListNew = array();
336
    for ($i = 0; $i < count($taggedTextList); $i++) {
337

    
338
      // elements of the same type concatenated by a separator should be merged together
339
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
340
        $taggedName = clone $taggedTextList[$i];
341
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
342
        $taggedNameListNew[] = $taggedName;
343
        ++$i;
344
        ++$i;
345
        continue;
346
      }
347
      // no special handling
348
      $taggedNameListNew[] = $taggedTextList[$i];
349

    
350
    }
351
    $taggedTextList = $taggedNameListNew;
352
  }
353
}
354

    
355
function split_secref_from_tagged_text(&$tagged_text) {
356

    
357
  $extracted_tt = array();
358
  if (is_array($tagged_text)) {
359
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
360
      if ($tagged_text[$i + 1]->type == "secReference" && $tagged_text[$i]->type == "separator"){
361
        $extracted_tt[0] = $tagged_text[$i];
362
        $extracted_tt[1] = $tagged_text[$i + 1];
363
        unset($tagged_text[$i]);
364
        unset($tagged_text[$i + 1]);
365
        // also get the microfererence which could be in $tagged_text[$i + 3]
366
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == "secReference"){
367
          $extracted_tt[2] = $tagged_text[$i + 2];
368
          $extracted_tt[3] = $tagged_text[$i + 3];
369
        }
370
        break;
371
      }
372
    }
373
  }
374
  return $extracted_tt;
375
}
376

    
377

    
378
function split_nomstatus_from_tagged_text(&$tagged_text) {
379

    
380
  $extracted_tt = array();
381
  if (is_array($tagged_text)) {
382
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
383
      if ($tagged_text[$i]->type == "nomStatus"){
384
        $extracted_tt[] = $tagged_text[$i];
385
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
386
          $extracted_tt[] = $tagged_text[$i + 1];
387
          unset($tagged_text[$i + 1]);
388
        }
389
        if ($tagged_text[$i - 1]->type == "separator"){
390
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
391
          unset($tagged_text[$i - 1]);
392
        }
393
        unset($tagged_text[$i]);
394
        break;
395
      }
396
    }
397
  }
398
  return $extracted_tt;
399
}
400

    
401
function find_tagged_text_elements($taggedTextList, $type){
402
  $matching_elements = array();
403
  if (is_array($taggedTextList)) {
404
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
405
      if($taggedTextList[$i]->type == $type){
406
        $matching_elements[] = $taggedTextList[$i];
407
      }
408
    }
409
  }
410
  return $matching_elements;
411
}
412

    
413
// ===================== END of Tagged Text functions ================== //
414

    
415
/**
416
 * Lists the classifications a taxon belongs to
417
 *
418
 * @param CDM type Taxon $taxon
419
 *   the taxon
420
 *
421
 * @return array
422
 *   aray of CDM instances of Type Classification
423
 */
424
function get_classifications_for_taxon($taxon) {
425

    
426
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
427
}
428

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

    
443
  if($profile_featureTree == NULL) {
444
    $profile_featureTree = cdm_ws_get(
445
      CDM_WS_FEATURETREE,
446
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
447
    );
448
    if (!$profile_featureTree) {
449
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
450
    }
451
  }
452

    
453
  return $profile_featureTree;
454
}
455

    
456
/**
457
 * Returns the chosen FeatureTree for SpecimenDescriptions.
458
 *
459
 * The FeatureTree returned is the one that has been set in the
460
 * dataportal settings (layout->taxon:specimen).
461
 * When the chosen FeatureTree is not found in the database,
462
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
463
 *
464
 * @return mixed
465
 *   A cdm FeatureTree object.
466
 */
467
function cdm_get_occurrence_featureTree() {
468
  static $occurrence_featureTree;
469

    
470
  if($occurrence_featureTree == NULL) {
471
    $occurrence_featureTree = cdm_ws_get(
472
      CDM_WS_FEATURETREE,
473
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
474
    );
475
    if (!$occurrence_featureTree) {
476
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
477
    }
478
  }
479
  return $occurrence_featureTree;
480
}
481

    
482
/**
483
 * Returns the FeatureTree for structured descriptions
484
 *
485
 * The FeatureTree returned is the one that has been set in the
486
 * dataportal settings (layout->taxon:profile).
487
 * When the chosen FeatureTree is not found in the database,
488
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
489
 *
490
 * @return mixed
491
 *   A cdm FeatureTree object.
492
 */
493
function get_structured_description_featureTree() {
494
  static $structured_description_featureTree;
495

    
496
  if($structured_description_featureTree == NULL) {
497
    $structured_description_featureTree = cdm_ws_get(
498
        CDM_WS_FEATURETREE,
499
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
500
    );
501
    if (!$structured_description_featureTree) {
502
      $structured_description_featureTree = cdm_ws_get(
503
          CDM_WS_FEATURETREE,
504
          UUID_DEFAULT_FEATURETREE
505
      );
506
    }
507
  }
508
  return $structured_description_featureTree;
509
}
510

    
511

    
512
/**
513
 * @todo Please document this function.
514
 * @see http://drupal.org/node/1354
515
 */
516
function set_last_taxon_page_tab($taxonPageTab) {
517
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
518
}
519

    
520
/**
521
 * @todo Please document this function.
522
 * @see http://drupal.org/node/1354
523
 */
524
function get_last_taxon_page_tab() {
525
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
526
    return $_SESSION['cdm']['taxon_page_tab'];
527
  }
528
  else {
529
    return FALSE;
530
  }
531
}
532

    
533
/**
534
 *
535
 * @param object $media
536
 * @param array $mimeTypes
537
 *    an array of mimetypes in their order of preference. e.g:
538
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
539
 * @param int $width
540
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
541
 * @param int $height
542
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
543
 *
544
 * @return array
545
 *   An array with preferred media representations or else an empty array.
546
 */
547
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
548
  $prefRepr = array();
549
  if (!isset($media->representations[0])) {
550
    return $prefRepr;
551
  }
552

    
553
  while (count($mimeTypes) > 0) {
554
    // getRepresentationByMimeType
555
    $mimeType = array_shift($mimeTypes);
556

    
557
    foreach ($media->representations as &$representation) {
558
      // If the mimetype is not known, try inferring it.
559
      if (!$representation->mimeType) {
560
        if (isset($representation->parts[0])) {
561
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
562
        }
563
      }
564

    
565
      if ($representation->mimeType == $mimeType) {
566
        // Preferred mimetype found -> erase all remaining mimetypes
567
        // to end loop.
568
        $mimeTypes = array();
569
        $expansionDeltaSum = 0;
570
        $valid_parts_cnt = 0;
571
        // Look for part with the best matching size.
572
        foreach ($representation->parts as $part) {
573
          if (empty($part->uri)) {
574
            // skip part if URI is missing
575
            continue;
576
          }
577
          $valid_parts_cnt++;
578
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
579

    
580
          // determine the optimal size
581
          if (isset($part->width) && isset($part->height)) {
582
            $expansion = $part->width * $part->height;
583
            if ($width != null && $height != null) {
584
              $optimalExpansion = $height * $width;
585
            } else {
586
              $optimalExpansion = PHP_INT_MAX;
587
            }
588
            // determine the difference
589
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
590
          }
591
          // sum up the expansionDeltas of all parts contained in the representation
592
          $expansionDeltaSum += $expansionDelta;
593
        }
594
        if($valid_parts_cnt > 0){
595
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
596
          $prefRepr[$expansionDeltaSum] = $representation;
597
        }
598
      }
599
    }
600
  }
601
  // Sort the array so that the smallest key value is the first in the array
602
  ksort($prefRepr);
603
  return $prefRepr;
604
}
605

    
606
/**
607
 * Infers the mime type of a file using the filename extension.
608
 *
609
 * The filename extension is used to infer the mime type.
610
 *
611
 * @param string $filepath
612
 *   The path to the respective file.
613
 *
614
 * @return string
615
 *   The mimetype for the file or FALSE if the according mime type could
616
 *   not be found.
617
 */
618
function infer_mime_type($filepath) {
619
  static $mimemap = NULL;
620
  if (!$mimemap) {
621
    $mimemap = array(
622
      'jpg' => 'image/jpeg',
623
      'jpeg' => 'image/jpeg',
624
      'png' => 'image/png',
625
      'gif' => 'image/gif',
626
      'giff' => 'image/gif',
627
      'tif' => 'image/tif',
628
      'tiff' => 'image/tif',
629
      'pdf' => 'application/pdf',
630
      'html' => 'text/html',
631
      'htm' => 'text/html',
632
    );
633
  }
634
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
635
  if (isset($mimemap[$extension])) {
636
    return $mimemap[$extension];
637
  }
638
  else {
639
    // FIXME remove this hack just return FALSE;
640
    return 'text/html';
641
  }
642
}
643

    
644
/**
645
 * Converts an ISO 8601 org.joda.time.Partial to a year.
646
 *
647
 * The function expects an ISO 8601 time representation of a
648
 * org.joda.time.Partial of the form yyyy-MM-dd.
649
 *
650
 * @param string $partial
651
 *   ISO 8601 time representation of a org.joda.time.Partial.
652
 *
653
 * @return string
654
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
655
 */
656
function partialToYear($partial) {
657
  if (is_string($partial)) {
658
    $year = substr($partial, 0, 4);
659
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
660
      return $year;
661
    }
662
  }
663
  return '';
664
}
665

    
666
/**
667
 * Converts an ISO 8601 org.joda.time.Partial to a month.
668
 *
669
 * This function expects an ISO 8601 time representation of a
670
 * org.joda.time.Partial of the form yyyy-MM-dd.
671
 * In case the month is unknown (= ???) NULL is returned.
672
 *
673
 * @param string $partial
674
 *   ISO 8601 time representation of a org.joda.time.Partial.
675
 *
676
 * @return string
677
 *   A month.
678
 */
679
function partialToMonth($partial) {
680
  if (is_string($partial)) {
681
    $month = substr($partial, 5, 2);
682
    if (preg_match("/[0-9][0-9]/", $month)) {
683
      return $month;
684
    }
685
  }
686
  return '';
687
}
688

    
689
/**
690
 * Converts an ISO 8601 org.joda.time.Partial to a day.
691
 *
692
 * This function expects an ISO 8601 time representation of a
693
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
694
 * In case the day is unknown (= ???) NULL is returned.
695
 *
696
 * @param string $partial
697
 *   ISO 8601 time representation of a org.joda.time.Partial.
698
 *
699
 * @return string
700
 *   A day.
701
 */
702
function partialToDay($partial) {
703
  if (is_string($partial)) {
704
    $day = substr($partial, 8, 2);
705
    if (preg_match("/[0-9][0-9]/", $day)) {
706
      return $day;
707
    }
708
  }
709
  return '';
710
}
711

    
712
/**
713
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
714
 *
715
 * This function expects an ISO 8601 time representations of a
716
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
717
 * four digit year, month and day with dashes:
718
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
719
 *
720
 * The partial may contain question marks eg: "1973-??-??",
721
 * these are turned in to '00' or are stripped depending of the $stripZeros
722
 * parameter.
723
 *
724
 * @param string $partial
725
 *   org.joda.time.Partial.
726
 * @param bool $stripZeros
727
 *   If set to TRUE the zero (00) month and days will be hidden:
728
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
729
 * @param string @format
730
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
731
 *    - "YYYY": Year only
732
 *    - "YYYY-MM-DD": this is the default
733
 *
734
 * @return string
735
 *   YYYY-MM-DD formatted year, month, day.
736
 */
737
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
738

    
739
  $y = NULL; $m = NULL; $d = NULL;
740

    
741
  if(strpos($format, 'YY') !== FALSE){
742
    $y = partialToYear($partial);
743
  }
744
  if(strpos($format, 'MM') !== FALSE){
745
    $m = partialToMonth($partial);
746
  }
747
  if(strpos($format, 'DD') !== FALSE){
748
    $d = partialToDay($partial);
749
  }
750

    
751
  $y = $y ? $y : '00';
752
  $m = $m ? $m : '00';
753
  $d = $d ? $d : '00';
754

    
755
  $date = '';
756

    
757
  if ($y == '00' && $stripZeros) {
758
    return '';
759
  }
760
  else {
761
    $date = $y;
762
  }
763

    
764
  if ($m == '00' && $stripZeros) {
765
    return $date;
766
  }
767
  else {
768
    $date .= "-" . $m;
769
  }
770

    
771
  if ($d == '00' && $stripZeros) {
772
    return $date;
773
  }
774
  else {
775
    $date .= "-" . $d;
776
  }
777
  return $date;
778
}
779

    
780
/**
781
 * Converts a time period to a string.
782
 *
783
 * See also partialToDate($partial, $stripZeros).
784
 *
785
 * @param object $period
786
 *   An JodaTime org.joda.time.Period object.
787
 * @param bool $stripZeros
788
 *   If set to True, the zero (00) month and days will be hidden:
789
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
790
 * @param string @format
791
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
792
 *    - "YYYY": Year only
793
 *    - "YYYY-MM-DD": this is the default
794
 *
795
 * @return string
796
 *   Returns a date in the form of a string.
797
 */
798
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
799
  $dateString = '';
800
  if($period->freeText){
801
    $dateString = $period->freeText;
802
  } else {
803
    if ($period->start) {
804
      $dateString = partialToDate($period->start, $stripZeros, $format);
805
    }
806
    if ($period->end) {
807
      $end_str = partialToDate($period->end, $stripZeros, $format);
808
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
809
    }
810
  }
811
  return $dateString;
812
}
813

    
814
/**
815
 * returns the earliest date available in the $period in a normalized
816
 * form suitable for sorting, e.g.:
817
 *
818
 *  - 1956-00-00
819
 *  - 0000-00-00
820
 *  - 1957-03-00
821
 *
822
 * that is either the start date is returned if set otherwise the
823
 * end date
824
 *
825
 * @param  $period
826
 *    An JodaTime org.joda.time.Period object.
827
 * @return string normalized form of the date
828
 *   suitable for sorting
829
 */
830
function timePeriodAsOrderKey($period) {
831
  $dateString = '';
832
  if ($period->start) {
833
    $dateString = partialToDate($period->start, false);
834
  }
835
  if ($period->end) {
836
    $dateString .= partialToDate($period->end, false);
837
  }
838
  return $dateString;
839
}
840

    
841
/**
842
 * Composes a absolute CDM web service URI with parameters and querystring.
843
 *
844
 * @param string $uri_pattern
845
 *   String with place holders ($0, $1, ..) that should be replaced by the
846
 *   according element of the $pathParameters array.
847
 * @param array $pathParameters
848
 *   An array of path elements, or a single element.
849
 * @param string $query
850
 *   A query string to append to the URL.
851
 *
852
 * @return string
853
 *   A complete URL with parameters to a CDM webservice.
854
 */
855
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
856
  if (empty($pathParameters)) {
857
    $pathParameters = array();
858
  }
859

    
860
  // (1)
861
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
862
  // according element of the $pathParameters array.
863
  static $helperArray = array();
864
  if (isset($pathParameters) && !is_array($pathParameters)) {
865
    $helperArray[0] = $pathParameters;
866
    $pathParameters = $helperArray;
867
  }
868

    
869
  $i = 0;
870
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
871
    if (count($pathParameters) <= $i) {
872
        drupal_set_message(
873
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
874
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
875
          'error');
876
      break;
877
    }
878
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
879
    ++$i;
880
  }
881

    
882
  // (2)
883
  // Append all remaining element of the $pathParameters array as path
884
  // elements.
885
  if (count($pathParameters) > $i) {
886
    // Strip trailing slashes.
887
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
888
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
889
    }
890
    while (count($pathParameters) > $i) {
891
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
892
      ++$i;
893
    }
894
  }
895

    
896
  // (3)
897
  // Append the query string supplied by $query.
898
  if (isset($query)) {
899
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
900
  }
901

    
902
  $path = $uri_pattern;
903

    
904
  $uri = variable_get('cdm_webservice_url', '') . $path;
905
  return $uri;
906
}
907

    
908
/**
909
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
910
 *     together with a theme name to such a proxy function?
911
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
912
 *     Maybe we want to have two different proxy functions, one with theming and one without?
913
 *
914
 * @param string $uri
915
 *     A URI to a CDM Rest service from which to retrieve an object
916
 * @param string|null $hook
917
 *     (optional) The hook name to which the retrieved object should be passed.
918
 *     Hooks can either be a theme_hook() or compose_hook() implementation
919
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
920
 *     suitable for drupal_render()
921
 *
922
 * @todo Please document this function.
923
 * @see http://drupal.org/node/1354
924
 */
925
function proxy_content($uri, $hook = NULL) {
926

    
927
  $args = func_get_args();
928
  $do_gzip = function_exists('gzencode');
929
  $uriEncoded = array_shift($args);
930
  $uri = urldecode($uriEncoded);
931
  $hook = array_shift($args);
932
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
933

    
934
  $post_data = null;
935

    
936
  if ($request_method == "POST" || $request_method == "PUT") {
937
    // read response body via inputstream module
938
    $post_data = file_get_contents("php://input");
939
  }
940

    
941
  // Find and deserialize arrays.
942
  foreach ($args as &$arg) {
943
    // FIXME use regex to find serialized arrays.
944
    //       or should we accept json instead of php serializations?
945
    if (strpos($arg, "a:") === 0) {
946
      $arg = unserialize($arg);
947
    }
948
  }
949

    
950
  // In all these cases perform a simple get request.
951
  // TODO reconsider caching logic in this function.
952

    
953
  if (empty($hook)) {
954
    // simply return the webservice response
955
    // Print out JSON, the cache cannot be used since it contains objects.
956
    $http_response = cdm_http_request($uri, $request_method, $post_data);
957
    if (isset($http_response->headers)) {
958
      foreach ($http_response->headers as $hname => $hvalue) {
959
        drupal_add_http_header($hname, $hvalue);
960
      }
961
    }
962
    if (isset($http_response->data)) {
963
      print $http_response->data;
964
      flush();
965
    }
966
    exit(); // leave drupal here
967
  } else {
968
    // $hook has been supplied
969
    // handle $hook either as compose ot theme hook
970
    // pass through theme or comose hook
971
    // compose hooks can be called without data, therefore
972
    // passing the $uri in this case is not always a requirement
973

    
974
    if($uri && $uri != 'NULL') {
975
    // do a security check since the $uri will be passed
976
    // as absolute URI to cdm_ws_get()
977
      if (!_is_cdm_ws_uri($uri)) {
978
        drupal_set_message(
979
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
980
          'error'
981
        );
982
        return '';
983
      }
984

    
985
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
986
    } else {
987
      $obj = NULL;
988
    }
989

    
990
    $reponse_data = NULL;
991

    
992
    if (function_exists('compose_' . $hook)){
993
      // call compose hook
994

    
995
      $elements =  call_user_func('compose_' . $hook, $obj);
996
      // pass the render array to drupal_render()
997
      $reponse_data = drupal_render($elements);
998
    } else {
999
      // call theme hook
1000

    
1001
      // TODO use theme registry to get the registered hook info and
1002
      //    use these defaults
1003
      switch($hook) {
1004
        case 'cdm_taxontree':
1005
          $variables = array(
1006
            'tree' => $obj,
1007
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
1008
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
1009
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
1010
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
1011
            );
1012
          $reponse_data = theme($hook, $variables);
1013
          break;
1014

    
1015
        case 'cdm_list_of_taxa':
1016
            $variables = array(
1017
              'records' => $obj,
1018
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
1019
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
1020
            $reponse_data = theme($hook, $variables);
1021
            break;
1022

    
1023
        case 'cdm_media_caption':
1024
          $variables = array(
1025
            'media' => $obj,
1026
            // $args[0] is set in taxon_image_gallery_default in
1027
            // cdm_dataportal.page.theme.
1028
            'elements' => isset($args[0]) ? $args[0] : array(
1029
            'title',
1030
            'description',
1031
            'artist',
1032
            'location',
1033
            'rights',
1034
          ),
1035
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
1036
          );
1037
          $reponse_data = theme($hook, $variables);
1038
          break;
1039

    
1040
        default:
1041
          drupal_set_message(t(
1042
          'Theme !theme is not yet supported by the function !function.', array(
1043
          '!theme' => $hook,
1044
          '!function' => __FUNCTION__,
1045
          )), 'error');
1046
          break;
1047
      } // END of theme hook switch
1048
    } // END of tread as theme hook
1049

    
1050

    
1051
    if($do_gzip){
1052
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1053
      drupal_add_http_header('Content-Encoding', 'gzip');
1054
    }
1055
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1056
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1057

    
1058
    print $reponse_data;
1059
  } // END of handle $hook either as compose ot theme hook
1060

    
1061
}
1062

    
1063
/**
1064
 * @todo Please document this function.
1065
 * @see http://drupal.org/node/1354
1066
 */
1067
function setvalue_session() {
1068
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1069
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1070
    $var_keys = explode('][', $var_keys);
1071
  }
1072
  else {
1073
    return;
1074
  }
1075
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1076

    
1077
  // Prevent from malicous tags.
1078
  $val = strip_tags($val);
1079

    
1080
  $session_var = &$_SESSION;
1081
  //$i = 0;
1082
  foreach ($var_keys as $key) {
1083
    // $hasMoreKeys = ++$i < count($session);
1084
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1085
      $session_var[$key] = array();
1086
    }
1087
    $session_var = &$session_var[$key];
1088
  }
1089
  $session_var = $val;
1090
  if (isset($_REQUEST['destination'])) {
1091
    drupal_goto($_REQUEST['destination']);
1092
  }
1093
}
1094

    
1095
/**
1096
 * @todo Please document this function.
1097
 * @see http://drupal.org/node/1354
1098
 */
1099
function uri_uriByProxy($uri, $theme = FALSE) {
1100
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1101
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1102
}
1103

    
1104
/**
1105
 * Composes the the absolute REST service URI to the annotations pager
1106
 * for the given CDM entity.
1107
 *
1108
 * NOTE: Not all CDM Base types are yet supported.
1109
 *
1110
 * @param $cdmBase
1111
 *   The CDM entity to construct the annotations pager uri for
1112
 */
1113
function cdm_compose_annotations_uri($cdmBase) {
1114

    
1115
  if (!$cdmBase->uuid) {
1116
    return;
1117
  }
1118

    
1119
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
1120

    
1121
  if($ws_base_uri === null){
1122
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1123
  }
1124
  return cdm_compose_url($ws_base_uri, array(
1125
    $cdmBase->uuid,
1126
    'annotations',
1127
  ));
1128
}
1129

    
1130
/**
1131
 * Provides the base URI of the cdm REST service responsible for the passed simple name
1132
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
1133
 *
1134
 * @param $cdm_type_simple
1135
 *    simple name of a CDM java class
1136
 * @return null|string
1137
 */
1138
function cdm_ws_base_uri($cdm_type_simple)
1139
{
1140
  $ws_base_uri = NULL;
1141
  switch ($cdm_type_simple) {
1142
    case 'TaxonBase':
1143
    case 'Taxon':
1144
    case 'Synonym':
1145
      $ws_base_uri = CDM_WS_TAXON;
1146
      break;
1147

    
1148
    case 'TaxonName':
1149
      $ws_base_uri = CDM_WS_NAME;
1150
      break;
1151

    
1152
    case 'Media':
1153
      $ws_base_uri = CDM_WS_MEDIA;
1154
      break;
1155

    
1156
    case 'Reference':
1157
      $ws_base_uri = CDM_WS_REFERENCE;
1158
      break;
1159

    
1160
    case 'Distribution':
1161
    case 'TextData':
1162
    case 'TaxonInteraction':
1163
    case 'QuantitativeData':
1164
    case 'IndividualsAssociation':
1165
    case 'CommonTaxonName':
1166
    case 'CategoricalData':
1167
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1168
      break;
1169

    
1170
    case 'PolytomousKey':
1171
    case 'MediaKey':
1172
    case 'MultiAccessKey':
1173
      $ws_base_uri = $cdm_type_simple;
1174
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1175
      break;
1176

    
1177
    default:
1178
      $ws_base_uri = null;
1179
  }
1180
  return $ws_base_uri;
1181
}
1182

    
1183
/**
1184
 * Enter description here...
1185
 *
1186
 * @param string $resourceURI
1187
 * @param int $pageSize
1188
 *   The maximum number of entities returned per page.
1189
 *   The default page size as configured in the cdm server
1190
 *   will be used if set to NULL
1191
 *   to return all entities in a single page).
1192
 * @param int $pageNumber
1193
 *   The number of the page to be returned, the first page has the
1194
 *   pageNumber = 0
1195
 * @param array $query
1196
 *   A array holding the HTTP request query parameters for the request
1197
 * @param string $method
1198
 *   The HTTP method to use, valid values are "GET" or "POST"
1199
 * @param bool $absoluteURI
1200
 *   TRUE when the URL should be treated as absolute URL.
1201
 *
1202
 * @return the a CDM Pager object
1203
 *
1204
 */
1205
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1206

    
1207
  $query['pageNumber'] = $pageNumber;
1208
  $query['pageSize'] = $pageSize;
1209

    
1210
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1211
}
1212

    
1213
/**
1214
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1215
 *
1216
 * @param string $resourceURI
1217
 * @param array $query
1218
 *   A array holding the HTTP request query parameters for the request
1219
 * @param string $method
1220
 *   The HTTP method to use, valid values are "GET" or "POST";
1221
 * @param bool $absoluteURI
1222
 *   TRUE when the URL should be treated as absolute URL.
1223
 *
1224
 * @return array
1225
 *     A list of CDM entitites
1226
 *
1227
 */
1228
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1229
  $page_index = 0;
1230
  // using a bigger page size to avoid to many multiple requests
1231
  $page_size = 500;
1232
  $entities = array();
1233

    
1234
  while ($page_index !== FALSE){
1235
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1236
    if(isset($pager->records) && is_array($pager->records)) {
1237
      $entities = array_merge($entities, $pager->records);
1238
      if(!empty($pager->nextIndex)){
1239
        $page_index = $pager->nextIndex;
1240
      } else {
1241
        $page_index = FALSE;
1242
      }
1243
    } else {
1244
      $page_index = FALSE;
1245
    }
1246
  }
1247
  return $entities;
1248
}
1249

    
1250
/*
1251
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1252
  $viewrank = _cdm_taxonomy_compose_viewrank();
1253
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1254
  ? '/' . $path : '') ;
1255
}
1256
*/
1257

    
1258
/**
1259
 * @todo Enter description here...
1260
 *
1261
 * @param string $taxon_uuid
1262
 *  The UUID of a cdm taxon instance
1263
 * @param string $ignore_rank_limit
1264
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1265
 *
1266
 * @return string
1267
 *   A cdm REST service URL path to a Classification
1268
 */
1269
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1270

    
1271
  $view_uuid = get_current_classification_uuid();
1272
  $rank_uuid = NULL;
1273
  if (!$ignore_rank_limit) {
1274
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1275
  }
1276

    
1277
  if (!empty($taxon_uuid)) {
1278
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1279
      $view_uuid,
1280
      $taxon_uuid,
1281
    ));
1282
  }
1283
  else {
1284
    if (is_uuid($rank_uuid)) {
1285
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1286
        $view_uuid,
1287
        $rank_uuid,
1288
      ));
1289
    }
1290
    else {
1291
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1292
        $view_uuid,
1293
      ));
1294
    }
1295
  }
1296
}
1297

    
1298
/**
1299
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1300
 *
1301
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1302
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1303
 *
1304
 * Operates in two modes depending on whether the parameter
1305
 * $taxon_uuid is set or NULL.
1306
 *
1307
 * A) $taxon_uuid = NULL:
1308
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1309
 *  2. otherwise return the default classification as defined by the admin via the settings
1310
 *
1311
 * b) $taxon_uuid is set:
1312
 *   return the classification to whcih the taxon belongs to.
1313
 *
1314
 * @param UUID $taxon_uuid
1315
 *   The UUID of a cdm taxon instance
1316
 */
1317
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1318

    
1319
    $response = NULL;
1320

    
1321
    // 1st try
1322
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1323

    
1324
    if ($response == NULL) {
1325
      // 2dn try by ignoring the rank limit
1326
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1327
    }
1328

    
1329
    if ($response == NULL) {
1330
      // 3rd try, last fallback:
1331
      //    return the default classification
1332
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1333
        // Delete the session value and try again with the default.
1334
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1335
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1336
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1337
      }
1338
      else {
1339
        // Check if taxonomictree_uuid is valid.
1340
        // expecting an array of taxonNodes,
1341
        // empty classifications are ok so no warning in this case!
1342
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1343
        if (!is_array($test)) {
1344
          // The default set by the admin seems to be invalid or is not even set.
1345
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1346
        }
1347
        if (count($test) == 0) {
1348
          // The default set by the admin seems to be invalid or is not even set.
1349
          drupal_set_message("The chosen classification is empty.", 'status');
1350
        }
1351
      }
1352
    }
1353

    
1354
  return $response;
1355
}
1356

    
1357
/**
1358
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1359
 * 
1360
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1361
 * variable is set.
1362
 *
1363
 * @param string $taxon_uuid
1364
 *
1365
 * @return array
1366
 *   An array of CDM TaxonNodeDTO objects
1367
 */
1368
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1369
  $view_uuid = get_current_classification_uuid();
1370
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1371

    
1372
  $response = NULL;
1373
  if (is_uuid($rank_uuid)) {
1374
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1375
      $view_uuid,
1376
      $taxon_uuid,
1377
      $rank_uuid,
1378
    ));
1379
  }
1380
  else {
1381
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1382
      $view_uuid,
1383
      $taxon_uuid,
1384
    ));
1385
  }
1386

    
1387
  if ($response == NULL) {
1388
    // Error handing.
1389
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1390
//      // Delete the session value and try again with the default.
1391
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1392
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1393
//    }
1394
//    else {
1395
      // Check if taxonomictree_uuid is valid.
1396
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1397
      if ($test == NULL) {
1398
        // The default set by the admin seems to be invalid or is not even set.
1399
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1400
      }
1401
//    }
1402
  }
1403

    
1404
  return $response;
1405
}
1406

    
1407

    
1408
// =============================Terms and Vocabularies ========================================= //
1409

    
1410
/**
1411
 * Returns the localized representation for the given term.
1412
 *
1413
 * @param Object $definedTermBase
1414
 * 	  of cdm type DefinedTermBase
1415
 * @return string
1416
 * 	  the localized representation_L10n of the term,
1417
 *    otherwise the titleCache as fall back,
1418
 *    otherwise the default_representation which defaults to an empty string
1419
 */
1420
function cdm_term_representation($definedTermBase, $default_representation = '') {
1421
  if ( isset($definedTermBase->representation_L10n) ) {
1422
    return $definedTermBase->representation_L10n;
1423
  } elseif ( isset($definedTermBase->titleCache)) {
1424
    return $definedTermBase->titleCache;
1425
  }
1426
  return $default_representation;
1427
}
1428

    
1429
/**
1430
 * Returns the abbreviated localized representation for the given term.
1431
 *
1432
 * @param Object $definedTermBase
1433
 * 	  of cdm type DefinedTermBase
1434
 * @return string
1435
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1436
 *    if this representation is not available the function delegates the
1437
 *    call to cdm_term_representation()
1438
 */
1439
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1440
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1441
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1442
  } else {
1443
    cdm_term_representation($definedTermBase, $default_representation);
1444
  }
1445
}
1446

    
1447
/**
1448
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1449
 *
1450
 * The options array is suitable for drupal form API elements that allow multiple choices.
1451
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1452
 *
1453
 * @param array $terms
1454
 *   a list of CDM DefinedTermBase instances
1455
 *
1456
 * @param $term_label_callback
1457
 *   A callback function to override the term representations
1458
 *
1459
 * @param bool $empty_option
1460
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1461
 *
1462
 * @return array
1463
 *   the terms in an array as options for a form element that allows multiple choices.
1464
 */
1465
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1466
  $options = array();
1467
  if(isset($terms) && is_array($terms)) {
1468
    foreach ($terms as $term) {
1469
      if ($term_label_callback && function_exists($term_label_callback)) {
1470
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1471
      } else {
1472
        //TODO use cdm_term_representation() here?
1473
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1474
      }
1475
    }
1476
  }
1477

    
1478
  if($empty_option !== FALSE){
1479
    array_unshift ($options, "");
1480
  }
1481

    
1482
  return $options;
1483
}
1484

    
1485
/**
1486
 * Creates and array of options for drupal select form elements.
1487
 *
1488
 * @param $vocabulary_uuid
1489
 *   The UUID of the CDM Term Vocabulary
1490
 * @param $term_label_callback
1491
 *   An optional call back function which can be used to modify the term label
1492
 * @param bool $empty_option
1493
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1494
 * @param array $include_filter
1495
 *   An associative array consisting of a field name an regular expression. All term matching
1496
 *   these filter are included. The value of the field is converted to a String by var_export()
1497
 *   so a boolean 'true' can be matched by '/true/'
1498
 * @param string $order_by
1499
 *   One of the order by constants defined in this file
1500
 * @return mixed
1501
 */
1502
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1503
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1504

    
1505
  static $vocabularyOptions = array();
1506

    
1507
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1508
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1509
      array(
1510
        'orderBy' => $order_by
1511
      )
1512
    );
1513

    
1514
    // apply the include filter
1515
    if($include_filter != null){
1516
      $included_terms = array();
1517

    
1518
      foreach ($terms as $term){
1519
        $include = true;
1520
        foreach ($include_filter as $field=>$regex){
1521
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1522
          if(!$include){
1523
            break;
1524
          }
1525
        }
1526
        if($include){
1527
          $included_terms[] = $term;
1528
        }
1529
      }
1530

    
1531
      $terms = $included_terms;
1532
    }
1533

    
1534
    // make options list
1535
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1536
  }
1537

    
1538
  $options = $vocabularyOptions[$vocabulary_uuid];
1539

    
1540
  return $options;
1541
}
1542

    
1543
/**
1544
 * @param $term_type string one of
1545
 *  - Unknown
1546
 *  - Language
1547
 *  - NamedArea
1548
 *  - Rank
1549
 *  - Feature
1550
 *  - AnnotationType
1551
 *  - MarkerType
1552
 *  - ExtensionType
1553
 *  - DerivationEventType
1554
 *  - PresenceAbsenceTerm
1555
 *  - NomenclaturalStatusType
1556
 *  - NameRelationshipType
1557
 *  - HybridRelationshipType
1558
 *  - SynonymRelationshipType
1559
 *  - TaxonRelationshipType
1560
 *  - NameTypeDesignationStatus
1561
 *  - SpecimenTypeDesignationStatus
1562
 *  - InstitutionType
1563
 *  - NamedAreaType
1564
 *  - NamedAreaLevel
1565
 *  - RightsType
1566
 *  - MeasurementUnit
1567
 *  - StatisticalMeasure
1568
 *  - MaterialOrMethod
1569
 *  - Material
1570
 *  - Method
1571
 *  - Modifier
1572
 *  - Scope
1573
 *  - Stage
1574
 *  - KindOfUnit
1575
 *  - Sex
1576
 *  - ReferenceSystem
1577
 *  - State
1578
 *  - NaturalLanguageTerm
1579
 *  - TextFormat
1580
 *  - DeterminationModifier
1581
 *  - DnaMarker
1582
 *
1583
 * @param  $order_by
1584
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1585
 *  possible values:
1586
 *    - CDM_ORDER_BY_ID_ASC
1587
 *    - CDM_ORDER_BY_ID_DESC
1588
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1589
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1590
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1591
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1592
 * @param bool $empty_option
1593
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1594
 * @return array
1595
 *    the terms in an array as options for a form element that allows multiple choices.
1596
 */
1597
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1598
  $terms = cdm_ws_fetch_all(
1599
    CDM_WS_TERM,
1600
    array(
1601
      'class' => $term_type,
1602
      'orderBy' => $order_by
1603
    )
1604
  );
1605
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1606
}
1607

    
1608

    
1609
/**
1610
 * @todo Please document this function.
1611
 * @see http://drupal.org/node/1354
1612
 */
1613
function _cdm_relationship_type_term_label_callback($term) {
1614
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1615
    return $term->representation_L10n_abbreviatedLabel . ' : '
1616
    . t('@term', array('@term' => $term->representation_L10n));
1617
  }
1618
else {
1619
    return t('@term', array('@term' => $term->representation_L10n));
1620
  }
1621
}
1622

    
1623
// ========================================================================================== //
1624
/**
1625
 * @todo Improve documentation of this function.
1626
 *
1627
 * eu.etaxonomy.cdm.model.description.
1628
 * CategoricalData
1629
 * CommonTaxonName
1630
 * Distribution
1631
 * IndividualsAssociation
1632
 * QuantitativeData
1633
 * TaxonInteraction
1634
 * TextData
1635
 */
1636
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1637
  static $types = array(
1638
    "CategoricalData",
1639
    "CommonTaxonName",
1640
    "Distribution",
1641
    "IndividualsAssociation",
1642
    "QuantitativeData",
1643
    "TaxonInteraction",
1644
    "TextData",
1645
  );
1646

    
1647
  static $options = NULL;
1648
  if ($options == NULL) {
1649
    $options = array();
1650
    if ($prependEmptyElement) {
1651
      $options[' '] = '';
1652
    }
1653
    foreach ($types as $type) {
1654
      // No internatianalization here since these are purely technical terms.
1655
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1656
    }
1657
  }
1658
  return $options;
1659
}
1660

    
1661

    
1662
/**
1663
 * Fetches all TaxonDescription descriptions elements which are associated to the
1664
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1665
 * feature tree.
1666
 * @param $feature_tree
1667
 *     The CDM FeatureTree to be used as template
1668
 * @param $taxon_uuid
1669
 *     The UUID of the taxon
1670
 * @param $excludes
1671
 *     UUIDs of features to be excluded
1672
 * @return$feature_tree
1673
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1674
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1675
 *     witch will hold the according $descriptionElements.
1676
 */
1677
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1678

    
1679
  if (!$feature_tree) {
1680
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1681
      In order to see the species profiles of your taxa, please select a
1682
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1683
    return FALSE;
1684
  }
1685

    
1686
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1687
      array(
1688
      'taxon' => $taxon_uuid,
1689
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1690
      ),
1691
      'POST'
1692
  );
1693

    
1694
  // Combine all descriptions into one feature tree.
1695
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1696
  $feature_tree->root->childNodes = $merged_nodes;
1697

    
1698
  return $feature_tree;
1699
}
1700

    
1701
/**
1702
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1703
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1704
 * be requested for the annotations.
1705
 *
1706
 * @param string $cdmBase
1707
 *   An annotatable cdm entity.
1708
 * @param array $includeTypes
1709
 *   If an array of annotation type uuids is supplied by this parameter the
1710
 *   list of annotations is resticted to those which belong to this type.
1711
 *
1712
 * @return array
1713
 *   An array of Annotation objects or an empty array.
1714
 */
1715
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1716

    
1717
  if(!isset($cdmBase->annotations)){
1718
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1719
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1720
  }
1721

    
1722
  $annotations = array();
1723
  foreach ($cdmBase->annotations as $annotation) {
1724
    if ($includeTypes) {
1725
      if (
1726
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1727
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1728
      ) {
1729
        $annotations[] = $annotation;
1730
      }
1731
    }
1732
    else {
1733
      $annotations[] = $annotation;
1734
    }
1735
  }
1736
  return $annotations;
1737

    
1738
}
1739

    
1740
/**
1741
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1742
 *
1743
 * @param object $annotatable_entity
1744
 *   The CDM AnnotatableEntity to load annotations for
1745
 */
1746
function cdm_load_annotations(&$annotatable_entity) {
1747
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1748
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1749
    if (is_array($annotations)) {
1750
      $annotatable_entity->annotations = $annotations;
1751
    }
1752
  }
1753
}
1754

    
1755
/**
1756
 * Extends the $cdm_entity object by the field if it is not already existing.
1757
 *
1758
 * This function can only be used for fields with 1 to many relations.
1759
  *
1760
 * @param $cdm_base_type
1761
 * @param $field_name
1762
 * @param $cdm_entity
1763
 */
1764
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1765
{
1766
  if (!isset($cdm_entity->$field_name)) {
1767
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1768
    $cdm_entity->$field_name = $items;
1769
  }
1770
}
1771

    
1772

    
1773
/**
1774
 * Get a NomenclaturalReference string.
1775
 *
1776
 * Returns the NomenclaturalReference string with correctly placed
1777
 * microreference (= reference detail) e.g.
1778
 * in Phytotaxa 43: 1-48. 2012.
1779
 *
1780
 * @param string $referenceUuid
1781
 *   UUID of the reference.
1782
 * @param string $microreference
1783
 *   Reference detail.
1784
 *
1785
 * @return string
1786
 *   a NomenclaturalReference.
1787
 */
1788
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1789

    
1790
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1791
  if(is_array($microreference) || is_object($microreference)) {
1792
    return '';
1793
  }
1794

    
1795
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1796
    $referenceUuid,
1797
  ), "microReference=" . urlencode($microreference));
1798

    
1799
  if ($obj) {
1800
    return $obj->String;
1801
  }
1802
  else {
1803
    return NULL;
1804
  }
1805
}
1806

    
1807
/**
1808
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1809
 *
1810
 * @param $feature_tree_nodes
1811
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1812
 * @param $feature_uuid
1813
 *    The UUID of the Feature
1814
 * @return returns the FeatureNode or null
1815
 */
1816
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1817

    
1818
  // 1. scan this level
1819
  foreach ($feature_tree_nodes as $node){
1820
    if($node->feature->uuid == $feature_uuid){
1821
      return $node;
1822
    }
1823
  }
1824

    
1825
  // 2. descend into childen
1826
  foreach ($feature_tree_nodes as $node){
1827
    if(is_array($node->childNodes)){
1828
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1829
      if($node) {
1830
        return $node;
1831
      }
1832
    }
1833
  }
1834
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1835
  return $null_var;
1836
}
1837

    
1838
/**
1839
 * Merges the given featureNodes structure with the descriptionElements.
1840
 *
1841
 * This method is used in preparation for rendering the descriptionElements.
1842
 * The descriptionElements which belong to a specific feature node are appended
1843
 * to a the feature node by creating a new field:
1844
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1845
 * The descriptionElements will be cleared in advance in order to allow reusing the
1846
 * same feature tree without the risk of mixing sets of description elements.
1847
 *
1848
 * which originally is not existing in the cdm.
1849
 *
1850
 *
1851
 *
1852
 * @param array $featureNodes
1853
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1854
 *    may have children.
1855
 * @param array $descriptionElements
1856
 *    An flat array of cdm DescriptionElements
1857
 * @return array
1858
 *    The $featureNodes structure enriched with the according $descriptionElements
1859
 */
1860
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1861

    
1862
  foreach ($featureNodes as &$node) {
1863
    // since the $featureNodes array is reused for each description
1864
    // it is necessary to clear the custom node fields in advance
1865
    if(isset($node->descriptionElements)){
1866
      unset($node->descriptionElements);
1867
    }
1868

    
1869
    // Append corresponding elements to an additional node field:
1870
    // $node->descriptionElements.
1871
    foreach ($descriptionElements as $element) {
1872
      if ($element->feature->uuid == $node->feature->uuid) {
1873
        if (!isset($node->descriptionElements)) {
1874
          $node->descriptionElements = array();
1875
        }
1876
        $node->descriptionElements[] = $element;
1877
      }
1878
    }
1879

    
1880
    // Recurse into node children.
1881
    if (isset($node->childNodes[0])) {
1882
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1883
      $node->childNodes = $mergedChildNodes;
1884
    }
1885

    
1886
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1887
      unset($node);
1888
    }
1889

    
1890
  }
1891

    
1892
  return $featureNodes;
1893
}
1894

    
1895
/**
1896
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1897
 *
1898
 * The response from the HTTP GET request is returned as object.
1899
 * The response objects coming from the webservice configured in the
1900
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1901
 *  in a level 2 (L2) cache.
1902
 *
1903
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1904
 * function, this cache persists only per each single page execution.
1905
 * Any object coming from the webservice is stored into it by default.
1906
 * In contrast to this default caching mechanism the L2 cache only is used if
1907
 * the 'cdm_webservice_cache' variable is set to TRUE,
1908
 * which can be set using the modules administrative settings section.
1909
 * Objects stored in this L2 cache are serialized and stored
1910
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1911
 * objects that are stored in the database will persist as
1912
 * long as the drupal cache is not being cleared and are available across
1913
 * multiple script executions.
1914
 *
1915
 * @param string $uri
1916
 *   URL to the webservice.
1917
 * @param array $pathParameters
1918
 *   An array of path parameters.
1919
 * @param string $query
1920
 *   A query string to be appended to the URL.
1921
 * @param string $method
1922
 *   The HTTP method to use, valid values are "GET" or "POST";
1923
 * @param bool $absoluteURI
1924
 *   TRUE when the URL should be treated as absolute URL.
1925
 *
1926
 * @return object| array
1927
 *   The de-serialized webservice response object.
1928
 */
1929
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1930

    
1931
  static $cacheL1 = array();
1932

    
1933
  $data = NULL;
1934
  // store query string in $data and clear the query, $data will be set as HTTP request body
1935
  if($method == 'POST'){
1936
    $data = $query;
1937
    $query = NULL;
1938
  }
1939

    
1940
  // Transform the given uri path or pattern into a proper webservice uri.
1941
  if (!$absoluteURI) {
1942
    $uri = cdm_compose_url($uri, $pathParameters, $query);
1943
  }
1944

    
1945
  // read request parameter 'cacheL2_refresh'
1946
  // which allows refreshing the level 2 cache
1947
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
1948

    
1949
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
1950
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
1951

    
1952
  if($method == 'GET'){
1953
    $cache_key = $uri;
1954
  } else {
1955
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
1956
    // crc32 is faster but creates much shorter hashes
1957
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
1958
  }
1959

    
1960
  if (array_key_exists($cache_key, $cacheL1)) {
1961
    $cacheL1_obj = $cacheL1[$uri];
1962
  }
1963

    
1964
  $set_cacheL1 = FALSE;
1965
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
1966
    $set_cacheL1 = TRUE;
1967
  }
1968

    
1969
  // Only cache cdm webservice URIs.
1970
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
1971
  $cacheL2_entry = FALSE;
1972

    
1973
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
1974
    // Try to get object from cacheL2.
1975
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
1976
  }
1977

    
1978
  if (isset($cacheL1_obj)) {
1979
    //
1980
    // The object has been found in the L1 cache.
1981
    //
1982
    $obj = $cacheL1_obj;
1983
    if (cdm_debug_block_visible()) {
1984
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
1985
    }
1986
  }
1987
  elseif ($cacheL2_entry) {
1988
    //
1989
    // The object has been found in the L2 cache.
1990
    //
1991
    $duration_parse_start = microtime(TRUE);
1992
    $obj = unserialize($cacheL2_entry->data);
1993
    $duration_parse = microtime(TRUE) - $duration_parse_start;
1994

    
1995
    if (cdm_debug_block_visible()) {
1996
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
1997
    }
1998
  }
1999
  else {
2000
    //
2001
    // Get the object from the webservice and cache it.
2002
    //
2003
    $duration_fetch_start = microtime(TRUE);
2004
    // Request data from webservice JSON or XML.
2005
    $response = cdm_http_request($uri, $method, $data);
2006
    $response_body = NULL;
2007
    if (isset($response->data)) {
2008
      $response_body = $response->data;
2009
    }
2010
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2011
    $duration_parse_start = microtime(TRUE);
2012

    
2013
    // Parse data and create object.
2014
    $obj = cdm_load_obj($response_body);
2015

    
2016
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2017

    
2018
    if (cdm_debug_block_visible()) {
2019
      if ($obj || $response_body == "[]") {
2020
        $status = 'valid';
2021
      }
2022
      else {
2023
        $status = 'invalid';
2024
      }
2025
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2026
    }
2027
    if ($set_cacheL2) {
2028
      // Store the object in cache L2.
2029
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2030
      // flag serialized is set properly in the cache table.
2031
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2032
    }
2033
  }
2034
  if ($obj) {
2035
    // Store the object in cache L1.
2036
    if ($set_cacheL1) {
2037
      $cacheL1[$cache_key] = $obj;
2038
    }
2039
  }
2040
  return $obj;
2041
}
2042

    
2043
/**
2044
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2045
 *
2046
 * The cdm_ws_debug block will display the debug information.
2047
 *
2048
 * @param $uri
2049
 *    The CDM REST URI to which the request has been send
2050
 * @param string $method
2051
 *    The HTTP request method, either 'GET' or 'POST'
2052
 * @param string $post_data
2053
 *    The datastring send with a post request
2054
 * @param $duration_fetch
2055
 *    The time in seconds it took to fetch the data from the web service
2056
 * @param $duration_parse
2057
 *    Time in seconds which was needed to parse the json response
2058
 * @param $datasize
2059
 *    Size of the data received from the server
2060
 * @param $status
2061
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2062
 * @return bool
2063
 *    TRUE if adding the debug information was successful
2064
 */
2065
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2066

    
2067
  static $initial_time = NULL;
2068
  if(!$initial_time) {
2069
    $initial_time = microtime(TRUE);
2070
  }
2071
  $time = microtime(TRUE) - $initial_time;
2072

    
2073
  // Decompose uri into path and query element.
2074
  $uri_parts = explode("?", $uri);
2075
  $query = array();
2076
  if (count($uri_parts) == 2) {
2077
    $path = $uri_parts[0];
2078
  }
2079
  else {
2080
    $path = $uri;
2081
  }
2082

    
2083
  if(strpos($uri, '?') > 0){
2084
    $json_uri = str_replace('?', '.json?', $uri);
2085
    $xml_uri = str_replace('?', '.xml?', $uri);
2086
  } else {
2087
    $json_uri = $uri . '.json';
2088
    $xml_uri = $json_uri . '.xml';
2089
  }
2090

    
2091
  // data links to make data accecsible as json and xml
2092
  $data_links = '';
2093
  if (_is_cdm_ws_uri($path)) {
2094

    
2095
    // see ./js/http-method-link.js
2096

    
2097
    if($method == 'GET'){
2098
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2099
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2100
      $data_links .= '<br/>';
2101
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2102
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2103
    } else {
2104
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2105
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2106
      $data_links .= '<br/>';
2107
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2108
    }
2109
  }
2110
  else {
2111
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2112
  }
2113

    
2114
  //
2115
  $data = array(
2116
      'ws_uri' => $uri,
2117
      'method' => $method,
2118
      'post_data' => $post_data,
2119
      'time' => sprintf('%3.3f', $time),
2120
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2121
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2122
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2123
      'status' => $status,
2124
      'data_links' => $data_links
2125
  );
2126
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2127
    $_SESSION['cdm']['ws_debug'] = array();
2128
  }
2129
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2130

    
2131
  // Mark this page as being uncacheable.
2132
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2133
  drupal_page_is_cacheable(FALSE);
2134

    
2135
  // Messages not set when DB connection fails.
2136
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2137
}
2138

    
2139
/**
2140
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2141
 * the visibility depends on whether
2142
 *  - the block is enabled
2143
 *  - the visibility restrictions in the block settings are satisfied
2144
 */
2145
function cdm_debug_block_visible() {
2146
  static $is_visible = null;
2147

    
2148
  if($is_visible === null){
2149
      $block = block_load('cdm_api', 'cdm_ws_debug');
2150
      $is_visible = isset($block->status) && $block->status == 1;
2151
      if($is_visible){
2152
        $blocks = array($block);
2153
        // Checks the page, user role, and user-specific visibilty settings.
2154
        block_block_list_alter($blocks);
2155
        $is_visible = count($blocks) > 0;
2156
      }
2157
  }
2158
  return $is_visible;
2159
}
2160

    
2161
/**
2162
 * @todo Please document this function.
2163
 * @see http://drupal.org/node/1354
2164
 */
2165
function cdm_load_obj($response_body) {
2166
  $obj = json_decode($response_body);
2167

    
2168
  if (!(is_object($obj) || is_array($obj))) {
2169
    ob_start();
2170
    $obj_dump = ob_get_contents();
2171
    ob_clean();
2172
    return FALSE;
2173
  }
2174

    
2175
  return $obj;
2176
}
2177

    
2178
/**
2179
 * Do a http request to a CDM RESTful web service.
2180
 *
2181
 * @param string $uri
2182
 *   The webservice url.
2183
 * @param string $method
2184
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2185
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2186
 * @param $data: A string containing the request body, formatted as
2187
 *     'param=value&param=value&...'. Defaults to NULL.
2188
 *
2189
 * @return object
2190
 *   The object as returned by drupal_http_request():
2191
 *   An object that can have one or more of the following components:
2192
 *   - request: A string containing the request body that was sent.
2193
 *   - code: An integer containing the response status code, or the error code
2194
 *     if an error occurred.
2195
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2196
 *   - status_message: The status message from the response, if a response was
2197
 *     received.
2198
 *   - redirect_code: If redirected, an integer containing the initial response
2199
 *     status code.
2200
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2201
 *     target.
2202
 *   - error: If an error occurred, the error message. Otherwise not set.
2203
 *   - headers: An array containing the response headers as name/value pairs.
2204
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2205
 *     easy access the array keys are returned in lower case.
2206
 *   - data: A string containing the response body that was received.
2207
 */
2208
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2209
  static $acceptLanguage = NULL;
2210
  $header = array();
2211
  
2212
  if(!$acceptLanguage && module_exists('i18n')){
2213
    $acceptLanguage = i18n_language_content()->language;
2214
  }
2215

    
2216
  if (!$acceptLanguage) {
2217
    if (function_exists('apache_request_headers')) {
2218
      $headers = apache_request_headers();
2219
      if (isset($headers['Accept-Language'])) {
2220
        $acceptLanguage = $headers['Accept-Language'];
2221
      }
2222
    }
2223
  }
2224

    
2225
  if ($method != "GET" && $method != "POST") {
2226
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2227
  }
2228

    
2229
  if (_is_cdm_ws_uri($uri)) {
2230
    $header['Accept'] = 'application/json';
2231
    $header['Accept-Language'] = $acceptLanguage;
2232
    $header['Accept-Charset'] = 'UTF-8';
2233
  }
2234

    
2235
  if($method == "POST") {
2236
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2237
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2238
  }
2239

    
2240

    
2241
  cdm_dd($uri);
2242
  return drupal_http_request($uri, array(
2243
      'headers' => $header,
2244
      'method' => $method,
2245
      'data' => $data,
2246
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2247
      )
2248
   );
2249
}
2250

    
2251
/**
2252
 * Concatenates recursively the fields of all features contained in the given
2253
 * CDM FeatureTree root node.
2254
 *
2255
 * @param $rootNode
2256
 *     A CDM FeatureTree node
2257
 * @param
2258
 *     The character to be used as glue for concatenation, default is ', '
2259
 * @param $field_name
2260
 *     The field name of the CDM Features
2261
 * @param $excludes
2262
 *     Allows defining a set of values to be excluded. This refers to the values
2263
 *     in the field denoted by the $field_name parameter
2264
 *
2265
 */
2266
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2267
  $out = '';
2268

    
2269
  $pre_child_separator = $separator;
2270
  $post_child_separator = '';
2271

    
2272
  foreach ($root_node->childNodes as $feature_node) {
2273
    $out .= ($out ? $separator : '');
2274
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2275
      $out .= $feature_node->feature->$field_name;
2276
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2277
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2278
        if (strlen($childlabels)) {
2279
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2280
        }
2281
      }
2282
    }
2283
  }
2284
  return $out;
2285
}
2286

    
2287
/**
2288
 * Create a one-dimensional form options array.
2289
 *
2290
 * Creates an array of all features in the feature tree of feature nodes,
2291
 * the node labels are indented by $node_char and $childIndent depending on the
2292
 * hierachy level.
2293
 *
2294
 * @param - $rootNode
2295
 * @param - $node_char
2296
 * @param - $childIndentStr
2297
 * @param - $childIndent
2298
 *   ONLY USED INTERNALLY!
2299
 *
2300
 * @return array
2301
 *   A one dimensional Drupal form options array.
2302
 */
2303
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2304
  $options = array();
2305
  foreach ($rootNode->childNodes as $featureNode) {
2306
    $indent_prefix = '';
2307
    if ($childIndent) {
2308
      $indent_prefix = $childIndent . $node_char . " ";
2309
    }
2310
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2311
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2312
      // Foreach ($featureNode->childNodes as $childNode){
2313
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2314
      $options = array_merge_recursive($options, $childList);
2315
      // }
2316
    }
2317
  }
2318
  return $options;
2319
}
2320

    
2321
/**
2322
 * Returns an array with all available FeatureTrees and the representations of the selected
2323
 * FeatureTree as a detail view.
2324
 *
2325
 * @param boolean $add_default_feature_free
2326
 * @return array
2327
 *  associative array with following keys:
2328
 *  -options: Returns an array with all available Feature Trees
2329
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2330
 *
2331
 */
2332
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2333

    
2334
  $options = array();
2335
  $tree_representations = array();
2336
  $feature_trees = array();
2337

    
2338
  // Set tree that contains all features.
2339
  if ($add_default_feature_free) {
2340
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2341
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2342
  }
2343

    
2344
  // Get feature trees from database.
2345
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2346
  if (is_array($persited_trees)) {
2347
    $feature_trees = array_merge($feature_trees, $persited_trees);
2348
  }
2349

    
2350
  foreach ($feature_trees as $featureTree) {
2351

    
2352
    if(!is_object($featureTree)){
2353
      continue;
2354
    }
2355
    // Do not add the DEFAULT_FEATURETREE again,
2356
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2357
      $options[$featureTree->uuid] = $featureTree->titleCache;
2358
    }
2359

    
2360
    // Render the hierarchic tree structure
2361
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2362

    
2363
      // Render the hierarchic tree structure.
2364
      $treeDetails = '<div class="featuretree_structure">'
2365
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2366
        . '</div>';
2367

    
2368
      $form = array();
2369
      $form['featureTree-' .  $featureTree->uuid] = array(
2370
        '#type' => 'fieldset',
2371
        '#title' => 'Show details',
2372
        '#attributes' => array('class' => array('collapsible collapsed')),
2373
        // '#collapsible' => TRUE,
2374
        // '#collapsed' => TRUE,
2375
      );
2376
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2377
        '#markup' => $treeDetails,
2378
      );
2379

    
2380
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2381
    }
2382

    
2383
  } // END loop over feature trees
2384

    
2385
  // return $options;
2386
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2387
}
2388

    
2389
/**
2390
 * Provides the list of available classifications in form of an options array.
2391
 *
2392
 * The options array is suitable for drupal form API elements that allow multiple choices.
2393
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2394
 *
2395
 * The classifications are ordered alphabetically whereas the classification
2396
 * chosen as default will always appear on top of the array, followed by a
2397
 * blank line below.
2398
 *
2399
 * @param bool $add_none_option
2400
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2401
 *
2402
 * @return array
2403
 *   classifications in an array as options for a form element that allows multiple choices.
2404
 */
2405
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2406

    
2407
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2408

    
2409
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2410
  $default_classification_label = '';
2411

    
2412
  // add all classifications
2413
  $taxonomic_tree_options = array();
2414
  if ($add_none_option) {
2415
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2416
  }
2417
  if ($taxonTrees) {
2418
    foreach ($taxonTrees as $tree) {
2419
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2420
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2421
      } else {
2422
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2423
        $default_classification_label = $tree->titleCache;
2424
      }
2425
    }
2426
  }
2427
  // oder alphabetically the space
2428
  asort($taxonomic_tree_options);
2429

    
2430
  // now set the labels
2431
  //   for none
2432
  if ($add_none_option) {
2433
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2434
  }
2435

    
2436
  //   for default_classification
2437
  if (is_uuid($default_classification_uuid)) {
2438
    $taxonomic_tree_options[$default_classification_uuid] =
2439
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2440
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2441
  }
2442

    
2443
  return $taxonomic_tree_options;
2444
}
2445

    
2446
/**
2447
 * @todo Please document this function.
2448
 * @see http://drupal.org/node/1354
2449
 */
2450
function cdm_api_secref_cache_prefetch(&$secUuids) {
2451
  // Comment @WA: global variables should start with a single underscore
2452
  // followed by the module and another underscore.
2453
  global $_cdm_api_secref_cache;
2454
  if (!is_array($_cdm_api_secref_cache)) {
2455
    $_cdm_api_secref_cache = array();
2456
  }
2457
  $uniqueUuids = array_unique($secUuids);
2458
  $i = 0;
2459
  $param = '';
2460
  while ($i++ < count($uniqueUuids)) {
2461
    $param .= $secUuids[$i] . ',';
2462
    if (strlen($param) + 37 > 2000) {
2463
      _cdm_api_secref_cache_add($param);
2464
      $param = '';
2465
    }
2466
  }
2467
  if ($param) {
2468
    _cdm_api_secref_cache_add($param);
2469
  }
2470
}
2471

    
2472
/**
2473
 * @todo Please document this function.
2474
 * @see http://drupal.org/node/1354
2475
 */
2476
function cdm_api_secref_cache_get($secUuid) {
2477
  global $_cdm_api_secref_cache;
2478
  if (!is_array($_cdm_api_secref_cache)) {
2479
    $_cdm_api_secref_cache = array();
2480
  }
2481
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2482
    _cdm_api_secref_cache_add($secUuid);
2483
  }
2484
  return $_cdm_api_secref_cache[$secUuid];
2485
}
2486

    
2487
/**
2488
 * @todo Please document this function.
2489
 * @see http://drupal.org/node/1354
2490
 */
2491
function cdm_api_secref_cache_clear() {
2492
  global $_cdm_api_secref_cache;
2493
  $_cdm_api_secref_cache = array();
2494
}
2495

    
2496

    
2497
/**
2498
 * Validates if the given string is a uuid.
2499
 *
2500
 * @param string $str
2501
 *   The string to validate.
2502
 *
2503
 * return bool
2504
 *   TRUE if the string is a UUID.
2505
 */
2506
function is_uuid($str) {
2507
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2508
}
2509

    
2510
/**
2511
 * Checks if the given $object is a valid cdm entity.
2512
 *
2513
 * An object is considered a cdm entity if it has a string field $object->class
2514
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2515
 * The function is null save.
2516
 *
2517
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2518
 *
2519
 * @param mixed $object
2520
 *   The object to validate
2521
 *
2522
 * @return bool
2523
 *   True if the object is a cdm entity.
2524
 */
2525
function is_cdm_entity($object) {
2526
  return
2527
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2528
    && is_string($object->uuid) && is_uuid($object->uuid);
2529
}
2530

    
2531
/**
2532
 * @todo Please document this function.
2533
 * @see http://drupal.org/node/1354
2534
 */
2535
function _cdm_api_secref_cache_add($secUuidsStr) {
2536
  global $_cdm_api_secref_cache;
2537
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2538
  // Batch fetching not jet reimplemented thus:
2539
  /*
2540
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2541
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2542
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2543
  */
2544
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2545
}
2546

    
2547
/**
2548
 * Checks if the given uri starts with a cdm webservice url.
2549
 *
2550
 * Checks if the uri starts with the cdm webservice url stored in the
2551
 * Drupal variable 'cdm_webservice_url'.
2552
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2553
 *
2554
 * @param string $uri
2555
 *   The URI to test.
2556
 *
2557
 * @return bool
2558
 *   True if the uri starts with a cdm webservice url.
2559
 */
2560
function _is_cdm_ws_uri($uri) {
2561
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2562
}
2563

    
2564
/**
2565
 * @todo Please document this function.
2566
 * @see http://drupal.org/node/1354
2567
 */
2568
function queryString($elements) {
2569
  $query = '';
2570
  foreach ($elements as $key => $value) {
2571
    if (is_array($value)) {
2572
      foreach ($value as $v) {
2573
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2574
      }
2575
    }
2576
    else {
2577
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2578
    }
2579
  }
2580
  return $query;
2581
}
2582

    
2583
/**
2584
 * Implementation of the magic method __clone to allow deep cloning of objects
2585
 * and arrays.
2586
 */
2587
function __clone() {
2588
  foreach ($this as $name => $value) {
2589
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2590
      $this->$name = clone($this->$name);
2591
    }
2592
  }
2593
}
2594

    
2595
/**
2596
 * Compares the given CDM Term instances by the  representationL10n.
2597
 *
2598
 * Can also be used with TermDTOs. To be used in usort()
2599
 *
2600
 * @see http://php.net/manual/en/function.usort.php
2601
 *
2602
 * @param $term1
2603
 *   The first CDM Term instance
2604
 * @param $term2
2605
 *   The second CDM Term instance
2606
 * @return int
2607
 *   The result of the comparison
2608
 */
2609
function compare_terms_by_representationL10n($term1, $term2) {
2610

    
2611
  if (!isset($term1->representation_L10n)) {
2612
    $term1->representationL10n = '';
2613
  }
2614
  if (!isset($term2->representation_L10n)) {
2615
    $term2->representationL10n = '';
2616
  }
2617

    
2618
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2619
}
2620

    
2621
function compare_terms_by_order_index($term1, $term2) {
2622

    
2623

    
2624
  if (!isset($term1->orderIndex)) {
2625
    $a = 0;
2626
  } else {
2627
    $a = $term1->orderIndex;
2628
  }
2629
  if (!isset($term2->orderIndex)) {
2630
    $b = 0;
2631
  } else {
2632
    $b = $term2->orderIndex;
2633
  }
2634

    
2635
  if ($a == $b) {
2636
    return 0;
2637
  }
2638
  return ($a < $b) ? -1 : 1;
2639

    
2640
}
2641

    
2642

    
2643
/**
2644
 * Make a 'deep copy' of an array.
2645
 *
2646
 * Make a complete deep copy of an array replacing
2647
 * references with deep copies until a certain depth is reached
2648
 * ($maxdepth) whereupon references are copied as-is...
2649
 *
2650
 * @see http://us3.php.net/manual/en/ref.array.php
2651
 *
2652
 * @param array $array
2653
 * @param array $copy passed by reference
2654
 * @param int $maxdepth
2655
 * @param int $depth
2656
 */
2657
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2658
  if ($depth > $maxdepth) {
2659
    $copy = $array;
2660
    return;
2661
  }
2662
  if (!is_array($copy)) {
2663
    $copy = array();
2664
  }
2665
  foreach ($array as $k => &$v) {
2666
    if (is_array($v)) {
2667
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2668
    }
2669
    else {
2670
      $copy[$k] = $v;
2671
    }
2672
  }
2673
}
2674

    
2675
/**
2676
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2677
 *
2678
 */
2679
function _add_js_ws_debug() {
2680

    
2681
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2682
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2683
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2684
    // use the developer versions of js libs
2685
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2686
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2687
  }
2688
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2689
    array(
2690
      'type' => 'file',
2691
      'weight' => JS_LIBRARY,
2692
      'cache' => TRUE)
2693
    );
2694

    
2695
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2696
    array(
2697
      'type' => 'file',
2698
      'weight' => JS_LIBRARY,
2699
      'cache' => TRUE)
2700
    );
2701
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2702
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2703

    
2704
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2705
    array(
2706
      'type' => 'file',
2707
      'weight' => JS_LIBRARY,
2708
      'cache' => TRUE)
2709
    );
2710
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2711
    array(
2712
    'type' => 'file',
2713
    'weight' => JS_LIBRARY,
2714
    'cache' => TRUE)
2715
    );
2716

    
2717
}
2718

    
2719
/**
2720
 * @todo Please document this function.
2721
 * @see http://drupal.org/node/1354
2722
 */
2723
function _no_classfication_uuid_message() {
2724
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2725
    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.');
2726
  }
2727
  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.');
2728
}
2729

    
2730
/**
2731
 * Implementation of hook flush_caches
2732
 *
2733
 * Add custom cache tables to the list of cache tables that
2734
 * will be cleared by the Clear button on the Performance page or whenever
2735
 * drupal_flush_all_caches is invoked.
2736
 *
2737
 * @author W.Addink <waddink@eti.uva.nl>
2738
 *
2739
 * @return array
2740
 *   An array with custom cache tables to include.
2741
 */
2742
function cdm_api_flush_caches() {
2743
  return array('cache_cdm_ws');
2744
}
2745

    
2746
/**
2747
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2748
 *
2749
 * @param $data
2750
 *   The variable to log to the drupal_debug.txt log file.
2751
 * @param $label
2752
 *   (optional) If set, a label to output before $data in the log file.
2753
 *
2754
 * @return
2755
 *   No return value if successful, FALSE if the log file could not be written
2756
 *   to.
2757
 *
2758
 * @see cdm_dataportal_init() where the log file is reset on each requests
2759
 * @see dd()
2760
 * @see http://drupal.org/node/314112
2761
 *
2762
 */
2763
function cdm_dd($data, $label = NULL) {
2764
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2765
    return dd($data, $label);
2766
  }
2767
}
2768

    
Add picture from clipboard (Maximum size: 40 MB)