first pass RT4 merge, RT#13852
[freeside.git] / rt / sbin / rt-fulltext-indexer.in
1 #!@PERL@
2 # BEGIN BPS TAGGED BLOCK {{{
3 #
4 # COPYRIGHT:
5 #
6 # This software is Copyright (c) 1996-2012 Best Practical Solutions, LLC
7 #                                          <sales@bestpractical.com>
8 #
9 # (Except where explicitly superseded by other copyright notices)
10 #
11 #
12 # LICENSE:
13 #
14 # This work is made available to you under the terms of Version 2 of
15 # the GNU General Public License. A copy of that license should have
16 # been provided with this software, but in any event can be snarfed
17 # from www.gnu.org.
18 #
19 # This work is distributed in the hope that it will be useful, but
20 # WITHOUT ANY WARRANTY; without even the implied warranty of
21 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
22 # General Public License for more details.
23 #
24 # You should have received a copy of the GNU General Public License
25 # along with this program; if not, write to the Free Software
26 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
27 # 02110-1301 or visit their web page on the internet at
28 # http://www.gnu.org/licenses/old-licenses/gpl-2.0.html.
29 #
30 #
31 # CONTRIBUTION SUBMISSION POLICY:
32 #
33 # (The following paragraph is not intended to limit the rights granted
34 # to you to modify and distribute this software under the terms of
35 # the GNU General Public License and is only of importance to you if
36 # you choose to contribute your changes and enhancements to the
37 # community by submitting them to Best Practical Solutions, LLC.)
38 #
39 # By intentionally submitting any modifications, corrections or
40 # derivatives to this work, or any other work intended for use with
41 # Request Tracker, to Best Practical Solutions, LLC, you confirm that
42 # you are the copyright holder for those contributions and you grant
43 # Best Practical Solutions,  LLC a nonexclusive, worldwide, irrevocable,
44 # royalty-free, perpetual, license to use, copy, create derivative
45 # works based on those contributions, and sublicense and distribute
46 # those contributions and any derivatives thereof.
47 #
48 # END BPS TAGGED BLOCK }}}
49 use strict;
50 use warnings;
51 no warnings 'once';
52
53 # fix lib paths, some may be relative
54 BEGIN {
55     require File::Spec;
56     my @libs = ("@RT_LIB_PATH@", "@LOCAL_LIB_PATH@");
57     my $bin_path;
58
59     for my $lib (@libs) {
60         unless ( File::Spec->file_name_is_absolute($lib) ) {
61             unless ($bin_path) {
62                 if ( File::Spec->file_name_is_absolute(__FILE__) ) {
63                     $bin_path = ( File::Spec->splitpath(__FILE__) )[1];
64                 }
65                 else {
66                     require FindBin;
67                     no warnings "once";
68                     $bin_path = $FindBin::Bin;
69                 }
70             }
71             $lib = File::Spec->catfile( $bin_path, File::Spec->updir, $lib );
72         }
73         unshift @INC, $lib;
74     }
75 }
76
77 BEGIN {
78     use RT;
79     RT::LoadConfig();
80     RT::Init();
81 };
82 use RT::Interface::CLI ();
83
84 my %OPT = (
85     help        => 0,
86     debug       => 0,
87 );
88 my @OPT_LIST = qw(help|h! debug!);
89
90 my $db_type = RT->Config->Get('DatabaseType');
91 if ( $db_type eq 'Pg' ) {
92     %OPT = (
93         %OPT,
94         limit  => 0,
95         all    => 0,
96     );
97     push @OPT_LIST, 'limit=i', 'all!';
98 }
99 elsif ( $db_type eq 'mysql' ) {
100     %OPT = (
101         %OPT,
102         limit    => 0,
103         all      => 0,
104         xmlpipe2 => 0,
105     );
106     push @OPT_LIST, 'limit=i', 'all!', 'xmlpipe2!';
107 }
108 elsif ( $db_type eq 'Oracle' ) {
109     %OPT = (
110         %OPT,
111         memory => '2M',
112     );
113     push @OPT_LIST, qw(memory=s);
114 }
115
116 use Getopt::Long qw(GetOptions);
117 GetOptions( \%OPT, @OPT_LIST );
118
119 if ( $OPT{'help'} ) {
120     RT::Interface::CLI->ShowHelp(
121         Sections => 'NAME|DESCRIPTION|'. uc($db_type),
122     );
123 }
124
125 my $fts_config = RT->Config->Get('FullTextSearch') || {};
126 unless ( $fts_config->{'Enable'} ) {
127     print STDERR <<EOT;
128
129 Full text search is disabled in your RT configuration.  Run
130 @RT_SBIN_PATH_R@/rt-setup-fulltext-index to configure and enable it.
131
132 EOT
133     exit 1;
134 }
135 unless ( $fts_config->{'Indexed'} ) {
136     print STDERR <<EOT;
137
138 Full text search is enabled in your RT configuration, but not with any
139 full-text database indexing -- hence this tool is not required.  Read
140 the documentation for %FullTextSearch in your RT_Config for more details.
141
142 EOT
143     exit 1;
144 }
145
146 if ( $db_type eq 'Oracle' ) {
147     my $index = $fts_config->{'IndexName'} || 'rt_fts_index';
148     $RT::Handle->dbh->do(
149         "begin ctx_ddl.sync_index(?, ?); end;", undef,
150         $index, $OPT{'memory'}
151     );
152     exit;
153 } elsif ( $db_type eq 'mysql' ) {
154     unless ($OPT{'xmlpipe2'}) {
155         print STDERR <<EOT;
156
157 Updates to the external Sphinx index are done via running the sphinx
158 `indexer` tool:
159
160     indexer rt
161
162 EOT
163         exit 1;
164     }
165 }
166
167 my @types = qw(text html);
168 foreach my $type ( @types ) {
169   REDO:
170     my $attachments = attachments($type);
171     $attachments->Limit(
172         FIELD => 'id',
173         OPERATOR => '>',
174         VALUE => last_indexed($type)
175     );
176     $attachments->OrderBy( FIELD => 'id', ORDER => 'asc' );
177     $attachments->RowsPerPage( $OPT{'limit'} || 100 );
178
179     my $found = 0;
180     while ( my $a = $attachments->Next ) {
181         next if filter( $type, $a );
182         debug("Found attachment #". $a->id );
183         my $txt = extract($type, $a) or next;
184         $found++;
185         process( $type, $a, $txt );
186         debug("Processed attachment #". $a->id );
187     }
188     finalize( $type, $attachments ) if $found;
189     clean( $type );
190     goto REDO if $OPT{'all'} and $attachments->Count == ($OPT{'limit'} || 100)
191 }
192
193 sub attachments {
194     my $type = shift;
195     my $res = RT::Attachments->new( RT->SystemUser );
196     my $txn_alias = $res->Join(
197         ALIAS1 => 'main',
198         FIELD1 => 'TransactionId',
199         TABLE2 => 'Transactions',
200         FIELD2 => 'id',
201     );
202     $res->Limit(
203         ALIAS => $txn_alias,
204         FIELD => 'ObjectType',
205         VALUE => 'RT::Ticket',
206     );
207     my $ticket_alias = $res->Join(
208         ALIAS1 => $txn_alias,
209         FIELD1 => 'ObjectId',
210         TABLE2 => 'Tickets',
211         FIELD2 => 'id',
212     );
213     $res->Limit(
214         ALIAS => $ticket_alias,
215         FIELD => 'Status',
216         OPERATOR => '!=',
217         VALUE => 'deleted'
218     );
219
220     return goto_specific(
221         suffix => $type,
222         error => "Don't know how to find $type attachments",
223         arguments => [$res],
224     );
225 }
226
227 sub last_indexed {
228     my ($type) = (@_);
229     return goto_specific(
230         suffix => $db_type,
231         error => "Don't know how to find last indexed $type attachment for $db_type DB",
232         arguments => \@_,
233     );
234 }
235
236 sub filter {
237     my $type = shift;
238     return goto_specific(
239         suffix    => $type,
240         arguments => \@_,
241     );
242 }
243
244 sub extract {
245     my $type = shift;
246     return goto_specific(
247         suffix    => $type,
248         error     => "No way to convert $type attachment into text",
249         arguments => \@_,
250     );
251 }
252
253 sub process {
254     return goto_specific(
255         suffix    => $db_type,
256         error     => "No processer for $db_type DB",
257         arguments => \@_,
258     );
259 }
260
261 sub finalize {
262     return goto_specific(
263         suffix    => $db_type,
264         arguments => \@_,
265     );
266 }
267
268 sub clean {
269     return goto_specific(
270         suffix    => $db_type,
271         arguments => \@_,
272     );
273 }
274
275 {
276 sub last_indexed_mysql {
277     my $type = shift;
278     my $attr = $RT::System->FirstAttribute('LastIndexedAttachments');
279     return 0 unless $attr;
280     return 0 unless exists $attr->{ $type };
281     return $attr->{ $type } || 0;
282 }
283
284 sub process_mysql {
285     my ($type, $attachment, $text) = (@_);
286
287     my $doc = sphinx_template();
288
289     my $element = $doc->createElement('sphinx:document');
290     $element->setAttribute( id => $attachment->id );
291     $element->appendTextChild( content => $$text );
292
293     $doc->documentElement->appendChild( $element );
294 }
295
296 my $doc = undef;
297 sub sphinx_template {
298     return $doc if $doc;
299
300     require XML::LibXML;
301     $doc = XML::LibXML::Document->new('1.0', 'UTF-8');
302     my $root = $doc->createElement('sphinx:docset');
303     $doc->setDocumentElement( $root );
304
305     my $schema = $doc->createElement('sphinx:schema');
306     $root->appendChild( $schema );
307     foreach ( qw(content) ) {
308         my $field = $doc->createElement('sphinx:field');
309         $field->setAttribute( name => $_ );
310         $schema->appendChild( $field );
311     }
312
313     return $doc;
314 }
315
316 sub finalize_mysql {
317     my ($type, $attachments) = @_;
318     sphinx_template()->toFH(*STDOUT, 1);
319 }
320
321 sub clean_mysql {
322     $doc = undef;
323 }
324
325 }
326
327 sub last_indexed_pg {
328     my $type = shift;
329     my $attachments = attachments( $type );
330     my $alias = 'main';
331     if ( $fts_config->{'Table'} && $fts_config->{'Table'} ne 'Attachments' ) {
332         $alias = $attachments->Join(
333             TYPE    => 'left',
334             FIELD1 => 'id',
335             TABLE2  => $fts_config->{'Table'},
336             FIELD2 => 'id',
337         );
338     }
339     $attachments->Limit(
340         ALIAS => $alias,
341         FIELD => $fts_config->{'Column'},
342         OPERATOR => 'IS NOT',
343         VALUE => 'NULL',
344     );
345     $attachments->OrderBy( FIELD => 'id', ORDER => 'desc' );
346     $attachments->RowsPerPage( 1 );
347     my $res = $attachments->First;
348     return 0 unless $res;
349     return $res->id;
350 }
351
352 sub process_pg {
353     my ($type, $attachment, $text) = (@_);
354
355     my $dbh = $RT::Handle->dbh;
356     my $table = $fts_config->{'Table'};
357     my $column = $fts_config->{'Column'};
358
359     my $query;
360     if ( $table ) {
361         if ( my ($id) = $dbh->selectrow_array("SELECT id FROM $table WHERE id = ?", undef, $attachment->id) ) {
362             $query = "UPDATE $table SET $column = to_tsvector(?) WHERE id = ?";
363         } else {
364             $query = "INSERT INTO $table($column, id) VALUES(to_tsvector(?), ?)";
365         }
366     } else {
367         $query = "UPDATE Attachments SET $column = to_tsvector(?) WHERE id = ?";
368     }
369
370     my $status = eval { $dbh->do( $query, undef, $$text, $attachment->id ) };
371     unless ( $status ) {
372         if ($dbh->errstr =~ /string is too long for tsvector/) {
373             warn "Attachment @{[$attachment->id]} not indexed, as it contains too many unique words to be indexed";
374         } else {
375             die "error: ". $dbh->errstr;
376         }
377     }
378 }
379
380 sub attachments_text {
381     my $res = shift;
382     $res->Limit( FIELD => 'ContentType', VALUE => 'text/plain' );
383     return $res;
384 }
385
386 sub extract_text {
387     my $attachment = shift;
388     my $text = $attachment->Content;
389     return undef unless defined $text && length($text);
390     return \$text;
391 }
392
393 sub attachments_html {
394     my $res = shift;
395     $res->Limit( FIELD => 'ContentType', VALUE => 'text/html' );
396     return $res;
397 }
398
399 sub filter_html {
400     my $attachment = shift;
401     if ( my $parent = $attachment->ParentObj ) {
402 # skip html parts that are alternatives
403         return 1 if $parent->id
404             && $parent->ContentType eq 'mulitpart/alternative';
405     }
406     return 0;
407 }
408
409 sub extract_html {
410     my $attachment = shift;
411     my $text = $attachment->Content;
412     return undef unless defined $text && length($text);
413 # TODO: html -> text
414     return \$text;
415 }
416
417 sub goto_specific {
418     my %args = (@_);
419
420     my $func = (caller(1))[3];
421     $func =~ s/.*:://;
422     my $call = $func ."_". lc $args{'suffix'};
423     unless ( defined &$call ) {
424         return undef unless $args{'error'};
425         require Carp; Carp::croak( $args{'error'} );
426     }
427     @_ = @{ $args{'arguments'} };
428     goto &$call;
429 }
430
431
432 # helper functions
433 sub debug    { print @_, "\n" if $OPT{debug}; 1 }
434 sub error    { $RT::Logger->error(_(@_)); 1 }
435 sub warning  { $RT::Logger->warn(_(@_)); 1 }
436
437 =head1 NAME
438
439 rt-fulltext-indexer - Indexer for full text search
440
441 =head1 DESCRIPTION
442
443 This is a helper script to keep full text indexes in sync with data.
444 Read F<docs/full_text_indexing.pod> for complete details on how and when
445 to run it.
446
447 =head1 AUTHOR
448
449 Ruslan Zakirov E<lt>ruz@bestpractical.comE<gt>,
450 Alex Vandiver E<lt>alexmv@bestpractical.comE<gt>
451
452 =cut
453