rt 4.2.15
[freeside.git] / rt / share / html / Search / Build.html
1 %# BEGIN BPS TAGGED BLOCK {{{
2 %#
3 %# COPYRIGHT:
4 %#
5 %# This software is Copyright (c) 1996-2018 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 %# Data flow here:
50 %#   The page receives a Query from the previous page, and maybe arguments
51 %#   corresponding to actions.  (If it doesn't get a Query argument, it pulls
52 %#   one out of the session hash.  Also, it could be getting just a raw query from
53 %#   Build/Edit.html (Advanced).)
54 %#
55 %#   After doing some stuff with default arguments and saved searches, the ParseQuery
56 %#   function (which is similar to, but not the same as, _parser in lib/RT/Tickets.pm)
57 %#   converts the Query into a RT::Interface::Web::QueryBuilder::Tree.  This mason file
58 %#   then adds stuff to or modifies the tree based on the actions that had been requested
59 %#   by clicking buttons.  It then calls GetQueryAndOptionList on the tree to generate
60 %#   the SQL query (which is saved as a hidden input) and the option list for the Clauses
61 %#   box in the top right corner.
62 %#
63 %#   Worthwhile refactoring: the tree manipulation code for the actions could use some cleaning
64 %#   up.  The node-adding code is different in the "add" actions from in ParseQuery, which leads
65 %#   to things like ParseQuery correctly not quoting numbers in numerical fields, while the "add"
66 %#   action does quote it (this breaks SQLite).
67 %#
68 <& /Elements/Header, Title => $title &>
69 <& /Elements/Tabs, %TabArgs &>
70 <form method="post" action="Build.html" name="BuildQuery" id="BuildQuery">
71 <input type="hidden" class="hidden" name="SavedSearchId" value="<% $saved_search{'Id'} %>" />
72 <input type="hidden" class="hidden" name="SavedChartSearchId" value="<% $ARGS{'SavedChartSearchId'} %>" />
73 <input type="hidden" class="hidden" name="Query" value="<% $query{'Query'} %>" />
74 <input type="hidden" class="hidden" name="Format" value="<% $query{'Format'} %>" />
75
76
77
78
79 <div id="pick-criteria">
80     <& Elements/PickCriteria, query => $query{'Query'}, queues => $queues &>
81 <& /Elements/Submit,  Label => loc('Add these terms'), SubmitId => 'AddClause', Name => 'AddClause'&>
82 <& /Elements/Submit, Label => loc('Add these terms and Search'), SubmitId => 'DoSearch', Name => 'DoSearch'&>
83 </div>
84
85
86 <div id="editquery">
87 <& Elements/EditQuery,
88     %ARGS,
89     actions => \@actions,
90     optionlist => $optionlist,
91     Description => $saved_search{'Description'},
92     &>
93 </div>
94 <div id="editsearches">
95     <& Elements/EditSearches, %saved_search, CurrentSearch => \%query &>
96 </div>
97
98 <span id="display-options">
99 <& Elements/DisplayOptions,
100     %ARGS, %query,
101     AvailableColumns => $AvailableColumns,
102     CurrentFormat    => $CurrentFormat,
103 &>
104 </span>
105 <& /Elements/Submit, Label => loc('Update format and Search'), Name => 'DoSearch', id=>"formatbuttons"&>
106 </form>
107
108 <%INIT>
109 use RT::Interface::Web::QueryBuilder;
110 use RT::Interface::Web::QueryBuilder::Tree;
111
112 $ARGS{SavedChartSearchId} ||= 'new';
113
114 my $title = loc("Query Builder");
115
116 my %query;
117 for( qw(Query Format OrderBy Order RowsPerPage) ) {
118     $query{$_} = $ARGS{$_};
119 }
120
121 my %saved_search;
122 my @actions = $m->comp( 'Elements/EditSearches:Init', %ARGS, Query => \%query, SavedSearch => \%saved_search);
123
124 if ( $NewQuery ) {
125
126     # Wipe all data-carrying variables clear if we want a new
127     # search, or we're deleting an old one..
128     %query = ();
129     %saved_search = ( Id => 'new' );
130
131     # ..then wipe the session out..
132     delete $session{'CurrentSearchHash'};
133
134     # ..and the search results.
135     $session{'tickets'}->CleanSlate if defined $session{'tickets'};
136 }
137
138 { # Attempt to load what we can from the session and preferences, set defaults
139
140     my $current = $session{'CurrentSearchHash'};
141     my $prefs = $session{'CurrentUser'}->UserObj->Preferences("SearchDisplay") || {};
142     my $default = { Query => '',
143                     Format => '',
144                     OrderBy => RT->Config->Get('DefaultSearchResultOrderBy'),
145                     Order => RT->Config->Get('DefaultSearchResultOrder'),
146                     RowsPerPage => 50 };
147
148     for( qw(Query Format OrderBy Order RowsPerPage) ) {
149         $query{$_} = $current->{$_} unless defined $query{$_};
150         $query{$_} = $prefs->{$_} unless defined $query{$_};
151         $query{$_} = $default->{$_} unless defined $query{$_};
152     }
153
154     for( qw(Order OrderBy) ) {
155         if (ref $query{$_} eq "ARRAY") {
156             $query{$_} = join( '|', @{ $query{$_} } );
157         }
158     }
159     if ( $query{'Format'} ) {
160         # Clean unwanted junk from the format
161         $query{'Format'} = $m->comp( '/Elements/ScrubHTML', Content => $query{'Format'} );
162     }
163 }
164
165 my $ParseQuery = sub {
166     my ($string, $results) = @_;
167
168     my $tree = RT::Interface::Web::QueryBuilder::Tree->new('AND');
169     @$results = $tree->ParseSQL( Query => $string, CurrentUser => $session{'CurrentUser'} );
170
171     return $tree;
172 };
173
174 my @parse_results;
175 my $tree = $ParseQuery->( $query{'Query'}, \@parse_results );
176
177 # if parsing went poorly, send them to the edit page to fix it
178 if ( @parse_results ) {
179     push @actions, @parse_results;
180     return $m->comp(
181         "Edit.html",
182         Query => $query{'Query'},
183         Format => $query{'Format'},
184         SavedSearchId => $saved_search{'Id'},
185         SavedChartSearchId => $ARGS{'SavedChartSearchId'},
186         actions => \@actions,
187     );
188 }
189
190 my @options = $tree->GetDisplayedNodes;
191 my @current_values = grep defined, @options[@clauses];
192 my @new_values = ();
193
194 my $cf_field_names =
195     join "|",
196      map quotemeta,
197     grep { $RT::Tickets::FIELD_METADATA{$_}->[0] eq 'CUSTOMFIELD' }
198     sort keys %RT::Tickets::FIELD_METADATA;
199
200 # Try to find if we're adding a clause
201 foreach my $arg ( keys %ARGS ) {
202     next unless $arg =~ m/^ValueOf([\w\.]+|($cf_field_names).\{.*?\})$/
203                 && ( ref $ARGS{$arg} eq "ARRAY"
204                      ? grep $_ ne '', @{ $ARGS{$arg} }
205                      : $ARGS{$arg} ne '' );
206
207     # We're adding a $1 clause
208     my $field = $1;
209
210     my ($op, $value);
211
212     #figure out if it's a grouping
213     my $keyword = $ARGS{ $field . "Field" } || $field;
214
215     my ( @ops, @values );
216     if ( ref $ARGS{ 'ValueOf' . $field } eq "ARRAY" ) {
217         # we have many keys/values to iterate over, because there is
218         # more than one CF with the same name.
219         @ops    = @{ $ARGS{ $field . 'Op' } };
220         @values = @{ $ARGS{ 'ValueOf' . $field } };
221     }
222     else {
223         @ops    = ( $ARGS{ $field . 'Op' } );
224         @values = ( $ARGS{ 'ValueOf' . $field } );
225     }
226     $RT::Logger->error("Bad Parameters passed into Query Builder")
227         unless @ops == @values;
228
229     for ( my $i = 0; $i < @ops; $i++ ) {
230         my ( $op, $value ) = ( $ops[$i], $values[$i] );
231         next if !defined $value || $value eq '';
232         my $rawvalue = $value;
233
234         if ( $value =~ /^NULL$/i && $op =~ /=/ ) {
235             if ( $op eq '=' ) {
236                 $op = "IS";
237             }
238             elsif ( $op eq '!=' ) {
239                 $op = "IS NOT";
240             }
241         }
242         elsif ($value =~ /\D/) {
243             $value =~ s/(['\\])/\\$1/g;
244             $value = "'$value'";
245         }
246
247         if ($keyword =~ s/(['\\])/\\$1/g or $keyword =~ /[^{}\w\.]/) {
248             $keyword = "'$keyword'";
249         }
250
251         my $clause = {
252             Key   => $keyword,
253             Op    => $op,
254             Value => $value,
255             RawValue => $rawvalue,
256         };
257
258         push @new_values, RT::Interface::Web::QueryBuilder::Tree->new($clause);
259     }
260 }
261
262
263 push @actions, $m->comp('Elements/EditQuery:Process',
264     %ARGS,
265     Tree     => $tree,
266     Selected => \@current_values,
267     New      => \@new_values,
268 );
269
270 # Rebuild $Query based on the additions / movements
271
272 my $optionlist_arrayref;
273 ($query{'Query'}, $optionlist_arrayref) = $tree->GetQueryAndOptionList(\@current_values);
274
275 my $optionlist = join "\n", map { qq(<option value="$_->{INDEX}" $_->{SELECTED}>) 
276                                   . ("&nbsp;" x (5 * $_->{DEPTH}))
277                                   . $m->interp->apply_escapes($_->{TEXT}, 'h') . qq(</option>) } @$optionlist_arrayref;
278
279
280 my $queues = $tree->GetReferencedQueues;
281
282 # Deal with format changes
283 my ( $AvailableColumns, $CurrentFormat );
284 ( $query{'Format'}, $AvailableColumns, $CurrentFormat ) = $m->comp(
285     'Elements/BuildFormatString',
286     %ARGS,
287     queues => $queues,
288     Format => $query{'Format'},
289 );
290
291
292 # if we're asked to save the current search, save it
293 push @actions, $m->comp( 'Elements/EditSearches:Save', %ARGS, Query => \%query, SavedSearch => \%saved_search);
294
295 # Populate the "query" context with saved search data
296
297 if ($ARGS{SavedSearchSave}) {
298     $query{'SavedSearchId'} = $saved_search{'Id'};
299 }
300
301 # Push the updates into the session so we don't lose 'em
302
303 $session{'CurrentSearchHash'} = {
304     %query,
305     SearchId    => $saved_search{'Id'},
306     Object      => $saved_search{'Object'},
307     Description => $saved_search{'Description'},
308 };
309
310
311 # Show the results, if we were asked.
312
313 if ( $ARGS{'DoSearch'} ) {
314     my $redir_query_string = $m->comp(
315         '/Elements/QueryString',
316         %query,
317         SavedChartSearchId => $ARGS{'SavedChartSearchId'},
318         SavedSearchId => $saved_search{'Id'},
319     );
320     RT::Interface::Web::Redirect(RT->Config->Get('WebURL') . 'Search/Results.html?' . $redir_query_string);
321     $m->abort;
322 }
323
324
325 # Build a querystring for the tabs
326
327 my %TabArgs = ();
328 if ($NewQuery) {
329     $TabArgs{QueryString} = 'NewQuery=1';
330 }
331 elsif ( $query{'Query'} ) {
332     $TabArgs{QueryArgs} = \%query;
333 }
334
335 </%INIT>
336
337 <%ARGS>
338 $NewQuery => 0
339 @clauses => ()
340 </%ARGS>