Project

General

Profile

Download (28.5 KB) Statistics
| Branch: | Tag: | Revision:
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: enclose it in "
554
    if(!str_beginsWith($form_params['query'], '"')){
555
      $form_params['query'] = '"' . $form_params['query'];
556
    }
557
    if(!str_endsWith($form_params['query'], '"')){
558
      $form_params['query'] = $form_params['query'] . '"' ;
559
    }
560
  }
561

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

    
575

    
576
  return $form_params;
577
}
578

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

    
594
  $classification = &drupal_static(__FUNCTION__);
595

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

    
605
  return $classification !== FALSE ? $classification : NULL;
606
}
607

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

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

    
626
  return $request_sanitized;
627
}
628

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

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

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

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

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

    
664
  return $taxon_pager;
665
}
666

    
667

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

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

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

    
684
  $request = remove_drupal_form_params($_REQUEST);
685

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

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

    
709
  // cleanup
710
  if(isset($request_params['typeDesignationStatusUuids'])){
711
    if(!$request_params['typeDesignationStatusUuids']
712
      || $request_params['typeDesignationStatusUuids'] == "0"
713
      || (isset($request_params['typeDesignationStatusUuids'][0]) && !$request_params['typeDesignationStatusUuids'][0])){
714
      unset($request_params['typeDesignationStatusUuids']);
715
    }
716

    
717
  }
718

    
719
  $registration_pager = cdm_ws_get('registrationDTO/find', NULL, queryString($request_params));
720

    
721
  return $registration_pager;
722
}
723

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

    
753
  uasort($term_dto_tree, 'compare_terms_by_order_index');
754
  foreach ($term_dto_tree as $uuid => $dto) {
755
    $label = $prefix . '<span class="child-label">'
756
      .  $dto->representation_L10n
757
      . '</span><span class="child-label-abbreviated"> (' . $dto->representation_L10n_abbreviatedLabel . ')</span>';
758
    $options[$uuid] = $label;
759
    if (isset($dto->children) && is_array($dto->children)) {
760
      term_tree_as_options(
761
        $dto->children,
762
        $options, $prefix
763
          . '<span data-cdm-parent="' . $uuid . '" class="parent"></span>'
764
      );
765
    }
766
  }
767

    
768
  return $options;
769
}
770

    
771

    
772
function cdm_dataportal_search_registration_form($form, &$form_state) {
773

    
774
  $filter_presets = (isset($_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER]) ? $_SESSION['cdm'][SESSION_KEY_SEARCH_REGISTRATION_FILTER] : array());
775
  $filter_presets = array_merge($filter_presets, remove_drupal_form_params($_REQUEST));
776
  $form['#action'] =  url('/cdm_dataportal/search/registration/');
777
  $form['#method'] = 'get';
778
  $form['#attributes'] = array('class' => array('search-filter'));
779
  $form['identifier'] = array(
780
    '#type' => 'textfield',
781
    '#title' => t('Identifier'),
782
    '#default_value' => $filter_presets['identifier'],
783
    '#size' => 20,
784
    '#maxlength' => 128
785
  );
786
  $form['taxon_name'] = array(
787
    '#type' => 'textfield',
788
    '#title' => t('Scientific name'),
789
    '#default_value' => $filter_presets['taxon_name'],
790
    '#size' => 20,
791
    '#maxlength' => 128
792
  );
793
  $form['type_designation_status'] = array(
794
    '#type' => 'select',
795
    '#title' => t('Type designation status'),
796
    '#multiple' => true,
797
    '#options' => cdm_terms_by_type_as_option('TypeDesignationStatusBase', null, null, TRUE),
798
    '#default_value' => $filter_presets['type_designation_status']
799
  );
800

    
801
  $form['submit'] = array(
802
    '#type' => 'submit',
803
    '#attributes' => array('class' => array('fa-icon'), 'title' => t('Search')),
804
    '#value' => decode_entities('&#xf002;'), // fontawesome search icon
805
//    '#prefix' => "<div class=\"form-item\"><label>&nbsp</label>",
806
//    '#suffix' => "</div>"
807

    
808
  );
809
  return $form;
810
}
811

    
812

    
813
/**
814
 * Compose the result set of a registration search from a pager object
815
 *
816
 * @param $registration_pager
817
 *    The pager containing registration objects
818
 *
819
 * @return
820
 *   A drupal render array.
821
 *
822
 * @ingroup compose
823
 *
824
 * TODO compose function into search.inc ?
825
 */
826
function compose_registrations_search_results($registration_pager){
827

    
828
  $render_array = array();
829
  $render_array['pre'] = markup_to_render_array("<div class=\"cdm-item-list\">");
830
  if($registration_pager != null){
831
    $items_render_array = array();
832
    foreach($registration_pager->records as $registration) {
833
      $summary_markup = cdm_tagged_text_to_markup($registration->summaryTaggedText);
834
      $items_render_array[]  = markup_to_render_array(
835
        "<div class=\"item\"><div class=\"" . html_class_attribute_ref(new TypedEntityReference("Registration", $registration->uuid)) . "\">"
836
          . "<div class=\"identifier\">"
837
          . l($registration->identifier, path_to_registration($registration->identifier), array('absolute' => true, 'attributes' => array('class' => array('identifier'))))
838
          . "</div>"
839
          . $summary_markup
840
          . "</div></div>"
841
        );
842
      ;
843
    }
844
    $render_array['items'] = $items_render_array;
845
    $render_array['pager'] =  markup_to_render_array(theme('cdm_pager', array(
846
          'pager' => $registration_pager,
847
          'path' => "cdm_dataportal/search/registration",
848
          'parameters' => $_REQUEST,
849
        )));
850

    
851
  } else {
852
    $render_array['items'] = markup_to_render_array("No results! Please use the search filter.");
853
  }
854
  $render_array['post'] = markup_to_render_array("</div>");
855

    
856
  return $render_array;
857

    
858
}
(11-11/18)