]> git.uio.no Git - usit-rt.git/blob - lib/RT/SQL.pm
Initial commit 4.0.5-3
[usit-rt.git] / lib / RT / SQL.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2012 Best Practical Solutions, LLC
6 #                                          <sales@bestpractical.com>
7 #
8 # (Except where explicitly superseded by other copyright notices)
9 #
10 #
11 # LICENSE:
12 #
13 # This work is made available to you under the terms of Version 2 of
14 # the GNU General Public License. A copy of that license should have
15 # been provided with this software, but in any event can be snarfed
16 # from www.gnu.org.
17 #
18 # This work is distributed in the hope that it will be useful, but
19 # WITHOUT ANY WARRANTY; without even the implied warranty of
20 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
21 # General Public License for more details.
22 #
23 # You should have received a copy of the GNU General Public License
24 # along with this program; if not, write to the Free Software
25 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 # 02110-1301 or visit their web page on the internet at
27 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
28 #
29 #
30 # CONTRIBUTION SUBMISSION POLICY:
31 #
32 # (The following paragraph is not intended to limit the rights granted
33 # to you to modify and distribute this software under the terms of
34 # the GNU General Public License and is only of importance to you if
35 # you choose to contribute your changes and enhancements to the
36 # community by submitting them to Best Practical Solutions, LLC.)
37 #
38 # By intentionally submitting any modifications, corrections or
39 # derivatives to this work, or any other work intended for use with
40 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
41 # you are the copyright holder for those contributions and you grant
42 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
43 # royalty-free, perpetual, license to use, copy, create derivative
44 # works based on those contributions, and sublicense and distribute
45 # those contributions and any derivatives thereof.
46 #
47 # END BPS TAGGED BLOCK }}}
48
49 package RT::SQL;
50
51 use strict;
52 use warnings;
53
54
55 use constant HAS_BOOLEAN_PARSER => do {
56     local $@;
57     eval { require Parse::BooleanLogic; 1 }
58 };
59
60 # States
61 use constant VALUE       => 1;
62 use constant AGGREG      => 2;
63 use constant OP          => 4;
64 use constant OPEN_PAREN  => 8;
65 use constant CLOSE_PAREN => 16;
66 use constant KEYWORD     => 32;
67 my @tokens = qw[VALUE AGGREGATOR OPERATOR OPEN_PAREN CLOSE_PAREN KEYWORD];
68
69 use Regexp::Common qw /delimited/;
70 my $re_aggreg      = qr[(?i:AND|OR)];
71 my $re_delim       = qr[$RE{delimited}{-delim=>qq{\'\"}}];
72 my $re_value       = qr[[+-]?\d+|NULL|$re_delim];
73 my $re_keyword     = qr[[{}\w\.]+|$re_delim];
74 my $re_op          = qr[=|!=|>=|<=|>|<|(?i:IS NOT)|(?i:IS)|(?i:NOT LIKE)|(?i:LIKE)|(?i:NOT STARTSWITH)|(?i:STARTSWITH)|(?i:NOT ENDSWITH)|(?i:ENDSWITH)]; # long to short
75 my $re_open_paren  = qr[\(];
76 my $re_close_paren = qr[\)];
77
78 sub ParseToArray {
79     my ($string) = shift;
80
81     my ($tree, $node, @pnodes);
82     $node = $tree = [];
83
84     my %callback;
85     $callback{'OpenParen'} = sub { push @pnodes, $node; $node = []; push @{ $pnodes[-1] }, $node };
86     $callback{'CloseParen'} = sub { $node = pop @pnodes };
87     $callback{'EntryAggregator'} = sub { push @$node, $_[0] };
88     $callback{'Condition'} = sub { push @$node, { key => $_[0], op => $_[1], value => $_[2] } };
89
90     Parse($string, \%callback);
91     return $tree;
92 }
93
94 sub Parse {
95     my ($string, $cb) = @_;
96     my $loc = sub {HTML::Mason::Commands::loc(@_)};
97     $string = '' unless defined $string;
98
99     my $want = KEYWORD | OPEN_PAREN;
100     my $last = 0;
101
102     my $depth = 0;
103     my ($key,$op,$value) = ("","","");
104
105     # order of matches in the RE is important.. op should come early,
106     # because it has spaces in it.    otherwise "NOT LIKE" might be parsed
107     # as a keyword or value.
108
109     while ($string =~ /(
110                         $re_aggreg
111                         |$re_op
112                         |$re_keyword
113                         |$re_value
114                         |$re_open_paren
115                         |$re_close_paren
116                        )/iogx )
117     {
118         my $match = $1;
119
120         # Highest priority is last
121         my $current = 0;
122         $current = OP          if ($want & OP)          && $match =~ /^$re_op$/io;
123         $current = VALUE       if ($want & VALUE)       && $match =~ /^$re_value$/io;
124         $current = KEYWORD     if ($want & KEYWORD)     && $match =~ /^$re_keyword$/io;
125         $current = AGGREG      if ($want & AGGREG)      && $match =~ /^$re_aggreg$/io;
126         $current = OPEN_PAREN  if ($want & OPEN_PAREN)  && $match =~ /^$re_open_paren$/io;
127         $current = CLOSE_PAREN if ($want & CLOSE_PAREN) && $match =~ /^$re_close_paren$/io;
128
129
130         unless ($current && $want & $current) {
131             my $tmp = substr($string, 0, pos($string)- length($match));
132             $tmp .= '>'. $match .'<--here'. substr($string, pos($string));
133             my $msg = $loc->("Wrong query, expecting a [_1] in '[_2]'", _BitmaskToString($want), $tmp);
134             return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
135             die $msg;
136         }
137
138         # State Machine:
139
140         # Parens are highest priority
141         if ( $current & OPEN_PAREN ) {
142             $cb->{'OpenParen'}->();
143             $depth++;
144             $want = KEYWORD | OPEN_PAREN;
145         }
146         elsif ( $current & CLOSE_PAREN ) {
147             $cb->{'CloseParen'}->();
148             $depth--;
149             $want = AGGREG;
150             $want |= CLOSE_PAREN if $depth;
151         }
152         elsif ( $current & AGGREG ) {
153             $cb->{'EntryAggregator'}->( $match );
154             $want = KEYWORD | OPEN_PAREN;
155         }
156         elsif ( $current & KEYWORD ) {
157             $key = $match;
158             $want = OP;
159         }
160         elsif ( $current & OP ) {
161             $op = $match;
162             $want = VALUE;
163         }
164         elsif ( $current & VALUE ) {
165             $value = $match;
166
167             # Remove surrounding quotes and unescape escaped
168             # characters from $key, $match
169             for ( $key, $value ) {
170                 if ( /$re_delim/o ) {
171                     substr($_,0,1) = "";
172                     substr($_,-1,1) = "";
173                 }
174                 s!\\(.)!$1!g;
175             }
176
177             $cb->{'Condition'}->( $key, $op, $value );
178
179             ($key,$op,$value) = ("","","");
180             $want = AGGREG;
181             $want |= CLOSE_PAREN if $depth;
182         } else {
183             my $msg = $loc->("Query parser is lost");
184             return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
185             die $msg;
186         }
187
188         $last = $current;
189     } # while
190
191     unless( !$last || $last & (CLOSE_PAREN | VALUE) ) {
192         my $msg = $loc->("Incomplete query, last element ([_1]) is not close paren or value in '[_2]'",
193                          _BitmaskToString($last),
194                          $string);
195         return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
196         die $msg;
197     }
198
199     if( $depth ) {
200         my $msg = $loc->("Incomplete query, [quant,_1,unclosed paren] in '[_2]'", $depth, $string);
201         return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
202         die $msg;
203     }
204 }
205
206 sub _BitmaskToString {
207     my $mask = shift;
208
209     my @res;
210     for( my $i = 0; $i<@tokens; $i++ ) {
211         next unless $mask & (1<<$i);
212         push @res, $tokens[$i];
213     }
214
215     my $tmp = join ', ', splice @res, 0, -1;
216     unshift @res, $tmp if $tmp;
217     return join ' or ', @res;
218 }
219
220 sub PossibleCustomFields {
221     my %args = (Query => undef, CurrentUser => undef, @_);
222
223     my $cfs = RT::CustomFields->new( $args{'CurrentUser'} );
224     my $ocf_alias = $cfs->_OCFAlias;
225     $cfs->LimitToLookupType( 'RT::Queue-RT::Ticket' );
226
227     my $tree;
228     if ( HAS_BOOLEAN_PARSER ) {
229         $tree = Parse::BooleanLogic->filter(
230             RT::SQL::ParseToArray( $args{'Query'} ),
231             sub { $_[0]->{'key'} =~ /^Queue(?:\z|\.)/ },
232         );
233     }
234     if ( $tree && @$tree ) {
235         my $clause = 'QUEUES';
236         my $queue_alias = $cfs->Join(
237             TYPE   => 'LEFT',
238             ALIAS1 => $ocf_alias,
239             FIELD1 => 'ObjectId',
240             TABLE2 => 'Queues',
241             FIELD2 => 'id',
242         );
243         $cfs->_OpenParen($clause);
244         $cfs->Limit(
245             SUBCLAUSE       => $clause,
246             ENTRYAGGREGATOR => 'AND',
247             ALIAS           => $ocf_alias,
248             FIELD           => 'ObjectId',
249             VALUE           => 0,
250         );
251         $cfs->_OpenParen($clause);
252
253         my $ea = 'OR';
254         Parse::BooleanLogic->walk(
255             $tree,
256             {
257                 open_paren  => sub { $cfs->_OpenParen($clause) },
258                 close_paren => sub { $cfs->_CloseParen($clause) },
259                 operator    => sub { $ea = $_[0] },
260                 operand     => sub {
261                     my ($key, $op, $value) = @{$_[0]}{'key', 'op', 'value'};
262                     my (undef, @sub) = split /\./, $key;
263                     push @sub, $value =~ /\D/? 'Name' : 'id'
264                         unless @sub;
265                     
266                     die "Couldn't handle ". join('.', 'Queue', @sub) if @sub > 1;
267                     $cfs->Limit(
268                         SUBCLAUSE       => $clause,
269                         ENTRYAGGREGATOR => $ea,
270                         ALIAS           => $queue_alias,
271                         FIELD           => $sub[0],
272                         OPERATOR        => $op,
273                         VALUE           => $value,
274                     );
275                 },
276             }
277         );
278
279         $cfs->_CloseParen($clause);
280         $cfs->_CloseParen($clause);
281     } else {
282         $cfs->Limit(
283             ENTRYAGGREGATOR => 'AND',
284             ALIAS           => $ocf_alias,
285             FIELD           => 'ObjectId',
286             OPERATOR        => 'IS NOT',
287             VALUE           => 'NULL',
288         );
289     }
290     return $cfs;
291 }
292
293
294 RT::Base->_ImportOverlays();
295
296 1;