Project

General

Profile

Download (23.2 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 necessary fields
36
 * for internal processing and has the textfield element $form['query']
37
 * which holds the query term.
38
 *
39
 * @param string $action_path
40
 *   The Drupal path to be put into the action url to which the form will
41
 *   be submitted.
42
 * @param string $search_webservice
43
 *   The cdm-remote webservice to be used, valid values are defined by
44
 *   the constants: FIXME.
45
 * @param string $query_field_default_value
46
 *   A default text for the query field
47
 * @param string $query_field_description
48
 *   The description text for the query field
49
 * @param string $process
50
 *   The value for #process, if NULL (default), 'cdm_dataportal_search_process'
51
 *   is used.
52
 *
53
 * @return array
54
 *   The prepared form array.
55
 */
56
function cdm_dataportal_search_form_prepare($action_path, $search_webservice, $query_field_default_value, $query_field_description, $process = NULL) {
57

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

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

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

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

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

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

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

    
120
  return $form;
121
}
122

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

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

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

    
157

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

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

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

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

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

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

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

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

    
221
  if ($advanced_form) {
222

    
223
    // --- ADVANCED SEARCH FORM ---
224
    //
225

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
394
  return $form;
395
}
396

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

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

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

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

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

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

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

    
490
/**
491
 * Processes the query parameters of the search form.
492
 *
493
 * Reads the query parameters from $_REQUEST and modifies and adds additional
494
 * query parameters if necessary.
495
 *
496
 *  - Filters $_REQUEST by a list of valid request parameters
497
 *  - modifies geographic_range parameters
498
 *  - adds taxon tree uuid if it is missing and if it should not be
499
 *    ignored (parameter value = 'IGNORE')
500
 *  - and more
501
 *
502
 * @param $search_endpoint string
503
 *    The web service endpoint which will be used for executing the search.
504
 *    Usually one of CDM_WS_PORTAL_TAXON_SEARCH, CDM_WS_PORTAL_TAXON_FIND,
505
 *    CDM_WS_PORTAL_TAXON_FINDBY_DESCRIPTIONELEMENT_FULLTEXT.
506
 * @return array
507
 *   the processed request parameters submitted by the search form and
508
 *   also stores them in $_SESSION['cdm']['search']
509
 */
510
function cdm_dataportal_search_request($search_endpoint)
511
{
512

    
513
  $form_params = array();
514

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

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

    
523
  $form_params['query'] = trim($_REQUEST['query']);
524

    
525

    
526
  // --- handle geographic range
527
  // Split of geographic range.
528
  unset($form_params['areas']);
529

    
530
  $area_filter_preset = null;
531
  if (variable_get(CDM_SEARCH_AREA_FILTER_PRESET, '')) {
532
    $area_filter_preset = explode(',', variable_get(CDM_SEARCH_AREA_FILTER_PRESET, ''));
533
  }
534

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

    
552
  // Simple search will not submit a 'tree' query parameter,
553
  // so we add it here from what is stored in the session unless
554
  // SIMPLE_SEARCH_IGNORE_CLASSIFICATION is checked in the settings.
555
  if (!isset($form_params['tree']) && !variable_get(SIMPLE_SEARCH_IGNORE_CLASSIFICATION, 0)) {
556
    $form_params['tree'] = get_current_classification_uuid();
557
  }
558
  // Store in session.
559
  $_SESSION['cdm']['search'] = $form_params;
560

    
561
  // ----------- further processing that must not be store in the session --------- //
562

    
563
  if($search_endpoint == CDM_WS_PORTAL_TAXON_SEARCH){
564
    // lucene based taxon search always as phrase search: enclose it in "
565
    if(!str_beginsWith($form_params['query'], '"')){
566
      $form_params['query'] = '"' . $form_params['query'];
567
    }
568
    if(!str_endsWith($form_params['query'], '"')){
569
      $form_params['query'] = $form_params['query'] . '"' ;
570
    }
571
  }
572

    
573
  // If the 'NONE' classification has been chosen (advanced search)
574
  // delete the tree information to avoid unknown uuid exceptions in the
575
  // cdm service.
576
  if (isset($form_params['tree'])
577
    && ($form_params['tree'] == 'NONE' || !is_uuid($form_params['tree']))
578
  ) {
579
    // $form_params['ignore_classification'] =  TRUE;
580
    unset($form_params['tree']);
581
  }
582
  // else {
583
  //   $form_params['ignore_classification'] =  NULL;
584
  // }
585

    
586

    
587
  return $form_params;
588
}
589

    
590
/**
591
 * Provides the classification to which the last search has been limited to..
592
 *
593
 * This function should only be used after the cdm_dataportal_search_execute()
594
 * handler has been run, otherwise it will return the information from the last
595
 * search executed. The information is retrieved from
596
 * the $_SESSION variable:  $_SESSION['cdm']['search']['tree']
597
 *
598
 * @return object
599
 *   the CDM classification instance which has been used a filter for the
600
 *   last processed search
601
 *   or NULL, it it was on all classifications
602
 */
603
function cdm_dataportal_searched_in_classification() {
604

    
605
  $classification = &drupal_static(__FUNCTION__);
606

    
607
  if (!isset($classification)) {
608
    if (isset($_SESSION['cdm']['search']['tree'])) {
609
      $classification = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY, ($_SESSION['cdm']['search']['tree']));
610
    }
611
    else {
612
      $classification = FALSE;
613
    }
614
  }
615

    
616
  return $classification !== FALSE ? $classification : NULL;
617
}
618

    
619
/**
620
 * Removes Drupal internal form elements from query.
621
 */
622
function cdm_dataportal_search_process($form, &$form_state) {
623
  unset($form['form_id']);
624
  unset($form['form_token']);
625
  return $form;
626
}
627

    
628
/**
629
 * Sends a search request to the cdm server.
630
 *
631
 * The parameters to build the query are taken obtained by calling
632
 * cdm_dataportal_search_request() which reads the query parameters
633
 * from $_REQUEST and add additional query parameters if nessecary.
634
 *
635
 * @see cdm_dataportal_search_request()
636
 */
637
function cdm_dataportal_search_execute() {
638

    
639
  // Store as last search in session.
640
  $_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
641

    
642
  // Validate the search webservice parameter:
643
  if (!isset($_REQUEST['ws'])) {
644
    drupal_set_message(
645
      t("Invalid search, webservice parameter 'ws' is missing"), 'warning'
646
    );
647
    return NULL;
648
  }
649
  if (!cdm_dataportal_search_form_path_for_ws($_REQUEST['ws'])) {
650
    // Endpoint is unknown.
651
    drupal_set_message(
652
      t("Invalid search webservice parameter 'ws' given"), 'warning'
653
    );
654
    return NULL;
655
  }
656

    
657
  // Read the query parameters from $_REQUEST and add additional query
658
  // parameters if necessary.
659
  $request_params = cdm_dataportal_search_request($_REQUEST['ws']);
660

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

    
663
  return $taxon_pager;
664
}
665

    
666
/**
667
 * Transforms the termDTO tree into options array.
668
 *
669
 *   TermDto:
670
 *      - partOfUuid:
671
 *      - representation_L10n:
672
 *      - representation_L10n_abbreviatedLabel:
673
 *      - uuid:
674
 *      - vocabularyUuid:
675
 *      - children: array of TermDto
676
 *
677
 * The options array is suitable for drupal form API elements that
678
 * allow multiple choices.
679
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
680
 *
681
 * @param array $term_dto_tree
682
 *   a hierarchic array of CDM TermDto instances, with additional
683
 * 'children' field:
684
 * @param array $options
685
 *   Internally used for recursive calls
686
 * @param string $prefix
687
 *   Internally used for recursive calls
688
 *
689
 * @return array
690
 *   the terms in an array as options for a form element that allows
691
 *   multiple choices.
692
 */
693
function term_tree_as_options($term_dto_tree, &$options = array(), $prefix = '') {
694

    
695
  uasort($term_dto_tree, 'compare_terms_by_order_index');
696
  foreach ($term_dto_tree as $uuid => $dto) {
697
    $label = $prefix . '<span class="child-label">'
698
      .  $dto->representation_L10n
699
      . '</span><span class="child-label-abbreviated"> (' . $dto->representation_L10n_abbreviatedLabel . ')</span>';
700
    $options[$uuid] = $label;
701
    if (isset($dto->children) && is_array($dto->children)) {
702
      term_tree_as_options(
703
        $dto->children,
704
        $options, $prefix
705
          . '<span data-cdm-parent="' . $uuid . '" class="parent"></span>'
706
      );
707
    }
708
  }
709

    
710
  return $options;
711
}
(11-11/18)