Project

General

Profile

Download (22.6 KB) Statistics
| Branch: | Tag: | Revision:
1
<?php
2
/**
3
 * @file
4
 * Search related functions.
5
 */
6

    
7
/**
8
 * Returns a Drupal path to a search form for a CDM webservice.
9
 *
10
 * For a given CDM webservice end-point, the drupal page path to the
11
 * according search form is returned.
12
 * cdm webservice end points are defined in constant variables like:
13
 * <code>CDM_WS_PORTAL_TAXON_FIND</code> and
14
 * <code>CDM_WS_PORTAL_TAXON_FINDBY_DESCRIPTIONELEMENT_FULLTEXT</code>
15
 *
16
 * @param string $ws_endpoint
17
 *   The cdm webservice endpoint for which to find the search form path.
18
 *
19
 * @return string
20
 *   The Drupal path found.
21
 */
22
function cdm_dataportal_search_form_path_for_ws($ws_endpoint) {
23
  static $form_ws_map = array(
24
    CDM_WS_PORTAL_TAXON_FIND => "cdm_dataportal/search",
25
    CDM_WS_PORTAL_TAXON_SEARCH => "cdm_dataportal/search",
26
    CDM_WS_PORTAL_TAXON_FINDBY_DESCRIPTIONELEMENT_FULLTEXT => "cdm_dataportal/search/taxon_by_description",
27
  );
28
  return $form_ws_map[$ws_endpoint];
29
}
30

    
31
/**
32
 * Prepares a form array for a general purpose search form.
33
 *
34
 * The form is used for general purpose search functionality in the
35
 * dataportal. The form returned is populated with all nessecary fields
36
 * for internal processing and has the textfield element $form['query']
37
 * which holds the query term.
38
 * he sub tree array can be extended to contain additional search parameters.
39
 *
40
 * @param string $action_path
41
 *   The Drupal path to be put into the action url to which the form will
42
 *   be submitted.
43
 * @param string $search_webservice
44
 *   The cdm-remote webservice to be used, valid values are defined by
45
 *   the constants: FIXME.
46
 * @param string $query_field_default_value
47
 *   A default text for the query field
48
 * @param string $query_field_description
49
 *   The description text for the query field
50
 * @param string $process
51
 *   The value for #process, if NULL (default), 'cdm_dataportal_search_process'
52
 *   is used.
53
 *
54
 * @return array
55
 *   The prepared form array.
56
 */
57
function cdm_dataportal_search_form_prepare($action_path, $search_webservice, $query_field_default_value, $query_field_description, $process = NULL) {
58

    
59
  if ($process == NULL) {
60
    $process = 'cdm_dataportal_search_process';
61
  }
62

    
63
  $form['#method'] = 'get';
64
  //
65
  //  $form['#process'] = array(
66
  //  $process => array(),
67
  //  );
68
  //
69
  $form['#action'] = url($action_path, array(
70
    'absolute' => TRUE,
71
  ));
72

    
73
  $form['ws'] = array(
74
    '#type' => 'hidden',
75
    '#value' => $search_webservice,
76
    '#name' => 'ws',
77
  );
78

    
79
  $form['query'] = array(
80
    '#weight' => 0,
81
    '#type' => 'textfield',
82
    '#size' => 68,
83
    // This causes the description to display also when hovering over
84
    // the textfield.
85
    // This is wanted behaviour for the simple seach but could
86
    // be disabled for the advances search.
87
    '#attributes' => array(
88
      'title' => $query_field_description,
89
    ),
90
    '#description' => $query_field_description,
91
    '#value' => $query_field_default_value,
92
    // '#description' => $query_field_description,
93
  );
94
  if(variable_get('cdm_dataportal_taxon_auto_suggest')){
95
      $form['query']['#autocomplete_path'] = 'cdm_dataportal/taxon/autosuggest////';
96
  }
97

    
98
    $form['search'] = array(
99
    '#weight' => 3,
100
    '#tree' => TRUE,
101
    // '#type' => $advanced_form ? 'fieldset': 'hidden',
102
    '#title' => t('Options'),
103
  );
104

    
105
  // Clean URL get forms breaks if we don't give it a 'q'.
106
  if (!(bool) variable_get('clean_url', '0')) {
107
    $form['search']['q'] = array(
108
      '#type' => 'hidden',
109
      '#value' => $action_path,
110
      '#name' => 'q',
111
    );
112
  }
113

    
114
  $form['submit'] = array(
115
    '#weight' => 5,
116
    '#type' => 'submit',
117
    '#name' => '',
118
    '#value' => t('Search'),
119
  );
120

    
121
  return $form;
122
}
123

    
124
function cdm_dataportal_taxon_autosuggest($classificationUuid = NULL, $areaUuid = NULL, $status = NULL, $string) {
125
  $matches = array();
126

    
127
  $queryParams = array();
128
  $queryParams['query'] = $string.'*';
129
  if((is_null($classificationUuid) || $classificationUuid=='') && isset($_SESSION['cdm']['taxonomictree_uuid'])){
130
    $classificationUuid = $_SESSION['cdm']['taxonomictree_uuid'];// if no classification uuid is set use the current one
131
  }
132
  if($classificationUuid){
133
    $queryParams['classificationUuid'] = $classificationUuid;
134
  }
135
  if($areaUuid){
136
    $queryParams['area'] = $areaUuid;
137
  }
138
  if($status){
139
    $queryParams['status'] = $status ;
140
  }
141
  $queryParams['pageNumber'] = '0';
142
  $queryParams['pageSize'] = '10';
143
  $queryParams['doTaxa'] = true;
144
  $queryParams['doSynonyms'] = true;
145
  $queryParams['doMisappliedNames'] = true;
146
  $queryParams['doTaxaByCommonNames'] = true;
147

    
148
  $search_results = cdm_ws_get(CDM_WS_TAXON_SEARCH, NULL, queryString($queryParams));
149
  foreach($search_results->records as $record){
150
      $titleCache = $record->entity->titleCache;
151
      preg_match('/(.*) sec.*/', $titleCache, $trimmedTitle); //remove sec reference
152
      $trimmedTitle = trim($trimmedTitle[1]);
153
      $matches[$trimmedTitle] = check_plain($trimmedTitle);
154
  }
155
  drupal_json_output($matches);
156
}
157

    
158

    
159
  /**
160
 * Creates a search form for searching on taxa.
161
 *
162
 * If advanced $advanced_form id TRUE the form will offer additional choices
163
 *
164
 * @param array $form
165
 *   A drupal form array
166
 * @param array $form_state
167
 *   The drupal form state passed as reference
168
 * @param bool $advanced_form
169
 *   default is FALSE
170
 * @param bool $classification_select
171
 *   set TRUE to offer a classification selector in the form - default is FALSE
172
 *   if only available in the advanced mode
173
 *
174
 * @return array
175
 *   the form array
176
 */
177
function cdm_dataportal_search_taxon_form($form, &$form_state, $advanced_form = FALSE, $classification_select = TRUE) {
178

    
179
  $query_field_default_value = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
180

    
181
  if ($advanced_form || variable_get(SIMPLE_SEARCH_USE_LUCENE_BACKEND, FALSE)) {
182
    $search_service_endpoint = CDM_WS_PORTAL_TAXON_SEARCH;
183
  }
184
  else {
185
    $search_service_endpoint = CDM_WS_PORTAL_TAXON_FIND;
186
  }
187

    
188
  $form = cdm_dataportal_search_form_prepare(
189
    'cdm_dataportal/search/results/taxon',
190
    $search_service_endpoint,
191
    $query_field_default_value,
192
    t('Enter the name or part of a name you wish to search for.
193
      The asterisk  character * can be used as wildcard, but must not be used as first character.'),
194
      NULL
195
  );
196

    
197
  if (!$advanced_form) {
198
    $form['query']['#size'] = 20;
199
  }
200

    
201
  $form['search']['pageSize'] = array(
202
    '#weight' => -1,
203
    '#type' => 'hidden',
204
    '#value' => variable_get('cdm_dataportal_search_items_on_page', 25),
205
  );
206

    
207
  $form['search']['pageNumber'] = array(
208
    '#weight' => -1,
209
    '#type' => 'hidden',
210
    '#value' => 0,
211
  );
212

    
213
  $search_taxa_mode_settings = get_array_variable_merged(
214
    CDM_SEARCH_TAXA_MODE,
215
    CDM_SEARCH_TAXA_MODE_DEFAULT
216
  );
217
  $preset_do_taxa = $search_taxa_mode_settings['doTaxa'] !== 0;
218
  $preset_do_synonyms = $search_taxa_mode_settings['doSynonyms'] !== 0;
219
  $preset_do_taxa_by_common_names = $search_taxa_mode_settings['doTaxaByCommonNames'] !== 0;
220
  $preset_do_misapplied_names = $search_taxa_mode_settings['doMisappliedNames'] !== 0;
221

    
222
  if ($advanced_form) {
223

    
224
    // --- ADVANCED SEARCH FORM ---
225
    //
226

    
227
    // Get presets from settings.
228
    $preset_classification_uuid = get_current_classification_uuid();
229

    
230
    // Overwrite presets by user choice stored in session.
231
    if (isset($_SESSION['cdm']['search'])) {
232
      $preset_do_taxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
233
      $preset_do_synonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
234
      $preset_do_misapplied_names = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
235
      $preset_do_taxa_by_common_names = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
236
      if (isset($_SESSION['cdm']['search']['tree'])) {
237
        $preset_classification_uuid = $_SESSION['cdm']['search']['tree'];
238
      }
239
    }
240

    
241
    if ($classification_select === TRUE) {
242
      $form['search']['tree'] = array(
243
        '#title' => t('Classification'),
244
        '#weight' => 1,
245
        '#type' => 'select',
246
        '#default_value' => get_current_classification_uuid(),
247
        '#options' => cdm_get_taxontrees_as_options(TRUE),
248
        '#description' => t('A filter to limit the search to a specific classification. Choosing <em>--- ALL ---</em> will disable this filter.'),
249
      );
250
    }
251

    
252
    // General search parameters.
253
    $form['search']['doTaxa'] = array(
254
      '#weight' => 2,
255
      '#type' => 'checkbox',
256
      '#title' => t('Include') . ' ' . t('accepted taxa'),
257
      '#value' => $preset_do_taxa,
258
    );
259
    $form['search']['doSynonyms'] = array(
260
      '#weight' => 3,
261
      '#type' => 'checkbox',
262
      '#title' => t('Include') . ' ' . t('synonyms'),
263
      '#value' => $preset_do_synonyms,
264
    );
265
    $form['search']['doMisappliedNames'] = array(
266
      '#weight' => 4,
267
      '#type' => 'checkbox',
268
      '#title' => t('Include') . ' ' . t('misapplied names'),
269
      '#value' => $preset_do_misapplied_names,
270
    );
271
    $form['search']['doTaxaByCommonNames'] = array(
272
      '#weight' => 5,
273
      '#type' => 'checkbox',
274
      '#title' => t('Include') . ' ' . t('common names'),
275
      '#value' => $preset_do_taxa_by_common_names,
276
    );
277

    
278
    $area_term_dtos = cdm_ws_fetch_all(
279
      CDM_WS_DESCRIPTION_NAMEDAREAS_IN_USE,
280
      array('includeAllParents' => 'true')
281
    );
282

    
283
    // create map: term_uuid => term
284
    $term_map = array();
285
    foreach ($area_term_dtos as $term_dto) {
286
      $term_map[$term_dto->uuid] = $term_dto;
287
    }
288

    
289
    $term_tree = array();
290
    // mixed_vocabularies will contain the uuid vocabularies which
291
    // also contain terms of foreign vocabularies due to the term
292
    // hierarchy
293
    $mixed_vocabularies = array();
294

    
295
    // Build hierarchy of the terms regardless of the vocabulary.
296
    foreach ($term_map as $term_dto) {
297
      if (!empty($term_dto->partOfUuid)) {
298
        // Children.
299
        $parent =& $term_map[$term_dto->partOfUuid];
300
        if ($parent) {
301
          if (!isset($parent->children)) {
302
            $parent->children = array();
303
          }
304
          $parent->children[$term_dto->uuid] = $term_dto;
305
          if ($parent->vocabularyUuid != $term_dto->vocabularyUuid) {
306
            $mixed_vocabularies[$parent->vocabularyUuid] = $parent->vocabularyUuid;
307
          }
308
        }
309
      }
310
      else {
311
        // group root nodes by vocabulary
312
        if (!isset($term_tree[$term_dto->vocabularyUuid])) {
313
          $term_tree[$term_dto->vocabularyUuid] = array();
314
        }
315
        $term_tree[$term_dto->vocabularyUuid][$term_dto->uuid] = $term_dto;
316
      }
317
    }
318

    
319
    $show_area_filter = ! variable_get(CDM_SEARCH_AREA_FILTER_PRESET, '');
320

    
321
    if($show_area_filter){
322
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/search_area_filter.js');
323

    
324
      drupal_add_js('jQuery(document).ready(function() {
325
        jQuery(\'#edit-search-areas\').search_area_filter(\'#edit-search-areas-areas-filter\');
326
      });
327
      ', array('type' => 'inline'));
328

    
329
      $form['search']['areas'] = array(
330
        '#type' => 'fieldset',
331
        '#title' => t('Filter by distribution areas'),
332
        '#description' => t('The search will return taxa having distribution
333
        information for at least one of the selected areas.') . ' '
334
          .(count($term_tree) > 1 ? t('The areas are grouped
335
        by the vocabularies to which the highest level areas belong.') : ''),
336
      );
337
      $form['search']['areas']['areas_filter'] = array(
338
        '#type' => 'textfield',
339
        '#description' => t('Type to filter the areas listed below.'),
340
      );
341
      $vocab_cnt = 0;
342
      $areas_defaults = array();
343
      if (isset($_SESSION['cdm']['search']['area'])) {
344
        $areas_defaults = explode(',', $_SESSION['cdm']['search']['area']);
345
      }
346
      _add_js_resizable_element('.resizable-box', true);
347
      foreach ($term_tree as $vocab_uuid => $term_dto_tree) {
348
        $vocabulary = cdm_ws_get(CDM_WS_TERMVOCABULARY, array($vocab_uuid));
349
        $areas_options = term_tree_as_options($term_dto_tree);
350
        $form['search']['areas']['area'][$vocab_cnt++] = array(
351
          '#prefix' => '<strong>' . $vocabulary->representation_L10n
352
            . (isset($mixed_vocabularies[$vocab_uuid]) ? ' <span title="Contains terms of at least one other area vocabulary.">(' . t('mixed') . ')</span>': '')
353
            . '</strong><div class="resizable-container"><div class="resizable-box">',
354
          '#type' => 'checkboxes',
355
          '#default_value' => $areas_defaults,
356
          '#options' => $areas_options,
357
          '#suffix' => '</div></div>'
358
        );
359
      }
360
    }
361

    
362
  }
363
  else {
364
    // --- SIMPLE SEARCH FORM ---
365
    //
366

    
367
    // Overwrite presets by user choice stored in session.
368
    if (isset($_SESSION['cdm']['search'])) {
369
      $preset_do_misapplied_names = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
370
    }
371

    
372
    $form['search']['doTaxa'] = array(
373
      '#weight' => -2,
374
      '#type' => 'hidden',
375
      '#value' => $preset_do_taxa,
376
    );
377
    $form['search']['doSynonyms'] = array(
378
      '#weight' => -3,
379
      '#type' => 'hidden',
380
      '#value' => $preset_do_synonyms,
381
    );
382
    $form['search']['doMisappliedNames'] = array(
383
      '#weight' => -4,
384
      '#type' => 'checkbox',
385
      '#title' => t('Misapplied names'),
386
      '#value' => $preset_do_misapplied_names,
387
    );
388
    $form['search']['doTaxaByCommonNames'] = array(
389
      '#weight' => -5,
390
      '#type' => 'hidden',
391
      '#value' => $preset_do_taxa_by_common_names,
392
    );
393
  }
394

    
395
  return $form;
396
}
397

    
398
/**
399
 * Wrapper function for cdm_dataportal_search_taxon_form().
400
 *
401
 * This function makes ot possible possible to just pass the
402
 * correct $form_id 'cdm_dataportal_search_taxon_form_advanced' to
403
 * drupal_get_form like:
404
 * drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
405
 *
406
 * @param array $form
407
 *   A drupal form array
408
 * @param array $form_state
409
 *   The drupal form state passed as reference
410
 *
411
 * @return array
412
 *   The form array
413
 */
414
function cdm_dataportal_search_taxon_form_advanced($form, &$form_state) {
415
  return cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
416
}
417

    
418
/**
419
 * Form for searching taxa by the findByDescriptionElementFullText rest service.
420
 */
421
function cdm_dataportal_search_taxon_by_description_form() {
422
  $query_field_default_value = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
423

    
424
  $form = cdm_dataportal_search_form_prepare(
425
    'cdm_dataportal/search/results/taxon',
426
    CDM_WS_PORTAL_TAXON_FINDBY_DESCRIPTIONELEMENT_FULLTEXT,
427
    $query_field_default_value,
428
    t("Enter the text you wish to search for. The asterisk character * can be
429
        used as wildcard, but must not be used as first character. Terms can be combined with 'AND'. To search for a
430
        full phrase enclose the terms in parentheses. For more syntactical
431
        options please refer to the !link.",
432
      array(
433
        '!link' => l(
434
          t('Apache Lucene - Query Parser Syntax'),
435
          'http://lucene.apache.org/core/old_versioned_docs/versions/2_9_1/queryparsersyntax.html', array(
436
            'attributes' => array(
437
              'absolute' => TRUE,
438
              'html' => TRUE),
439
          )
440
        ),
441
      )
442
    ),
443
    NULL
444
  );
445

    
446
  $form['search']['tree'] = array(
447
    '#weight' => -1,
448
    '#type' => 'hidden',
449
    '#value' => get_current_classification_uuid(),
450
  );
451

    
452
  $form['search']['hl'] = array(
453
    '#weight' => -1,
454
    '#type' => 'hidden',
455
    '#value' => 1,
456
  );
457

    
458
  // Only available to admins:
459
  if (!isset($_SESSION['cdm']['search']['clazz'])) {
460
    $_SESSION['cdm']['search']['clazz'] = '';
461
  }
462
  if (module_exists("user") && user_access('administer')) {
463
    $form['search']['clazz'] = array(
464
      '#type' => 'select',
465
      '#title' => t('Limit to description item type'),
466
      '#default_value' => $_SESSION['cdm']['search']['clazz'],
467
      '#options' => cdm_descriptionElementTypes_as_option(TRUE),
468
    );
469
  }
470

    
471
  $profile_feature_tree = get_profile_feature_tree();
472
  $feature_options = _featureTree_nodes_as_feature_options($profile_feature_tree->root);
473
  if (isset($_SESSION['cdm']['search']['features'])) {
474
    $form['search']['features'] = array(
475
      '#type' => 'checkboxes',
476
      '#title' => t('Limit to selected features'),
477
      '#default_value' => $_SESSION['cdm']['search']['features'],
478
      '#options' => $feature_options,
479
    );
480
  }
481
  else {
482
    $form['search']['features'] = array(
483
      '#type' => 'checkboxes',
484
      '#title' => t('Limit to selected features'),
485
      '#options' => $feature_options,
486
    );
487
  }
488
  return $form;
489
}
490

    
491
/**
492
 * Processes the query parameters of the search form.
493
 *
494
 * Reads the query parameters from $_REQUEST and modifies and adds additional
495
 * query parameters if nessecary.
496
 *
497
 *  - Filters $_REQUEST by a list of valid request parameters
498
 *  - modifies geographic_range parameters
499
 *  - adds taxon tree uuid if it is missing and if it should not be
500
 *    ignored (parameter value = 'IGNORE')
501
 *  - and more
502
 *
503
 *
504
 * @return array
505
 *   the processed request parameters submitted by the search form and
506
 *   also stores them in $_SESSION['cdm']['search']
507
 */
508
function cdm_dataportal_search_request()
509
{
510

    
511
  $form_params = array();
512

    
513
  if (isset($_REQUEST['search']) && is_array($_REQUEST['search'])) {
514
    array_deep_copy($_REQUEST['search'], $form_params);
515
  }
516

    
517
  if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
518
    $form_params = array_merge($form_params, $_REQUEST['pager']);
519
  }
520

    
521
  $form_params['query'] = trim($_REQUEST['query']);
522

    
523
  // --- handle geographic range
524
  // Split of geographic range.
525
  unset($form_params['areas']);
526

    
527
  $area_filter_preset = null;
528
  if (variable_get(CDM_SEARCH_AREA_FILTER_PRESET, '')) {
529
    $area_filter_preset = explode(',', variable_get(CDM_SEARCH_AREA_FILTER_PRESET, ''));
530
  }
531

    
532
  $area_uuids = array();
533
  if($area_filter_preset){
534
    $area_uuids = $area_filter_preset;
535
  }
536
  elseif (isset($_REQUEST['search']['areas']['area']) && is_array($_REQUEST['search']['areas']['area'])) {
537
    foreach ($_REQUEST['search']['areas']['area'] as $areas) {
538
      $area_uuids = array_merge($area_uuids, $areas);
539
    }
540
    // The area filter is limited to areas with non absent distribution status
541
    $presence_terms_options = cdm_vocabulary_as_option(UUID_PRESENCE_ABSENCE_TERM, null, FALSE, array('absenceTerm' => '/false/'));
542
    $presence_term_uuids = array_keys($presence_terms_options);
543
    $form_params['status'] = $presence_term_uuids;
544
  }
545
  if(count($area_uuids) > 0){
546
    $form_params['area'] = implode(',', $area_uuids);
547
  }
548

    
549
  // Simple search will not submit a 'tree' query parameter,
550
  // so we add it here from what is stored in the session unless
551
  // SIMPLE_SEARCH_IGNORE_CLASSIFICATION is checked in the settings.
552
  if (!isset($form_params['tree']) && !variable_get(SIMPLE_SEARCH_IGNORE_CLASSIFICATION, 0)) {
553
    $form_params['tree'] = get_current_classification_uuid();
554
  }
555
  // If the 'NONE' classification has been chosen (advanced search)
556
  // delete the tree information to avoid unknown uuid exceptions in the
557
  // cdm service.
558
  if (isset($form_params['tree'])
559
    && ($form_params['tree'] == 'NONE' || !is_uuid($form_params['tree']))
560
  ) {
561
    // $form_params['ignore_classification'] =  TRUE;
562
    unset($form_params['tree']);
563
  }
564
  // else {
565
  //   $form_params['ignore_classification'] =  NULL;
566
  // }
567

    
568
  // Store in session.
569
  $_SESSION['cdm']['search'] = $form_params;
570

    
571
  return $form_params;
572
}
573

    
574
/**
575
 * Provides the classification to which the last search has been limited to..
576
 *
577
 * This function should only be used after the cdm_dataportal_search_execute()
578
 * handler has been run, otherwise it will return the information from the last
579
 * search executed. The information is retrieved from
580
 * the $_SESSION variable:  $_SESSION['cdm']['search']['tree']
581
 *
582
 * @return object
583
 *   the CDM classification instance which has been used a filter for the
584
 *   last processed search
585
 *   or NULL, it it was on all classifications
586
 */
587
function cdm_dataportal_searched_in_classification() {
588

    
589
  $classification = &drupal_static(__FUNCTION__);
590

    
591
  if (!isset($classification)) {
592
    if (isset($_SESSION['cdm']['search']['tree'])) {
593
      $classification = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY, ($_SESSION['cdm']['search']['tree']));
594
    }
595
    else {
596
      $classification = FALSE;
597
    }
598
  }
599

    
600
  return $classification !== FALSE ? $classification : NULL;
601
}
602

    
603
/**
604
 * Removes Drupal internal form elements from query.
605
 */
606
function cdm_dataportal_search_process($form, &$form_state) {
607
  unset($form['form_id']);
608
  unset($form['form_token']);
609
  return $form;
610
}
611

    
612
/**
613
 * Sends a search request at the cdm web server.
614
 *
615
 * The parameters to build the query are taken obtained by calling
616
 * cdm_dataportal_search_request() which reads the query parameters
617
 * from $_REQUEST and add additional query parameters if nessecary.
618
 *
619
 * @see cdm_dataportal_search_request()
620
 */
621
function cdm_dataportal_search_execute() {
622

    
623
  // Store as last search in session.
624
  $_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
625

    
626
  // Validate the search webservice parameter:
627
  if (!isset($_REQUEST['ws'])) {
628
    drupal_set_message(
629
      t("Invalid search webservice parameter 'ws' given"), 'warning'
630
    );
631
    return NULL;
632
  }
633
  if (!cdm_dataportal_search_form_path_for_ws($_REQUEST['ws'])) {
634
    // Endpoint is unknown.
635
    drupal_set_message(
636
      t("Invalid search webservice parameter 'ws' given"), 'warning'
637
    );
638
    return NULL;
639
  }
640

    
641
  // Read the query parameters from $_REQUEST and add additional query
642
  // parameters if necessary.
643
  $request_params = cdm_dataportal_search_request();
644

    
645
  $taxon_pager = cdm_ws_get($_REQUEST['ws'], NULL, queryString($request_params));
646

    
647
  return $taxon_pager;
648
}
649

    
650
/**
651
 * Transforms the termDTO tree into options array.
652
 *
653
 *   TermDto:
654
 *      - partOfUuid:
655
 *      - representation_L10n:
656
 *      - representation_L10n_abbreviatedLabel:
657
 *      - uuid:
658
 *      - vocabularyUuid:
659
 *      - children: array of TermDto
660
 *
661
 * The options array is suitable for drupal form API elements that
662
 * allow multiple choices.
663
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
664
 *
665
 * @param array $term_dto_tree
666
 *   a hierarchic array of CDM TermDto instances, with additional
667
 * 'children' field:
668
 * @param array $options
669
 *   Internally used for recursive calls
670
 * @param string $prefix
671
 *   Internally used for recursive calls
672
 *
673
 * @return array
674
 *   the terms in an array as options for a form element that allows
675
 *   multiple choices.
676
 */
677
function term_tree_as_options($term_dto_tree, &$options = array(), $prefix = '') {
678

    
679
  uasort($term_dto_tree, 'compare_terms_by_order_index');
680
  foreach ($term_dto_tree as $uuid => $dto) {
681
    $label = $prefix . '<span class="child-label">'
682
      .  $dto->representation_L10n
683
      . '</span><span class="child-label-abbreviated"> (' . $dto->representation_L10n_abbreviatedLabel . ')</span>';
684
    $options[$uuid] = $label;
685
    if (isset($dto->children) && is_array($dto->children)) {
686
      term_tree_as_options(
687
        $dto->children,
688
        $options, $prefix
689
          . '<span data-cdm-parent="' . $uuid . '" class="parent"></span>'
690
      );
691
    }
692
  }
693

    
694
  return $options;
695
}
(11-11/16)