e696dd25fbf9bc343b3cc0a961a80a77d946f6fd
[freeside.git] / rt / lib / RT / SQL.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2011 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 use constant HAS_BOOLEAN_PARSER => do {
55     local $@;
56     eval { require Parse::BooleanLogic; 1 }
57 };
58
59 # States
60 use constant VALUE       => 1;
61 use constant AGGREG      => 2;
62 use constant OP          => 4;
63 use constant OPEN_PAREN  => 8;
64 use constant CLOSE_PAREN => 16;
65 use constant KEYWORD     => 32;
66 my @tokens = qw[VALUE AGGREGATOR OPERATOR OPEN_PAREN CLOSE_PAREN KEYWORD];
67
68 use Regexp::Common qw /delimited/;
69 my $re_aggreg      = qr[(?i:AND|OR)];
70 my $re_delim       = qr[$RE{delimited}{-delim=>qq{\'\"}}];
71 my $re_value       = qr[[+-]?\d+|NULL|$re_delim];
72 my $re_keyword     = qr[[{}\w\.]+|$re_delim];
73 my $re_op          = qr[=|!=|>=|<=|>|<|(?i:IS NOT)|(?i:IS)|(?i:NOT LIKE)|(?i:LIKE)]; # long to short
74 my $re_open_paren  = qr[\(];
75 my $re_close_paren = qr[\)];
76
77 sub ParseToArray {
78     my ($string) = shift;
79
80     my ($tree, $node, @pnodes);
81     $node = $tree = [];
82
83     my %callback;
84     $callback{'OpenParen'} = sub { push @pnodes, $node; $node = []; push @{ $pnodes[-1] }, $node };
85     $callback{'CloseParen'} = sub { $node = pop @pnodes };
86     $callback{'EntryAggregator'} = sub { push @$node, $_[0] };
87     $callback{'Condition'} = sub { push @$node, { key => $_[0], op => $_[1], value => $_[2] } };
88
89     Parse($string, \%callback);
90     return $tree;
91 }
92
93 sub Parse {
94     my ($string, $cb) = @_;
95     $string = '' unless defined $string;
96
97     my $want = KEYWORD | OPEN_PAREN;
98     my $last = 0;
99
100     my $depth = 0;
101     my ($key,$op,$value) = ("","","");
102
103     # order of matches in the RE is important.. op should come early,
104     # because it has spaces in it.    otherwise "NOT LIKE" might be parsed
105     # as a keyword or value.
106
107     while ($string =~ /(
108                         $re_aggreg
109                         |$re_op
110                         |$re_keyword
111                         |$re_value
112                         |$re_open_paren
113                         |$re_close_paren
114                        )/iogx )
115     {
116         my $match = $1;
117
118         # Highest priority is last
119         my $current = 0;
120         $current = OP          if ($want & OP)          && $match =~ /^$re_op$/io;
121         $current = VALUE       if ($want & VALUE)       && $match =~ /^$re_value$/io;
122         $current = KEYWORD     if ($want & KEYWORD)     && $match =~ /^$re_keyword$/io;
123         $current = AGGREG      if ($want & AGGREG)      && $match =~ /^$re_aggreg$/io;
124         $current = OPEN_PAREN  if ($want & OPEN_PAREN)  && $match =~ /^$re_open_paren$/io;
125         $current = CLOSE_PAREN if ($want & CLOSE_PAREN) && $match =~ /^$re_close_paren$/io;
126
127
128         unless ($current && $want & $current) {
129             my $tmp = substr($string, 0, pos($string)- length($match));
130             $tmp .= '>'. $match .'<--here'. substr($string, pos($string));
131             my $msg = "Wrong query, expecting a ". _BitmaskToString($want) ." in '$tmp'";
132             return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
133             die $msg;
134         }
135
136         # State Machine:
137
138         # Parens are highest priority
139         if ( $current & OPEN_PAREN ) {
140             $cb->{'OpenParen'}->();
141             $depth++;
142             $want = KEYWORD | OPEN_PAREN;
143         }
144         elsif ( $current & CLOSE_PAREN ) {
145             $cb->{'CloseParen'}->();
146             $depth--;
147             $want = AGGREG;
148             $want |= CLOSE_PAREN if $depth;
149         }
150         elsif ( $current & AGGREG ) {
151             $cb->{'EntryAggregator'}->( $match );
152             $want = KEYWORD | OPEN_PAREN;
153         }
154         elsif ( $current & KEYWORD ) {
155             $key = $match;
156             $want = OP;
157         }
158         elsif ( $current & OP ) {
159             $op = $match;
160             $want = VALUE;
161         }
162         elsif ( $current & VALUE ) {
163             $value = $match;
164
165             # Remove surrounding quotes and unescape escaped
166             # characters from $key, $match
167             for ( $key, $value ) {
168                 if ( /$re_delim/o ) {
169                     substr($_,0,1) = "";
170                     substr($_,-1,1) = "";
171                 }
172                 s!\\(.)!$1!g;
173             }
174
175             $cb->{'Condition'}->( $key, $op, $value );
176
177             ($key,$op,$value) = ("","","");
178             $want = AGGREG;
179             $want |= CLOSE_PAREN if $depth;
180         } else {
181             my $msg = "Query parser is lost";
182             return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
183             die $msg;
184         }
185
186         $last = $current;
187     } # while
188
189     unless( !$last || $last & (CLOSE_PAREN | VALUE) ) {
190         my $msg = "Incomplete query, last element ("
191             . _BitmaskToString($last)
192             . ") is not CLOSE_PAREN or VALUE in '$string'";
193         return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
194         die $msg;
195     }
196
197     if( $depth ) {
198         my $msg = "Incomplete query, $depth paren(s) isn't closed in '$string'";
199         return $cb->{'Error'}->( $msg ) if $cb->{'Error'};
200         die $msg;
201     }
202 }
203
204 sub _BitmaskToString {
205     my $mask = shift;
206
207     my @res;
208     for( my $i = 0; $i<@tokens; $i++ ) {
209         next unless $mask & (1<<$i);
210         push @res, $tokens[$i];
211     }
212
213     my $tmp = join ', ', splice @res, 0, -1;
214     unshift @res, $tmp if $tmp;
215     return join ' or ', @res;
216 }
217
218 sub PossibleCustomFields {
219     my %args = (Query => undef, CurrentUser => undef, @_);
220
221     my $cfs = RT::CustomFields->new( $args{'CurrentUser'} );
222     my $ocf_alias = $cfs->_OCFAlias;
223     $cfs->LimitToLookupType( 'RT::Queue-RT::Ticket' );
224
225     my $tree;
226     if ( HAS_BOOLEAN_PARSER ) {
227         $tree = Parse::BooleanLogic->filter(
228             RT::SQL::ParseToArray( $args{'Query'} ),
229             sub { $_[0]->{'key'} =~ /^Queue(?:\z|\.)/ },
230         );
231     }
232     if ( $tree && @$tree ) {
233         my $clause = 'QUEUES';
234         my $queue_alias = $cfs->Join(
235             TYPE   => 'LEFT',
236             ALIAS1 => $ocf_alias,
237             FIELD1 => 'ObjectId',
238             TABLE2 => 'Queues',
239             FIELD2 => 'id',
240         );
241         $cfs->_OpenParen($clause);
242         $cfs->Limit(
243             SUBCLAUSE       => $clause,
244             ENTRYAGGREGATOR => 'AND',
245             ALIAS           => $ocf_alias,
246             FIELD           => 'ObjectId',
247             VALUE           => 0,
248         );
249         $cfs->_OpenParen($clause);
250
251         my $ea = 'OR';
252         Parse::BooleanLogic->walk(
253             $tree,
254             {
255                 open_paren  => sub { $cfs->_OpenParen($clause) },
256                 close_paren => sub { $cfs->_CloseParen($clause) },
257                 operator    => sub { $ea = $_[0] },
258                 operand     => sub {
259                     my ($key, $op, $value) = @{$_[0]}{'key', 'op', 'value'};
260                     my (undef, @sub) = split /\./, $key;
261                     push @sub, $value =~ /\D/? 'Name' : 'id'
262                         unless @sub;
263                     
264                     die "Couldn't handle ". join('.', 'Queue', @sub) if @sub > 1;
265                     $cfs->Limit(
266                         SUBCLAUSE       => $clause,
267                         ENTRYAGGREGATOR => $ea,
268                         ALIAS           => $queue_alias,
269                         FIELD           => $sub[0],
270                         OPERATOR        => $op,
271                         VALUE           => $value,
272                     );
273                 },
274             }
275         );
276
277         $cfs->_CloseParen($clause);
278         $cfs->_CloseParen($clause);
279     } else {
280         $cfs->Limit(
281             ENTRYAGGREGATOR => 'AND',
282             ALIAS           => $ocf_alias,
283             FIELD           => 'ObjectId',
284             OPERATOR        => 'IS NOT',
285             VALUE           => 'NULL',
286         );
287     }
288     return $cfs;
289 }
290
291
292 eval "require RT::SQL_Vendor";
293 if ($@ && $@ !~ qr{^Can't locate RT/SQL_Vendor.pm}) {
294     die $@;
295 };
296
297 eval "require RT::SQL_Local";
298 if ($@ && $@ !~ qr{^Can't locate RT/SQL_Local.pm}) {
299     die $@;
300 };
301
302 1;