Project

General

Profile

Download (18.7 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_FINDBY_DESCRIPTIONELEMENT_FULLTEXT => "cdm_dataportal/search/taxon_by_description",
26
  );
27
  return $form_ws_map[$ws_endpoint];
28
}
29

    
30
/**
31
 * Prepares a form array for a general purpose search form.
32
 *
33
 * The form is used for general purpose search functionality in the
34
 * dataportal. The form returned is populated with all nessecary fields
35
 * for internal processing and has the textfield element $form['query']
36
 * which holds the query term.
37
 * he sub tree array can be extended to contain additional search parameters.
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
 * @param string $query_field_description
47
 * @param string $process
48
 *   The value for #process, if NULL (default), 'cdm_dataportal_search_process'
49
 *   is used.
50
 *
51
 * @return array
52
 *   The prepared form array.
53
 */
54
function cdm_dataportal_search_form_prepare($action_path, $search_webservice, $query_field_default_value, $query_field_description, $process = NULL) {
55
  if ($process == NULL) {
56
    $process = 'cdm_dataportal_search_process';
57
  }
58
  $form['#method'] = 'get';
59
  /*
60
  $form['#process'] = array(
61
    $process => array(),
62
  );
63
  */
64
  $form['#action'] = url($action_path, array(
65
    'absolute' => TRUE,
66
  ));
67

    
68
  $form['ws'] = array(
69
    '#type' => 'hidden',
70
    '#value' => $search_webservice,
71
    '#name' => 'ws',
72
  );
73

    
74
  $form['query'] = array(
75
    '#weight' => 0,
76
    '#type' => 'textfield',
77
    '#size' => 68,
78
  // Comment @WA: this causes the description to display also when hovering over
79
  // the textfield.
80
  // I think this should be removed, although it is currently there in
81
  // D5 portals.
82
    '#attributes' => array(
83
      'title' => $query_field_description,
84
    ),
85
    '#description' => $query_field_description,
86
    '#value' => $query_field_default_value,
87
    // '#description' => $query_field_description,
88
  );
89

    
90
  $form['search'] = array(
91
    '#weight' => 3,
92
    '#tree' => TRUE,
93
    // '#type' => $advancedForm ? 'fieldset': 'hidden',
94
    '#title' => t('Options'),
95
  );
96

    
97
  // Clean URL get forms breaks if we don't give it a 'q'.
98
  if (!(bool) variable_get('clean_url', '0')) {
99
    $form['search']['q'] = array(
100
      '#type' => 'hidden',
101
      '#value' => $action_path,
102
      '#name' => 'q',
103
    );
104
  }
105

    
106
  $form['submit'] = array(
107
    '#weight' => 5,
108
    '#type' => 'submit',
109
    '#name' => '',
110
    '#value' => t('Search'),
111
  );
112

    
113
  return $form;
114
}
115

    
116
/**
117
 * Creates a search form for searching on taxa.
118
 *
119
 * If advanced $advancedForm id TRUE the form will offer additinal choices
120
 *
121
 * @param unknown_type $form
122
 * @param unknown_type $form_state
123
 * @param bool $advancedForm
124
 *    default is FALSE
125
 * @param bool $classificationSelect
126
 *    set TRUE to offer a classifiaction selector in the form - default is FALSE
127
 *    if only available in the advanced mode
128
 *
129
 * @return
130
 *   the form array
131
 *
132
 */
133
function cdm_dataportal_search_taxon_form($form, &$form_state, $advancedForm = FALSE, $classificationSelect = TRUE) {
134
  global $theme_key;
135

    
136
  $tdwg_level_select = (isset($_SESSION['cdm']['search']['tdwg_level_select']) ? $_SESSION['cdm']['search']['tdwg_level_select'] : 2);
137
  $selected_areas = (isset($_SESSION['cdm']['search']['area']) ? $_SESSION['cdm']['search']['area'] : FALSE);
138
  $query_field_default_value = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
139

    
140
  $form = cdm_dataportal_search_form_prepare('cdm_dataportal/search/results/taxon', CDM_WS_PORTAL_TAXON_FIND, $query_field_default_value, t('Enter the name or part of a name you wish to search for. The asterisk  character * can always be used as wildcard.'), NULL);
141

    
142
  if (!$advancedForm) {
143
    $form['query']['#size'] = 20;
144
  }
145

    
146
  $form['search']['pageSize'] = array(
147
    '#weight' => -1,
148
    '#type' => 'hidden',
149
    '#value' => variable_get('cdm_dataportal_search_items_on_page', 25),
150
  );
151

    
152
  $form['search']['pageNumber'] = array(
153
    '#weight' => -1,
154
    '#type' => 'hidden',
155
    '#value' => 0,
156
  );
157

    
158
  if ($advancedForm) {
159

    
160
    // --- ADVANCED SEARCH FORM ---
161
    //
162

    
163
    // Get presets from settings.
164
    $preset_doTaxa = variable_get('cdm_search_doTaxa', 1);
165
    $preset_doSynonyms = variable_get('cdm_search_doSynonyms', 1);
166
    $preset_doTaxaByCommonNames = variable_get('cdm_search_doTaxaByCommonNames', 0);
167
    $preset_doMisappliedNames = variable_get('cdm_search_doMisappliedNames', 1);
168
    $preset_UseDefaults = variable_get('cdm_search_use_default_values', 1);
169
    $preset_classification_uuid = get_taxonomictree_uuid_selected();
170

    
171
    // Overwrite presets by user choice stored in session.
172
    if (isset($_SESSION['cdm']['search']) && !$preset_UseDefaults) {
173
      $preset_doTaxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
174
      $preset_doSynonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
175
      $preset_doMisappliedNames = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
176
      $preset_doTaxaByCommonNames = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
177
      if (isset($_SESSION['cdm']['search']['tree'])) {
178
        $preset_classification_uuid = $_SESSION['cdm']['search']['tree'];
179
      }
180
    }
181

    
182

    
183
   if ($classificationSelect === TRUE) {
184
      $form['search']['tree'] = array(
185
        '#title' => t('Classification'),
186
        '#weight' => 1,
187
        '#type' => 'select',
188
        '#default_value' => get_taxonomictree_uuid_selected(),
189
        '#options' => cdm_get_taxontrees_as_options(TRUE),
190
        '#description' => t('A filter to limit the search to a specific classification.')
191
      );
192
   }
193

    
194
    // General search parameters.
195
    $form['search']['doTaxa'] = array(
196
      '#weight' => 2,
197
      '#type' => 'checkbox',
198
      '#title' => t('Search for accepted taxa'),
199
      '#value' => $preset_doTaxa,
200
    );
201
    $form['search']['doSynonyms'] = array(
202
      '#weight' => 3,
203
      '#type' => 'checkbox',
204
      '#title' => t('Search for synonyms'),
205
      '#value' => $preset_doSynonyms,
206
    );
207
    $form['search']['doMisappliedNames'] = array(
208
      '#weight' => 4,
209
      '#type' => 'checkbox',
210
      '#title' => t('Search for misapplied names'),
211
      '#value' => $preset_doMisappliedNames,
212
    );
213
    $form['search']['doTaxaByCommonNames'] = array(
214
      '#weight' => 5,
215
      '#type' => 'checkbox',
216
      '#title' => t('Search for common names'),
217
      '#value' => $preset_doTaxaByCommonNames
218
    );
219

    
220
    // Geographic Range.
221
    $form['search']['geographic_range'] = array(
222
      '#type' => 'fieldset',
223
      '#weight' => 5,
224
      '#tree' => TRUE,
225
      '#title' => t('Geographic range'),
226
    );
227

    
228
    $form['search']['geographic_range']['tdwg_level_select'] = array(
229
      '#type' => 'radios',
230
      '#title' => t('Select a TDWG distribution level and code'),
231
      '#default_value' => $tdwg_level_select,
232
      '#options' => array(
233
        t('TDWG level-1, i.e. a continent'),
234
        t('TDWG level-2'),
235
        t('TDWG level-3, i.e. a country'),
236
        t('TDWG level-4'),
237
      ),
238
    );
239
    $tdwg[1] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '1');
240
    $tdwg[2] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '2');
241
    $tdwg[3] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '3');
242
    $tdwg[4] = cdm_ws_get(CDM_WS_TDWG_LEVEL, '4');
243

    
244
    $tdwg_js = '';
245
    foreach ($tdwg as $key => $tdwg_level) {
246
      $tdwgOptions = array();
247
      $tdwgOptionsSelected = array();
248
      foreach ($tdwg_level as $area) {
249
        $representation = $area->representations[0];
250
        $tdwgOptions[$representation->abbreviatedLabel] = $area->representation_L10n;
251
        if (is_array($selected_areas) && in_array($representation->abbreviatedLabel, $selected_areas)) {
252
          // $area->uuid;
253
          $tdwgOptionsSelected[] = $representation->abbreviatedLabel;
254
        }
255
      }
256
      asort($tdwgOptions);
257
      $form['search']['geographic_range']['tdwg_level_' . $key] = array(
258
        '#type' => 'select',
259
        '#title' => t('TDWG level') . ' ' . $key,
260
        '#default_value' => $tdwgOptionsSelected,
261
        '#multiple' => TRUE,
262
        '#options' => $tdwgOptions,
263
      );
264
      $tdwg_js .= "$('#edit-search-geographic-range-tdwg-level-$key').parent()" . ($tdwg_level_select + 1 == $key ? '.show()' : '.hide()') . ";\n";
265
    }
266

    
267
    drupal_add_js(
268
    "jQuery(document).ready(function($){
269
      $(\"input[name='search[geographic_range][tdwg_level_select]']\").change(
270
        function(){
271
          var selectId = $(\"input[name='search[geographic_range][tdwg_level_select]']:checked\").val();
272
          var i;
273
          for(i = 0; i < 4; i++){
274

    
275
            if(selectId == i){
276
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1) ).parent().fadeIn('slow');
277
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
278
            } else {
279
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).parent().fadeOut('slow');
280
              $('#edit-search-geographic-range-tdwg-level-' + (i + 1)).children().removeAttr('selected');
281
            }
282
          }
283
        }
284
      );
285

    
286
    $tdwg_js
287
    });",
288
    array('type' => 'inline'));
289
  }
290
  else {
291
    // --- SIMPLE SEARCH FORM ---
292
    //
293

    
294
    $preset_doTaxa = variable_get('cdm_search_doTaxa', 1);
295
    $preset_doSynonyms = variable_get('cdm_search_doSynonyms', 1);
296
    $preset_doTaxaByCommonNames = variable_get('cdm_search_doTaxaByCommonNames', 0);
297
    $preset_doMisappliedNames = variable_get('cdm_search_doMisappliedNames', 1);
298
    $preset_UseDefaults = variable_get('cdm_search_use_default_values', 1);
299

    
300
    // Overwrite presets by user choice stored in session.
301
    if (isset($_SESSION['cdm']['search']) && !$preset_UseDefaults) {
302
      $preset_doMisappliedNames = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
303
    }
304

    
305
    $form['search']['doTaxa'] = array(
306
      '#weight' => -2,
307
      '#type' => 'hidden',
308
      '#value' => $preset_doTaxa,
309
    );
310
    $form['search']['doSynonyms'] = array(
311
      '#weight' => -3,
312
      '#type' => 'hidden',
313
      '#value' => $preset_doSynonyms,
314
    );
315
    $form['search']['doMisappliedNames'] = array(
316
      '#weight' => -4,
317
      '#type' => 'checkbox',
318
      '#title' => t('Misapplied names'),
319
      '#value' => $preset_doMisappliedNames,
320
    );
321
    $form['search']['doTaxaByCommonNames'] = array(
322
      '#weight' => -5,
323
      '#type' => 'hidden',
324
      '#value' => $preset_doTaxaByCommonNames,
325
    );
326
  }
327

    
328
  return $form;
329
}
330
/**
331
 * @todo Please document this function.
332
 * @see http://drupal.org/node/1354
333
 */
334
function cdm_dataportal_search_taxon_form_advanced($form, &$form_state) {
335
  return cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
336
}
337

    
338
/**
339
 * Search form for the searching taxa by the findByDescriptionElementFullText
340
 * rest service.
341
 */
342
function cdm_dataportal_search_taxon_by_description_form() {
343
  $query_field_default_value = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
344

    
345
  $form = cdm_dataportal_search_form_prepare(
346
      'cdm_dataportal/search/results/taxon',
347
      CDM_WS_PORTAL_TAXON_FINDBY_DESCRIPTIONELEMENT_FULLTEXT,
348
      $query_field_default_value,
349
      t("Enter the text you wish to search for. The asterisk character * can be
350
        used as wildcard. Terms can be combined with 'AND'. To search for a
351
        full phrase enclose the terms in parentheses. For more syntactial
352
        options please refer to the !link.", array(
353
          '!link' => l(t('Apache Lucene - Query Parser Syntax'), 'http://lucene.apache.org/core/old_versioned_docs/versions/2_9_1/queryparsersyntax.html', array(
354
             'attributes' => array('absolute' => TRUE, 'html' => TRUE))),
355
        )),
356
      NULL
357
      );
358

    
359
  $form['search']['tree'] = array(
360
    '#weight' => -1,
361
    '#type' => 'hidden',
362
    '#value' => get_taxonomictree_uuid_selected(),
363
  );
364

    
365
  $form['search']['hl'] = array(
366
    '#weight' => -1,
367
    '#type' => 'hidden',
368
    '#value' => 1,
369
  );
370

    
371
  // Only avaiable to admins:
372
  if (!isset($_SESSION['cdm']['search']['clazz'])) {
373
    $_SESSION['cdm']['search']['clazz'] = '';
374
  }
375
  if (module_exists("user") && user_access('administer')) {
376
    $form['search']['clazz'] = array(
377
      '#type' => 'select',
378
      '#title' => t('Limit to DescriptionElement type'),
379
      '#default_value' => $_SESSION['cdm']['search']['clazz'],
380
      '#options' => cdm_descriptionElementTypes_as_option(TRUE),
381
    );
382
  }
383

    
384
  /*
385
  see cdm_get_featureTrees_as_options() ... $treeRepresentation =
386
  $featureTree->titleCache; if(is_array($featureTree->root->children) &&
387
  count($featureTree->root->children) > 0){ // render the hierarchic tree
388
  structure $treeDetails = '<div class="featuretree_structure">'
389
  //.cdm_featureTree_elements_toString($featureTree->root)
390
  .theme('featureTree_hierarchy', $featureTree->uuid) .'</div>'; $form =
391
  array(); $form['featureTree-'.$featureTree->uuid] = array( '#type' =>
392
  'fieldset', '#title' => t('Show details'), '#collapsible' => TRUE,
393
  '#collapsed' => TRUE, );
394
  $form['featureTree-'.$featureTree->uuid]['details'] =
395
  array('#value'=>$treeDetails); $treeRepresentation .= drupal_render($form);
396
  */
397

    
398
  $profile_featureTree = get_profile_featureTree();
399
  $feature_options = _featureTree_nodes_as_feature_options($profile_featureTree->root);
400
  if (isset($_SESSION['cdm']['search']['features'])) {
401
    $form['search']['features'] = array(
402
      '#type' => 'checkboxes',
403
      '#title' => t('Limit to selected features'),
404
      '#default_value' => $_SESSION['cdm']['search']['features'],
405
      '#options' => $feature_options,
406
    );
407
  }
408
  else {
409
    $form['search']['features'] = array(
410
      '#type' => 'checkboxes',
411
      '#title' => t('Limit to selected features'),
412
      '#options' => $feature_options,
413
    );
414
  }
415
  return $form;
416
}
417

    
418
/**
419
 * Reads the query parameters from $_REQUEST and modifies and adds additional query parameters if nessecary.
420
 *
421
 *  - Filters $_REQUEST by a list of valid request parameters
422
 *  - modifies geographic_range parameters
423
 *  - adds taxon tree uuid if it is missing and if it should not be
424
 *    ignored (parameter value = 'IGNORE')
425
 *  - and more
426
 *
427
 *
428
 * @return
429
 *   the processed request parameters submitted by the search form and
430
 *   also stores them in $_SESSION['cdm']['search']
431
 */
432
function cdm_dataportal_search_form_request() {
433

    
434
  $form_params = array();
435

    
436
  if (isset($_REQUEST['search']) && is_array($_REQUEST['search'])) {
437
    array_deep_copy($_REQUEST['search'], $form_params);
438
  }
439

    
440
  if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
441
    $form_params = array_merge($form_params, $_REQUEST['pager']);
442
  }
443

    
444
  $form_params['query'] = trim($_REQUEST['query']);
445

    
446
  // --- handle geographic range
447
  // Split of geographic range.
448
  if (isset($_REQUEST['search']['geographic_range']) && is_array($_REQUEST['search']['geographic_range'])) {
449
    $geographicRange = $_REQUEST['search']['geographic_range'];
450
    // Remove from form.
451
    unset($form_params['geographic_range']);
452
    $form_params['tdwg_level_select'] = $geographicRange['tdwg_level_select'];
453
    for ($i = 1; $i < 5; $i++) {
454
      if (isset($geographicRange['tdwg_level_' . $i])) {
455
        $form_params['area'] = $geographicRange['tdwg_level_' . $i];
456
      }
457
    }
458
  }
459

    
460
  // simple search will not submit a 'tree' query parameter, so we add it here from
461
  // what is stored in the session unless 'simple_search_ignore_classification'
462
  // is checked in the settings
463
  if (!isset($form_params['tree']) && !variable_get('simple_search_ignore_classification', 1)) {
464
    $form_params['tree'] = get_taxonomictree_uuid_selected();
465
  }
466
  // if the 'NONE' classification has been chosen (adanced search) delete the tree information
467
  // to avoid unknown uuid exceptions in the cdm service
468
  if (isset($form_params['tree']) && ($form_params['tree'] == 'NONE' || ! is_uuid($form_params['tree']))) {
469
//     $form_params['ignore_classification'] =  TRUE;
470
    unset($form_params['tree']);
471
  }
472
//   else {
473
//     $form_params['ignore_classification'] =  NULL;
474
//   }
475

    
476
  // Store in session.
477
  $_SESSION['cdm']['search'] = $form_params;
478

    
479
  return $form_params;
480
}
481

    
482
/**
483
 * Provides the classification the last search has been run on if any.
484
 *
485
 * This function should only be used after the cdm_dataportal_search_execute() handler has been run,
486
 * otherwise it will return the infomation from the last search executed. The information is retrieved from
487
 * the $_SESSION variable:  $_SESSION['cdm']['search']['tree']
488
 *
489
 * @return
490
 *    the CDM classification instance which has been used a filter for the last processed search
491
 *    or NULL, it it was on all classifications
492
 */
493
function cdm_dataportal_searched_in_classification() {
494

    
495
  $classification = &drupal_static(__FUNCTION__);
496

    
497
  if (!isset($classification)) {
498
    if (isset($_SESSION['cdm']['search']['tree'])) {
499
      $classification = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY, ($_SESSION['cdm']['search']['tree']));
500
    } else {
501
      $classification = FALSE;
502
    }
503
  }
504

    
505
  return $classification !== FALSE ?  $classification : NULL;
506
}
507

    
508
/**
509
 * Removes Drupal internal form elements from query.
510
 */
511
function cdm_dataportal_search_process($form, &$form_state) {
512
  unset($form['form_id']);
513
  unset($form['form_token']);
514
  return $form;
515
}
516

    
517
/**
518
 * Sends a search request at the cdm web server.
519
 *
520
 * The parameters to build the query are taken obtained by calling
521
 * cdm_dataportal_search_form_request() which reads the query parameters
522
 * from $_REQUEST and add additional query parameters if nessecary.
523
 *
524
 * @see cdm_dataportal_search_form_request()
525
 *
526
 */
527
function cdm_dataportal_search_execute() {
528

    
529
  // Store as last search in session.
530
  $_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
531

    
532
  // Validate the search webservice parameter:
533
  if (!isset($_REQUEST['ws'])) {// Check is ws.
534
    // Endpoint is unknown.
535
    drupal_set_message(t('webservice parameter \'ws\' missing'), 'warning');
536
    return NULL;
537
  }
538
  if (!cdm_dataportal_search_form_path_for_ws($_REQUEST['ws'])) {// Check is ws.
539
    // Endpoint is unknown.
540
    drupal_set_message(t('Invalid search webservice parameter  \'ws\' given'), 'warning');
541
    return NULL;
542
  }
543

    
544
  // read the query parameters from $_REQUEST and add additional query parameters if nessecary.
545
  $request_params = cdm_dataportal_search_form_request();
546

    
547
  $taxonPager = cdm_ws_get($_REQUEST['ws'], NULL, queryString($request_params));
548

    
549
  return $taxonPager;
550
}
(8-8/14)