Project

General

Profile

Statistics
| Branch: | Tag: | Revision:

cdm-dataportal / modules / cdm_dataportal / cdm_dataportal.search.php @ a0557101

History | View | Annotate | Download (29.1 KB)

1
<?php
2
/**
3
 * @file
4
 * Search related functions.
5
 */
6

    
7
define("SESSION_KEY_SEARCH_REGISTRATION_FILTER", "SESSION_KEY_SEARCH_REGISTRATION_FILTER");
8

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

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

    
57

    
58
  $form['#method'] = 'get';
59
  $form['#action'] = url($action_path, array(
60
    'absolute' => TRUE,
61
  ));
62

    
63
  $form['ws'] = array(
64
    '#type' => 'hidden',
65
    '#value' => $search_webservice,
66
    '#name' => 'ws',
67
  );
68

    
69
  $form['query'] = array(
70
    '#weight' => 0,
71
    '#type' => 'textfield',
72
    '#size' => 68,
73
    // This causes the description to display also when hovering over
74
    // the textfield.
75
    // This is wanted behaviour for the simple seach but could
76
    // be disabled for the advances search.
77
    '#attributes' => array(
78
      'title' => $query_field_description,
79
    ),
80
    '#description' => $query_field_description,
81
    '#value' => $query_field_default_value,
82
    // '#description' => $query_field_description,
83
  );
84
  if(variable_get(SIMPLE_SEARCH_AUTO_SUGGEST)){
85
      $form['query']['#autocomplete_path'] = 'cdm_dataportal/taxon/autosuggest////';
86
  }
87

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

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

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

    
111
  return $form;
112
}
113

    
114
function cdm_dataportal_taxon_autosuggest($classificationUuid = NULL, $areaUuid = NULL, $status = NULL, $string) {
115
  $matches = array();
116

    
117
  $queryParams = array();
118
  $queryParams['query'] = $string.'*';
119
  if((is_null($classificationUuid) || $classificationUuid=='') && isset($_SESSION['cdm']['taxonomictree_uuid'])){
120
    $classificationUuid = $_SESSION['cdm']['taxonomictree_uuid'];// if no classification uuid is set use the current one
121
  }
122
  if($classificationUuid){
123
    $queryParams['classificationUuid'] = $classificationUuid;
124
  }
125
  if($areaUuid){
126
    $queryParams['area'] = $areaUuid;
127
  }
128
  if($status){
129
    $queryParams['status'] = $status ;
130
  }
131
  $queryParams['pageNumber'] = '0';
132
  $queryParams['pageSize'] = '10';
133
  $queryParams['doTaxa'] = true;
134
  $queryParams['doSynonyms'] = true;
135
  $queryParams['doMisappliedNames'] = true;
136
  $queryParams['doTaxaByCommonNames'] = true;
137

    
138
  $search_results = cdm_ws_get(CDM_WS_TAXON_SEARCH, NULL, queryString($queryParams));
139
  foreach($search_results->records as $record){
140
      $titleCache = $record->entity->titleCache;
141
      preg_match('/(.*) sec.*/', $titleCache, $trimmedTitle); //remove sec reference
142
      $trimmedTitle = trim($trimmedTitle[1]);
143
      $matches[$trimmedTitle] = check_plain($trimmedTitle);
144
  }
145
  drupal_json_output($matches);
146
}
147

    
148

    
149
  /**
150
 * Creates a search form for searching on taxa.
151
 *
152
 * If advanced $advanced_form id TRUE the form will offer additional choices
153
 *
154
 * @param array $form
155
 *   A drupal form array
156
 * @param array $form_state
157
 *   The drupal form state passed as reference
158
 * @param bool $advanced_form
159
 *   default is FALSE
160
 * @param bool $classification_select
161
 *   set TRUE to offer a classification selector in the form - default is FALSE
162
 *   if only available in the advanced mode
163
 *
164
 * @return array
165
 *   the form array
166
 */
167
function cdm_dataportal_search_taxon_form($form, &$form_state, $advanced_form = FALSE, $classification_select = TRUE) {
168

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

    
171
  if ($advanced_form || variable_get(SIMPLE_SEARCH_USE_LUCENE_BACKEND, FALSE)) {
172
    $search_service_endpoint = CDM_WS_PORTAL_TAXON_SEARCH;
173
  }
174
  else {
175
    $search_service_endpoint = CDM_WS_PORTAL_TAXON_FIND;
176
  }
177

    
178
  $form = cdm_dataportal_search_form_prepare(
179
    'cdm_dataportal/search/results/taxon',
180
    $search_service_endpoint,
181
    $query_field_default_value,
182
    t('Enter the name or part of a name you wish to search for.
183
      The asterisk  character * can be used as wildcard, but must not be used as first character.')
184
  );
185

    
186
  if (!$advanced_form) {
187
    $form['query']['#size'] = 20;
188
  }
189

    
190
  $form['search']['pageSize'] = array(
191
    '#weight' => -1,
192
    '#type' => 'hidden',
193
    '#value' => variable_get('cdm_dataportal_search_items_on_page', 25),
194
  );
195

    
196
  $form['search']['pageNumber'] = array(
197
    '#weight' => -1,
198
    '#type' => 'hidden',
199
    '#value' => 0,
200
  );
201

    
202
  $search_taxa_mode_settings = get_array_variable_merged(
203
    CDM_SEARCH_TAXA_MODE,
204
    CDM_SEARCH_TAXA_MODE_DEFAULT
205
  );
206
  $preset_do_taxa = $search_taxa_mode_settings['doTaxa'] !== 0;
207
  $preset_do_synonyms = $search_taxa_mode_settings['doSynonyms'] !== 0;
208
  $preset_do_taxa_by_common_names = $search_taxa_mode_settings['doTaxaByCommonNames'] !== 0;
209
  $preset_do_misapplied_names = $search_taxa_mode_settings['doMisappliedNames'] !== 0;
210

    
211
  if ($advanced_form) {
212

    
213
    // --- ADVANCED SEARCH FORM ---
214
    //
215

    
216
    // Get presets from settings.
217
    $preset_classification_uuid = get_current_classification_uuid();
218

    
219
    // Overwrite presets by user choice stored in session.
220
    if (isset($_SESSION['cdm']['search'])) {
221
      $preset_do_taxa = (isset($_SESSION['cdm']['search']['doTaxa']) ? 1 : 0);
222
      $preset_do_synonyms = (isset($_SESSION['cdm']['search']['doSynonyms']) ? 1 : 0);
223
      $preset_do_misapplied_names = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
224
      $preset_do_taxa_by_common_names = (isset($_SESSION['cdm']['search']['doTaxaByCommonNames']) ? 1 : 0);
225
      if (isset($_SESSION['cdm']['search']['tree'])) {
226
        $preset_classification_uuid = $_SESSION['cdm']['search']['tree'];
227
      }
228
    }
229

    
230
    if ($classification_select === TRUE) {
231
      $form['search']['tree'] = array(
232
        '#title' => t('Classification'),
233
        '#weight' => 1,
234
        '#type' => 'select',
235
        '#default_value' => $preset_classification_uuid,
236
        '#options' => cdm_get_taxontrees_as_options(TRUE),
237
        '#description' => t('A filter to limit the search to a specific classification. Choosing <em>--- ALL ---</em> will disable this filter.'),
238
      );
239
    }
240

    
241
    // General search parameters.
242
    $form['search']['doTaxa'] = array(
243
      '#weight' => 2,
244
      '#type' => 'checkbox',
245
      '#title' => t('Include') . ' ' . t('accepted taxa'),
246
      '#value' => $preset_do_taxa,
247
    );
248
    $form['search']['doSynonyms'] = array(
249
      '#weight' => 3,
250
      '#type' => 'checkbox',
251
      '#title' => t('Include') . ' ' . t('synonyms'),
252
      '#value' => $preset_do_synonyms,
253
    );
254
    $form['search']['doMisappliedNames'] = array(
255
      '#weight' => 4,
256
      '#type' => 'checkbox',
257
      '#title' => t('Include') . ' ' . t('misapplied names'),
258
      '#value' => $preset_do_misapplied_names,
259
    );
260
    $form['search']['doTaxaByCommonNames'] = array(
261
      '#weight' => 5,
262
      '#type' => 'checkbox',
263
      '#title' => t('Include') . ' ' . t('common names'),
264
      '#value' => $preset_do_taxa_by_common_names,
265
    );
266

    
267
    $area_term_dtos = cdm_ws_fetch_all(
268
      CDM_WS_DESCRIPTION_NAMEDAREAS_IN_USE,
269
      array('includeAllParents' => 'true')
270
    );
271

    
272
    // create map: term_uuid => term
273
    $term_map = array();
274
    foreach ($area_term_dtos as $term_dto) {
275
      $term_map[$term_dto->uuid] = $term_dto;
276
    }
277

    
278
    $term_tree = array();
279
    // mixed_vocabularies will contain the uuid vocabularies which
280
    // also contain terms of foreign vocabularies due to the term
281
    // hierarchy
282
    $mixed_vocabularies = array();
283

    
284
    // Build hierarchy of the terms regardless of the vocabulary.
285
    foreach ($term_map as $term_dto) {
286
      if (!empty($term_dto->partOfUuid)) {
287
        // Children.
288
        $parent =& $term_map[$term_dto->partOfUuid];
289
        if ($parent) {
290
          if (!isset($parent->children)) {
291
            $parent->children = array();
292
          }
293
          $parent->children[$term_dto->uuid] = $term_dto;
294
          if ($parent->vocabularyUuid != $term_dto->vocabularyUuid) {
295
            $mixed_vocabularies[$parent->vocabularyUuid] = $parent->vocabularyUuid;
296
          }
297
        }
298
      }
299
      else {
300
        // group root nodes by vocabulary
301
        if (!isset($term_tree[$term_dto->vocabularyUuid])) {
302
          $term_tree[$term_dto->vocabularyUuid] = array();
303
        }
304
        $term_tree[$term_dto->vocabularyUuid][$term_dto->uuid] = $term_dto;
305
      }
306
    }
307

    
308
    $show_area_filter = ! variable_get(CDM_SEARCH_AREA_FILTER_PRESET, '');
309

    
310
    if($show_area_filter){
311
      drupal_add_js(drupal_get_path('module', 'cdm_dataportal') . '/js/search_area_filter.js');
312

    
313
      drupal_add_js('jQuery(document).ready(function() {
314
        jQuery(\'#edit-search-areas\').search_area_filter(\'#edit-search-areas-areas-filter\');
315
      });
316
      ', array('type' => 'inline'));
317

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

    
351
  }
352
  else {
353
    // --- SIMPLE SEARCH FORM ---
354
    //
355

    
356
    // Overwrite presets by user choice stored in session.
357
    if (isset($_SESSION['cdm']['search'])) {
358
      $preset_do_misapplied_names = (isset($_SESSION['cdm']['search']['doMisappliedNames']) ? 1 : 0);
359
    }
360

    
361
    $form['search']['doTaxa'] = array(
362
      '#weight' => -2,
363
      '#type' => 'hidden',
364
      '#value' => $preset_do_taxa,
365
    );
366
    $form['search']['doSynonyms'] = array(
367
      '#weight' => -3,
368
      '#type' => 'hidden',
369
      '#value' => $preset_do_synonyms,
370
    );
371
    $form['search']['doMisappliedNames'] = array(
372
      '#weight' => -4,
373
      '#type' => 'checkbox',
374
      '#title' => t('Misapplied names'),
375
      '#value' => $preset_do_misapplied_names,
376
    );
377
    $form['search']['doTaxaByCommonNames'] = array(
378
      '#weight' => -5,
379
      '#type' => 'hidden',
380
      '#value' => $preset_do_taxa_by_common_names,
381
    );
382
  }
383

    
384
  return $form;
385
}
386

    
387
/**
388
 * Wrapper function for cdm_dataportal_search_taxon_form().
389
 *
390
 * This function makes ot possible possible to just pass the
391
 * correct $form_id 'cdm_dataportal_search_taxon_form_advanced' to
392
 * drupal_get_form like:
393
 * drupal_get_form('cdm_dataportal_search_taxon_form_advanced');
394
 *
395
 * @param array $form
396
 *   A drupal form array
397
 * @param array $form_state
398
 *   The drupal form state passed as reference
399
 *
400
 * @return array
401
 *   The form array
402
 */
403
function cdm_dataportal_search_taxon_form_advanced($form, &$form_state) {
404
  return cdm_dataportal_search_taxon_form($form, $form_state, TRUE);
405
}
406

    
407
/**
408
 * Form for searching taxa by the findByDescriptionElementFullText rest service.
409
 */
410
function cdm_dataportal_search_taxon_by_description_form() {
411
  $query_field_default_value = (isset($_SESSION['cdm']['search']['query']) ? $_SESSION['cdm']['search']['query'] : '');
412

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

    
434
  $form['search']['tree'] = array(
435
    '#weight' => -1,
436
    '#type' => 'hidden',
437
    '#value' => get_current_classification_uuid(),
438
  );
439

    
440
  $form['search']['hl'] = array(
441
    '#weight' => -1,
442
    '#type' => 'hidden',
443
    '#value' => 1,
444
  );
445

    
446
  // Only available to admins:
447
  if (!isset($_SESSION['cdm']['search']['clazz'])) {
448
    $_SESSION['cdm']['search']['clazz'] = '';
449
  }
450
  if (module_exists("user") && user_access('administer')) {
451
    $form['search']['clazz'] = array(
452
      '#type' => 'select',
453
      '#title' => t('Limit to description item type'),
454
      '#default_value' => $_SESSION['cdm']['search']['clazz'],
455
      '#options' => cdm_descriptionElementTypes_as_option(TRUE),
456
    );
457
  }
458

    
459
  $profile_feature_tree = get_profile_feature_tree();
460
  $feature_options = _featureTree_nodes_as_feature_options($profile_feature_tree->root);
461
  if (isset($_SESSION['cdm']['search']['features'])) {
462
    $form['search']['features'] = array(
463
      '#type' => 'checkboxes',
464
      '#title' => t('Limit to selected features'),
465
      '#default_value' => $_SESSION['cdm']['search']['features'],
466
      '#options' => $feature_options,
467
    );
468
  }
469
  else {
470
    $form['search']['features'] = array(
471
      '#type' => 'checkboxes',
472
      '#title' => t('Limit to selected features'),
473
      '#options' => $feature_options,
474
    );
475
  }
476
  return $form;
477
}
478

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

    
502
  $form_params = array();
503

    
504
  if (isset($_REQUEST['search']) && is_array($_REQUEST['search'])) {
505
    array_deep_copy($_REQUEST['search'], $form_params);
506
  }
507

    
508
  if (isset($_REQUEST['pager']) && is_array($_REQUEST['pager'])) {
509
    $form_params = array_merge($form_params, $_REQUEST['pager']);
510
  }
511

    
512
  $form_params['query'] = trim($_REQUEST['query']);
513

    
514

    
515
  // --- handle geographic range
516
  // Split of geographic range.
517
  unset($form_params['areas']);
518

    
519
  $area_filter_preset = null;
520
  if (variable_get(CDM_SEARCH_AREA_FILTER_PRESET, '')) {
521
    $area_filter_preset = explode(',', variable_get(CDM_SEARCH_AREA_FILTER_PRESET, ''));
522
  }
523

    
524
  $area_uuids = array();
525
  if($area_filter_preset){
526
    $area_uuids = $area_filter_preset;
527
  }
528
  elseif (isset($_REQUEST['search']['areas']['area']) && is_array($_REQUEST['search']['areas']['area'])) {
529
    foreach ($_REQUEST['search']['areas']['area'] as $areas) {
530
      $area_uuids = array_merge($area_uuids, $areas);
531
    }
532
    // The area filter is limited to areas with non absent distribution status
533
    $presence_terms_options = cdm_vocabulary_as_option(UUID_PRESENCE_ABSENCE_TERM, null, FALSE, array('absenceTerm' => '/false/'));
534
    $presence_term_uuids = array_keys($presence_terms_options);
535
    $form_params['status'] = $presence_term_uuids;
536
  }
537
  if(count($area_uuids) > 0){
538
    $form_params['area'] = implode(',', $area_uuids);
539
  }
540

    
541
  // Simple search will not submit a 'tree' query parameter,
542
  // so we add it here from what is stored in the session unless
543
  // SIMPLE_SEARCH_IGNORE_CLASSIFICATION is checked in the settings.
544
  if (!isset($form_params['tree']) && !variable_get(SIMPLE_SEARCH_IGNORE_CLASSIFICATION, 0)) {
545
    $form_params['tree'] = get_current_classification_uuid();
546
  }
547
  // Store in session.
548
  $_SESSION['cdm']['search'] = $form_params;
549

    
550
  // ----------- further processing that must not be store in the session --------- //
551

    
552
  if($search_endpoint == CDM_WS_PORTAL_TAXON_SEARCH){
553
    // lucene based taxon search always as phrase search if the query string contains a whitespace --> enclose it in "
554
    if(preg_match("/\s+/", $form_params['query'])){
555
      if(!str_beginsWith($form_params['query'], '"')){
556
        $form_params['query'] = '"' . $form_params['query'];
557
      }
558
      if(!str_endsWith($form_params['query'], '"')){
559
        $form_params['query'] = $form_params['query'] . '"' ;
560
      }
561
    }
562
  }
563

    
564
  // If the 'NONE' classification has been chosen (advanced search)
565
  // delete the tree information to avoid unknown uuid exceptions in the
566
  // cdm service.
567
  if (isset($form_params['tree'])
568
    && ($form_params['tree'] == 'NONE' || !is_uuid($form_params['tree']))
569
  ) {
570
    // $form_params['ignore_classification'] =  TRUE;
571
    unset($form_params['tree']);
572
  }
573
  // else {
574
  //   $form_params['ignore_classification'] =  NULL;
575
  // }
576

    
577

    
578
  return $form_params;
579
}
580

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

    
596
  $classification = &drupal_static(__FUNCTION__);
597

    
598
  if (!isset($classification)) {
599
    if (isset($_SESSION['cdm']['search']['tree'])) {
600
      $classification = cdm_ws_get(CDM_WS_PORTAL_TAXONOMY, ($_SESSION['cdm']['search']['tree']));
601
    }
602
    else {
603
      $classification = FALSE;
604
    }
605
  }
606

    
607
  return $classification !== FALSE ? $classification : NULL;
608
}
609

    
610
/**
611
 * Removed the drupal internal form parameters 'form_id', 'form_token', 'form_build_id' from the request array.
612
 *
613
 * @param $request array
614
 *   Pass $_REQUEST as paramter
615
 * @return array
616
 *  The $request array without drupal internal form parameters
617
 */
618
function remove_drupal_form_params($request) {
619

    
620
  static $exclude_keys = array('form_id', 'form_token', 'form_build_id');
621
  $request_sanitized = array();
622
  foreach ($request as $key => $value) {
623
    if(!array_search($key, $exclude_keys)){
624
      $request_sanitized[$key] = $value;
625
    }
626
  }
627

    
628
  return $request_sanitized;
629
}
630

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

    
642
  // Store as last search in session.
643
  $_SESSION['cdm']['last_search'] = $_SERVER['REQUEST_URI'];
644

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

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

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

    
666
  return $taxon_pager;
667
}
668

    
669

    
670
/**
671
 * Sends a request to search for registrations to the cdm server.
672
 */
673
function cdm_dataportal_search_registrations_execute()
674
{
675

    
676
  static $query_param_map = array(
677
    'identifier' => 'identifierFilterPattern',
678
    'taxon_name'=> 'taxonNameFilterPattern',
679
    'type_designation_status' => 'typeDesignationStatusUuids',
680
  );
681

    
682
  // Read the query parameters from $_REQUEST and add additional query
683
  // parameters if necessary.
684
  $request_params = array();
685

    
686
  $request = remove_drupal_form_params($_REQUEST);
687

    
688
  if(count($request) > 0){
689
    $_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER] = $request;
690
    foreach ($query_param_map as $filter_key => $query_param){
691
      if (isset($request[$filter_key])) {
692
        $request_params[$query_param] = $request[$filter_key];
693
      }
694
    }
695
    if(isset($request['pager']['pageNumber'])){
696
      $request_params['pageNumber'] = $request['pager']['pageNumber'];
697
    }
698
  }
699

    
700
  if(count($request_params) == 0 && isset($_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER])){
701
    foreach ($query_param_map as $filter_key => $query_param){
702
      if (isset($_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER][$filter_key])) {
703
        $request_params[$query_param] = $_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER][$filter_key];
704
      }
705
    }
706
    if(isset($_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER]['pager']['pageNumber'])){
707
      $request_params['pageNumber'] = $_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER]['pager']['pageNumber'];
708
    }
709
  }
710

    
711
  // cleanup
712
  if(isset($request_params['typeDesignationStatusUuids'])){
713
    if(!$request_params['typeDesignationStatusUuids']
714
      || $request_params['typeDesignationStatusUuids'] == "0"
715
      || (isset($request_params['typeDesignationStatusUuids'][0]) && !$request_params['typeDesignationStatusUuids'][0])){
716
      unset($request_params['typeDesignationStatusUuids']);
717
    }
718
  }
719
  if(isset($request_params['taxonNameFilterPattern'])){
720
    // trim and remove empty taxon name query strings
721
    $request_params['taxonNameFilterPattern'] = trim($request_params['taxonNameFilterPattern']);
722
    if(!$request_params['taxonNameFilterPattern']){
723
      unset($request_params['taxonNameFilterPattern']);
724
    }
725
  }
726

    
727
  $registration_pager = cdm_ws_get('registrationDTO/find', NULL, queryString($request_params));
728

    
729
  return $registration_pager;
730
}
731

    
732
/**
733
 * Transforms the termDTO tree into options array.
734
 *
735
 *   TermDto:
736
 *      - partOfUuid:
737
 *      - representation_L10n:
738
 *      - representation_L10n_abbreviatedLabel:
739
 *      - uuid:
740
 *      - vocabularyUuid:
741
 *      - children: array of TermDto
742
 *
743
 * The options array is suitable for drupal form API elements that
744
 * allow multiple choices.
745
 * @see http://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#options
746
 *
747
 * @param array $term_dto_tree
748
 *   a hierarchic array of CDM TermDto instances, with additional
749
 * 'children' field:
750
 * @param array $options
751
 *   Internally used for recursive calls
752
 * @param string $prefix
753
 *   Internally used for recursive calls
754
 *
755
 * @return array
756
 *   the terms in an array as options for a form element that allows
757
 *   multiple choices.
758
 */
759
function term_tree_as_options($term_dto_tree, &$options = array(), $prefix = '') {
760

    
761
  uasort($term_dto_tree, 'compare_terms_by_order_index');
762
  foreach ($term_dto_tree as $uuid => $dto) {
763
    $label = $prefix . '<span class="child-label">'
764
      .  $dto->representation_L10n
765
      . '</span><span class="child-label-abbreviated"> (' . $dto->representation_L10n_abbreviatedLabel . ')</span>';
766
    $options[$uuid] = $label;
767
    if (isset($dto->children) && is_array($dto->children)) {
768
      term_tree_as_options(
769
        $dto->children,
770
        $options, $prefix
771
          . '<span data-cdm-parent="' . $uuid . '" class="parent"></span>'
772
      );
773
    }
774
  }
775

    
776
  return $options;
777
}
778

    
779

    
780
function cdm_dataportal_search_registration_form($form, &$form_state) {
781

    
782
  static $filter_presets_empty = array(
783
    'identifier'=> null,
784
    'taxon_name'=> null,
785
    'type_designation_status' => null
786
  );
787

    
788
  _add_font_awesome_font();
789

    
790
  $filter_presets = (isset($_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER]) ? $_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER] : array());
791
  $filter_presets = array_merge($filter_presets_empty, $filter_presets, remove_drupal_form_params($_REQUEST));
792
  $form['#action'] =  url('/cdm_dataportal/search/registration/');
793
  $form['#method'] = 'get';
794
  $form['#attributes'] = array('class' => array('search-filter'));
795
  $form['identifier'] = array(
796
    '#type' => 'textfield',
797
    '#title' => t('Identifier'),
798
    '#default_value' => $filter_presets['identifier'],
799
    '#size' => 20,
800
    '#maxlength' => 128
801
  );
802
  $form['taxon_name'] = array(
803
    '#type' => 'textfield',
804
    '#title' => t('Scientific name'),
805
    '#default_value' => $filter_presets['taxon_name'],
806
    '#size' => 20,
807
    '#maxlength' => 128
808
  );
809
  $form['type_designation_status'] = array(
810
    '#type' => 'select',
811
    '#title' => t('Type designation status'),
812
    '#multiple' => true,
813
    '#options' => cdm_terms_by_type_as_option('TypeDesignationStatusBase', null, null, TRUE),
814
    '#default_value' => $filter_presets['type_designation_status']
815
  );
816

    
817
  $form['submit'] = array(
818
    '#type' => 'submit',
819
    '#attributes' => array('class' => array('fa-icon'), 'title' => t('Search')),
820
    '#value' => decode_entities('&#xf002;'), // fontawesome search icon
821
//    '#prefix' => "<div class=\"form-item\"><label>&nbsp</label>",
822
//    '#suffix' => "</div>"
823

    
824
  );
825
  return $form;
826
}
827

    
828

    
829
/**
830
 * Compose the result set of a registration search from a pager object
831
 *
832
 * @param $registration_pager
833
 *    The pager containing registration objects
834
 *
835
 * @return
836
 *   A drupal render array.
837
 *
838
 * @ingroup compose
839
 *
840
 * TODO compose function into search.inc ?
841
 */
842
function compose_registrations_search_results($registration_pager){
843

    
844
  $render_array = array();
845
  $render_array['pre'] = markup_to_render_array("<div class=\"cdm-item-list\">");
846
  if($registration_pager != null){
847
    $items_render_array = array();
848
    foreach($registration_pager->records as $registration) {
849
      $summary_markup = cdm_tagged_text_to_markup($registration->summaryTaggedText);
850
      $items_render_array[]  = markup_to_render_array(
851
        "<div class=\"item\"><div class=\"" . html_class_attribute_ref(new TypedEntityReference("Registration", $registration->uuid)) . "\">"
852
          . "<div class=\"identifier\">"
853
          . l($registration->identifier, path_to_registration($registration->identifier), array('absolute' => true, 'attributes' => array('class' => array('identifier'))))
854
          . "</div>"
855
          . $summary_markup
856
          . "</div></div>"
857
        );
858
      ;
859
    }
860
    $render_array['items'] = $items_render_array;
861
    $render_array['pager'] =  markup_to_render_array(theme('cdm_pager', array(
862
          'pager' => $registration_pager,
863
          'path' => "cdm_dataportal/search/registration",
864
          'parameters' => $_REQUEST,
865
        )));
866

    
867
  } else {
868
    $render_array['items'] = markup_to_render_array("No results! Please use the search filter.");
869
  }
870
  $render_array['post'] = markup_to_render_array("</div>");
871

    
872
  return $render_array;
873

    
874
}
Add picture from clipboard (Maximum size: 40 MB)