Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_api / cdm_api.module @ 83dc60b9

History | View | Annotate | Download (85.5 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
function tagged_text_new($tag_type, $text = null){
196
  $tt = new stdClass();
197
  $tt->type = $tag_type;
198
  $tt->text = $text;
199
  return $tt;
200
}
201

    
202
/**
203
 * Walks the passed TaggedText array to find all elements which have a
204
 * TaggedText->entityReference. For each of these the taggedTexts is loaded
205
 * from the webservice and the original entry in the TaggedText array will be
206
 * replaced by the newly loaded array.
207
 *
208
 * @param array $taggedtxt
209
 *    The original TaggedText array
210
 * @param array $skiptags
211
 *    Optional list of tag names to skip
212
 * @return array
213
 *    The new tagged text with all TaggedText->entityReference objects expanded
214
 */
215
function cdm_tagged_text_expand_entity_references(array $taggedtxt, $skiptags = array()) {
216
  $tagged_text_expanded = array();
217
  foreach ($taggedtxt as $tt) {
218
    if (isset($tt->entityReference) && !in_array($tt->type, $skiptags)) {
219
      $base_uri = cdm_ws_base_uri($tt->entityReference->type);
220
      if($base_uri){
221
        $tagged_text_method = "/taggedText";
222
        if($base_uri == CDM_WS_NAME){
223
          $tagged_text_method = "/taggedName";
224
        }
225
        $referenced_tt = cdm_ws_get($base_uri . "/" . $tt->entityReference->uuid . $tagged_text_method);
226
        if($referenced_tt){
227
          $tagged_text_expanded = array_merge($tagged_text_expanded, $referenced_tt);
228
          continue;
229
        }
230
      }
231
    }
232
    // default case
233
    $tagged_text_expanded[] = $tt;
234
  }
235
  return $tagged_text_expanded;
236
}
237

    
238
/**
239
 * Converts an array of TaggedText items into corresponding html tags.
240
 *
241
 * Each item is provided with a class attribute which is set to the key of the
242
 * TaggedText item.
243
 *
244
 * Tagged text where the type starts with 'PLACEHOLDER_' will be added to the markup as plain text whereas the
245
 * taggedText->type wrapped in curly brackets: '{'. $tt->text . '}' is used as text.
246
 * see tagged_text_extract_secref()
247
 *
248
 * @param array $taggedtxt
249
 *   Array with text items to convert.
250
 * @param array $skiptags
251
 *   Array of tag names to skip
252
 *
253
 * @return string
254
 *   The markup.
255
 */
256
function cdm_tagged_text_to_markup(array $taggedtxt, $skiptags = array()) {
257

    
258
  $tag = 'span';
259
  $out = '';
260
  $was_separator = false;
261
  $i = 0;
262
  foreach ($taggedtxt as $tt) {
263
    if (!in_array($tt->type, $skiptags) && $tt->text) {
264
      $class_attr = $tt->type;
265

    
266
      if(isset($tt->entityReference)){
267
        $class_attr .= " " . html_class_attribute_ref($tt->entityReference);
268
      }
269
      $is_last = $i + 1 == count($taggedtxt);
270
      $is_separator = is_tagged_text_sepatator_type($tt->type);
271
      $glue = !$is_separator && !$was_separator && !$is_last ? ' ' : '';
272
      if(str_beginsWith($tt->type, 'PLACEHOLDER_')){
273
        $out .=  '{'. $tt->type . '}';
274
      } else {
275
        $out .= '<' . $tag . ' class="' . $class_attr . '">'
276
          . t('@text', array('@text' => $tt->text))
277
          . '</' . $tag . '>'
278
          . $glue;
279
        }
280
      $was_separator = $is_separator;
281
    }
282
    $i++;
283
  }
284
  return $out;
285
}
286

    
287
/**
288
 * Converts an array of TaggedText items into corresponding plain text string
289
 *
290
 * Each item is provided with a class attribute which is set to the key of the
291
 * TaggedText item.
292
 *
293
 * @param array $taggedtxt
294
 *   Array with text items to convert.
295
 * @param array $skiptags
296
 *   Array of tag names to skip
297
 *
298
 * @return string
299
 *   The plain text
300
 */
301
function cdm_tagged_text_to_string(array $taggedtxt, $skiptags = array()) {
302

    
303
  $out = '';
304
  $was_separator = false;
305
  $i = 0;
306
  foreach ($taggedtxt as $tt) {
307
    if (!in_array($tt->type, $skiptags) && $tt->text) {
308
      $is_last = $i + 1 == count($taggedtxt);
309
      $is_separator = is_tagged_text_sepatator_type($tt->type);
310
      $glue = !$is_separator && !$was_separator && !$is_last ? ' ' : '';
311
      $out .= t('@text', array('@text' => $tt->text)) . $glue;
312
      $was_separator = $is_separator;
313
    }
314
    $i++;
315
  }
316
  return $out;
317
}
318

    
319
/**
320
 * See cdmlib: boolean eu.etaxonomy.cdm.strategy.cache.TagEnum.isSeparator();
321
 *
322
 * @return bool
323
 */
324
function is_tagged_text_sepatator_type($tagged_text_type){
325
    static $separator_names = array('separator', 'postSeparator');
326
		$result = array_search($tagged_text_type, $separator_names) !== false;
327
    return $result;
328
}
329

    
330

    
331
/**
332
 * Finds the text tagged with $tag_type in an array of taggedText instances.
333
 *
334
 *
335
 * @param array $taggedtxt
336
 *   Array with text items.
337
 * @param array $include_tag_types
338
 *   Array of the tag types for which to find text items in the $taggedtxt array, or NULL
339
 *   to return all texts.
340
 *
341
 * @return array
342
 *   An array with the texts mapped by $tag_type.
343
 */
344
function cdm_tagged_text_values(array $taggedtxt, $include_tag_types = NULL) {
345
  $tokens = array();
346
  if (!empty($taggedtxt)) {
347
    foreach ($taggedtxt as $tagtxt) {
348
      if ($include_tag_types === NULL || array_search($tagtxt->type, $include_tag_types) !== false) {
349
        $tokens[] = $tagtxt->text;
350
      }
351
    }
352
  }
353
  return $tokens;
354
}
355

    
356
/**
357
 * Preprocess the taggedTitle arrays.
358
 *
359
 * Step 1: Turns 'newly' introduces tag types ("hybridSign")
360
 * into tag type "name"
361
 *
362
 * Step 2: Two taggedTexts which have the same type and which have
363
 * a separator between them are merged together.
364
 *
365
 * @param array $taggedTextList
366
 *    An array of TaggedText objects
367
 */
368
function normalize_tagged_text(&$taggedTextList) {
369

    
370
  if (is_array($taggedTextList)) {
371

    
372
    // First pass: rename.
373
    for ($i = 0; $i < count($taggedTextList); $i++) {
374

    
375
      if ($taggedTextList[$i]->type == "hybridSign") {
376
        $taggedTextList[$i]->type = "name";
377
      }
378
    }
379

    
380
    // Second pass: resolve separators.
381
    $taggedNameListNew = array();
382
    for ($i = 0; $i < count($taggedTextList); $i++) {
383

    
384
      // elements of the same type concatenated by a separator should be merged together
385
      if (isset($taggedTextList[$i + 2]) && $taggedTextList[$i + 1]->type == "separator" && $taggedTextList[$i]->type == $taggedTextList[$i + 2]->type) {
386
        $taggedName = clone $taggedTextList[$i];
387
        $taggedName->text = $taggedName->text . $taggedTextList[$i + 1]->text . $taggedTextList[$i + 2]->text;
388
        $taggedNameListNew[] = $taggedName;
389
        ++$i;
390
        ++$i;
391
        continue;
392
      }
393
      // no special handling
394
      $taggedNameListNew[] = $taggedTextList[$i];
395

    
396
    }
397
    $taggedTextList = $taggedNameListNew;
398
  }
399
}
400

    
401
/**
402
 * Extracts the tagged text for sec references with separator and citation detail from a tagged text array.
403
 * @param $tagged_text
404
 *    The tagged text to operate on
405
 * @param string $ref_tag_type
406
 *    The tagtype for a secreference is "secReference", but "relSecReference" is also used in case of relationships.
407
 * @param bool $replace_with_placeholder
408
 *    Indicates the method to add a empty placeholder tagged text alement as relpacement for the extrated tagged text
409
 *    elements.
410
 * @return array
411
 */
412
function tagged_text_extract_secref(&$tagged_text, $ref_tag_type = "secReference", $replace_with_placeholder = false) {
413

    
414
  $extracted_tt = array();
415
  if (is_array($tagged_text)) {
416
    $extract_pos = null;
417
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
418
      if ($tagged_text[$i + 1]->type == $ref_tag_type && $tagged_text[$i]->type == "separator"){
419
        $extracted_tt[0] = $tagged_text[$i];
420
        $extracted_tt[1] = $tagged_text[$i + 1];
421

    
422
        if($replace_with_placeholder){
423
          // text must not be null, see cdm_tagged_text_to_markup()
424
          $tagged_text[$i] = tagged_text_new("PLACEHOLDER_" . $ref_tag_type, "PLACEHOLDER_" . $ref_tag_type);
425
        } else {
426
          unset($tagged_text[$i]);
427
        }
428
        unset($tagged_text[$i + 1]);
429
        // also get the microreference which could be in $tagged_text[$i + 3]
430
        if(isset($tagged_text[$i + 3])  && $tagged_text[$i + 2]->type == "separator" && $tagged_text[$i + 3]->type == $ref_tag_type){
431
          $extracted_tt[2] = $tagged_text[$i + 2];
432
          $extracted_tt[3] = $tagged_text[$i + 3];
433
          unset($tagged_text[$i + 2]);
434
          unset($tagged_text[$i + 3]);
435
        }
436
        break;
437
      }
438
    }
439
  }
440
  $tagged_text = array_values($tagged_text); // re-index array to make it continuous again
441
  return $extracted_tt;
442
}
443

    
444
function tagged_text_extract_nomstatus(&$tagged_text) {
445

    
446
  $extracted_tt = array();
447
  if (is_array($tagged_text)) {
448
    for ($i = 0; $i < count($tagged_text) - 1; $i++) {
449
      if ($tagged_text[$i]->type == "nomStatus"){
450
        $extracted_tt[] = $tagged_text[$i];
451
        if(isset($tagged_text[$i + 1]) && $tagged_text[$i + 1]->type == "postSeparator"){
452
          $extracted_tt[] = $tagged_text[$i + 1];
453
          unset($tagged_text[$i + 1]);
454
        }
455
        if ($tagged_text[$i - 1]->type == "separator"){
456
          array_unshift($extracted_tt, $tagged_text[$i - 1]);
457
          unset($tagged_text[$i - 1]);
458
        }
459
        unset($tagged_text[$i]);
460
        break;
461
      }
462
    }
463
  }
464
  return $extracted_tt;
465
}
466

    
467
function find_tagged_text_elements($taggedTextList, $type){
468
  $matching_elements = array();
469
  if (is_array($taggedTextList)) {
470
    for ($i = 0; $i < count($taggedTextList) - 1; $i++) {
471
      if($taggedTextList[$i]->type == $type){
472
        $matching_elements[] = $taggedTextList[$i];
473
      }
474
    }
475
  }
476
  return $matching_elements;
477
}
478

    
479
// ===================== END of Tagged Text functions ================== //
480

    
481
/**
482
 * Lists the classifications a taxon belongs to
483
 *
484
 * @param CDM type Taxon $taxon
485
 *   the taxon
486
 *
487
 * @return array
488
 *   aray of CDM instances of Type Classification
489
 */
490
function get_classifications_for_taxon($taxon) {
491

    
492
  return cdm_ws_get(CDM_WS_TAXON_CLASSIFICATIONS, $taxon->uuid);;
493
}
494

    
495
/**
496
 * Returns the chosen FeatureTree for the taxon profile.
497
 *
498
 * The FeatureTree profile returned is the one that has been set in the
499
 * dataportal settings (layout->taxon:profile).
500
 * When the chosen FeatureTree is not found in the database,
501
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
502
 *
503
 * @return mixed
504
 *   A cdm FeatureTree object.
505
 */
506
function get_profile_feature_tree() {
507
  static $profile_featureTree;
508

    
509
  if($profile_featureTree == NULL) {
510
    $profile_featureTree = cdm_ws_get(
511
      CDM_WS_FEATURETREE,
512
      variable_get(CDM_PROFILE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
513
    );
514
    if (!$profile_featureTree) {
515
      $profile_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
516
    }
517
  }
518

    
519
  return $profile_featureTree;
520
}
521

    
522
/**
523
 * Returns the chosen FeatureTree for SpecimenDescriptions.
524
 *
525
 * The FeatureTree returned is the one that has been set in the
526
 * dataportal settings (layout->taxon:specimen).
527
 * When the chosen FeatureTree is not found in the database,
528
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
529
 *
530
 * @return mixed
531
 *   A cdm FeatureTree object.
532
 */
533
function cdm_get_occurrence_featureTree() {
534
  static $occurrence_featureTree;
535

    
536
  if($occurrence_featureTree == NULL) {
537
    $occurrence_featureTree = cdm_ws_get(
538
      CDM_WS_FEATURETREE,
539
      variable_get(CDM_OCCURRENCE_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
540
    );
541
    if (!$occurrence_featureTree) {
542
      $occurrence_featureTree = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
543
    }
544
  }
545
  return $occurrence_featureTree;
546
}
547

    
548
/**
549
 * Returns the FeatureTree for structured descriptions
550
 *
551
 * The FeatureTree returned is the one that has been set in the
552
 * dataportal settings (layout->taxon:profile).
553
 * When the chosen FeatureTree is not found in the database,
554
 * the standard feature tree (UUID_DEFAULT_FEATURETREE) will be returned.
555
 *
556
 * @return mixed
557
 *   A cdm FeatureTree object.
558
 */
559
function get_structured_description_featureTree() {
560
  static $structured_description_featureTree;
561

    
562
  if($structured_description_featureTree == NULL) {
563
    $structured_description_featureTree = cdm_ws_get(
564
        CDM_WS_FEATURETREE,
565
        variable_get(CDM_DATAPORTAL_STRUCTURED_DESCRIPTION_FEATURETREE_UUID, UUID_DEFAULT_FEATURETREE)
566
    );
567
    if (!$structured_description_featureTree) {
568
      $structured_description_featureTree = cdm_ws_get(
569
          CDM_WS_FEATURETREE,
570
          UUID_DEFAULT_FEATURETREE
571
      );
572
    }
573
  }
574
  return $structured_description_featureTree;
575
}
576

    
577

    
578
/**
579
 * @todo Please document this function.
580
 * @see http://drupal.org/node/1354
581
 */
582
function set_last_taxon_page_tab($taxonPageTab) {
583
  $_SESSION['cdm']['taxon_page_tab'] = $taxonPageTab;
584
}
585

    
586
/**
587
 * @todo Please document this function.
588
 * @see http://drupal.org/node/1354
589
 */
590
function get_last_taxon_page_tab() {
591
  if (isset($_SESSION['cdm']['taxon_page_tab'])) {
592
    return $_SESSION['cdm']['taxon_page_tab'];
593
  }
594
  else {
595
    return FALSE;
596
  }
597
}
598

    
599
/**
600
 *
601
 * @param object $media
602
 * @param array $mimeTypes
603
 *    an array of mimetypes in their order of preference. e.g:
604
 *    array('application/pdf', 'image/png', 'image/jpeg', 'image/gif', 'text/html')
605
 * @param int $width
606
 *    The width of the optimal image. If null, the method will return the representation with the biggest expansion
607
 * @param int $height
608
 *    The height of the optimal image. If null, the method will return the representation with the biggest expansion
609
 *
610
 * @return array
611
 *   An array with preferred media representations or else an empty array.
612
 */
613
function cdm_preferred_media_representations($media, array $mimeTypes, $width = NULL, $height = NULL) {
614
  $prefRepr = array();
615
  if (!isset($media->representations[0])) {
616
    return $prefRepr;
617
  }
618

    
619
  while (count($mimeTypes) > 0) {
620
    // getRepresentationByMimeType
621
    $mimeType = array_shift($mimeTypes);
622

    
623
    foreach ($media->representations as &$representation) {
624
      // If the mimetype is not known, try inferring it.
625
      if (!$representation->mimeType) {
626
        if (isset($representation->parts[0])) {
627
          $representation->mimeType = infer_mime_type($representation->parts[0]->uri);
628
        }
629
      }
630

    
631
      if ($representation->mimeType == $mimeType) {
632
        // Preferred mimetype found -> erase all remaining mimetypes
633
        // to end loop.
634
        $mimeTypes = array();
635
        $expansionDeltaSum = 0;
636
        $valid_parts_cnt = 0;
637
        // Look for part with the best matching size.
638
        foreach ($representation->parts as $part) {
639
          if (empty($part->uri)) {
640
            // skip part if URI is missing
641
            continue;
642
          }
643
          $valid_parts_cnt++;
644
          $expansionDelta = PHP_INT_MAX; // biggest delta for unknown sizes
645

    
646
          // determine the optimal size
647
          if (isset($part->width) && isset($part->height)) {
648
            $expansion = $part->width * $part->height;
649
            if ($width != null && $height != null) {
650
              $optimalExpansion = $height * $width;
651
            } else {
652
              $optimalExpansion = PHP_INT_MAX;
653
            }
654
            // determine the difference
655
            $expansionDelta = $expansion > $optimalExpansion ? $expansion - $optimalExpansion : $optimalExpansion - $expansion;
656
          }
657
          // sum up the expansionDeltas of all parts contained in the representation
658
          $expansionDeltaSum += $expansionDelta;
659
        }
660
        if($valid_parts_cnt > 0){
661
          $expansionDeltaSum = $expansionDeltaSum / $valid_parts_cnt;
662
          $prefRepr[$expansionDeltaSum] = $representation;
663
        }
664
      }
665
    }
666
  }
667
  // Sort the array so that the smallest key value is the first in the array
668
  ksort($prefRepr);
669
  return $prefRepr;
670
}
671

    
672
/**
673
 * Infers the mime type of a file using the filename extension.
674
 *
675
 * The filename extension is used to infer the mime type.
676
 *
677
 * @param string $filepath
678
 *   The path to the respective file.
679
 *
680
 * @return string
681
 *   The mimetype for the file or FALSE if the according mime type could
682
 *   not be found.
683
 */
684
function infer_mime_type($filepath) {
685
  static $mimemap = NULL;
686
  if (!$mimemap) {
687
    $mimemap = array(
688
      'jpg' => 'image/jpeg',
689
      'jpeg' => 'image/jpeg',
690
      'png' => 'image/png',
691
      'gif' => 'image/gif',
692
      'giff' => 'image/gif',
693
      'tif' => 'image/tif',
694
      'tiff' => 'image/tif',
695
      'pdf' => 'application/pdf',
696
      'html' => 'text/html',
697
      'htm' => 'text/html',
698
    );
699
  }
700
  $extension = substr($filepath, strrpos($filepath, '.') + 1);
701
  if (isset($mimemap[$extension])) {
702
    return $mimemap[$extension];
703
  }
704
  else {
705
    // FIXME remove this hack just return FALSE;
706
    return 'text/html';
707
  }
708
}
709

    
710
/**
711
 * Converts an ISO 8601 org.joda.time.Partial to a year.
712
 *
713
 * The function expects an ISO 8601 time representation of a
714
 * org.joda.time.Partial of the form yyyy-MM-dd.
715
 *
716
 * @param string $partial
717
 *   ISO 8601 time representation of a org.joda.time.Partial.
718
 *
719
 * @return string
720
 *   Returns the year. In case the year is unknown (= ????), it returns NULL.
721
 */
722
function partialToYear($partial) {
723
  if (is_string($partial)) {
724
    $year = substr($partial, 0, 4);
725
    if (preg_match("/[0-9][0-9][0-9][0-9]/", $year)) {
726
      return $year;
727
    }
728
  }
729
  return '';
730
}
731

    
732
/**
733
 * Converts an ISO 8601 org.joda.time.Partial to a month.
734
 *
735
 * This function expects an ISO 8601 time representation of a
736
 * org.joda.time.Partial of the form yyyy-MM-dd.
737
 * In case the month is unknown (= ???) NULL is returned.
738
 *
739
 * @param string $partial
740
 *   ISO 8601 time representation of a org.joda.time.Partial.
741
 *
742
 * @return string
743
 *   A month.
744
 */
745
function partialToMonth($partial) {
746
  if (is_string($partial)) {
747
    $month = substr($partial, 5, 2);
748
    if (preg_match("/[0-9][0-9]/", $month)) {
749
      return $month;
750
    }
751
  }
752
  return '';
753
}
754

    
755
/**
756
 * Converts an ISO 8601 org.joda.time.Partial to a day.
757
 *
758
 * This function expects an ISO 8601 time representation of a
759
 * org.joda.time.Partial of the form yyyy-MM-dd and returns the day as string.
760
 * In case the day is unknown (= ???) NULL is returned.
761
 *
762
 * @param string $partial
763
 *   ISO 8601 time representation of a org.joda.time.Partial.
764
 *
765
 * @return string
766
 *   A day.
767
 */
768
function partialToDay($partial) {
769
  if (is_string($partial)) {
770
    $day = substr($partial, 8, 2);
771
    if (preg_match("/[0-9][0-9]/", $day)) {
772
      return $day;
773
    }
774
  }
775
  return '';
776
}
777

    
778
/**
779
 * Converts an ISO 8601 org.joda.time.Partial to YYYY-MM-DD.
780
 *
781
 * This function expects an ISO 8601 time representations of a
782
 * org.joda.time.Partial of the form yyyy-MM-dd and returns
783
 * four digit year, month and day with dashes:
784
 * YYYY-MM-DD eg: "2012-06-30", "1956-00-00"
785
 *
786
 * The partial may contain question marks eg: "1973-??-??",
787
 * these are turned in to '00' or are stripped depending of the $stripZeros
788
 * parameter.
789
 *
790
 * @param string $partial
791
 *   org.joda.time.Partial.
792
 * @param bool $stripZeros
793
 *   If set to TRUE the zero (00) month and days will be hidden:
794
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
795
 * @param string @format
796
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
797
 *    - "YYYY": Year only
798
 *    - "YYYY-MM-DD": this is the default
799
 *
800
 * @return string
801
 *   YYYY-MM-DD formatted year, month, day.
802
 */
803
function partialToDate($partial, $stripZeros = TRUE, $format= "YYYY-MM-DD") {
804

    
805
  $y = NULL; $m = NULL; $d = NULL;
806

    
807
  if(strpos($format, 'YY') !== FALSE){
808
    $y = partialToYear($partial);
809
  }
810
  if(strpos($format, 'MM') !== FALSE){
811
    $m = partialToMonth($partial);
812
  }
813
  if(strpos($format, 'DD') !== FALSE){
814
    $d = partialToDay($partial);
815
  }
816

    
817
  $y = $y ? $y : '00';
818
  $m = $m ? $m : '00';
819
  $d = $d ? $d : '00';
820

    
821
  $date = '';
822

    
823
  if ($y == '00' && $stripZeros) {
824
    return '';
825
  }
826
  else {
827
    $date = $y;
828
  }
829

    
830
  if ($m == '00' && $stripZeros) {
831
    return $date;
832
  }
833
  else {
834
    $date .= "-" . $m;
835
  }
836

    
837
  if ($d == '00' && $stripZeros) {
838
    return $date;
839
  }
840
  else {
841
    $date .= "-" . $d;
842
  }
843
  return $date;
844
}
845

    
846
/**
847
 * Converts a time period to a string.
848
 *
849
 * See also partialToDate($partial, $stripZeros).
850
 *
851
 * @param object $period
852
 *   An JodaTime org.joda.time.Period object.
853
 * @param bool $stripZeros
854
 *   If set to True, the zero (00) month and days will be hidden:
855
 *   eg 1956-00-00 becomes 1956. The default is TRUE.
856
 * @param string @format
857
 * 	 Can ve used to specify the format of the date string, currently the following format strings are supported
858
 *    - "YYYY": Year only
859
 *    - "YYYY-MM-DD": this is the default
860
 *
861
 * @return string
862
 *   Returns a date in the form of a string.
863
 */
864
function timePeriodToString($period, $stripZeros = TRUE, $format = "YYYY-MM-DD") {
865
  $dateString = '';
866
  if($period->freeText){
867
    $dateString = $period->freeText;
868
  } else {
869
    if ($period->start) {
870
      $dateString = partialToDate($period->start, $stripZeros, $format);
871
    }
872
    if ($period->end) {
873
      $end_str = partialToDate($period->end, $stripZeros, $format);
874
      $dateString .= ($dateString && $end_str > 0 ? ' ' . t('to') . ' ' : '') . $end_str;
875
    }
876
  }
877
  return $dateString;
878
}
879

    
880
/**
881
 * returns the earliest date available in the $period in a normalized
882
 * form suitable for sorting, e.g.:
883
 *
884
 *  - 1956-00-00
885
 *  - 0000-00-00
886
 *  - 1957-03-00
887
 *
888
 * that is either the start date is returned if set otherwise the
889
 * end date
890
 *
891
 * @param  $period
892
 *    An JodaTime org.joda.time.Period object.
893
 * @return string normalized form of the date
894
 *   suitable for sorting
895
 */
896
function timePeriodAsOrderKey($period) {
897
  $dateString = '';
898
  if ($period->start) {
899
    $dateString = partialToDate($period->start, false);
900
  }
901
  if ($period->end) {
902
    $dateString .= partialToDate($period->end, false);
903
  }
904
  return $dateString;
905
}
906

    
907
/**
908
 * Composes a absolute CDM web service URI with parameters and querystring.
909
 *
910
 * @param string $uri_pattern
911
 *   String with place holders ($0, $1, ..) that should be replaced by the
912
 *   according element of the $pathParameters array.
913
 * @param array $pathParameters
914
 *   An array of path elements, or a single element.
915
 * @param string $query
916
 *   A query string to append to the URL.
917
 *
918
 * @return string
919
 *   A complete URL with parameters to a CDM webservice.
920
 */
921
function cdm_compose_url($uri_pattern, $pathParameters = array(), $query = NULL) {
922
  if (empty($pathParameters)) {
923
    $pathParameters = array();
924
  }
925

    
926
  // (1)
927
  // Substitute all place holders ($0, $1, ..) in the $uri_pattern by the
928
  // according element of the $pathParameters array.
929
  static $helperArray = array();
930
  if (isset($pathParameters) && !is_array($pathParameters)) {
931
    $helperArray[0] = $pathParameters;
932
    $pathParameters = $helperArray;
933
  }
934

    
935
  $i = 0;
936
  while (strpos($uri_pattern, "$" . $i) !== FALSE) {
937
    if (count($pathParameters) <= $i) {
938
        drupal_set_message(
939
          t('cdm_compose_url(): missing pathParameter @index for !uri_pattern',
940
            array('@index' => $i, '!uri-pattern' => $uri_pattern )),
941
          'error');
942
      break;
943
    }
944
    $uri_pattern = str_replace("$" . $i, rawurlencode($pathParameters[$i]), $uri_pattern);
945
    ++$i;
946
  }
947

    
948
  // (2)
949
  // Append all remaining element of the $pathParameters array as path
950
  // elements.
951
  if (count($pathParameters) > $i) {
952
    // Strip trailing slashes.
953
    if (strrchr($uri_pattern, '/') == strlen($uri_pattern)) {
954
      $uri_pattern = substr($uri_pattern, 0, strlen($uri_pattern) - 1);
955
    }
956
    while (count($pathParameters) > $i) {
957
      $uri_pattern .= '/' . rawurlencode($pathParameters[$i]);
958
      ++$i;
959
    }
960
  }
961

    
962
  // (3)
963
  // Append the query string supplied by $query.
964
  if (isset($query)) {
965
    $uri_pattern .= (strpos($uri_pattern, '?') !== FALSE ? '&' : '?') . $query;
966
  }
967

    
968
  $path = $uri_pattern;
969

    
970
  $uri = variable_get('cdm_webservice_url', '') . $path;
971
  return $uri;
972
}
973

    
974
/**
975
 * @todo wouldn't it more elegant and secure to only pass a uuid and additional function parameters
976
 *     together with a theme name to such a proxy function?
977
 *     Well this would not be covering all use cases but maybe all which involve AHAH.
978
 *     Maybe we want to have two different proxy functions, one with theming and one without?
979
 *
980
 * @param string $uri
981
 *     A URI to a CDM Rest service from which to retrieve an object
982
 * @param string|null $hook
983
 *     (optional) The hook name to which the retrieved object should be passed.
984
 *     Hooks can either be a theme_hook() or compose_hook() implementation
985
 *     'theme' hook functions return a string whereas 'compose' hooks are returning render arrays
986
 *     suitable for drupal_render()
987
 *
988
 * @todo Please document this function.
989
 * @see http://drupal.org/node/1354
990
 */
991
function proxy_content($uri, $hook = NULL) {
992

    
993
  $args = func_get_args();
994
  $do_gzip = function_exists('gzencode');
995
  $uriEncoded = array_shift($args);
996
  $uri = urldecode($uriEncoded);
997
  $hook = array_shift($args);
998
  $request_method = strtoupper($_SERVER["REQUEST_METHOD"]);
999

    
1000
  $post_data = null;
1001

    
1002
  if ($request_method == "POST" || $request_method == "PUT") {
1003
    // read response body via inputstream module
1004
    $post_data = file_get_contents("php://input");
1005
  }
1006

    
1007
  // Find and deserialize arrays.
1008
  foreach ($args as &$arg) {
1009
    // FIXME use regex to find serialized arrays.
1010
    //       or should we accept json instead of php serializations?
1011
    if (strpos($arg, "a:") === 0) {
1012
      $arg = unserialize($arg);
1013
    }
1014
  }
1015

    
1016
  // In all these cases perform a simple get request.
1017
  // TODO reconsider caching logic in this function.
1018

    
1019
  if (empty($hook)) {
1020
    // simply return the webservice response
1021
    // Print out JSON, the cache cannot be used since it contains objects.
1022
    $http_response = cdm_http_request($uri, $request_method, $post_data);
1023
    if (isset($http_response->headers)) {
1024
      foreach ($http_response->headers as $hname => $hvalue) {
1025
        drupal_add_http_header($hname, $hvalue);
1026
      }
1027
    }
1028
    if (isset($http_response->data)) {
1029
      print $http_response->data;
1030
      flush();
1031
    }
1032
    exit(); // leave drupal here
1033
  } else {
1034
    // $hook has been supplied
1035
    // handle $hook either as compose ot theme hook
1036
    // pass through theme or comose hook
1037
    // compose hooks can be called without data, therefore
1038
    // passing the $uri in this case is not always a requirement
1039

    
1040
    if($uri && $uri != 'NULL') {
1041
    // do a security check since the $uri will be passed
1042
    // as absolute URI to cdm_ws_get()
1043
      if (!_is_cdm_ws_uri($uri)) {
1044
        drupal_set_message(
1045
          'Invalid call of proxy_content() with callback parameter \'' . $hook . '\' and URI:' . $uri,
1046
          'error'
1047
        );
1048
        return '';
1049
      }
1050

    
1051
      $obj = cdm_ws_get($uri, NULL, $post_data, $request_method, TRUE);
1052
    } else {
1053
      $obj = NULL;
1054
    }
1055

    
1056
    $reponse_data = NULL;
1057

    
1058
    if (function_exists('compose_' . $hook)){
1059
      // call compose hook
1060

    
1061
      $elements =  call_user_func('compose_' . $hook, $obj);
1062
      // pass the render array to drupal_render()
1063
      $reponse_data = drupal_render($elements);
1064
    } else {
1065
      // call theme hook
1066

    
1067
      // TODO use theme registry to get the registered hook info and
1068
      //    use these defaults
1069
      switch($hook) {
1070
        case 'cdm_taxontree':
1071
          $variables = array(
1072
            'tree' => $obj,
1073
            'filterIncludes' => isset($args[0]) ? $args[0] : NULL,
1074
            'show_filter_switch' => isset($args[1]) ? $args[1] : FALSE,
1075
            'tree_node_callback' => isset($args[2]) ? $args[2] : FALSE,
1076
            'element_name'=> isset($args[3]) ? $args[3] : FALSE,
1077
            );
1078
          $reponse_data = theme($hook, $variables);
1079
          break;
1080

    
1081
        case 'cdm_list_of_taxa':
1082
            $variables = array(
1083
              'records' => $obj,
1084
              'freetextSearchResults' => isset($args[0]) ? $args[0] : array(),
1085
              'show_classification' => isset($args[1]) ? $args[1] : FALSE);
1086
            $reponse_data = theme($hook, $variables);
1087
            break;
1088

    
1089
        case 'cdm_media_caption':
1090
          $variables = array(
1091
            'media' => $obj,
1092
            // $args[0] is set in taxon_image_gallery_default in
1093
            // cdm_dataportal.page.theme.
1094
            'elements' => isset($args[0]) ? $args[0] : array(
1095
            'title',
1096
            'description',
1097
            'artist',
1098
            'location',
1099
            'rights',
1100
          ),
1101
            'sources_as_content' =>  isset($args[1]) ? $args[1] : FALSE
1102
          );
1103
          $reponse_data = theme($hook, $variables);
1104
          break;
1105

    
1106
        default:
1107
          drupal_set_message(t(
1108
          'Theme !theme is not yet supported by the function !function.', array(
1109
          '!theme' => $hook,
1110
          '!function' => __FUNCTION__,
1111
          )), 'error');
1112
          break;
1113
      } // END of theme hook switch
1114
    } // END of tread as theme hook
1115

    
1116

    
1117
    if($do_gzip){
1118
      $reponse_data = gzencode($reponse_data, 2, FORCE_GZIP);
1119
      drupal_add_http_header('Content-Encoding', 'gzip');
1120
    }
1121
    drupal_add_http_header('Content-Type', 'text/html; charset=utf-8');
1122
    drupal_add_http_header('Content-Length', strlen($reponse_data));
1123

    
1124
    print $reponse_data;
1125
  } // END of handle $hook either as compose ot theme hook
1126

    
1127
}
1128

    
1129
/**
1130
 * @todo Please document this function.
1131
 * @see http://drupal.org/node/1354
1132
 */
1133
function setvalue_session() {
1134
  if ($_REQUEST['var'] && strlen($_REQUEST['var']) > 4) {
1135
    $var_keys = substr($_REQUEST['var'], 1, strlen($_REQUEST['var']) - 2);
1136
    $var_keys = explode('][', $var_keys);
1137
  }
1138
  else {
1139
    return;
1140
  }
1141
  $val = isset($_REQUEST['val']) ? $_REQUEST['val'] : NULL;
1142

    
1143
  // Prevent from malicous tags.
1144
  $val = strip_tags($val);
1145

    
1146
  $session_var = &$_SESSION;
1147
  //$i = 0;
1148
  foreach ($var_keys as $key) {
1149
    // $hasMoreKeys = ++$i < count($session);
1150
    if (!isset($session_var[$key]) || !is_array($session_var[$key])) {
1151
      $session_var[$key] = array();
1152
    }
1153
    $session_var = &$session_var[$key];
1154
  }
1155
  $session_var = $val;
1156
  if (isset($_REQUEST['destination'])) {
1157
    drupal_goto($_REQUEST['destination']);
1158
  }
1159
}
1160

    
1161
/**
1162
 * @todo Please document this function.
1163
 * @see http://drupal.org/node/1354
1164
 */
1165
function uri_uriByProxy($uri, $theme = FALSE) {
1166
  // usage: url('cdm_api/proxy/'.urlencode($content_url)."/$theme");)
1167
  return url('cdm_api/proxy/' . urlencode($uri) . (isset($theme) ? "/$theme" : ''));
1168
}
1169

    
1170
/**
1171
 * Composes the the absolute REST service URI to the annotations pager
1172
 * for the given CDM entity.
1173
 *
1174
 * NOTE: Not all CDM Base types are yet supported.
1175
 *
1176
 * @param $cdmBase
1177
 *   The CDM entity to construct the annotations pager uri for
1178
 */
1179
function cdm_compose_annotations_uri($cdmBase) {
1180

    
1181
  if (!$cdmBase->uuid) {
1182
    return;
1183
  }
1184

    
1185
  $ws_base_uri = cdm_ws_base_uri($cdmBase->class);
1186

    
1187
  if($ws_base_uri === null){
1188
      trigger_error(check_plain('Unsupported CDM Class - no annotations available for ' . $cdmBase->class), E_USER_ERROR);
1189
  }
1190
  return cdm_compose_url($ws_base_uri, array(
1191
    $cdmBase->uuid,
1192
    'annotations',
1193
  ));
1194
}
1195

    
1196
/**
1197
 * Provides the base URI of the cdm REST service responsible for the passed simple name
1198
 * of a CDM java class. For example 'TaxonName' is the simple name of 'eu.etaxonomy.cdm.model.name.TaxonName'
1199
 *
1200
 * @param $cdm_type_simple
1201
 *    simple name of a CDM java class
1202
 * @return null|string
1203
 */
1204
function cdm_ws_base_uri($cdm_type_simple)
1205
{
1206
  $ws_base_uri = NULL;
1207
  switch ($cdm_type_simple) {
1208
    case 'TaxonBase':
1209
    case 'Taxon':
1210
    case 'Synonym':
1211
      $ws_base_uri = CDM_WS_TAXON;
1212
      break;
1213

    
1214
    case 'TaxonName':
1215
      $ws_base_uri = CDM_WS_NAME;
1216
      break;
1217

    
1218
    case 'Media':
1219
      $ws_base_uri = CDM_WS_MEDIA;
1220
      break;
1221

    
1222
    case 'Reference':
1223
      $ws_base_uri = CDM_WS_REFERENCE;
1224
      break;
1225

    
1226
    case 'Distribution':
1227
    case 'TextData':
1228
    case 'TaxonInteraction':
1229
    case 'QuantitativeData':
1230
    case 'IndividualsAssociation':
1231
    case 'CommonTaxonName':
1232
    case 'CategoricalData':
1233
      $ws_base_uri = CDM_WS_DESCRIPTIONELEMENT;
1234
      break;
1235

    
1236
    case 'PolytomousKey':
1237
    case 'MediaKey':
1238
    case 'MultiAccessKey':
1239
      $ws_base_uri = $cdm_type_simple;
1240
      $ws_base_uri{0} = strtolower($ws_base_uri{0});
1241
      break;
1242

    
1243
    default:
1244
      $ws_base_uri = null;
1245
  }
1246
  return $ws_base_uri;
1247
}
1248

    
1249
/**
1250
 * Enter description here...
1251
 *
1252
 * @param string $resourceURI
1253
 * @param int $pageSize
1254
 *   The maximum number of entities returned per page.
1255
 *   The default page size as configured in the cdm server
1256
 *   will be used if set to NULL
1257
 *   to return all entities in a single page).
1258
 * @param int $pageNumber
1259
 *   The number of the page to be returned, the first page has the
1260
 *   pageNumber = 0
1261
 * @param array $query
1262
 *   A array holding the HTTP request query parameters for the request
1263
 * @param string $method
1264
 *   The HTTP method to use, valid values are "GET" or "POST"
1265
 * @param bool $absoluteURI
1266
 *   TRUE when the URL should be treated as absolute URL.
1267
 *
1268
 * @return the a CDM Pager object
1269
 *
1270
 */
1271
function cdm_ws_page($resourceURI, $pageSize, $pageNumber, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1272

    
1273
  $query['pageNumber'] = $pageNumber;
1274
  $query['pageSize'] = $pageSize;
1275

    
1276
  return cdm_ws_get($resourceURI, NULL, queryString($query), $method, $absoluteURI);
1277
}
1278

    
1279
/**
1280
 * Fetches all entities from the given REST endpoint using the pager mechanism.
1281
 *
1282
 * @param string $resourceURI
1283
 * @param array $query
1284
 *   A array holding the HTTP request query parameters for the request
1285
 * @param string $method
1286
 *   The HTTP method to use, valid values are "GET" or "POST";
1287
 * @param bool $absoluteURI
1288
 *   TRUE when the URL should be treated as absolute URL.
1289
 *
1290
 * @return array
1291
 *     A list of CDM entitites
1292
 *
1293
 */
1294
function cdm_ws_fetch_all($resourceURI, array $query = array(), $method = 'GET', $absoluteURI = FALSE) {
1295
  $page_index = 0;
1296
  // using a bigger page size to avoid to many multiple requests
1297
  $page_size = 500;
1298
  $entities = array();
1299

    
1300
  while ($page_index !== FALSE){
1301
    $pager =  cdm_ws_page($resourceURI, $page_size, $page_index, $query,  $method, $absoluteURI);
1302
    if(isset($pager->records) && is_array($pager->records)) {
1303
      $entities = array_merge($entities, $pager->records);
1304
      if(!empty($pager->nextIndex)){
1305
        $page_index = $pager->nextIndex;
1306
      } else {
1307
        $page_index = FALSE;
1308
      }
1309
    } else {
1310
      $page_index = FALSE;
1311
    }
1312
  }
1313
  return $entities;
1314
}
1315

    
1316
/*
1317
function cdm_ws_taxonomy_compose_resourcePath($path = NULL){
1318
  $viewrank = _cdm_taxonomy_compose_viewrank();
1319
  return CDM_WS_PORTAL_TAXONOMY . '/' . ($viewrank ? $viewrank : '' ) . ($path
1320
  ? '/' . $path : '') ;
1321
}
1322
*/
1323

    
1324
/**
1325
 * @todo Enter description here...
1326
 *
1327
 * @param string $taxon_uuid
1328
 *  The UUID of a cdm taxon instance
1329
 * @param string $ignore_rank_limit
1330
 *   Whether to ignore the variable 'taxontree_ranklimit' set by admin in the settings
1331
 *
1332
 * @return string
1333
 *   A cdm REST service URL path to a Classification
1334
 */
1335
function cdm_compose_taxonomy_root_level_path($taxon_uuid = FALSE, $ignore_rank_limit = FALSE) {
1336

    
1337
  $view_uuid = get_current_classification_uuid();
1338
  $rank_uuid = NULL;
1339
  if (!$ignore_rank_limit) {
1340
    $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1341
  }
1342

    
1343
  if (!empty($taxon_uuid)) {
1344
    return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_OF_TAXON, array(
1345
      $view_uuid,
1346
      $taxon_uuid,
1347
    ));
1348
  }
1349
  else {
1350
    if (is_uuid($rank_uuid)) {
1351
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES_AT_RANK, array(
1352
        $view_uuid,
1353
        $rank_uuid,
1354
      ));
1355
    }
1356
    else {
1357
      return cdm_compose_url(CDM_WS_PORTAL_TAXONOMY_CHILDNODES, array(
1358
        $view_uuid,
1359
      ));
1360
    }
1361
  }
1362
}
1363

    
1364
/**
1365
 * Retrieves from the cdm web service with the first level of childnodes of a classification.
1366
 *
1367
 * The level is either the real root level ot it is a lover level if a rank limit has been set.
1368
 * (@see  cdm_compose_taxonomy_root_level_path() for more on the rank limit).
1369
 *
1370
 * Operates in two modes depending on whether the parameter
1371
 * $taxon_uuid is set or NULL.
1372
 *
1373
 * A) $taxon_uuid = NULL:
1374
 *  1. retrieve the Classification for the uuid set in the $_SESSION['cdm']['taxonomictree_uuid']
1375
 *  2. otherwise return the default classification as defined by the admin via the settings
1376
 *
1377
 * b) $taxon_uuid is set:
1378
 *   return the classification to whcih the taxon belongs to.
1379
 *
1380
 * @param UUID $taxon_uuid
1381
 *   The UUID of a cdm taxon instance
1382
 */
1383
function cdm_ws_taxonomy_root_level($taxon_uuid = NULL) {
1384

    
1385
    $response = NULL;
1386

    
1387
    // 1st try
1388
    $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid), NULL, NULL, 'GET', TRUE);
1389

    
1390
    if ($response == NULL) {
1391
      // 2dn try by ignoring the rank limit
1392
      $response = cdm_ws_get(cdm_compose_taxonomy_root_level_path($taxon_uuid, TRUE), NULL, NULL, 'GET', TRUE);
1393
    }
1394

    
1395
    if ($response == NULL) {
1396
      // 3rd try, last fallback:
1397
      //    return the default classification
1398
      if (isset($_SESSION['cdm']['taxonomictree_uuid']) && is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1399
        // Delete the session value and try again with the default.
1400
        unset($_SESSION['cdm']['taxonomictree_uuid']);
1401
        drupal_set_message("Could not find a valid classification, falling back to the default classification.", 'warning');
1402
        return cdm_ws_taxonomy_root_level($taxon_uuid);
1403
      }
1404
      else {
1405
        // Check if taxonomictree_uuid is valid.
1406
        // expecting an array of taxonNodes,
1407
        // empty classifications are ok so no warning in this case!
1408
        $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1409
        if (!is_array($test)) {
1410
          // The default set by the admin seems to be invalid or is not even set.
1411
          drupal_set_message(_no_classfication_uuid_message(), 'warning');
1412
        }
1413
        if (count($test) == 0) {
1414
          // The default set by the admin seems to be invalid or is not even set.
1415
          drupal_set_message("The chosen classification is empty.", 'status');
1416
        }
1417
      }
1418
    }
1419

    
1420
  return $response;
1421
}
1422

    
1423
/**
1424
 * Determines the tree path of the taxon given as uuid to the root of the classification tree.
1425
 * 
1426
 * The root either is the absolute root of the tree or a rank specific root if the TAXONTREE_RANKLIMIT
1427
 * variable is set.
1428
 *
1429
 * @param string $taxon_uuid
1430
 *
1431
 * @return array
1432
 *   An array of CDM TaxonNodeDTO objects
1433
 */
1434
function cdm_ws_taxonomy_pathFromRoot($taxon_uuid) {
1435
  $view_uuid = get_current_classification_uuid();
1436
  $rank_uuid = variable_get(TAXONTREE_RANKLIMIT, TAXONTREE_RANKLIMIT_DEFAULT);
1437

    
1438
  $response = NULL;
1439
  if (is_uuid($rank_uuid)) {
1440
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM_TO_RANK, array(
1441
      $view_uuid,
1442
      $taxon_uuid,
1443
      $rank_uuid,
1444
    ));
1445
  }
1446
  else {
1447
    $response = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY_PATH_FROM, array(
1448
      $view_uuid,
1449
      $taxon_uuid,
1450
    ));
1451
  }
1452

    
1453
  if ($response == NULL) {
1454
    // Error handing.
1455
//    if (is_uuid($_SESSION['cdm']['taxonomictree_uuid'])) {
1456
//      // Delete the session value and try again with the default.
1457
//      unset($_SESSION['cdm']['taxonomictree_uuid']);
1458
//      return cdm_ws_taxonomy_pathFromRoot($taxon_uuid);
1459
//    }
1460
//    else {
1461
      // Check if taxonomictree_uuid is valid.
1462
      $test = cdm_ws_get(cdm_compose_taxonomy_root_level_path(), NULL, NULL, 'GET', TRUE);
1463
      if ($test == NULL) {
1464
        // The default set by the admin seems to be invalid or is not even set.
1465
        drupal_set_message(_no_classfication_uuid_message(), 'warning');
1466
      }
1467
//    }
1468
  }
1469

    
1470
  return $response;
1471
}
1472

    
1473

    
1474
// =============================Terms and Vocabularies ========================================= //
1475

    
1476
/**
1477
 * Returns the localized representation for the given term.
1478
 *
1479
 * @param Object $definedTermBase
1480
 * 	  of cdm type DefinedTermBase
1481
 * @return string
1482
 * 	  the localized representation_L10n of the term,
1483
 *    otherwise the titleCache as fall back,
1484
 *    otherwise the default_representation which defaults to an empty string
1485
 */
1486
function cdm_term_representation($definedTermBase, $default_representation = '') {
1487
  if ( isset($definedTermBase->representation_L10n) ) {
1488
    return $definedTermBase->representation_L10n;
1489
  } elseif ( isset($definedTermBase->titleCache)) {
1490
    return $definedTermBase->titleCache;
1491
  }
1492
  return $default_representation;
1493
}
1494

    
1495
/**
1496
 * Returns the abbreviated localized representation for the given term.
1497
 *
1498
 * @param Object $definedTermBase
1499
 * 	  of cdm type DefinedTermBase
1500
 * @return string
1501
 * 	  the localized representation_L10n_abbreviatedLabel of the term,
1502
 *    if this representation is not available the function delegates the
1503
 *    call to cdm_term_representation()
1504
 */
1505
function cdm_term_representation_abbreviated($definedTermBase, $default_representation = '') {
1506
  if ( isset($definedTermBase->representation_L10n_abbreviatedLabel) ) {
1507
    return $definedTermBase->representation_L10n_abbreviatedLabel;
1508
  } else {
1509
    cdm_term_representation($definedTermBase, $default_representation);
1510
  }
1511
}
1512

    
1513
/**
1514
 * Transforms the list of the given term base instances to a alphabetical ordered options array.
1515
 *
1516
 * The options array is suitable for drupal form API elements that allow multiple choices.
1517
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
1518
 *
1519
 * @param array $terms
1520
 *   a list of CDM DefinedTermBase instances
1521
 *
1522
 * @param $term_label_callback
1523
 *   A callback function to override the term representations
1524
 *
1525
 * @param bool $empty_option
1526
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1527
 *
1528
 * @return array
1529
 *   the terms in an array as options for a form element that allows multiple choices.
1530
 */
1531
function cdm_terms_as_options($terms, $term_label_callback = NULL, $empty_option = FALSE){
1532
  $options = array();
1533
  if(isset($terms) && is_array($terms)) {
1534
    foreach ($terms as $term) {
1535
      if ($term_label_callback && function_exists($term_label_callback)) {
1536
        $options[$term->uuid] = call_user_func($term_label_callback, $term);
1537
      } else {
1538
        //TODO use cdm_term_representation() here?
1539
        $options[$term->uuid] = t('@term', array('@term' => $term->representation_L10n));
1540
      }
1541
    }
1542
  }
1543

    
1544
  if($empty_option !== FALSE){
1545
    array_unshift ($options, "");
1546
  }
1547

    
1548
  return $options;
1549
}
1550

    
1551
/**
1552
 * Creates and array of options for drupal select form elements.
1553
 *
1554
 * @param $vocabulary_uuid
1555
 *   The UUID of the CDM Term Vocabulary
1556
 * @param $term_label_callback
1557
 *   An optional call back function which can be used to modify the term label
1558
 * @param bool $empty_option
1559
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1560
 * @param array $include_filter
1561
 *   An associative array consisting of a field name an regular expression. All term matching
1562
 *   these filter are included. The value of the field is converted to a String by var_export()
1563
 *   so a boolean 'true' can be matched by '/true/'
1564
 * @param string $order_by
1565
 *   One of the order by constants defined in this file
1566
 * @return mixed
1567
 */
1568
function cdm_vocabulary_as_option($vocabulary_uuid, $term_label_callback = NULL, $empty_option = FALSE,
1569
                                  array $include_filter = null, $order_by = CDM_ORDER_BY_ORDER_INDEX_ASC) {
1570

    
1571
  static $vocabularyOptions = array();
1572

    
1573
  if (!isset($vocabularyOptions[$vocabulary_uuid])) {
1574
    $terms = cdm_ws_fetch_all('termVocabulary/' . $vocabulary_uuid . '/terms',
1575
      array(
1576
        'orderBy' => $order_by
1577
      )
1578
    );
1579

    
1580
    // apply the include filter
1581
    if($include_filter != null){
1582
      $included_terms = array();
1583

    
1584
      foreach ($terms as $term){
1585
        $include = true;
1586
        foreach ($include_filter as $field=>$regex){
1587
          $include =  preg_match($regex, var_export($term->$field, true)) === 1;
1588
          if(!$include){
1589
            break;
1590
          }
1591
        }
1592
        if($include){
1593
          $included_terms[] = $term;
1594
        }
1595
      }
1596

    
1597
      $terms = $included_terms;
1598
    }
1599

    
1600
    // make options list
1601
    $vocabularyOptions[$vocabulary_uuid] = cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1602
  }
1603

    
1604
  $options = $vocabularyOptions[$vocabulary_uuid];
1605

    
1606
  return $options;
1607
}
1608

    
1609
/**
1610
 * @param $term_type string one of
1611
 *  - Unknown
1612
 *  - Language
1613
 *  - NamedArea
1614
 *  - Rank
1615
 *  - Feature
1616
 *  - AnnotationType
1617
 *  - MarkerType
1618
 *  - ExtensionType
1619
 *  - DerivationEventType
1620
 *  - PresenceAbsenceTerm
1621
 *  - NomenclaturalStatusType
1622
 *  - NameRelationshipType
1623
 *  - HybridRelationshipType
1624
 *  - SynonymRelationshipType
1625
 *  - TaxonRelationshipType
1626
 *  - NameTypeDesignationStatus
1627
 *  - SpecimenTypeDesignationStatus
1628
 *  - InstitutionType
1629
 *  - NamedAreaType
1630
 *  - NamedAreaLevel
1631
 *  - RightsType
1632
 *  - MeasurementUnit
1633
 *  - StatisticalMeasure
1634
 *  - MaterialOrMethod
1635
 *  - Material
1636
 *  - Method
1637
 *  - Modifier
1638
 *  - Scope
1639
 *  - Stage
1640
 *  - KindOfUnit
1641
 *  - Sex
1642
 *  - ReferenceSystem
1643
 *  - State
1644
 *  - NaturalLanguageTerm
1645
 *  - TextFormat
1646
 *  - DeterminationModifier
1647
 *  - DnaMarker
1648
 *
1649
 * @param  $order_by
1650
 *  Optionally sort option (default: CDM_ORDER_BY_TITLE_CACHE_ASC)
1651
 *  possible values:
1652
 *    - CDM_ORDER_BY_ID_ASC
1653
 *    - CDM_ORDER_BY_ID_DESC
1654
 *    - CDM_ORDER_BY_TITLE_CACHE_ASC
1655
 *    - CDM_ORDER_BY_TITLE_CACHE_DESC
1656
 *    - CDM_ORDER_BY_ORDER_INDEX_ASC (can only be used with OrderedTerms!!)
1657
 *    - CDM_ORDER_BY_ORDER_INDEX_DESC (can only be used with OrderedTerms!!)
1658
 * @param bool $empty_option
1659
 *   An additional element do be placed at the beginning og the list. This element will be the default option.
1660
 * @return array
1661
 *    the terms in an array as options for a form element that allows multiple choices.
1662
 */
1663
function cdm_terms_by_type_as_option($term_type, $order_by = CDM_ORDER_BY_TITLE_CACHE_ASC, $term_label_callback = NULL, $empty_option = FALSE){
1664
  $terms = cdm_ws_fetch_all(
1665
    CDM_WS_TERM,
1666
    array(
1667
      'class' => $term_type,
1668
      'orderBy' => $order_by
1669
    )
1670
  );
1671
  return cdm_terms_as_options($terms, $term_label_callback, $empty_option);
1672
}
1673

    
1674

    
1675
/**
1676
 * @todo Please document this function.
1677
 * @see http://drupal.org/node/1354
1678
 */
1679
function _cdm_relationship_type_term_label_callback($term) {
1680
  if (isset($term->representation_L10n_abbreviatedLabel)) {
1681
    return $term->representation_L10n_abbreviatedLabel . ' : '
1682
    . t('@term', array('@term' => $term->representation_L10n));
1683
  }
1684
else {
1685
    return t('@term', array('@term' => $term->representation_L10n));
1686
  }
1687
}
1688

    
1689
// ========================================================================================== //
1690
/**
1691
 * @todo Improve documentation of this function.
1692
 *
1693
 * eu.etaxonomy.cdm.model.description.
1694
 * CategoricalData
1695
 * CommonTaxonName
1696
 * Distribution
1697
 * IndividualsAssociation
1698
 * QuantitativeData
1699
 * TaxonInteraction
1700
 * TextData
1701
 */
1702
function cdm_descriptionElementTypes_as_option($prependEmptyElement = FALSE) {
1703
  static $types = array(
1704
    "CategoricalData",
1705
    "CommonTaxonName",
1706
    "Distribution",
1707
    "IndividualsAssociation",
1708
    "QuantitativeData",
1709
    "TaxonInteraction",
1710
    "TextData",
1711
  );
1712

    
1713
  static $options = NULL;
1714
  if ($options == NULL) {
1715
    $options = array();
1716
    if ($prependEmptyElement) {
1717
      $options[' '] = '';
1718
    }
1719
    foreach ($types as $type) {
1720
      // No internatianalization here since these are purely technical terms.
1721
      $options["eu.etaxonomy.cdm.model.description." . $type] = $type;
1722
    }
1723
  }
1724
  return $options;
1725
}
1726

    
1727

    
1728
/**
1729
 * Fetches all TaxonDescription descriptions elements which are associated to the
1730
 * Taxon specified by the $taxon_uuid and merges the elements into the given
1731
 * feature tree.
1732
 * @param $feature_tree
1733
 *     The CDM FeatureTree to be used as template
1734
 * @param $taxon_uuid
1735
 *     The UUID of the taxon
1736
 * @param $excludes
1737
 *     UUIDs of features to be excluded
1738
 * @return$feature_tree
1739
 *     The CDM FeatureTree which was given as parameter merged tree whereas the
1740
 *     CDM FeatureNodes are extended by an additional field 'descriptionElements'
1741
 *     witch will hold the according $descriptionElements.
1742
 */
1743
function cdm_ws_descriptions_by_featuretree($feature_tree, $taxon_uuid, $exclude_uuids = array()) {
1744

    
1745
  if (!$feature_tree) {
1746
    drupal_set_message(check_plain(t("No 'FeatureTree' has been set so far.
1747
      In order to see the species profiles of your taxa, please select a
1748
      'FeatureTree' in the !settings"), array('!settings' => l(t('CDM Dataportal Settings'), 'admin/config/cdm_dataportal/layout'))), 'warning');
1749
    return FALSE;
1750
  }
1751

    
1752
  $description_elements = cdm_ws_fetch_all(CDM_WS_DESCRIPTIONELEMENT_BY_TAXON,
1753
      array(
1754
      'taxon' => $taxon_uuid,
1755
      'features' => cdm_featureTree_elements_toString($feature_tree->root, ',', 'uuid', $exclude_uuids)
1756
      ),
1757
      'POST'
1758
  );
1759

    
1760
  // Combine all descriptions into one feature tree.
1761
  $merged_nodes = _mergeFeatureTreeDescriptions($feature_tree->root->childNodes, $description_elements);
1762
  $feature_tree->root->childNodes = $merged_nodes;
1763

    
1764
  return $feature_tree;
1765
}
1766

    
1767
/**
1768
 * Returns a filtered a list of annotations for the cdm entity given as parameter $cdmBase.
1769
 * If the annotations are not yet already loded with the cdm entity the cdm REST service will
1770
 * be requested for the annotations.
1771
 *
1772
 * @param string $cdmBase
1773
 *   An annotatable cdm entity.
1774
 * @param array $includeTypes
1775
 *   If an array of annotation type uuids is supplied by this parameter the
1776
 *   list of annotations is resticted to those which belong to this type.
1777
 *
1778
 * @return array
1779
 *   An array of Annotation objects or an empty array.
1780
 */
1781
function cdm_ws_getAnnotationsFor(&$cdmBase, $includeTypes = FALSE) {
1782

    
1783
  if(!isset($cdmBase->annotations)){
1784
    $annotationUrl = cdm_compose_annotations_uri($cdmBase);
1785
    $cdmBase->annotations = cdm_ws_fetch_all($annotationUrl, array(), 'GET', TRUE);
1786
  }
1787

    
1788
  $annotations = array();
1789
  foreach ($cdmBase->annotations as $annotation) {
1790
    if ($includeTypes) {
1791
      if (
1792
        ( isset($annotation->annotationType->uuid) && in_array($annotation->annotationType->uuid, $includeTypes, TRUE) )
1793
        || ($annotation->annotationType === NULL && in_array('NULL_VALUE', $includeTypes, TRUE))
1794
      ) {
1795
        $annotations[] = $annotation;
1796
      }
1797
    }
1798
    else {
1799
      $annotations[] = $annotation;
1800
    }
1801
  }
1802
  return $annotations;
1803

    
1804
}
1805

    
1806
/**
1807
 * Loads the annotations from the REST service an adds them as field to the given $annotatable_entity.
1808
 *
1809
 * @param object $annotatable_entity
1810
 *   The CDM AnnotatableEntity to load annotations for
1811
 */
1812
function cdm_load_annotations(&$annotatable_entity) {
1813
  if (isset($annotatable_entity) && !isset($annotatable_entity->annotations)) {
1814
    $annotations = cdm_ws_getAnnotationsFor($annotatable_entity);
1815
    if (is_array($annotations)) {
1816
      $annotatable_entity->annotations = $annotations;
1817
    }
1818
  }
1819
}
1820

    
1821
/**
1822
 * Extends the $cdm_entity object by the field if it is not already existing.
1823
 *
1824
 * This function can only be used for fields with 1 to many relations.
1825
  *
1826
 * @param $cdm_base_type
1827
 * @param $field_name
1828
 * @param $cdm_entity
1829
 */
1830
function cdm_lazyload_array_field($cdm_base_type, $field_name, &$cdm_entity)
1831
{
1832
  if (!isset($cdm_entity->$field_name)) {
1833
    $items = cdm_ws_fetch_all('portal/' . $cdm_base_type . '/' . $cdm_entity->uuid . '/' . $field_name);
1834
    $cdm_entity->$field_name = $items;
1835
  }
1836
}
1837

    
1838

    
1839
/**
1840
 * Get a NomenclaturalReference string.
1841
 *
1842
 * Returns the NomenclaturalReference string with correctly placed
1843
 * microreference (= reference detail) e.g.
1844
 * in Phytotaxa 43: 1-48. 2012.
1845
 *
1846
 * @param string $referenceUuid
1847
 *   UUID of the reference.
1848
 * @param string $microreference
1849
 *   Reference detail.
1850
 *
1851
 * @return string
1852
 *   a NomenclaturalReference.
1853
 */
1854
function cdm_ws_getNomenclaturalReference($referenceUuid, $microreference) {
1855

    
1856
  // TODO the below statement avoids error boxes due to #4644 remove it once this ticket is solved
1857
  if(is_array($microreference) || is_object($microreference)) {
1858
    return '';
1859
  }
1860

    
1861
  $obj = cdm_ws_get(CDM_WS_NOMENCLATURAL_REFERENCE_CITATION, array(
1862
    $referenceUuid,
1863
  ), "microReference=" . urlencode($microreference));
1864

    
1865
  if ($obj) {
1866
    return $obj->String;
1867
  }
1868
  else {
1869
    return NULL;
1870
  }
1871
}
1872

    
1873
/**
1874
 * finds and returns the FeatureNode denoted by the given $feature_uuid
1875
 *
1876
 * @param $feature_tree_nodes
1877
 *    The nodes contained in CDM FeatureTree entitiy: $feature->root->childNodes
1878
 * @param $feature_uuid
1879
 *    The UUID of the Feature
1880
 * @return returns the FeatureNode or null
1881
 */
1882
function &cdm_feature_tree_find_node($feature_tree_nodes, $feature_uuid){
1883

    
1884
  // 1. scan this level
1885
  foreach ($feature_tree_nodes as $node){
1886
    if($node->feature->uuid == $feature_uuid){
1887
      return $node;
1888
    }
1889
  }
1890

    
1891
  // 2. descend into childen
1892
  foreach ($feature_tree_nodes as $node){
1893
    if(is_array($node->childNodes)){
1894
      $node = cdm_feature_tree_find_node($node->childNodes, $feature_uuid);
1895
      if($node) {
1896
        return $node;
1897
      }
1898
    }
1899
  }
1900
  $null_var = null; // kludgy workaround to avoid "PHP Notice: Only variable references should be returned by reference"
1901
  return $null_var;
1902
}
1903

    
1904
/**
1905
 * Merges the given featureNodes structure with the descriptionElements.
1906
 *
1907
 * This method is used in preparation for rendering the descriptionElements.
1908
 * The descriptionElements which belong to a specific feature node are appended
1909
 * to a the feature node by creating a new field:
1910
 *  - descriptionElements: the CDM DescriptionElements which belong to this feature
1911
 * The descriptionElements will be cleared in advance in order to allow reusing the
1912
 * same feature tree without the risk of mixing sets of description elements.
1913
 *
1914
 * which originally is not existing in the cdm.
1915
 *
1916
 *
1917
 *
1918
 * @param array $featureNodes
1919
 *    An array of cdm FeatureNodes which may be hierarchical since feature nodes
1920
 *    may have children.
1921
 * @param array $descriptionElements
1922
 *    An flat array of cdm DescriptionElements
1923
 * @return array
1924
 *    The $featureNodes structure enriched with the according $descriptionElements
1925
 */
1926
function _mergeFeatureTreeDescriptions($featureNodes, $descriptionElements) {
1927

    
1928
  foreach ($featureNodes as &$node) {
1929
    // since the $featureNodes array is reused for each description
1930
    // it is necessary to clear the custom node fields in advance
1931
    if(isset($node->descriptionElements)){
1932
      unset($node->descriptionElements);
1933
    }
1934

    
1935
    // Append corresponding elements to an additional node field:
1936
    // $node->descriptionElements.
1937
    foreach ($descriptionElements as $element) {
1938
      if ($element->feature->uuid == $node->feature->uuid) {
1939
        if (!isset($node->descriptionElements)) {
1940
          $node->descriptionElements = array();
1941
        }
1942
        $node->descriptionElements[] = $element;
1943
      }
1944
    }
1945

    
1946
    // Recurse into node children.
1947
    if (isset($node->childNodes[0])) {
1948
      $mergedChildNodes = _mergeFeatureTreeDescriptions($node->childNodes, $descriptionElements);
1949
      $node->childNodes = $mergedChildNodes;
1950
    }
1951

    
1952
    if(!isset($node->descriptionElements) && !isset($node->childNodes[0])){
1953
      unset($node);
1954
    }
1955

    
1956
  }
1957

    
1958
  return $featureNodes;
1959
}
1960

    
1961
/**
1962
 * Sends a GET or POST request to a CDM RESTService and returns a de-serialized object.
1963
 *
1964
 * The response from the HTTP GET request is returned as object.
1965
 * The response objects coming from the webservice configured in the
1966
 * 'cdm_webservice_url' variable are being cached in a level 1 (L1) and / or
1967
 *  in a level 2 (L2) cache.
1968
 *
1969
 * Since the L1 cache is implemented as static variable of the cdm_ws_get()
1970
 * function, this cache persists only per each single page execution.
1971
 * Any object coming from the webservice is stored into it by default.
1972
 * In contrast to this default caching mechanism the L2 cache only is used if
1973
 * the 'cdm_webservice_cache' variable is set to TRUE,
1974
 * which can be set using the modules administrative settings section.
1975
 * Objects stored in this L2 cache are serialized and stored
1976
 * using the drupal cache in the '{prefix}cache_cdm_ws' cache table. So the
1977
 * objects that are stored in the database will persist as
1978
 * long as the drupal cache is not being cleared and are available across
1979
 * multiple script executions.
1980
 *
1981
 * @param string $uri
1982
 *   URL to the webservice.
1983
 * @param array $pathParameters
1984
 *   An array of path parameters.
1985
 * @param string $query
1986
 *   A query string to be appended to the URL.
1987
 * @param string $method
1988
 *   The HTTP method to use, valid values are "GET" or "POST";
1989
 * @param bool $absoluteURI
1990
 *   TRUE when the URL should be treated as absolute URL.
1991
 *
1992
 * @return object| array
1993
 *   The de-serialized webservice response object.
1994
 */
1995
function cdm_ws_get($uri, $pathParameters = array(), $query = NULL, $method = "GET", $absoluteURI = FALSE) {
1996

    
1997
  static $cacheL1 = array();
1998

    
1999
  $data = NULL;
2000
  // store query string in $data and clear the query, $data will be set as HTTP request body
2001
  if($method == 'POST'){
2002
    $data = $query;
2003
    $query = NULL;
2004
  }
2005

    
2006
  // Transform the given uri path or pattern into a proper webservice uri.
2007
  if (!$absoluteURI) {
2008
    $uri = cdm_compose_url($uri, $pathParameters, $query);
2009
  }
2010

    
2011
  // read request parameter 'cacheL2_refresh'
2012
  // which allows refreshing the level 2 cache
2013
  $do_cacheL2_refresh = isset($_REQUEST['cacheL2_refresh']) && $_REQUEST['cacheL2_refresh'] == 1;
2014

    
2015
  $is_cdm_ws_uri = _is_cdm_ws_uri($uri);
2016
  $use_cacheL2 = variable_get('cdm_webservice_cache', 1);
2017

    
2018
  if($method == 'GET'){
2019
    $cache_key = $uri;
2020
  } else {
2021
    // sha1 creates longer hashes and thus will cause fewer collisions than md5.
2022
    // crc32 is faster but creates much shorter hashes
2023
    $cache_key = $uri . '[' . $method . ':' . sha1($data) .']';
2024
  }
2025

    
2026
  if (array_key_exists($cache_key, $cacheL1)) {
2027
    $cacheL1_obj = $cacheL1[$uri];
2028
  }
2029

    
2030
  $set_cacheL1 = FALSE;
2031
  if ($is_cdm_ws_uri && !isset($cacheL1_obj)) {
2032
    $set_cacheL1 = TRUE;
2033
  }
2034

    
2035
  // Only cache cdm webservice URIs.
2036
  $set_cacheL2 = $use_cacheL2 && $is_cdm_ws_uri && $set_cacheL1;
2037
  $cacheL2_entry = FALSE;
2038

    
2039
  if ($use_cacheL2 && !$do_cacheL2_refresh) {
2040
    // Try to get object from cacheL2.
2041
    $cacheL2_entry = cache_get($cache_key, 'cache_cdm_ws');
2042
  }
2043

    
2044
  if (isset($cacheL1_obj)) {
2045
    //
2046
    // The object has been found in the L1 cache.
2047
    //
2048
    $obj = $cacheL1_obj;
2049
    if (cdm_debug_block_visible()) {
2050
      cdm_ws_debug_add($uri, $method, $data, 0, 0, NULL, 'cacheL1');
2051
    }
2052
  }
2053
  elseif ($cacheL2_entry) {
2054
    //
2055
    // The object has been found in the L2 cache.
2056
    //
2057
    $duration_parse_start = microtime(TRUE);
2058
    $obj = unserialize($cacheL2_entry->data);
2059
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2060

    
2061
    if (cdm_debug_block_visible()) {
2062
      cdm_ws_debug_add($uri, $method, $data, 0, $duration_parse, NULL, 'cacheL2');
2063
    }
2064
  }
2065
  else {
2066
    //
2067
    // Get the object from the webservice and cache it.
2068
    //
2069
    $duration_fetch_start = microtime(TRUE);
2070
    // Request data from webservice JSON or XML.
2071
    $response = cdm_http_request($uri, $method, $data);
2072
    $response_body = NULL;
2073
    if (isset($response->data)) {
2074
      $response_body = $response->data;
2075
    }
2076
    $duration_fetch = microtime(TRUE) - $duration_fetch_start;
2077
    $duration_parse_start = microtime(TRUE);
2078

    
2079
    // Parse data and create object.
2080
    $obj = cdm_load_obj($response_body);
2081

    
2082
    $duration_parse = microtime(TRUE) - $duration_parse_start;
2083

    
2084
    if (cdm_debug_block_visible()) {
2085
      if ($obj || $response_body == "[]") {
2086
        $status = 'valid';
2087
      }
2088
      else {
2089
        $status = 'invalid';
2090
      }
2091
      cdm_ws_debug_add($uri, $method, $data, $duration_fetch, $duration_parse, strlen($response_body), $status);
2092
    }
2093
    if ($set_cacheL2) {
2094
      // Store the object in cache L2.
2095
      // Comment @WA perhaps better if Drupal serializedatas here? Then the
2096
      // flag serialized is set properly in the cache table.
2097
      cache_set($cache_key, serialize($obj), 'cache_cdm_ws', CACHE_TEMPORARY);
2098
    }
2099
  }
2100
  if ($obj) {
2101
    // Store the object in cache L1.
2102
    if ($set_cacheL1) {
2103
      $cacheL1[$cache_key] = $obj;
2104
    }
2105
  }
2106
  return $obj;
2107
}
2108

    
2109
/**
2110
 * Processes and stores the given information in $_SESSION['cdm']['ws_debug'] as table row.
2111
 *
2112
 * The cdm_ws_debug block will display the debug information.
2113
 *
2114
 * @param $uri
2115
 *    The CDM REST URI to which the request has been send
2116
 * @param string $method
2117
 *    The HTTP request method, either 'GET' or 'POST'
2118
 * @param string $post_data
2119
 *    The datastring send with a post request
2120
 * @param $duration_fetch
2121
 *    The time in seconds it took to fetch the data from the web service
2122
 * @param $duration_parse
2123
 *    Time in seconds which was needed to parse the json response
2124
 * @param $datasize
2125
 *    Size of the data received from the server
2126
 * @param $status
2127
 *    A status string, possible values are: 'valid', 'invalid', 'cacheL1', 'cacheL2'
2128
 * @return bool
2129
 *    TRUE if adding the debug information was successful
2130
 */
2131
function cdm_ws_debug_add($uri, $method, $post_data, $duration_fetch, $duration_parse, $datasize, $status) {
2132

    
2133
  static $initial_time = NULL;
2134
  if(!$initial_time) {
2135
    $initial_time = microtime(TRUE);
2136
  }
2137
  $time = microtime(TRUE) - $initial_time;
2138

    
2139
  // Decompose uri into path and query element.
2140
  $uri_parts = explode("?", $uri);
2141
  $query = array();
2142
  if (count($uri_parts) == 2) {
2143
    $path = $uri_parts[0];
2144
  }
2145
  else {
2146
    $path = $uri;
2147
  }
2148

    
2149
  if(strpos($uri, '?') > 0){
2150
    $json_uri = str_replace('?', '.json?', $uri);
2151
    $xml_uri = str_replace('?', '.xml?', $uri);
2152
  } else {
2153
    $json_uri = $uri . '.json';
2154
    $xml_uri = $json_uri . '.xml';
2155
  }
2156

    
2157
  // data links to make data accecsible as json and xml
2158
  $data_links = '';
2159
  if (_is_cdm_ws_uri($path)) {
2160

    
2161
    // see ./js/http-method-link.js
2162

    
2163
    if($method == 'GET'){
2164
      $data_links .= '<a href="' . $xml_uri . '" target="data">xml</a>-';
2165
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">proxied</a>';
2166
      $data_links .= '<br/>';
2167
      $data_links .= '<a href="' . $json_uri . '" target="data">json</a>-';
2168
      $data_links .= '<a href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">proxied</a>';
2169
    } else {
2170
      $js_link_activation = 'class="http-' . $method . '-link" data-cdm-http-post="' . $post_data . '" type="application/x-www-form-urlencoded"';
2171
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($xml_uri)) . '" target="data">xml-proxied</a>';
2172
      $data_links .= '<br/>';
2173
      $data_links .= '<a ' . $js_link_activation . ' href="' . url('cdm_api/proxy/' . urlencode($json_uri)) . '" target="data">json-proxied</a>';
2174
    }
2175
  }
2176
  else {
2177
    $data_links .= '<a href="' . $uri . '" target="data">open</a>';
2178
  }
2179

    
2180
  //
2181
  $data = array(
2182
      'ws_uri' => $uri,
2183
      'method' => $method,
2184
      'post_data' => $post_data,
2185
      'time' => sprintf('%3.3f', $time),
2186
      'fetch_seconds' => sprintf('%3.3f', $duration_fetch),
2187
      'parse_seconds' => sprintf('%3.3f', $duration_parse),
2188
      'size_kb' => sprintf('%3.1f', ($datasize / 1024)) ,
2189
      'status' => $status,
2190
      'data_links' => $data_links
2191
  );
2192
  if (!isset($_SESSION['cdm']['ws_debug'])) {
2193
    $_SESSION['cdm']['ws_debug'] = array();
2194
  }
2195
  $_SESSION['cdm']['ws_debug'][] = serialize($data);
2196

    
2197
  // Mark this page as being uncacheable.
2198
  // taken over from drupal_get_messages() but it is unsure if we really need this here
2199
  drupal_page_is_cacheable(FALSE);
2200

    
2201
  // Messages not set when DB connection fails.
2202
  return isset($_SESSION['cdm']['ws_debug']) ? $_SESSION['cdm']['ws_debug'] : NULL;
2203
}
2204

    
2205
/**
2206
 * helper function to dtermine if the cdm_debug_block should be displayed or not
2207
 * the visibility depends on whether
2208
 *  - the block is enabled
2209
 *  - the visibility restrictions in the block settings are satisfied
2210
 */
2211
function cdm_debug_block_visible() {
2212
  static $is_visible = null;
2213

    
2214
  if($is_visible === null){
2215
      $block = block_load('cdm_api', 'cdm_ws_debug');
2216
      $is_visible = isset($block->status) && $block->status == 1;
2217
      if($is_visible){
2218
        $blocks = array($block);
2219
        // Checks the page, user role, and user-specific visibilty settings.
2220
        block_block_list_alter($blocks);
2221
        $is_visible = count($blocks) > 0;
2222
      }
2223
  }
2224
  return $is_visible;
2225
}
2226

    
2227
/**
2228
 * @todo Please document this function.
2229
 * @see http://drupal.org/node/1354
2230
 */
2231
function cdm_load_obj($response_body) {
2232
  $obj = json_decode($response_body);
2233

    
2234
  if (!(is_object($obj) || is_array($obj))) {
2235
    ob_start();
2236
    $obj_dump = ob_get_contents();
2237
    ob_clean();
2238
    return FALSE;
2239
  }
2240

    
2241
  return $obj;
2242
}
2243

    
2244
/**
2245
 * Do a http request to a CDM RESTful web service.
2246
 *
2247
 * @param string $uri
2248
 *   The webservice url.
2249
 * @param string $method
2250
 *   The HTTP method to use, valid values are "GET" or "POST"; defaults to
2251
 *   "GET" even if NULL, FALSE or any invalid value is supplied.
2252
 * @param $data: A string containing the request body, formatted as
2253
 *     'param=value&param=value&...'. Defaults to NULL.
2254
 *
2255
 * @return object
2256
 *   The object as returned by drupal_http_request():
2257
 *   An object that can have one or more of the following components:
2258
 *   - request: A string containing the request body that was sent.
2259
 *   - code: An integer containing the response status code, or the error code
2260
 *     if an error occurred.
2261
 *   - protocol: The response protocol (e.g. HTTP/1.1 or HTTP/1.0).
2262
 *   - status_message: The status message from the response, if a response was
2263
 *     received.
2264
 *   - redirect_code: If redirected, an integer containing the initial response
2265
 *     status code.
2266
 *   - redirect_url: If redirected, a string containing the URL of the redirect
2267
 *     target.
2268
 *   - error: If an error occurred, the error message. Otherwise not set.
2269
 *   - headers: An array containing the response headers as name/value pairs.
2270
 *     HTTP header names are case-insensitive (RFC 2616, section 4.2), so for
2271
 *     easy access the array keys are returned in lower case.
2272
 *   - data: A string containing the response body that was received.
2273
 */
2274
function cdm_http_request($uri, $method = "GET", $data = NULL) {
2275
  static $acceptLanguage = NULL;
2276
  $header = array();
2277
  
2278
  if(!$acceptLanguage && module_exists('i18n')){
2279
    $acceptLanguage = i18n_language_content()->language;
2280
  }
2281

    
2282
  if (!$acceptLanguage) {
2283
    if (function_exists('apache_request_headers')) {
2284
      $headers = apache_request_headers();
2285
      if (isset($headers['Accept-Language'])) {
2286
        $acceptLanguage = $headers['Accept-Language'];
2287
      }
2288
    }
2289
  }
2290

    
2291
  if ($method != "GET" && $method != "POST") {
2292
    drupal_set_message('cdm_api.module#cdm_http_request() : unsupported HTTP request method ', 'error');
2293
  }
2294

    
2295
  if (_is_cdm_ws_uri($uri)) {
2296
    $header['Accept'] = 'application/json';
2297
    $header['Accept-Language'] = $acceptLanguage;
2298
    $header['Accept-Charset'] = 'UTF-8';
2299
  }
2300

    
2301
  if($method == "POST") {
2302
    // content type is application/x-www-form-urlencoded, so the request body uses the same format as the query string
2303
    $header['Content-Type'] = 'application/x-www-form-urlencoded';
2304
  }
2305

    
2306

    
2307
  cdm_dd($uri);
2308
  return drupal_http_request($uri, array(
2309
      'headers' => $header,
2310
      'method' => $method,
2311
      'data' => $data,
2312
      'timeout' => CDM_HTTP_REQUEST_TIMEOUT
2313
      )
2314
   );
2315
}
2316

    
2317
/**
2318
 * Concatenates recursively the fields of all features contained in the given
2319
 * CDM FeatureTree root node.
2320
 *
2321
 * @param $rootNode
2322
 *     A CDM FeatureTree node
2323
 * @param
2324
 *     The character to be used as glue for concatenation, default is ', '
2325
 * @param $field_name
2326
 *     The field name of the CDM Features
2327
 * @param $excludes
2328
 *     Allows defining a set of values to be excluded. This refers to the values
2329
 *     in the field denoted by the $field_name parameter
2330
 *
2331
 */
2332
function cdm_featureTree_elements_toString($root_node, $separator = ', ', $field_name = 'representation_L10n', $excludes = array()) {
2333
  $out = '';
2334

    
2335
  $pre_child_separator = $separator;
2336
  $post_child_separator = '';
2337

    
2338
  foreach ($root_node->childNodes as $feature_node) {
2339
    $out .= ($out ? $separator : '');
2340
    if(!in_array($feature_node->feature->$field_name, $excludes)) {
2341
      $out .= $feature_node->feature->$field_name;
2342
      if (is_array($feature_node->childNodes) && count($feature_node->childNodes) > 0) {
2343
        $childlabels = cdm_featureTree_elements_toString($feature_node, $separator, $field_name);
2344
        if (strlen($childlabels)) {
2345
            $out .=  $pre_child_separator . $childlabels . $post_child_separator;
2346
        }
2347
      }
2348
    }
2349
  }
2350
  return $out;
2351
}
2352

    
2353
/**
2354
 * Create a one-dimensional form options array.
2355
 *
2356
 * Creates an array of all features in the feature tree of feature nodes,
2357
 * the node labels are indented by $node_char and $childIndent depending on the
2358
 * hierachy level.
2359
 *
2360
 * @param - $rootNode
2361
 * @param - $node_char
2362
 * @param - $childIndentStr
2363
 * @param - $childIndent
2364
 *   ONLY USED INTERNALLY!
2365
 *
2366
 * @return array
2367
 *   A one dimensional Drupal form options array.
2368
 */
2369
function _featureTree_nodes_as_feature_options($rootNode, $node_char = "&#9500;&#9472; ", $childIndentStr = '&nbsp;', $childIndent = '') {
2370
  $options = array();
2371
  foreach ($rootNode->childNodes as $featureNode) {
2372
    $indent_prefix = '';
2373
    if ($childIndent) {
2374
      $indent_prefix = $childIndent . $node_char . " ";
2375
    }
2376
    $options[$featureNode->feature->uuid] = $indent_prefix . $featureNode->feature->representation_L10n;
2377
    if (isset($featureNode->childNodes) && is_array($featureNode->childNodes)) {
2378
      // Foreach ($featureNode->childNodes as $childNode){
2379
      $childList = _featureTree_nodes_as_feature_options($featureNode, $node_char, $childIndentStr, $childIndent . $childIndentStr);
2380
      $options = array_merge_recursive($options, $childList);
2381
      // }
2382
    }
2383
  }
2384
  return $options;
2385
}
2386

    
2387
/**
2388
 * Returns an array with all available FeatureTrees and the representations of the selected
2389
 * FeatureTree as a detail view.
2390
 *
2391
 * @param boolean $add_default_feature_free
2392
 * @return array
2393
 *  associative array with following keys:
2394
 *  -options: Returns an array with all available Feature Trees
2395
 *  -treeRepresentations: Returns representations of the selected Feature Tree as a detail view
2396
 *
2397
 */
2398
function cdm_get_featureTrees_as_options($add_default_feature_free = FALSE) {
2399

    
2400
  $options = array();
2401
  $tree_representations = array();
2402
  $feature_trees = array();
2403

    
2404
  // Set tree that contains all features.
2405
  if ($add_default_feature_free) {
2406
    $options[UUID_DEFAULT_FEATURETREE] = t('Default Featuretree (contains all features)');
2407
    $feature_trees[] = cdm_ws_get(CDM_WS_FEATURETREE, UUID_DEFAULT_FEATURETREE);
2408
  }
2409

    
2410
  // Get feature trees from database.
2411
  $persited_trees = cdm_ws_fetch_all(CDM_WS_FEATURETREES);
2412
  if (is_array($persited_trees)) {
2413
    $feature_trees = array_merge($feature_trees, $persited_trees);
2414
  }
2415

    
2416
  foreach ($feature_trees as $featureTree) {
2417

    
2418
    if(!is_object($featureTree)){
2419
      continue;
2420
    }
2421
    // Do not add the DEFAULT_FEATURETREE again,
2422
    if ($featureTree->uuid != UUID_DEFAULT_FEATURETREE) {
2423
      $options[$featureTree->uuid] = $featureTree->titleCache;
2424
    }
2425

    
2426
    // Render the hierarchic tree structure
2427
    if (is_array( $featureTree->root->childNodes) && count( $featureTree->root->childNodes) > 0) {
2428

    
2429
      // Render the hierarchic tree structure.
2430
      $treeDetails = '<div class="featuretree_structure">'
2431
        . theme('FeatureTree_hierarchy', array('FeatureTreeUuid' =>  $featureTree->uuid))
2432
        . '</div>';
2433

    
2434
      $form = array();
2435
      $form['featureTree-' .  $featureTree->uuid] = array(
2436
        '#type' => 'fieldset',
2437
        '#title' => 'Show details',
2438
        '#attributes' => array('class' => array('collapsible collapsed')),
2439
        // '#collapsible' => TRUE,
2440
        // '#collapsed' => TRUE,
2441
      );
2442
      $form['featureTree-' .  $featureTree->uuid]['details'] = array(
2443
        '#markup' => $treeDetails,
2444
      );
2445

    
2446
      $tree_representations[$featureTree->uuid] = drupal_render($form);
2447
    }
2448

    
2449
  } // END loop over feature trees
2450

    
2451
  // return $options;
2452
  return array('options' => $options, 'treeRepresentations' => $tree_representations);
2453
}
2454

    
2455
/**
2456
 * Provides the list of available classifications in form of an options array.
2457
 *
2458
 * The options array is suitable for drupal form API elements that allow multiple choices.
2459
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
2460
 *
2461
 * The classifications are ordered alphabetically whereas the classification
2462
 * chosen as default will always appear on top of the array, followed by a
2463
 * blank line below.
2464
 *
2465
 * @param bool $add_none_option
2466
 *   is true an addtional 'none' option will be added, optional parameter, defaults to FALSE
2467
 *
2468
 * @return array
2469
 *   classifications in an array as options for a form element that allows multiple choices.
2470
 */
2471
function cdm_get_taxontrees_as_options($add_none_option = FALSE) {
2472

    
2473
  $taxonTrees = cdm_ws_fetch_all(CDM_WS_PORTAL_TAXONOMY);
2474

    
2475
  $default_classification_uuid = variable_get(CDM_TAXONOMICTREE_UUID, FALSE);
2476
  $default_classification_label = '';
2477

    
2478
  // add all classifications
2479
  $taxonomic_tree_options = array();
2480
  if ($add_none_option) {
2481
    $taxonomic_tree_options['NONE'] = ' '; // one Space character at beginning to force on top;
2482
  }
2483
  if ($taxonTrees) {
2484
    foreach ($taxonTrees as $tree) {
2485
      if (!$default_classification_uuid || $default_classification_uuid != $tree->uuid) {
2486
        $taxonomic_tree_options[$tree->uuid] = $tree->titleCache;
2487
      } else {
2488
        $taxonomic_tree_options[$tree->uuid] = '  '; // two Space characters to force on top but below 'none' option , will be replaced below by titleCache
2489
        $default_classification_label = $tree->titleCache;
2490
      }
2491
    }
2492
  }
2493
  // oder alphabetically the space
2494
  asort($taxonomic_tree_options);
2495

    
2496
  // now set the labels
2497
  //   for none
2498
  if ($add_none_option) {
2499
    $taxonomic_tree_options['NONE'] =t('--- ALL ---');
2500
  }
2501

    
2502
  //   for default_classification
2503
  if (is_uuid($default_classification_uuid)) {
2504
    $taxonomic_tree_options[$default_classification_uuid] =
2505
      $default_classification_label ? $default_classification_label : '--- INVALID CHOICE ---'
2506
      . (count($taxonTrees) > 1 ? ' [' . t('DEFAULT CLASSIFICATION') . ']': '');
2507
  }
2508

    
2509
  return $taxonomic_tree_options;
2510
}
2511

    
2512
/**
2513
 * @todo Please document this function.
2514
 * @see http://drupal.org/node/1354
2515
 */
2516
function cdm_api_secref_cache_prefetch(&$secUuids) {
2517
  // Comment @WA: global variables should start with a single underscore
2518
  // followed by the module and another underscore.
2519
  global $_cdm_api_secref_cache;
2520
  if (!is_array($_cdm_api_secref_cache)) {
2521
    $_cdm_api_secref_cache = array();
2522
  }
2523
  $uniqueUuids = array_unique($secUuids);
2524
  $i = 0;
2525
  $param = '';
2526
  while ($i++ < count($uniqueUuids)) {
2527
    $param .= $secUuids[$i] . ',';
2528
    if (strlen($param) + 37 > 2000) {
2529
      _cdm_api_secref_cache_add($param);
2530
      $param = '';
2531
    }
2532
  }
2533
  if ($param) {
2534
    _cdm_api_secref_cache_add($param);
2535
  }
2536
}
2537

    
2538
/**
2539
 * @todo Please document this function.
2540
 * @see http://drupal.org/node/1354
2541
 */
2542
function cdm_api_secref_cache_get($secUuid) {
2543
  global $_cdm_api_secref_cache;
2544
  if (!is_array($_cdm_api_secref_cache)) {
2545
    $_cdm_api_secref_cache = array();
2546
  }
2547
  if (!array_key_exists($secUuid, $_cdm_api_secref_cache)) {
2548
    _cdm_api_secref_cache_add($secUuid);
2549
  }
2550
  return $_cdm_api_secref_cache[$secUuid];
2551
}
2552

    
2553
/**
2554
 * @todo Please document this function.
2555
 * @see http://drupal.org/node/1354
2556
 */
2557
function cdm_api_secref_cache_clear() {
2558
  global $_cdm_api_secref_cache;
2559
  $_cdm_api_secref_cache = array();
2560
}
2561

    
2562

    
2563
/**
2564
 * Validates if the given string is a uuid.
2565
 *
2566
 * @param string $str
2567
 *   The string to validate.
2568
 *
2569
 * return bool
2570
 *   TRUE if the string is a UUID.
2571
 */
2572
function is_uuid($str) {
2573
  return is_string($str) && strlen($str) == 36 && strpos($str, '-');
2574
}
2575

    
2576
/**
2577
 * Checks if the given $object is a valid cdm entity.
2578
 *
2579
 * An object is considered a cdm entity if it has a string field $object->class
2580
 * with at least 3 characters and if it has a valid uuid in $object->uuid.
2581
 * The function is null save.
2582
 *
2583
 * @author a.kohlbecker <a.kohlbecker@bgbm.org>
2584
 *
2585
 * @param mixed $object
2586
 *   The object to validate
2587
 *
2588
 * @return bool
2589
 *   True if the object is a cdm entity.
2590
 */
2591
function is_cdm_entity($object) {
2592
  return
2593
    isset($object->class) && is_string($object->class) && strlen($object->class) > 2 && $object->class != 'TypedEntityReference'
2594
    && is_string($object->uuid) && is_uuid($object->uuid);
2595
}
2596

    
2597
/**
2598
 * @todo Please document this function.
2599
 * @see http://drupal.org/node/1354
2600
 */
2601
function _cdm_api_secref_cache_add($secUuidsStr) {
2602
  global $_cdm_api_secref_cache;
2603
  $ref = cdm_ws_get(CDM_WS_REFERENCE, $secUuidsStr);
2604
  // Batch fetching not jet reimplemented thus:
2605
  /*
2606
  $assocRefSTOs = array(); if($refSTOs) { foreach($refSTOs as $ref){
2607
  $assocRefSTOs[$ref->uuid] = $ref; } $_cdm_api_secref_cache =
2608
  array_merge($_cdm_api_secref_cache, $assocRefSTOs); }
2609
  */
2610
  $_cdm_api_secref_cache[$ref->uuid] = $ref;
2611
}
2612

    
2613
/**
2614
 * Checks if the given uri starts with a cdm webservice url.
2615
 *
2616
 * Checks if the uri starts with the cdm webservice url stored in the
2617
 * Drupal variable 'cdm_webservice_url'.
2618
 * The 'cdm_webservice_url' can be set in the admins section of the portal.
2619
 *
2620
 * @param string $uri
2621
 *   The URI to test.
2622
 *
2623
 * @return bool
2624
 *   True if the uri starts with a cdm webservice url.
2625
 */
2626
function _is_cdm_ws_uri($uri) {
2627
  return str_beginsWith($uri, variable_get('cdm_webservice_url', '#EMPTY#'));
2628
}
2629

    
2630
/**
2631
 * @todo Please document this function.
2632
 * @see http://drupal.org/node/1354
2633
 */
2634
function queryString($elements) {
2635
  $query = '';
2636
  foreach ($elements as $key => $value) {
2637
    if (is_array($value)) {
2638
      foreach ($value as $v) {
2639
        $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($v);
2640
      }
2641
    }
2642
    else {
2643
      $query .= (strlen($query) > 0 ? '&' : '') . $key . '=' . urlencode($value);
2644
    }
2645
  }
2646
  return $query;
2647
}
2648

    
2649
/**
2650
 * Implementation of the magic method __clone to allow deep cloning of objects
2651
 * and arrays.
2652
 */
2653
function __clone() {
2654
  foreach ($this as $name => $value) {
2655
    if (gettype($value) == 'object' || gettype($value) == 'array') {
2656
      $this->$name = clone($this->$name);
2657
    }
2658
  }
2659
}
2660

    
2661
/**
2662
 * Compares the given CDM Term instances by the  representationL10n.
2663
 *
2664
 * Can also be used with TermDTOs. To be used in usort()
2665
 *
2666
 * @see http://php.net/manual/en/function.usort.php
2667
 *
2668
 * @param $term1
2669
 *   The first CDM Term instance
2670
 * @param $term2
2671
 *   The second CDM Term instance
2672
 * @return int
2673
 *   The result of the comparison
2674
 */
2675
function compare_terms_by_representationL10n($term1, $term2) {
2676

    
2677
  if (!isset($term1->representation_L10n)) {
2678
    $term1->representationL10n = '';
2679
  }
2680
  if (!isset($term2->representation_L10n)) {
2681
    $term2->representationL10n = '';
2682
  }
2683

    
2684
  return strcmp($term1->representation_L10n, $term2->representation_L10n);
2685
}
2686

    
2687
function compare_terms_by_order_index($term1, $term2) {
2688

    
2689

    
2690
  if (!isset($term1->orderIndex)) {
2691
    $a = 0;
2692
  } else {
2693
    $a = $term1->orderIndex;
2694
  }
2695
  if (!isset($term2->orderIndex)) {
2696
    $b = 0;
2697
  } else {
2698
    $b = $term2->orderIndex;
2699
  }
2700

    
2701
  if ($a == $b) {
2702
    return 0;
2703
  }
2704
  return ($a < $b) ? -1 : 1;
2705

    
2706
}
2707

    
2708

    
2709
/**
2710
 * Make a 'deep copy' of an array.
2711
 *
2712
 * Make a complete deep copy of an array replacing
2713
 * references with deep copies until a certain depth is reached
2714
 * ($maxdepth) whereupon references are copied as-is...
2715
 *
2716
 * @see http://us3.php.net/manual/en/ref.array.php
2717
 *
2718
 * @param array $array
2719
 * @param array $copy passed by reference
2720
 * @param int $maxdepth
2721
 * @param int $depth
2722
 */
2723
function array_deep_copy(&$array, &$copy, $maxdepth = 50, $depth = 0) {
2724
  if ($depth > $maxdepth) {
2725
    $copy = $array;
2726
    return;
2727
  }
2728
  if (!is_array($copy)) {
2729
    $copy = array();
2730
  }
2731
  foreach ($array as $k => &$v) {
2732
    if (is_array($v)) {
2733
      array_deep_copy($v, $copy[$k], $maxdepth, ++$depth);
2734
    }
2735
    else {
2736
      $copy[$k] = $v;
2737
    }
2738
  }
2739
}
2740

    
2741
/**
2742
 * Adds java script to create and enable a toggler for the cdm webservice debug block content.
2743
 *
2744
 */
2745
function _add_js_ws_debug() {
2746

    
2747
  $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.min.js';
2748
  $colorbox_js = '/js/colorbox/jquery.colorbox-min.js';
2749
  if (variable_get('cdm_js_devel_mode', FALSE)) {
2750
    // use the developer versions of js libs
2751
    $data_tables_js = '/js/DataTables-1.9.4/media/js/jquery.dataTables.js';
2752
    $colorbox_js = '/js/colorbox/jquery.colorbox.js';
2753
  }
2754
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $data_tables_js,
2755
    array(
2756
      'type' => 'file',
2757
      'weight' => JS_LIBRARY,
2758
      'cache' => TRUE)
2759
    );
2760

    
2761
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . $colorbox_js,
2762
    array(
2763
      'type' => 'file',
2764
      'weight' => JS_LIBRARY,
2765
      'cache' => TRUE)
2766
    );
2767
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/colorbox/colorbox.css');
2768
  drupal_add_css(drupal_get_path('module', 'cdm_dataportal') . '/js/DataTables-1.9.4/media/css/cdm_debug_table.css');
2769

    
2770
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/ws_debug_block.js',
2771
    array(
2772
      'type' => 'file',
2773
      'weight' => JS_LIBRARY,
2774
      'cache' => TRUE)
2775
    );
2776
  drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/http-method-link.js',
2777
    array(
2778
    'type' => 'file',
2779
    'weight' => JS_LIBRARY,
2780
    'cache' => TRUE)
2781
    );
2782

    
2783
}
2784

    
2785
/**
2786
 * @todo Please document this function.
2787
 * @see http://drupal.org/node/1354
2788
 */
2789
function _no_classfication_uuid_message() {
2790
  if (!cdm_ws_get(CDM_WS_PORTAL_TAXONOMY)) {
2791
    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.');
2792
  }
2793
  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.');
2794
}
2795

    
2796
/**
2797
 * Implementation of hook flush_caches
2798
 *
2799
 * Add custom cache tables to the list of cache tables that
2800
 * will be cleared by the Clear button on the Performance page or whenever
2801
 * drupal_flush_all_caches is invoked.
2802
 *
2803
 * @author W.Addink <waddink@eti.uva.nl>
2804
 *
2805
 * @return array
2806
 *   An array with custom cache tables to include.
2807
 */
2808
function cdm_api_flush_caches() {
2809
  return array('cache_cdm_ws');
2810
}
2811

    
2812
/**
2813
 * Logs if the drupal variable 'cdm_debug_mode' ist set true to drupal_debug.txt in the site's temp directory.
2814
 *
2815
 * @param $data
2816
 *   The variable to log to the drupal_debug.txt log file.
2817
 * @param $label
2818
 *   (optional) If set, a label to output before $data in the log file.
2819
 *
2820
 * @return
2821
 *   No return value if successful, FALSE if the log file could not be written
2822
 *   to.
2823
 *
2824
 * @see cdm_dataportal_init() where the log file is reset on each requests
2825
 * @see dd()
2826
 * @see http://drupal.org/node/314112
2827
 *
2828
 */
2829
function cdm_dd($data, $label = NULL) {
2830
  if(module_exists('devel') && variable_get('cdm_debug_mode', FALSE) && file_stream_wrapper_get_class('temporary') ){
2831
    return dd($data, $label);
2832
  }
2833
}
2834

    
Add picture from clipboard (Maximum size: 40 MB)