]> git.evergreen-ils.org Git - working/Evergreen.git/blob - Open-ILS/src/perlmods/lib/OpenILS/Application/Storage/QueryParser.pm
0661b5b96f996da31bfd4606432a2f7f653e30c6
[working/Evergreen.git] / Open-ILS / src / perlmods / lib / OpenILS / Application / Storage / QueryParser.pm
1 use strict;
2 use warnings;
3
4 package QueryParser;
5 use OpenSRF::Utils::JSON;
6
7 =head1 NAME
8
9 QueryParser - basic QueryParser class
10
11 =head1 SYNOPSIS
12
13 use QueryParser;
14 my $QParser = QueryParser->new(%args);
15
16 =head1 DESCRIPTION
17
18 Main entrypoint into the QueryParser functionality.
19
20 =head1 FUNCTIONS
21
22 =cut
23
24 # Note that the first key must match the name of the package.
25 our %parser_config = (
26     QueryParser => {
27         filters => [],
28         modifiers => [],
29         operators => { 
30             'and' => '&&',
31             'or' => '||',
32             float_start => '{{',
33             float_end => '}}',
34             group_start => '(',
35             group_end => ')',
36             required => '+',
37             disallowed => '-',
38             modifier => '#',
39             negated => '!'
40         }
41     }
42 );
43
44 sub canonicalize {
45     my $self = shift;
46     return QueryParser::Canonicalize::abstract_query2str_impl(
47         $self->parse_tree->to_abstract_query(@_)
48     );
49 }
50
51
52 =head2 facet_class_count
53
54     $count = $QParser->facet_class_count();
55 =cut
56
57 sub facet_class_count {
58     my $self = shift;
59     return @{$self->facet_classes};
60 }
61
62 =head2 search_class_count
63
64     $count = $QParser->search_class_count();
65 =cut
66
67 sub search_class_count {
68     my $self = shift;
69     return @{$self->search_classes};
70 }
71
72 =head2 filter_count
73
74     $count = $QParser->filter_count();
75 =cut
76
77 sub filter_count {
78     my $self = shift;
79     return @{$self->filters};
80 }
81
82 =head2 modifier_count
83
84     $count = $QParser->modifier_count();
85 =cut
86
87 sub modifier_count {
88     my $self = shift;
89     return @{$self->modifiers};
90 }
91
92 =head2 custom_data
93
94     $data = $QParser->custom_data($class);
95 =cut
96
97 sub custom_data {
98     my $class = shift;
99     $class = ref($class) || $class;
100
101     $parser_config{$class}{custom_data} ||= {};
102     return $parser_config{$class}{custom_data};
103 }
104
105 =head2 operators
106
107     $operators = $QParser->operators();
108
109 Returns hashref of the configured operators.
110 =cut
111
112 sub operators {
113     my $class = shift;
114     $class = ref($class) || $class;
115
116     $parser_config{$class}{operators} ||= {};
117     return $parser_config{$class}{operators};
118 }
119
120 sub allow_nested_modifiers {
121     my $class = shift;
122     my $v = shift;
123     $class = ref($class) || $class;
124
125     $parser_config{$class}{allow_nested_modifiers} = $v if (defined $v);
126     return $parser_config{$class}{allow_nested_modifiers};
127 }
128
129 =head2 filters
130
131     $filters = $QParser->filters();
132
133 Returns arrayref of the configured filters.
134 =cut
135
136 sub filters {
137     my $class = shift;
138     $class = ref($class) || $class;
139
140     $parser_config{$class}{filters} ||= [];
141     return $parser_config{$class}{filters};
142 }
143
144 =head2 filter_callbacks
145
146     $filter_callbacks = $QParser->filter_callbacks();
147
148 Returns hashref of the configured filter callbacks.
149 =cut
150
151 sub filter_callbacks {
152     my $class = shift;
153     $class = ref($class) || $class;
154
155     $parser_config{$class}{filter_callbacks} ||= {};
156     return $parser_config{$class}{filter_callbacks};
157 }
158
159 =head2 modifiers
160
161     $modifiers = $QParser->modifiers();
162
163 Returns arrayref of the configured modifiers.
164 =cut
165
166 sub modifiers {
167     my $class = shift;
168     $class = ref($class) || $class;
169
170     $parser_config{$class}{modifiers} ||= [];
171     return $parser_config{$class}{modifiers};
172 }
173
174 =head2 new
175
176     $QParser = QueryParser->new(%args);
177
178 Creates a new QueryParser object.
179 =cut
180
181 sub new {
182     my $class = shift;
183     $class = ref($class) || $class;
184
185     my %opts = @_;
186
187     my $self = bless {} => $class;
188
189     for my $o (keys %{QueryParser->operators}) {
190         $class->operator($o => QueryParser->operator($o)) unless ($class->operator($o));
191     }
192
193     for my $opt ( keys %opts) {
194         $self->$opt( $opts{$opt} ) if ($self->can($opt));
195     }
196
197     return $self;
198 }
199
200 =head2 new_plan
201
202     $query_plan = $QParser->new_plan();
203
204 Create a new query plan.
205 =cut
206
207 sub new_plan {
208     my $self = shift;
209     my $pkg = ref($self) || $self;
210     return do{$pkg.'::query_plan'}->new( QueryParser => $self, @_ );
211 }
212
213 =head2 add_search_filter
214
215     $QParser->add_search_filter($filter, [$callback]);
216
217 Adds a filter with the specified name and an optional callback to the
218 QueryParser configuration.
219 =cut
220
221 sub add_search_filter {
222     my $pkg = shift;
223     $pkg = ref($pkg) || $pkg;
224     my $filter = shift;
225     my $callback = shift;
226
227     return $filter if (grep { $_ eq $filter } @{$pkg->filters});
228     push @{$pkg->filters}, $filter;
229     $pkg->filter_callbacks->{$filter} = $callback if ($callback);
230     return $filter;
231 }
232
233 =head2 add_search_modifier
234
235     $QParser->add_search_modifier($modifier);
236
237 Adds a modifier with the specified name to the QueryParser configuration.
238 =cut
239
240 sub add_search_modifier {
241     my $pkg = shift;
242     $pkg = ref($pkg) || $pkg;
243     my $modifier = shift;
244
245     return $modifier if (grep { $_ eq $modifier } @{$pkg->modifiers});
246     push @{$pkg->modifiers}, $modifier;
247     return $modifier;
248 }
249
250 =head2 add_facet_class
251
252     $QParser->add_facet_class($facet_class);
253
254 Adds a facet class with the specified name to the QueryParser configuration.
255 =cut
256
257 sub add_facet_class {
258     my $pkg = shift;
259     $pkg = ref($pkg) || $pkg;
260     my $class = shift;
261
262     return $class if (grep { $_ eq $class } @{$pkg->facet_classes});
263
264     push @{$pkg->facet_classes}, $class;
265     $pkg->facet_fields->{$class} = [];
266
267     return $class;
268 }
269
270 =head2 add_search_class
271
272     $QParser->add_search_class($class);
273
274 Adds a search class with the specified name to the QueryParser configuration.
275 =cut
276
277 sub add_search_class {
278     my $pkg = shift;
279     $pkg = ref($pkg) || $pkg;
280     my $class = shift;
281
282     return $class if (grep { $_ eq $class } @{$pkg->search_classes});
283
284     push @{$pkg->search_classes}, $class;
285     $pkg->search_fields->{$class} = [];
286     $pkg->default_search_class( $pkg->search_classes->[0] ) if (@{$pkg->search_classes} == 1);
287
288     return $class;
289 }
290
291 =head2 add_search_modifier
292
293     $op = $QParser->operator($operator, [$newvalue]);
294
295 Retrieves or sets value for the specified operator. Valid operators and
296 their defaults are as follows:
297
298 =over 4
299
300 =item * and => &&
301
302 =item * or => ||
303
304 =item * group_start => (
305
306 =item * group_end => )
307
308 =item * required => +
309
310 =item * disallowed => -
311
312 =item * modifier => #
313
314 =back
315
316 =cut
317
318 sub operator {
319     my $class = shift;
320     $class = ref($class) || $class;
321     my $opname = shift;
322     my $op = shift;
323
324     return undef unless ($opname);
325
326     $parser_config{$class}{operators} ||= {};
327     $parser_config{$class}{operators}{$opname} = $op if ($op);
328
329     return $parser_config{$class}{operators}{$opname};
330 }
331
332 =head2 facet_classes
333
334     $classes = $QParser->facet_classes([\@newclasses]);
335
336 Returns arrayref of all configured facet classes after optionally
337 replacing configuration.
338 =cut
339
340 sub facet_classes {
341     my $class = shift;
342     $class = ref($class) || $class;
343     my $classes = shift;
344
345     $parser_config{$class}{facet_classes} ||= [];
346     $parser_config{$class}{facet_classes} = $classes if (ref($classes) && @$classes);
347     return $parser_config{$class}{facet_classes};
348 }
349
350 =head2 search_classes
351
352     $classes = $QParser->search_classes([\@newclasses]);
353
354 Returns arrayref of all configured search classes after optionally
355 replacing the previous configuration.
356 =cut
357
358 sub search_classes {
359     my $class = shift;
360     $class = ref($class) || $class;
361     my $classes = shift;
362
363     $parser_config{$class}{classes} ||= [];
364     $parser_config{$class}{classes} = $classes if (ref($classes) && @$classes);
365     return $parser_config{$class}{classes};
366 }
367
368 =head2 add_query_normalizer
369
370     $function = $QParser->add_query_normalizer($class, $field, $func, [\@params]);
371
372 =cut
373
374 sub add_query_normalizer {
375     my $pkg = shift;
376     $pkg = ref($pkg) || $pkg;
377     my $class = shift;
378     my $field = shift;
379     my $func = shift;
380     my $params = shift || [];
381
382     # do not add if function AND params are identical to existing member
383     return $func if (grep {
384         $_->{function} eq $func and 
385         OpenSRF::Utils::JSON->perl2JSON($_->{params}) eq OpenSRF::Utils::JSON->perl2JSON($params)
386     } @{$pkg->query_normalizers->{$class}->{$field}});
387
388     push(@{$pkg->query_normalizers->{$class}->{$field}}, { function => $func, params => $params });
389
390     return $func;
391 }
392
393 =head2 query_normalizers
394
395     $normalizers = $QParser->query_normalizers($class, $field);
396
397 Returns a list of normalizers associated with the specified search class
398 and field
399 =cut
400
401 sub query_normalizers {
402     my $pkg = shift;
403     $pkg = ref($pkg) || $pkg;
404
405     my $class = shift;
406     my $field = shift;
407
408     $parser_config{$pkg}{normalizers} ||= {};
409     if ($class) {
410         if ($field) {
411             $parser_config{$pkg}{normalizers}{$class}{$field} ||= [];
412             return $parser_config{$pkg}{normalizers}{$class}{$field};
413         } else {
414             return $parser_config{$pkg}{normalizers}{$class};
415         }
416     }
417
418     return $parser_config{$pkg}{normalizers};
419 }
420
421 =head2 add_filter_normalizer
422
423     $normalizer = $QParser->add_filter_normalizer($filter, $func, [\@params]);
424
425 Adds a normalizer function to the specified filter.
426 =cut
427
428 sub add_filter_normalizer {
429     my $pkg = shift;
430     $pkg = ref($pkg) || $pkg;
431     my $filter = shift;
432     my $func = shift;
433     my $params = shift || [];
434
435     return $func if (grep { $_ eq $func } @{$pkg->filter_normalizers->{$filter}});
436
437     push(@{$pkg->filter_normalizers->{$filter}}, { function => $func, params => $params });
438
439     return $func;
440 }
441
442 =head2 filter_normalizers
443
444     $normalizers = $QParser->filter_normalizers($filter);
445
446 Return arrayref of normalizer functions associated with the specified filter.
447 =cut
448
449 sub filter_normalizers {
450     my $pkg = shift;
451     $pkg = ref($pkg) || $pkg;
452
453     my $filter = shift;
454
455     $parser_config{$pkg}{filter_normalizers} ||= {};
456     if ($filter) {
457         $parser_config{$pkg}{filter_normalizers}{$filter} ||= [];
458         return $parser_config{$pkg}{filter_normalizers}{$filter};
459     }
460
461     return $parser_config{$pkg}{filter_normalizers};
462 }
463
464 =head2 default_search_class
465
466     $default_class = $QParser->default_search_class([$class]);
467
468 Set or return the default search class.
469 =cut
470
471 sub default_search_class {
472     my $pkg = shift;
473     $pkg = ref($pkg) || $pkg;
474     my $class = shift;
475     $QueryParser::parser_config{$pkg}{default_class} = $pkg->add_search_class( $class ) if $class;
476
477     return $QueryParser::parser_config{$pkg}{default_class};
478 }
479
480 =head2 remove_facet_class
481
482     $QParser->remove_facet_class($class);
483
484 Remove the specified facet class from the configuration.
485 =cut
486
487 sub remove_facet_class {
488     my $pkg = shift;
489     $pkg = ref($pkg) || $pkg;
490     my $class = shift;
491
492     return $class if (!grep { $_ eq $class } @{$pkg->facet_classes});
493
494     $pkg->facet_classes( [ grep { $_ ne $class } @{$pkg->facet_classes} ] );
495     delete $QueryParser::parser_config{$pkg}{facet_fields}{$class};
496
497     return $class;
498 }
499
500 =head2 remove_search_class
501
502     $QParser->remove_search_class($class);
503
504 Remove the specified search class from the configuration.
505 =cut
506
507 sub remove_search_class {
508     my $pkg = shift;
509     $pkg = ref($pkg) || $pkg;
510     my $class = shift;
511
512     return $class if (!grep { $_ eq $class } @{$pkg->search_classes});
513
514     $pkg->search_classes( [ grep { $_ ne $class } @{$pkg->search_classes} ] );
515     delete $QueryParser::parser_config{$pkg}{fields}{$class};
516
517     return $class;
518 }
519
520 =head2 add_facet_field
521
522     $QParser->add_facet_field($class, $field);
523
524 Adds the specified field (and facet class if it doesn't already exist)
525 to the configuration.
526 =cut
527
528 sub add_facet_field {
529     my $pkg = shift;
530     $pkg = ref($pkg) || $pkg;
531     my $class = shift;
532     my $field = shift;
533
534     $pkg->add_facet_class( $class );
535
536     return { $class => $field }  if (grep { $_ eq $field } @{$pkg->facet_fields->{$class}});
537
538     push @{$pkg->facet_fields->{$class}}, $field;
539
540     return { $class => $field };
541 }
542
543 =head2 facet_fields
544
545     $fields = $QParser->facet_fields($class);
546
547 Returns arrayref with list of fields for specified facet class.
548 =cut
549
550 sub facet_fields {
551     my $class = shift;
552     $class = ref($class) || $class;
553
554     $parser_config{$class}{facet_fields} ||= {};
555     return $parser_config{$class}{facet_fields};
556 }
557
558 =head2 add_search_field
559
560     $QParser->add_search_field($class, $field);
561
562 Adds the specified field (and facet class if it doesn't already exist)
563 to the configuration.
564 =cut
565
566 sub add_search_field {
567     my $pkg = shift;
568     $pkg = ref($pkg) || $pkg;
569     my $class = shift;
570     my $field = shift;
571
572     $pkg->add_search_class( $class );
573
574     return { $class => $field }  if (grep { $_ eq $field } @{$pkg->search_fields->{$class}});
575
576     push @{$pkg->search_fields->{$class}}, $field;
577
578     return { $class => $field };
579 }
580
581 =head2 search_fields
582
583     $fields = $QParser->search_fields();
584
585 Returns arrayref with list of configured search fields.
586 =cut
587
588 sub search_fields {
589     my $class = shift;
590     $class = ref($class) || $class;
591
592     $parser_config{$class}{fields} ||= {};
593     return $parser_config{$class}{fields};
594 }
595
596 =head2 add_search_class_alias
597
598     $QParser->add_search_class_alias($class, $alias);
599 =cut
600
601 sub add_search_class_alias {
602     my $pkg = shift;
603     $pkg = ref($pkg) || $pkg;
604     my $class = shift;
605     my $alias = shift;
606
607     $pkg->add_search_class( $class );
608
609     return { $class => $alias }  if (grep { $_ eq $alias } @{$pkg->search_class_aliases->{$class}});
610
611     push @{$pkg->search_class_aliases->{$class}}, $alias;
612
613     return { $class => $alias };
614 }
615
616 =head2 search_class_aliases
617
618     $aliases = $QParser->search_class_aliases($class);
619 =cut
620
621 sub search_class_aliases {
622     my $class = shift;
623     $class = ref($class) || $class;
624
625     $parser_config{$class}{class_map} ||= {};
626     return $parser_config{$class}{class_map};
627 }
628
629 =head2 add_search_field_alias
630
631     $QParser->add_search_field_alias($class, $field, $alias);
632 =cut
633
634 sub add_search_field_alias {
635     my $pkg = shift;
636     $pkg = ref($pkg) || $pkg;
637     my $class = shift;
638     my $field = shift;
639     my $alias = shift;
640
641     return { $class => { $field => $alias } }  if (grep { $_ eq $alias } @{$pkg->search_field_aliases->{$class}{$field}});
642
643     push @{$pkg->search_field_aliases->{$class}{$field}}, $alias;
644
645     return { $class => { $field => $alias } };
646 }
647
648 =head2 search_field_aliases
649
650     $aliases = $QParser->search_field_aliases();
651 =cut
652
653 sub search_field_aliases {
654     my $class = shift;
655     $class = ref($class) || $class;
656
657     $parser_config{$class}{field_alias_map} ||= {};
658     return $parser_config{$class}{field_alias_map};
659 }
660
661 =head2 remove_facet_field
662
663     $QParser->remove_facet_field($class, $field);
664 =cut
665
666 sub remove_facet_field {
667     my $pkg = shift;
668     $pkg = ref($pkg) || $pkg;
669     my $class = shift;
670     my $field = shift;
671
672     return { $class => $field }  if (!$pkg->facet_fields->{$class} || !grep { $_ eq $field } @{$pkg->facet_fields->{$class}});
673
674     $pkg->facet_fields->{$class} = [ grep { $_ ne $field } @{$pkg->facet_fields->{$class}} ];
675
676     return { $class => $field };
677 }
678
679 =head2 remove_search_field
680
681     $QParser->remove_search_field($class, $field);
682 =cut
683
684 sub remove_search_field {
685     my $pkg = shift;
686     $pkg = ref($pkg) || $pkg;
687     my $class = shift;
688     my $field = shift;
689
690     return { $class => $field }  if (!$pkg->search_fields->{$class} || !grep { $_ eq $field } @{$pkg->search_fields->{$class}});
691
692     $pkg->search_fields->{$class} = [ grep { $_ ne $field } @{$pkg->search_fields->{$class}} ];
693
694     return { $class => $field };
695 }
696
697 =head2 remove_search_field_alias
698
699     $QParser->remove_search_field_alias($class, $field, $alias);
700 =cut
701
702 sub remove_search_field_alias {
703     my $pkg = shift;
704     $pkg = ref($pkg) || $pkg;
705     my $class = shift;
706     my $field = shift;
707     my $alias = shift;
708
709     return { $class => { $field => $alias } }  if (!$pkg->search_field_aliases->{$class}{$field} || !grep { $_ eq $alias } @{$pkg->search_field_aliases->{$class}{$field}});
710
711     $pkg->search_field_aliases->{$class}{$field} = [ grep { $_ ne $alias } @{$pkg->search_field_aliases->{$class}{$field}} ];
712
713     return { $class => { $field => $alias } };
714 }
715
716 =head2 remove_search_class_alias
717
718     $QParser->remove_search_class_alias($class, $alias);
719 =cut
720
721 sub remove_search_class_alias {
722     my $pkg = shift;
723     $pkg = ref($pkg) || $pkg;
724     my $class = shift;
725     my $alias = shift;
726
727     return { $class => $alias }  if (!$pkg->search_class_aliases->{$class} || !grep { $_ eq $alias } @{$pkg->search_class_aliases->{$class}});
728
729     $pkg->search_class_aliases->{$class} = [ grep { $_ ne $alias } @{$pkg->search_class_aliases->{$class}} ];
730
731     return { $class => $alias };
732 }
733
734 =head2 debug
735
736     $debug = $QParser->debug([$debug]);
737
738 Return or set whether debugging output is enabled.
739 =cut
740
741 sub debug {
742     my $self = shift;
743     my $q = shift;
744     $self->{_debug} = $q if (defined $q);
745     return $self->{_debug};
746 }
747
748 =head2 query
749
750     $query = $QParser->query([$query]);
751
752 Return or set the query.
753 =cut
754
755 sub query {
756     my $self = shift;
757     my $q = shift;
758     $self->{_query} = " $q " if (defined $q);
759     return $self->{_query};
760 }
761
762 =head2 parse_tree
763
764     $parse_tree = $QParser->parse_tree([$parse_tree]);
765
766 Return or set the parse tree associated with the QueryParser.
767 =cut
768
769 sub parse_tree {
770     my $self = shift;
771     my $q = shift;
772     $self->{_parse_tree} = $q if (defined $q);
773     return $self->{_parse_tree};
774 }
775
776 sub floating_plan {
777     my $self = shift;
778     my $q = shift;
779     $self->{_top} = $q if (defined $q);
780     return $self->{_top};
781 }
782
783 =head2 parse
784
785     $QParser->parse([$query]);
786
787 Parse the specified query, or the query already associated with the QueryParser
788 object.
789 =cut
790
791 sub parse {
792     my $self = shift;
793     my $pkg = ref($self) || $self;
794     warn " ** parse package is $pkg\n" if $self->debug;
795 #    $self->parse_tree(
796 #        $self->decompose(
797 #            $self->query( shift() )
798 #        )
799 #    );
800
801     $self->decompose( $self->query( shift() ) );
802
803     if ($self->floating_plan) {
804         $self->floating_plan->add_node( $self->parse_tree );
805         $self->parse_tree( $self->floating_plan );
806     }
807
808     $self->parse_tree->plan_level(0);
809
810     return $self;
811 }
812
813 =head2 decompose
814
815     ($struct, $remainder) = $QParser->decompose($querystring, [$current_class], [$recursing], [$phrase_helper]);
816
817 This routine does the heavy work of parsing the query string recursively.
818 Returns the top level query plan, or the query plan from a lower level plus
819 the portion of the query string that needs to be processed at a higher level.
820 =cut
821
822 our $last_class = '';
823 our $last_type = '';
824 our $floating = 0;
825 our $fstart;
826
827 sub decompose {
828     my $self = shift;
829     my $pkg = ref($self) || $self;
830
831
832     $_ = shift;
833     my $current_class = shift || $self->default_search_class;
834
835     my $recursing = shift || 0;
836     my $phrase_helper = shift || 0;
837
838     # Build the search class+field uber-regexp
839     my $search_class_re = '^\s*(';
840     my $first_class = 1;
841
842     warn '  'x$recursing." ** decompose package is $pkg\n" if $self->debug;
843
844     my %seen_classes;
845     for my $class ( keys %{$pkg->search_field_aliases} ) {
846         warn '  'x$recursing." *** ... Looking for search fields in $class\n" if $self->debug;
847
848         for my $field ( keys %{$pkg->search_field_aliases->{$class}} ) {
849             warn '  'x$recursing." *** ... Looking for aliases of $field\n" if $self->debug;
850
851             for my $alias ( @{$pkg->search_field_aliases->{$class}{$field}} ) {
852                 my $aliasr = qr/$alias/;
853                 s/(^|\s+)$aliasr\|/$1$class\|$field#$alias\|/g;
854                 s/(^|\s+)$aliasr[:=]/$1$class\|$field#$alias:/g;
855                 warn '  'x$recursing." *** Rewriting: $alias ($aliasr) as $class\|$field\n" if $self->debug;
856             }
857         }
858
859         $search_class_re .= '|' unless ($first_class);
860         $first_class = 0;
861         $search_class_re .= $class . '(?:[|#][^:|]+)*';
862         $seen_classes{$class} = 1;
863     }
864
865     for my $class ( keys %{$pkg->search_class_aliases} ) {
866
867         for my $alias ( @{$pkg->search_class_aliases->{$class}} ) {
868             my $aliasr = qr/$alias/;
869             s/(^|[^|])\b$aliasr\|/$1$class#$alias\|/g;
870             s/(^|[^|])\b$aliasr[:=]/$1$class#$alias:/g;
871             warn '  'x$recursing." *** Rewriting: $alias ($aliasr) as $class\n" if $self->debug;
872         }
873
874         if (!$seen_classes{$class}) {
875             $search_class_re .= '|' unless ($first_class);
876             $first_class = 0;
877
878             $search_class_re .= $class . '(?:[|#][^:|]+)*';
879             $seen_classes{$class} = 1;
880         }
881     }
882     $search_class_re .= '):';
883
884     warn '  'x$recursing." ** Rewritten query: $_\n" if $self->debug;
885     warn '  'x$recursing." ** Search class RE: $search_class_re\n" if $self->debug;
886
887     my $required_op = $pkg->operator('required');
888     my $required_re = qr/\Q$required_op\E/;
889
890     my $disallowed_op = $pkg->operator('disallowed');
891     my $disallowed_re = qr/\Q$disallowed_op\E/;
892
893     my $and_op = $pkg->operator('and');
894     my $and_re = qr/^\s*\Q$and_op\E/;
895
896     my $or_op = $pkg->operator('or');
897     my $or_re = qr/^\s*\Q$or_op\E/;
898
899     my $group_start = $pkg->operator('group_start');
900     my $group_start_re = qr/^\s*\Q$group_start\E/;
901
902     my $group_end = $pkg->operator('group_end');
903     my $group_end_re = qr/^\s*\Q$group_end\E/;
904
905     my $float_start = $pkg->operator('float_start');
906     my $float_start_re = qr/^\s*\Q$float_start\E/;
907
908     my $float_end = $pkg->operator('float_end');
909     my $float_end_re = qr/^\s*\Q$float_end\E/;
910
911     my $modifier_tag = $pkg->operator('modifier');
912     my $modifier_tag_re = qr/^\s*\Q$modifier_tag\E/;
913
914     my $negated_op = $pkg->operator('negated');
915     my $negated_re = qr/\Q$negated_op\E/;
916
917     # Group start/end normally are ( and ), but can be overridden.
918     # We thus include ( and ) specifically due to filters, as well as : for classes.
919     my $phrase_cleanup_re = qr/\s*(\Q$required_op\E|\Q$disallowed_op\E|\Q$and_op\E|\Q$or_op\E|\Q$group_start\E|\Q$group_end\E|\Q$float_start\E|\Q$float_end\E|\Q$modifier_tag\E|\Q$negated_op\E|:|\(|\))/;
920
921     # Build the filter and modifier uber-regexps
922     my $facet_re = '^\s*(-?)((?:' . join( '|', @{$pkg->facet_classes}) . ')(?:\|\w+)*)\[(.+?)\]';
923     warn '  'x$recursing." ** Facet RE: $facet_re\n" if $self->debug;
924
925     my $filter_re = '^\s*(-?)(' . join( '|', @{$pkg->filters}) . ')\(([^()]+)\)';
926     my $filter_as_class_re = '^\s*(-?)(' . join( '|', @{$pkg->filters}) . '):\s*(\S+)';
927
928     my $modifier_re = '^\s*'.$modifier_tag_re.'(' . join( '|', @{$pkg->modifiers}) . ')\b';
929     my $modifier_as_class_re = '^\s*(' . join( '|', @{$pkg->modifiers}) . '):\s*(\S+)';
930
931     my $struct = shift || $self->new_plan( level => $recursing );
932     $self->parse_tree( $struct ) if (!$self->parse_tree);
933
934     my $remainder = '';
935
936     while (!$remainder) {
937         warn '  'x$recursing."Start of the loop. last_type: $last_type, joiner: ".$struct->joiner.", struct: $struct\n" if $self->debug;
938         if ($last_type eq 'FEND' and $fstart and $fstart !=  $struct) { # fall back further
939             $remainder = $_;
940             last;
941         } elsif ($last_type eq 'FEND') {
942             $fstart = undef;
943             $last_type = '';
944         }
945
946         if (/^\s*$/) { # end of an explicit group
947             local $last_type = '';
948             last;
949         } elsif (/$float_end_re/) { # end of an explicit group
950             warn '  'x$recursing."Encountered explicit float end, remainder: $'\n" if $self->debug;
951
952             $remainder = $';
953             $_ = '';
954
955             $floating = 0;
956             $last_type = 'FEND';
957             last;
958         } elsif (/$group_end_re/) { # end of an explicit group
959             warn '  'x$recursing."Encountered explicit group end, remainder: $'\n" if $self->debug;
960
961             $remainder = $';
962             $_ = '';
963
964             local $last_type = '';
965         } elsif ($self->filter_count && /$filter_re/) { # found a filter
966             warn '  'x$recursing."Encountered search filter: $1$2 set to $3\n" if $self->debug;
967
968             my $negate = ($1 eq $pkg->operator('disallowed')) ? 1 : 0;
969             $_ = $';
970
971             my $filter = $2;
972             my $params = [ split '[,]+', $3 ];
973
974             if ($pkg->filter_callbacks->{$filter}) {
975                 my $replacement = $pkg->filter_callbacks->{$filter}->($self, $struct, $filter, $params, $negate);
976                 $_ = "$replacement $_" if ($replacement);
977             } else {
978                 $struct->new_filter( $filter => $params, $negate );
979             }
980
981
982             local $last_type = '';
983         } elsif ($self->filter_count && /$filter_as_class_re/) { # found a filter
984             warn '  'x$recursing."Encountered search filter: $1$2 set to $3\n" if $self->debug;
985
986             my $negate = ($1 eq $pkg->operator('disallowed')) ? 1 : 0;
987             $_ = $';
988
989             my $filter = $2;
990             my $params = [ split '[,]+', $3 ];
991
992             if ($pkg->filter_callbacks->{$filter}) {
993                 my $replacement = $pkg->filter_callbacks->{$filter}->($self, $struct, $filter, $params, $negate);
994                 $_ = "$replacement $_" if ($replacement);
995             } else {
996                 $struct->new_filter( $filter => $params, $negate );
997             }
998
999             local $last_type = '';
1000         } elsif ($self->modifier_count && /$modifier_re/) { # found a modifier
1001             warn '  'x$recursing."Encountered search modifier: $1\n" if $self->debug;
1002
1003             $_ = $';
1004             if (!($struct->top_plan || $parser_config{$pkg}->{allow_nested_modifiers})) {
1005                 warn '  'x$recursing."  Search modifiers only allowed at the top level of the query\n" if $self->debug;
1006             } else {
1007                 $struct->new_modifier($1);
1008             }
1009
1010             local $last_type = '';
1011         } elsif ($self->modifier_count && /$modifier_as_class_re/) { # found a modifier
1012             warn '  'x$recursing."Encountered search modifier: $1\n" if $self->debug;
1013
1014             my $mod = $1;
1015
1016             $_ = $';
1017             if (!($struct->top_plan || $parser_config{$pkg}->{allow_nested_modifiers})) {
1018                 warn '  'x$recursing."  Search modifiers only allowed at the top level of the query\n" if $self->debug;
1019             } elsif ($2 =~ /^[ty1]/i) {
1020                 $struct->new_modifier($mod);
1021             }
1022
1023             local $last_type = '';
1024         } elsif (/$float_start_re/) { # start of an explicit float
1025             warn '  'x$recursing."Encountered explicit float start\n" if $self->debug;
1026             $floating = 1;
1027             $fstart = $struct;
1028
1029             $last_class = $current_class;
1030             $current_class = undef;
1031
1032             $self->floating_plan( $self->new_plan( floating => 1 ) ) if (!$self->floating_plan);
1033
1034             # pass the floating_plan struct to be modified by the float'ed chunk
1035             my ($floating_plan, $subremainder) = $self->new( debug => $self->debug )->decompose( $', undef, undef, undef,  $self->floating_plan);
1036             $_ = $subremainder;
1037             warn '  'x$recursing."Remainder after explicit float: $_\n" if $self->debug;
1038
1039             $current_class = $last_class;
1040
1041             $last_type = '';
1042         } elsif (/$group_start_re/) { # start of an explicit group
1043             warn '  'x$recursing."Encountered explicit group start\n" if $self->debug;
1044
1045             my ($substruct, $subremainder) = $self->decompose( $', $current_class, $recursing + 1 );
1046             $struct->add_node( $substruct ) if ($substruct);
1047             $_ = $subremainder;
1048             warn '  'x$recursing."Query remainder after bool group: $_\n" if $self->debug;
1049
1050             local $last_type = '';
1051
1052         } elsif (/$and_re/) { # ANDed expression
1053             $_ = $';
1054             warn '  'x$recursing."Encountered AND\n" if $self->debug;
1055             do {warn '  'x$recursing."!!! Already doing the bool dance for AND\n" if $self->debug; next} if ($last_type eq 'AND');
1056             do {warn '  'x$recursing."!!! Already doing the bool dance for OR\n" if $self->debug; next} if ($last_type eq 'OR');
1057             local $last_type = 'AND';
1058
1059             warn '  'x$recursing."Saving LHS, building RHS\n" if $self->debug;
1060             my $LHS = $struct;
1061             #my ($RHS, $subremainder) = $self->decompose( "$group_start $_ $group_end", $current_class, $recursing + 1 );
1062             my ($RHS, $subremainder) = $self->decompose( $_, $current_class, $recursing + 1 );
1063             $_ = $subremainder;
1064
1065             warn '  'x$recursing."RHS built\n" if $self->debug;
1066             warn '  'x$recursing."Post-AND remainder: $subremainder\n" if $self->debug;
1067
1068             my $wrapper = $self->new_plan( level => $recursing + 1 );
1069
1070             if ($LHS->floating) {
1071                 $wrapper->{query} = $LHS->{query};
1072                 my $outer_wrapper = $self->new_plan( level => $recursing + 1 );
1073                 $outer_wrapper->add_node($_) for ($wrapper,$RHS);
1074                 $LHS->{query} = [$outer_wrapper];
1075                 $struct = $LHS;
1076             } else {
1077                 $wrapper->add_node($_) for ($LHS, $RHS);
1078                 $wrapper->plan_level($wrapper->plan_level); # reset levels all the way down
1079                 $struct = $self->new_plan( level => $recursing );
1080                 $struct->add_node($wrapper);
1081             }
1082
1083             $self->parse_tree( $struct ) if ($self->parse_tree == $LHS);
1084
1085             local $last_type = '';
1086         } elsif (/$or_re/) { # ORed expression
1087             $_ = $';
1088             warn '  'x$recursing."Encountered OR\n" if $self->debug;
1089             do {warn '  'x$recursing."!!! Already doing the bool dance for AND\n" if $self->debug; next} if ($last_type eq 'AND');
1090             do {warn '  'x$recursing."!!! Already doing the bool dance for OR\n" if $self->debug; next} if ($last_type eq 'OR');
1091             local $last_type = 'OR';
1092
1093             warn '  'x$recursing."Saving LHS, building RHS\n" if $self->debug;
1094             my $LHS = $struct;
1095             #my ($RHS, $subremainder) = $self->decompose( "$group_start $_ $group_end", $current_class, $recursing + 1 );
1096             my ($RHS, $subremainder) = $self->decompose( $_, $current_class, $recursing + 2 );
1097             $_ = $subremainder;
1098
1099             warn '  'x$recursing."RHS built\n" if $self->debug;
1100             warn '  'x$recursing."Post-OR remainder: $subremainder\n" if $self->debug;
1101
1102             my $wrapper = $self->new_plan( level => $recursing + 1, joiner => '|' );
1103
1104             if ($LHS->floating) {
1105                 $wrapper->{query} = $LHS->{query};
1106                 my $outer_wrapper = $self->new_plan( level => $recursing + 1, joiner => '|' );
1107                 $outer_wrapper->add_node($_) for ($wrapper,$RHS);
1108                 $LHS->{query} = [$outer_wrapper];
1109                 $struct = $LHS;
1110             } else {
1111                 $wrapper->add_node($_) for ($LHS, $RHS);
1112                 $wrapper->plan_level($wrapper->plan_level); # reset levels all the way down
1113                 $struct = $self->new_plan( level => $recursing );
1114                 $struct->add_node($wrapper);
1115             }
1116
1117             $self->parse_tree( $struct ) if ($self->parse_tree == $LHS);
1118
1119             local $last_type = '';
1120         } elsif ($self->facet_class_count && /$facet_re/) { # changing current class
1121             warn '  'x$recursing."Encountered facet: $1$2 => $3\n" if $self->debug;
1122
1123             my $negate = ($1 eq $pkg->operator('disallowed')) ? 1 : 0;
1124             my $facet = $2;
1125             my $facet_value = [ split '\s*#\s*', $3 ];
1126             $struct->new_facet( $facet => $facet_value, $negate );
1127             $_ = $';
1128
1129             local $last_type = '';
1130         } elsif ($self->search_class_count && /$search_class_re/) { # changing current class
1131
1132             if ($last_type eq 'CLASS') {
1133                 $struct->remove_last_node( $current_class );
1134                 warn '  'x$recursing."Encountered class change with no searches!\n" if $self->debug;
1135             }
1136
1137             warn '  'x$recursing."Encountered class change: $1\n" if $self->debug;
1138
1139             $current_class = $struct->classed_node( $1 )->requested_class();
1140             $_ = $';
1141
1142             local $last_type = 'CLASS';
1143         } elsif (/^\s*($required_re|$disallowed_re)?"([^"]+)"/) { # phrase, always anded
1144             warn '  'x$recursing.'Encountered' . ($1 ? " ['$1' modified]" : '') . " phrase: $2\n" if $self->debug;
1145
1146             my $req_ness = $1 || '';
1147             my $phrase = $2;
1148
1149             if (!$phrase_helper) {
1150                 warn '  'x$recursing."Recursing into decompose with the phrase as a subquery\n" if $self->debug;
1151                 my $after = $';
1152                 my ($substruct, $subremainder) = $self->decompose( qq/$req_ness"$phrase"/, $current_class, $recursing + 1, 1 );
1153                 $struct->add_node( $substruct ) if ($substruct);
1154                 $_ = $after;
1155             } else {
1156                 warn '  'x$recursing."Directly parsing the phrase subquery\n" if $self->debug;
1157                 $struct->joiner( '&' );
1158
1159                 my $class_node = $struct->classed_node($current_class);
1160
1161                 if ($req_ness eq $disallowed_op) {
1162                     $class_node->negate(1);
1163                 }
1164                 $class_node->add_phrase( $phrase );
1165
1166                 # Cleanup the phrase to make it so that we don't parse things in it as anything other than atoms
1167                 $phrase =~ s/$phrase_cleanup_re/ /g;
1168
1169                 $_ = $phrase . $';
1170
1171             }
1172
1173             local $last_type = '';
1174
1175         } elsif (/^\s*($required_re|$disallowed_re)([^${group_end}${float_end}\s"]+)/) { # convert require/disallow word to {un}phrase
1176             warn '  'x$recursing."Encountered required atom (mini phrase), transforming for phrase parse: $1\n" if $self->debug;
1177
1178             $_ = $1 . '"' . $2 . '"' . $';
1179
1180             local $last_type = '';
1181         } elsif (/^\s*([^${group_end}${float_end}\s]+)/o) { # atom
1182             warn '  'x$recursing."Encountered atom: $1\n" if $self->debug;
1183             warn '  'x$recursing."Remainder: $'\n" if $self->debug;
1184
1185             my $atom = $1;
1186             my $after = $';
1187
1188             $_ = $after;
1189             local $last_type = '';
1190
1191             my $class_node = $struct->classed_node($current_class);
1192
1193             my $prefix = ($atom =~ s/^$negated_re//o) ? '!' : '';
1194             my $truncate = ($atom =~ s/\*$//o) ? '*' : '';
1195
1196             if ($atom ne '' and !grep { $atom =~ /^\Q$_\E+$/ } ('&','|')) { # throw away & and |, not allowed in tsquery, and not really useful anyway
1197 #                $class_node->add_phrase( $atom ) if ($atom =~ s/^$required_re//o);
1198
1199                 $class_node->add_fts_atom( $atom, suffix => $truncate, prefix => $prefix, node => $class_node );
1200                 $struct->joiner( '&' );
1201             }
1202
1203             local $last_type = '';
1204         } 
1205
1206         last unless ($_);
1207
1208     }
1209
1210     $struct = undef if 
1211         scalar(@{$struct->query_nodes}) == 0 &&
1212         scalar(@{$struct->filters}) == 0 &&
1213         !$struct->top_plan;
1214
1215     return $struct if !wantarray;
1216     return ($struct, $remainder);
1217 }
1218
1219 =head2 find_class_index
1220
1221     $index = $QParser->find_class_index($class, $query);
1222 =cut
1223
1224 sub find_class_index {
1225     my $class = shift;
1226     my $query = shift;
1227
1228     my ($class_part, @field_parts) = split '\|', $class;
1229     $class_part ||= $class;
1230
1231     for my $idx ( 0 .. scalar(@$query) - 1 ) {
1232         next unless ref($$query[$idx]);
1233         return $idx if ( $$query[$idx]{requested_class} && $class eq $$query[$idx]{requested_class} );
1234     }
1235
1236     push(@$query, { classname => $class_part, (@field_parts ? (fields => \@field_parts) : ()), requested_class => $class, ftsquery => [], phrases => [] });
1237     return -1;
1238 }
1239
1240 =head2 core_limit
1241
1242     $limit = $QParser->core_limit([$limit]);
1243
1244 Return and/or set the core_limit.
1245 =cut
1246
1247 sub core_limit {
1248     my $self = shift;
1249     my $l = shift;
1250     $self->{core_limit} = $l if ($l);
1251     return $self->{core_limit};
1252 }
1253
1254 =head2 superpage
1255
1256     $superpage = $QParser->superpage([$superpage]);
1257
1258 Return and/or set the superpage.
1259 =cut
1260
1261 sub superpage {
1262     my $self = shift;
1263     my $l = shift;
1264     $self->{superpage} = $l if ($l);
1265     return $self->{superpage};
1266 }
1267
1268 =head2 superpage_size
1269
1270     $size = $QParser->superpage_size([$size]);
1271
1272 Return and/or set the superpage size.
1273 =cut
1274
1275 sub superpage_size {
1276     my $self = shift;
1277     my $l = shift;
1278     $self->{superpage_size} = $l if ($l);
1279     return $self->{superpage_size};
1280 }
1281
1282
1283 #-------------------------------
1284 package QueryParser::_util;
1285
1286 # At this level, joiners are always & or |.  This is not
1287 # the external, configurable representation of joiners that
1288 # defaults to # && and ||.
1289 sub is_joiner {
1290     my $str = shift;
1291
1292     return (not ref $str and ($str eq '&' or $str eq '|'));
1293 }
1294
1295 sub default_joiner { '&' }
1296
1297 # 0 for different, 1 for the same.
1298 sub compare_abstract_atoms {
1299     my ($left, $right) = @_;
1300
1301     foreach (qw/prefix suffix content/) {
1302         no warnings;    # undef can stand in for '' here
1303         return 0 unless $left->{$_} eq $right->{$_};
1304     }
1305
1306     return 1;
1307 }
1308
1309 sub fake_abstract_atom_from_phrase {
1310     my $phrase = shift;
1311     my $neg = shift;
1312     my $qp_class = shift || 'QueryParser';
1313
1314     my $prefix = '"';
1315     if ($neg) {
1316         $prefix =
1317             $QueryParser::parser_config{$qp_class}{operators}{disallowed} .
1318             $prefix;
1319     }
1320
1321     return {
1322         "type" => "atom", "prefix" => $prefix, "suffix" => '"',
1323         "content" => $phrase
1324     }
1325 }
1326
1327 sub find_arrays_in_abstract {
1328     my ($hash) = @_;
1329
1330     my @arrays;
1331     foreach my $key (keys %$hash) {
1332         if (ref $hash->{$key} eq "ARRAY") {
1333             push @arrays, $hash->{$key};
1334             foreach (@{$hash->{$key}}) {
1335                 push @arrays, find_arrays_in_abstract($_);
1336             }
1337         }
1338     }
1339
1340     return @arrays;
1341 }
1342
1343 #-------------------------------
1344 package QueryParser::Canonicalize;  # not OO
1345 use Data::Dumper;
1346
1347 sub _abstract_query2str_filter {
1348     my $f = shift;
1349     my $qp_class = shift || 'QueryParser';
1350     my $qpconfig = $QueryParser::parser_config{$qp_class};
1351
1352     return sprintf(
1353         '%s%s(%s)',
1354         $f->{negate} ? $qpconfig->{operators}{disallowed} : "",
1355         $f->{name},
1356         join(",", @{$f->{args}})
1357     );
1358 }
1359
1360 sub _abstract_query2str_modifier {
1361     my $f = shift;
1362     my $qp_class = shift || 'QueryParser';
1363     my $qpconfig = $QueryParser::parser_config{$qp_class};
1364
1365     return $qpconfig->{operators}{modifier} . $f;
1366 }
1367
1368 sub _kid_list {
1369     my $children = shift;
1370     my $op = (keys %$children)[0];
1371     return @{$$children{$op}};
1372 }
1373
1374
1375 # This should produce an equivalent query to the original, given an
1376 # abstract_query.
1377 sub abstract_query2str_impl {
1378     my $abstract_query  = shift;
1379     my $depth = shift || 0;
1380
1381     my $qp_class ||= shift || 'QueryParser';
1382     my $force_qp_node = shift || 0;
1383     my $qpconfig = $QueryParser::parser_config{$qp_class};
1384
1385     my $fs = $qpconfig->{operators}{float_start};
1386     my $fe = $qpconfig->{operators}{float_end};
1387     my $gs = $qpconfig->{operators}{group_start};
1388     my $ge = $qpconfig->{operators}{group_end};
1389     my $and = $qpconfig->{operators}{and};
1390     my $or = $qpconfig->{operators}{or};
1391
1392     my $isnode = 0;
1393     my $size = 0;
1394     my $q = "";
1395
1396     if (exists $abstract_query->{type}) {
1397         if ($abstract_query->{type} eq 'query_plan') {
1398             $q .= join(" ", map { _abstract_query2str_filter($_, $qp_class) } @{$abstract_query->{filters}}) if
1399                 exists $abstract_query->{filters};
1400
1401             $q .= ($q ? ' ' : '') . join(" ", map { _abstract_query2str_modifier($_, $qp_class) } @{$abstract_query->{modifiers}}) if
1402                 exists $abstract_query->{modifiers};
1403
1404             $size = _kid_list($abstract_query->{children});
1405             $isnode = 1 if ($size > 1 and ($force_qp_node or $depth));
1406             #warn "size: $size, depth: $depth, isnode: $isnode, AQ: ".Dumper($abstract_query);
1407         } elsif ($abstract_query->{type} eq 'node') {
1408             if ($abstract_query->{alias}) {
1409                 $q .= ($q ? ' ' : '') . $abstract_query->{alias};
1410                 $q .= "|$_" foreach @{$abstract_query->{alias_fields}};
1411             } else {
1412                 $q .= ($q ? ' ' : '') . $abstract_query->{class};
1413                 $q .= "|$_" foreach @{$abstract_query->{fields}};
1414             }
1415             $q .= ":";
1416             $isnode = 1;
1417         } elsif ($abstract_query->{type} eq 'atom') {
1418             my $prefix = $abstract_query->{prefix} || '';
1419             $prefix = $qpconfig->{operators}{negated} if $prefix eq '!';
1420             $q .= ($q ? ' ' : '') . $prefix .
1421                 ($abstract_query->{content} || '') .
1422                 ($abstract_query->{suffix} || '');
1423         } elsif ($abstract_query->{type} eq 'facet') {
1424             # facet syntax [ # ] is hardcoded I guess?
1425             my $prefix = $abstract_query->{negate} ? $qpconfig->{operators}{disallowed} : '';
1426             $q .= ($q ? ' ' : '') . $prefix . $abstract_query->{name} . "[" .
1427                 join(" # ", @{$abstract_query->{values}}) . "]";
1428         }
1429     }
1430
1431     my $next_depth = int($size > 1);
1432
1433     if (exists $abstract_query->{children}) {
1434
1435         my $op = (keys(%{$abstract_query->{children}}))[0];
1436
1437         if ($abstract_query->{floating}) { # always the top node!
1438             my $sub_node = pop @{$abstract_query->{children}{$op}};
1439
1440             $abstract_query->{floating} = 0;
1441             $q = $fs . " " . abstract_query2str_impl($abstract_query,0,$qp_class, 1) . $fe. " ";
1442
1443             $abstract_query = $sub_node;
1444         }
1445
1446         if ($abstract_query && exists $abstract_query->{children}) {
1447             $op = (keys(%{$abstract_query->{children}}))[0];
1448             $q .= ($q ? ' ' : '') . join(
1449                 ($op eq '&' ? ' ' : " $or "),
1450                 map {
1451                     my $x = abstract_query2str_impl($_, $depth + $next_depth, $qp_class, $force_qp_node); $x =~ s/^\s+//; $x =~ s/\s+$//; $x;
1452                 } @{$abstract_query->{children}{$op}}
1453             );
1454         }
1455     } elsif ($abstract_query->{'&'} or $abstract_query->{'|'}) {
1456         my $op = (keys(%{$abstract_query}))[0];
1457         $q .= ($q ? ' ' : '') . join(
1458             ($op eq '&' ? ' ' : " $or "),
1459             map {
1460                     my $x = abstract_query2str_impl($_, $depth + $next_depth, $qp_class, $force_qp_node); $x =~ s/^\s+//; $x =~ s/\s+$//; $x;
1461             } @{$abstract_query->{$op}}
1462         );
1463     }
1464
1465     $q = "$gs$q$ge" if ($isnode);
1466
1467     return $q;
1468 }
1469
1470 #-------------------------------
1471 package QueryParser::query_plan;
1472
1473 sub QueryParser {
1474     my $self = shift;
1475     return undef unless ref($self);
1476     return $self->{QueryParser};
1477 }
1478
1479 sub new {
1480     my $pkg = shift;
1481     $pkg = ref($pkg) || $pkg;
1482     my %args = (query => [], joiner => '&', @_);
1483
1484     return bless \%args => $pkg;
1485 }
1486
1487 sub new_node {
1488     my $self = shift;
1489     my $pkg = ref($self) || $self;
1490     my $node = do{$pkg.'::node'}->new( plan => $self, @_ );
1491     $self->add_node( $node );
1492     return $node;
1493 }
1494
1495 sub new_facet {
1496     my $self = shift;
1497     my $pkg = ref($self) || $self;
1498     my $name = shift;
1499     my $args = shift;
1500     my $negate = shift;
1501
1502     my $node = do{$pkg.'::facet'}->new( plan => $self, name => $name, 'values' => $args, negate => $negate );
1503     $self->add_node( $node );
1504
1505     return $node;
1506 }
1507
1508 sub new_filter {
1509     my $self = shift;
1510     my $pkg = ref($self) || $self;
1511     my $name = shift;
1512     my $args = shift;
1513     my $negate = shift;
1514
1515     my $node = do{$pkg.'::filter'}->new( plan => $self, name => $name, args => $args, negate => $negate );
1516     $self->add_filter( $node );
1517
1518     return $node;
1519 }
1520
1521
1522 sub _merge_filters {
1523     my $left_filter = shift;
1524     my $right_filter = shift;
1525     my $join = shift;
1526
1527     return undef unless $left_filter or $right_filter;
1528     return $right_filter unless $left_filter;
1529     return $left_filter unless $right_filter;
1530
1531     my $args = $left_filter->{args} || [];
1532
1533     if ($join eq '|') {
1534         push(@$args, @{$right_filter->{args}});
1535
1536     } else {
1537         # find the intersect values
1538         my %new_vals;
1539         map { $new_vals{$_} = 1 } @{$right_filter->{args} || []};
1540         $args = [ grep { $new_vals{$_} } @$args ];
1541     }
1542
1543     $left_filter->{args} = $args;
1544     return $left_filter;
1545 }
1546
1547 sub collapse_filters {
1548     my $self = shift;
1549     my $name = shift;
1550
1551     # start by merging any filters at this level.
1552     # like-level filters are always ORed together
1553
1554     my $cur_filter;
1555     my @cur_filters = grep {$_->name eq $name } @{ $self->filters };
1556     if (@cur_filters) {
1557         $cur_filter = shift @cur_filters;
1558         my $args = $cur_filter->{args} || [];
1559         $cur_filter = _merge_filters($cur_filter, $_, '|') for @cur_filters;
1560     }
1561
1562     # next gather the collapsed filters from sub-plans and 
1563     # merge them with our own
1564
1565     my @subquery = @{$self->{query}};
1566
1567     while (@subquery) {
1568         my $blob = shift @subquery;
1569         shift @subquery; # joiner
1570         next unless $blob->isa('QueryParser::query_plan');
1571         my $sub_filter = $blob->collapse_filters($name);
1572         $cur_filter = _merge_filters($cur_filter, $sub_filter, $self->joiner);
1573     }
1574
1575     if ($self->QueryParser->debug) {
1576         my @args = ($cur_filter and $cur_filter->{args}) ? @{$cur_filter->{args}} : ();
1577         warn "collapse_filters($name) => [@args]\n";
1578     }
1579
1580     return $cur_filter;
1581 }
1582
1583 sub find_filter {
1584     my $self = shift;
1585     my $needle = shift;;
1586     return undef unless ($needle);
1587
1588     my $filter = $self->collapse_filters($needle);
1589
1590     warn "find_filter($needle) => " . 
1591         (($filter and $filter->{args}) ? "@{$filter->{args}}" : '[]') . "\n" 
1592         if $self->QueryParser->debug;
1593
1594     return $filter ? ($filter) : ();
1595 }
1596
1597 sub find_modifier {
1598     my $self = shift;
1599     my $needle = shift;;
1600     return undef unless ($needle);
1601     return grep { $_->name eq $needle } @{ $self->modifiers };
1602 }
1603
1604 sub new_modifier {
1605     my $self = shift;
1606     my $pkg = ref($self) || $self;
1607     my $name = shift;
1608
1609     my $node = do{$pkg.'::modifier'}->new( $name );
1610     $self->add_modifier( $node );
1611
1612     return $node;
1613 }
1614
1615 sub classed_node {
1616     my $self = shift;
1617     my $requested_class = shift;
1618
1619     my $node;
1620     for my $n (@{$self->{query}}) {
1621         next unless (ref($n) && $n->isa( 'QueryParser::query_plan::node' ));
1622         if ($n->requested_class eq $requested_class) {
1623             $node = $n;
1624             last;
1625         }
1626     }
1627
1628     if (!$node) {
1629         $node = $self->new_node;
1630         $node->requested_class( $requested_class );
1631     }
1632
1633     return $node;
1634 }
1635
1636 sub remove_last_node {
1637     my $self = shift;
1638     my $requested_class = shift;
1639
1640     my $old = pop(@{$self->query_nodes});
1641     pop(@{$self->query_nodes}) if (@{$self->query_nodes});
1642
1643     return $old;
1644 }
1645
1646 sub query_nodes {
1647     my $self = shift;
1648     return $self->{query};
1649 }
1650
1651 sub floating {
1652     my $self = shift;
1653     my $f = shift;
1654     $self->{floating} = $f if (defined $f);
1655     return $self->{floating};
1656 }
1657
1658 sub add_node {
1659     my $self = shift;
1660     my $node = shift;
1661
1662     $self->{query} ||= [];
1663     push(@{$self->{query}}, $self->joiner) if (@{$self->{query}});
1664     push(@{$self->{query}}, $node);
1665
1666     return $self;
1667 }
1668
1669 sub top_plan {
1670     my $self = shift;
1671
1672     return $self->{level} ? 0 : 1;
1673 }
1674
1675 sub plan_level {
1676     my $self = shift;
1677     my $level = shift;
1678
1679     if (defined $level) {
1680         $self->{level} = $level;
1681         for (@{$self->query_nodes}) {
1682             $_->plan_level($level + 1) if (ref and $_->isa('QueryParser::query_plan'));
1683         }
1684     }
1685             
1686     return $self->{level};
1687 }
1688
1689 sub joiner {
1690     my $self = shift;
1691     my $joiner = shift;
1692
1693     $self->{joiner} = $joiner if ($joiner);
1694     return $self->{joiner};
1695 }
1696
1697 sub modifiers {
1698     my $self = shift;
1699     $self->{modifiers} ||= [];
1700     return $self->{modifiers};
1701 }
1702
1703 sub add_modifier {
1704     my $self = shift;
1705     my $modifier = shift;
1706
1707     $self->{modifiers} ||= [];
1708     $self->{modifiers} = [ grep {$_->name ne $modifier->name} @{$self->{modifiers}} ];
1709
1710     push(@{$self->{modifiers}}, $modifier);
1711
1712     return $self;
1713 }
1714
1715 sub facets {
1716     my $self = shift;
1717     $self->{facets} ||= [];
1718     return $self->{facets};
1719 }
1720
1721 sub add_facet {
1722     my $self = shift;
1723     my $facet = shift;
1724
1725     $self->{facets} ||= [];
1726     $self->{facets} = [ grep {$_->name ne $facet->name} @{$self->{facets}} ];
1727
1728     push(@{$self->{facets}}, $facet);
1729
1730     return $self;
1731 }
1732
1733 sub filters {
1734     my $self = shift;
1735     $self->{filters} ||= [];
1736     return $self->{filters};
1737 }
1738
1739 sub add_filter {
1740     my $self = shift;
1741     my $filter = shift;
1742
1743     $self->{filters} ||= [];
1744
1745     push(@{$self->{filters}}, $filter);
1746
1747     return $self;
1748 }
1749
1750 # %opts supports two options at this time:
1751 #   no_phrases :
1752 #       If true, do not do anything to the phrases
1753 #       fields on any discovered nodes.
1754 #   with_config :
1755 #       If true, also return the query parser config as part of the blob.
1756 #       This will get set back to 0 before recursion to avoid repetition.
1757 sub to_abstract_query {
1758     my $self = shift;
1759     my %opts = @_;
1760
1761     my $pkg = ref $self->QueryParser || $self->QueryParser;
1762
1763     my $abstract_query = {
1764         type => "query_plan",
1765         floating => $self->floating,
1766         level => $self->plan_level,
1767         filters => [map { $_->to_abstract_query } @{$self->filters}],
1768         modifiers => [map { $_->to_abstract_query } @{$self->modifiers}]
1769     };
1770
1771     if ($opts{with_config}) {
1772         $opts{with_config} = 0;
1773         $abstract_query->{config} = $QueryParser::parser_config{$pkg};
1774     }
1775
1776     my $kids = [];
1777
1778     for my $qnode (@{$self->query_nodes}) {
1779         # Remember: qnode can be a joiner string, a node, or another query_plan
1780
1781         if (QueryParser::_util::is_joiner($qnode)) {
1782             if ($abstract_query->{children}) {
1783                 my $open_joiner = (keys(%{$abstract_query->{children}}))[0];
1784                 next if $open_joiner eq $qnode;
1785
1786                 my $oldroot = $abstract_query->{children};
1787                 $kids = [$oldroot];
1788                 $abstract_query->{children} = {$qnode => $kids};
1789             } else {
1790                 $abstract_query->{children} = {$qnode => $kids};
1791             }
1792         } else {
1793             push @$kids, $qnode->to_abstract_query(%opts);
1794         }
1795     }
1796
1797     $abstract_query->{children} ||= { QueryParser::_util::default_joiner() => $kids };
1798     return $abstract_query;
1799 }
1800
1801
1802 #-------------------------------
1803 package QueryParser::query_plan::node;
1804 use Data::Dumper;
1805 $Data::Dumper::Indent = 0;
1806
1807 sub new {
1808     my $pkg = shift;
1809     $pkg = ref($pkg) || $pkg;
1810     my %args = @_;
1811
1812     return bless \%args => $pkg;
1813 }
1814
1815 sub new_atom {
1816     my $self = shift;
1817     my $pkg = ref($self) || $self;
1818     return do{$pkg.'::atom'}->new( @_ );
1819 }
1820
1821 sub requested_class { # also split into classname, fields and alias
1822     my $self = shift;
1823     my $class = shift;
1824
1825     if ($class) {
1826         my @afields;
1827         my (undef, $alias) = split '#', $class;
1828         if ($alias) {
1829             $class =~ s/#[^|]+//;
1830             ($alias, @afields) = split '\|', $alias;
1831         }
1832
1833         my @fields = @afields;
1834         my ($class_part, @field_parts) = split '\|', $class;
1835         for my $f (@field_parts) {
1836              push(@fields, $f) unless (grep { $f eq $_ } @fields);
1837         }
1838
1839         $class_part ||= $class;
1840
1841         $self->{requested_class} = $class;
1842         $self->{alias} = $alias if $alias;
1843         $self->{alias_fields} = \@afields if $alias;
1844         $self->{classname} = $class_part;
1845         $self->{fields} = \@fields;
1846     }
1847
1848     return $self->{requested_class};
1849 }
1850
1851 sub plan {
1852     my $self = shift;
1853     my $plan = shift;
1854
1855     $self->{plan} = $plan if ($plan);
1856     return $self->{plan};
1857 }
1858
1859 sub alias {
1860     my $self = shift;
1861     my $alias = shift;
1862
1863     $self->{alias} = $alias if ($alias);
1864     return $self->{alias};
1865 }
1866
1867 sub alias_fields {
1868     my $self = shift;
1869     my $alias = shift;
1870
1871     $self->{alias_fields} = $alias if ($alias);
1872     return $self->{alias_fields};
1873 }
1874
1875 sub classname {
1876     my $self = shift;
1877     my $class = shift;
1878
1879     $self->{classname} = $class if ($class);
1880     return $self->{classname};
1881 }
1882
1883 sub fields {
1884     my $self = shift;
1885     my @fields = @_;
1886
1887     $self->{fields} ||= [];
1888     $self->{fields} = \@fields if (@fields);
1889     return $self->{fields};
1890 }
1891
1892 sub phrases {
1893     my $self = shift;
1894     my @phrases = @_;
1895
1896     $self->{phrases} ||= [];
1897     $self->{phrases} = \@phrases if (@phrases);
1898     return $self->{phrases};
1899 }
1900
1901 sub add_phrase {
1902     my $self = shift;
1903     my $phrase = shift;
1904
1905     push(@{$self->phrases}, $phrase);
1906
1907     return $self;
1908 }
1909
1910 sub negate {
1911     my $self = shift;
1912     my $negate = shift;
1913
1914     $self->{negate} = $negate if (defined $negate);
1915
1916     return $self->{negate};
1917 }
1918
1919 sub query_atoms {
1920     my $self = shift;
1921     my @query_atoms = @_;
1922
1923     $self->{query_atoms} ||= [];
1924     $self->{query_atoms} = \@query_atoms if (@query_atoms);
1925     return $self->{query_atoms};
1926 }
1927
1928 sub add_fts_atom {
1929     my $self = shift;
1930     my $atom = shift;
1931
1932     if (!ref($atom)) {
1933         my $content = $atom;
1934         my @parts = @_;
1935
1936         $atom = $self->new_atom( content => $content, @parts );
1937     }
1938
1939     push(@{$self->query_atoms}, $self->plan->joiner) if (@{$self->query_atoms});
1940     push(@{$self->query_atoms}, $atom);
1941
1942     return $self;
1943 }
1944
1945 sub add_dummy_atom {
1946     my $self = shift;
1947     my @parts = @_;
1948
1949     my $atom = $self->new_atom( @parts, dummy => 1 );
1950
1951     push(@{$self->query_atoms}, $self->plan->joiner) if (@{$self->query_atoms});
1952     push(@{$self->query_atoms}, $atom);
1953
1954     return $self;
1955 }
1956
1957 # This will find up to one occurence of @$short_list within @$long_list, and
1958 # replace it with the single atom $replacement.
1959 sub replace_phrase_in_abstract_query {
1960     my ($self, $short_list, $long_list, $replacement) = @_;
1961
1962     my $success = 0;
1963     my @already = ();
1964     my $goal = scalar @$short_list;
1965
1966     for (my $i = 0; $i < scalar (@$long_list); $i++) {
1967         my $right = $long_list->[$i];
1968
1969         if (QueryParser::_util::compare_abstract_atoms(
1970             $short_list->[scalar @already], $right
1971         )) {
1972             push @already, $i;
1973         } elsif (scalar @already) {
1974             @already = ();
1975             next;
1976         }
1977
1978         if (scalar @already == $goal) {
1979             splice @$long_list, $already[0], scalar(@already), $replacement;
1980             $success = 1;
1981             last;
1982         }
1983     }
1984
1985     return $success;
1986 }
1987
1988 sub to_abstract_query {
1989     my $self = shift;
1990     my %opts = @_;
1991
1992     my $pkg = ref $self->plan->QueryParser || $self->plan->QueryParser;
1993
1994     my $abstract_query = {
1995         "type" => "node",
1996         "alias" => $self->alias,
1997         "alias_fields" => $self->alias_fields,
1998         "class" => $self->classname,
1999         "fields" => $self->fields
2000     };
2001
2002     my $kids = [];
2003
2004     for my $qatom (@{$self->query_atoms}) {
2005         if (QueryParser::_util::is_joiner($qatom)) {
2006             if ($abstract_query->{children}) {
2007                 my $open_joiner = (keys(%{$abstract_query->{children}}))[0];
2008                 next if $open_joiner eq $qatom;
2009
2010                 my $oldroot = $abstract_query->{children};
2011                 $kids = [$oldroot];
2012                 $abstract_query->{children} = {$qatom => $kids};
2013             } else {
2014                 $abstract_query->{children} = {$qatom => $kids};
2015             }
2016         } else {
2017             push @$kids, $qatom->to_abstract_query;
2018         }
2019     }
2020
2021     $abstract_query->{children} ||= { QueryParser::_util::default_joiner() => $kids };
2022
2023     if ($self->{phrases} and not $opts{no_phrases}) {
2024         for my $phrase (@{$self->{phrases}}) {
2025             # Phrases appear duplication in a real QP tree, and we don't want
2026             # that duplication in our abstract query.  So for all our phrases,
2027             # break them into atoms as QP would, and remove any matching
2028             # sequences of atoms from our abstract query.
2029
2030             my $tmp_prefix = '';
2031             $tmp_prefix = $QueryParser::parser_config{$pkg}{operators}{disallowed} if ($self->{negate});
2032
2033             my $tmptree = $self->{plan}->{QueryParser}->new(query => $tmp_prefix.'"'.$phrase.'"')->parse->parse_tree;
2034             if ($tmptree) {
2035                 # For a well-behaved phrase, we should now have only one node
2036                 # in the $tmptree query plan, and that node should have an
2037                 # orderly list of atoms and joiners.
2038
2039                 if ($tmptree->{query} and scalar(@{$tmptree->{query}}) == 1) {
2040                     my $tmplist;
2041
2042                     eval {
2043                         $tmplist = $tmptree->{query}->[0]->to_abstract_query(
2044                             no_phrases => 1
2045                         )->{children}->{'&'}->[0]->{children}->{'&'};
2046                     };
2047                     next if $@;
2048
2049                     foreach (
2050                         QueryParser::_util::find_arrays_in_abstract($abstract_query->{children})
2051                     ) {
2052                         last if $self->replace_phrase_in_abstract_query(
2053                             $tmplist,
2054                             $_,
2055                             QueryParser::_util::fake_abstract_atom_from_phrase($phrase, $self->{negate}, $pkg)
2056                         );
2057                     }
2058                 }
2059             }
2060         }
2061     }
2062
2063     $abstract_query->{children} ||= { QueryParser::_util::default_joiner() => $kids };
2064     return $abstract_query;
2065 }
2066
2067 #-------------------------------
2068 package QueryParser::query_plan::node::atom;
2069
2070 sub new {
2071     my $pkg = shift;
2072     $pkg = ref($pkg) || $pkg;
2073     my %args = @_;
2074
2075     return bless \%args => $pkg;
2076 }
2077
2078 sub node {
2079     my $self = shift;
2080     return undef unless (ref $self);
2081     return $self->{node};
2082 }
2083
2084 sub content {
2085     my $self = shift;
2086     return undef unless (ref $self);
2087     return $self->{content};
2088 }
2089
2090 sub prefix {
2091     my $self = shift;
2092     return undef unless (ref $self);
2093     return $self->{prefix};
2094 }
2095
2096 sub suffix {
2097     my $self = shift;
2098     return undef unless (ref $self);
2099     return $self->{suffix};
2100 }
2101
2102 sub to_abstract_query {
2103     my ($self) = @_;
2104     
2105     return {
2106         (map { $_ => $self->$_ } qw/prefix suffix content/),
2107         "type" => "atom"
2108     };
2109 }
2110 #-------------------------------
2111 package QueryParser::query_plan::filter;
2112
2113 sub new {
2114     my $pkg = shift;
2115     $pkg = ref($pkg) || $pkg;
2116     my %args = @_;
2117
2118     return bless \%args => $pkg;
2119 }
2120
2121 sub plan {
2122     my $self = shift;
2123     return $self->{plan};
2124 }
2125
2126 sub name {
2127     my $self = shift;
2128     return $self->{name};
2129 }
2130
2131 sub negate {
2132     my $self = shift;
2133     return $self->{negate};
2134 }
2135
2136 sub args {
2137     my $self = shift;
2138     return $self->{args};
2139 }
2140
2141 sub to_abstract_query {
2142     my ($self) = @_;
2143     
2144     return {
2145         map { $_ => $self->$_ } qw/name negate args/
2146     };
2147 }
2148
2149 #-------------------------------
2150 package QueryParser::query_plan::facet;
2151
2152 sub new {
2153     my $pkg = shift;
2154     $pkg = ref($pkg) || $pkg;
2155     my %args = @_;
2156
2157     return bless \%args => $pkg;
2158 }
2159
2160 sub plan {
2161     my $self = shift;
2162     return $self->{plan};
2163 }
2164
2165 sub name {
2166     my $self = shift;
2167     return $self->{name};
2168 }
2169
2170 sub negate {
2171     my $self = shift;
2172     return $self->{negate};
2173 }
2174
2175 sub values {
2176     my $self = shift;
2177     return $self->{'values'};
2178 }
2179
2180 sub to_abstract_query {
2181     my ($self) = @_;
2182
2183     return {
2184         (map { $_ => $self->$_ } qw/name negate values/),
2185         "type" => "facet"
2186     };
2187 }
2188
2189 #-------------------------------
2190 package QueryParser::query_plan::modifier;
2191
2192 sub new {
2193     my $pkg = shift;
2194     $pkg = ref($pkg) || $pkg;
2195     my $modifier = shift;
2196     my $negate = shift;
2197
2198     return bless { name => $modifier, negate => $negate } => $pkg;
2199 }
2200
2201 sub name {
2202     my $self = shift;
2203     return $self->{name};
2204 }
2205
2206 sub negate {
2207     my $self = shift;
2208     return $self->{negate};
2209 }
2210
2211 sub to_abstract_query {
2212     my ($self) = @_;
2213     
2214     return $self->name;
2215 }
2216 1;
2217