RT count still running on 3.8.10 - porting to RT4.
[usit-rt.git] / lib / RT / Handle.pm
CommitLineData
84fb5b46
MKG
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=head1 NAME
50
51RT::Handle - RT's database handle
52
53=head1 SYNOPSIS
54
55 use RT;
56 BEGIN { RT::LoadConfig() };
57 use RT::Handle;
58
59=head1 DESCRIPTION
60
61C<RT::Handle> is RT specific wrapper over one of L<DBIx::SearchBuilder::Handle>
62classes. As RT works with different types of DBs we subclass repsective handler
63from L<DBIx::SerachBuilder>. Type of the DB is defined by C<DatabasseType> RT's
64config option. You B<must> load this module only when the configs have been
65loaded.
66
67=cut
68
69package RT::Handle;
70
71use strict;
72use warnings;
73
74use File::Spec;
75
76=head1 METHODS
77
78=head2 FinalizeDatabaseType
79
80Sets RT::Handle's superclass to the correct subclass of
81L<DBIx::SearchBuilder::Handle>, using the C<DatabaseType> configuration.
82
83=cut
84
85sub FinalizeDatabaseType {
86 eval {
87 use base "DBIx::SearchBuilder::Handle::". RT->Config->Get('DatabaseType');
88 };
89
90 if ($@) {
91 die "Unable to load DBIx::SearchBuilder database handle for '". RT->Config->Get('DatabaseType') ."'.\n".
92 "Perhaps you've picked an invalid database type or spelled it incorrectly.\n".
93 $@;
94 }
95}
96
97=head2 Connect
98
99Connects to RT's database using credentials and options from the RT config.
100Takes nothing.
101
102=cut
103
104sub Connect {
105 my $self = shift;
106 my %args = (@_);
107
108 my $db_type = RT->Config->Get('DatabaseType');
109 if ( $db_type eq 'Oracle' ) {
110 $ENV{'NLS_LANG'} = "AMERICAN_AMERICA.AL32UTF8";
111 $ENV{'NLS_NCHAR'} = "AL32UTF8";
112 }
113
114 $self->SUPER::Connect(
115 User => RT->Config->Get('DatabaseUser'),
116 Password => RT->Config->Get('DatabasePassword'),
117 %args,
118 );
119
120 if ( $db_type eq 'mysql' ) {
121 my $version = $self->DatabaseVersion;
122 ($version) = $version =~ /^(\d+\.\d+)/;
123 $self->dbh->do("SET NAMES 'utf8'") if $version >= 4.1;
124 }
125
126
127 if ( $db_type eq 'Pg' ) {
128 my $version = $self->DatabaseVersion;
129 ($version) = $version =~ /^(\d+\.\d+)/;
130 $self->dbh->do("SET bytea_output = 'escape'") if $version >= 9.0;
131 }
132
133
134
135 $self->dbh->{'LongReadLen'} = RT->Config->Get('MaxAttachmentSize');
136}
137
138=head2 BuildDSN
139
140Build the DSN for the RT database. Doesn't take any parameters, draws all that
141from the config.
142
143=cut
144
145
146sub BuildDSN {
147 my $self = shift;
148 # Unless the database port is a positive integer, we really don't want to pass it.
149 my $db_port = RT->Config->Get('DatabasePort');
150 $db_port = undef unless (defined $db_port && $db_port =~ /^(\d+)$/);
151 my $db_host = RT->Config->Get('DatabaseHost');
152 $db_host = undef unless $db_host;
153 my $db_name = RT->Config->Get('DatabaseName');
154 my $db_type = RT->Config->Get('DatabaseType');
155 $db_name = File::Spec->catfile($RT::VarPath, $db_name)
156 if $db_type eq 'SQLite' && !File::Spec->file_name_is_absolute($db_name);
157
158 my %args = (
159 Host => $db_host,
160 Database => $db_name,
161 Port => $db_port,
162 Driver => $db_type,
163 RequireSSL => RT->Config->Get('DatabaseRequireSSL'),
164 DisconnectHandleOnDestroy => 1,
165 );
166 if ( $db_type eq 'Oracle' && $db_host ) {
167 $args{'SID'} = delete $args{'Database'};
168 }
169 $self->SUPER::BuildDSN( %args );
170}
171
172=head2 DSN
173
174Returns the DSN for this handle. In order to get correct value you must
175build DSN first, see L</BuildDSN>.
176
177This is method can be called as class method, in this case creates
178temporary handle object, L</BuildDSN builds DSN> and returns it.
179
180=cut
181
182sub DSN {
183 my $self = shift;
184 return $self->SUPER::DSN if ref $self;
185
186 my $handle = $self->new;
187 $handle->BuildDSN;
188 return $handle->DSN;
189}
190
191=head2 SystemDSN
192
193Returns a DSN suitable for database creates and drops
194and user creates and drops.
195
196Gets RT's DSN first (see L<DSN>) and then change it according
197to requirements of a database system RT's using.
198
199=cut
200
201sub SystemDSN {
202 my $self = shift;
203
204 my $db_name = RT->Config->Get('DatabaseName');
205 my $db_type = RT->Config->Get('DatabaseType');
206
207 my $dsn = $self->DSN;
208 if ( $db_type eq 'mysql' ) {
209 # with mysql, you want to connect sans database to funge things
210 $dsn =~ s/dbname=\Q$db_name//;
211 }
212 elsif ( $db_type eq 'Pg' ) {
213 # with postgres, you want to connect to template1 database
214 $dsn =~ s/dbname=\Q$db_name/dbname=template1/;
215 }
216 return $dsn;
217}
218
219=head2 Database compatibility and integrity checks
220
221
222
223=cut
224
225sub CheckIntegrity {
226 my $self = shift;
227 $self = new $self unless ref $self;
228
229 unless ($RT::Handle and $RT::Handle->dbh) {
230 local $@;
231 unless ( eval { RT::ConnectToDatabase(); 1 } ) {
232 return (0, 'no connection', "$@");
233 }
234 }
235
236 require RT::CurrentUser;
237 my $test_user = RT::CurrentUser->new;
238 $test_user->Load('RT_System');
239 unless ( $test_user->id ) {
240 return (0, 'no system user', "Couldn't find RT_System user in the DB '". $self->DSN ."'");
241 }
242
243 $test_user = RT::CurrentUser->new;
244 $test_user->Load('Nobody');
245 unless ( $test_user->id ) {
246 return (0, 'no nobody user', "Couldn't find Nobody user in the DB '". $self->DSN ."'");
247 }
248
249 return $RT::Handle->dbh;
250}
251
252sub CheckCompatibility {
253 my $self = shift;
254 my $dbh = shift;
255 my $state = shift || 'post';
256
257 my $db_type = RT->Config->Get('DatabaseType');
258 if ( $db_type eq "mysql" ) {
259 # Check which version we're running
260 my $version = ($dbh->selectrow_array("show variables like 'version'"))[1];
261 return (0, "couldn't get version of the mysql server")
262 unless $version;
263
264 ($version) = $version =~ /^(\d+\.\d+)/;
265 return (0, "RT is unsupported on MySQL versions before 4.0.x, it's $version")
266 if $version < 4;
267
268 # MySQL must have InnoDB support
269 my $innodb = ($dbh->selectrow_array("show variables like 'have_innodb'"))[1];
270 if ( lc $innodb eq "no" ) {
271 return (0, "RT requires that MySQL be compiled with InnoDB table support.\n".
272 "See http://dev.mysql.com/doc/mysql/en/InnoDB.html");
273 } elsif ( lc $innodb eq "disabled" ) {
274 return (0, "RT requires that MySQL InnoDB table support be enabled.\n".
275 "Remove the 'skip-innodb' line from your my.cnf file, restart MySQL, and try again.\n");
276 }
277
278 if ( $state eq 'post' ) {
279 my $create_table = $dbh->selectrow_arrayref("SHOW CREATE TABLE Tickets")->[1];
280 unless ( $create_table =~ /(?:ENGINE|TYPE)\s*=\s*InnoDB/i ) {
281 return (0, "RT requires that all its tables be of InnoDB type. Upgrade RT tables.");
282 }
283 }
284 if ( $version >= 4.1 && $state eq 'post' ) {
285 my $create_table = $dbh->selectrow_arrayref("SHOW CREATE TABLE Attachments")->[1];
286 unless ( $create_table =~ /\bContent\b[^,]*BLOB/i ) {
287 return (0, "RT since version 3.8 has new schema for MySQL versions after 4.1.0\n"
288 ."Follow instructions in the UPGRADING.mysql file.");
289 }
290 }
291 }
292 return (1)
293}
294
295sub CheckSphinxSE {
296 my $self = shift;
297
298 my $dbh = $RT::Handle->dbh;
299 local $dbh->{'RaiseError'} = 0;
300 local $dbh->{'PrintError'} = 0;
301 my $has = ($dbh->selectrow_array("show variables like 'have_sphinx'"))[1];
302 $has ||= ($dbh->selectrow_array(
303 "select 'yes' from INFORMATION_SCHEMA.PLUGINS where PLUGIN_NAME = 'sphinx' AND PLUGIN_STATUS='active'"
304 ))[0];
305
306 return 0 unless lc($has||'') eq "yes";
307 return 1;
308}
309
310=head2 Database maintanance
311
312=head3 CreateDatabase $DBH
313
314Creates a new database. This method can be used as class method.
315
316Takes DBI handle. Many database systems require special handle to
317allow you to create a new database, so you have to use L<SystemDSN>
318method during connection.
319
320Fetches type and name of the DB from the config.
321
322=cut
323
324sub CreateDatabase {
325 my $self = shift;
326 my $dbh = shift or return (0, "No DBI handle provided");
327 my $db_type = RT->Config->Get('DatabaseType');
328 my $db_name = RT->Config->Get('DatabaseName');
329
330 my $status;
331 if ( $db_type eq 'SQLite' ) {
332 return (1, 'Skipped as SQLite doesn\'t need any action');
333 }
334 elsif ( $db_type eq 'Oracle' ) {
335 my $db_user = RT->Config->Get('DatabaseUser');
336 my $db_pass = RT->Config->Get('DatabasePassword');
337 $status = $dbh->do(
338 "CREATE USER $db_user IDENTIFIED BY $db_pass"
339 ." default tablespace USERS"
340 ." temporary tablespace TEMP"
341 ." quota unlimited on USERS"
342 );
343 unless ( $status ) {
344 return $status, "Couldn't create user $db_user identified by $db_pass."
345 ."\nError: ". $dbh->errstr;
346 }
347 $status = $dbh->do( "GRANT connect, resource TO $db_user" );
348 unless ( $status ) {
349 return $status, "Couldn't grant connect and resource to $db_user."
350 ."\nError: ". $dbh->errstr;
351 }
352 return (1, "Created user $db_user. All RT's objects should be in his schema.");
353 }
354 elsif ( $db_type eq 'Pg' ) {
355 $status = $dbh->do("CREATE DATABASE $db_name WITH ENCODING='UNICODE' TEMPLATE template0");
356 }
357 else {
358 $status = $dbh->do("CREATE DATABASE $db_name");
359 }
360 return ($status, $DBI::errstr);
361}
362
363=head3 DropDatabase $DBH
364
365Drops RT's database. This method can be used as class method.
366
367Takes DBI handle as first argument. Many database systems require
368a special handle to allow you to drop a database, so you may have
369to use L<SystemDSN> when acquiring the DBI handle.
370
371Fetches the type and name of the database from the config.
372
373=cut
374
375sub DropDatabase {
376 my $self = shift;
377 my $dbh = shift or return (0, "No DBI handle provided");
378
379 my $db_type = RT->Config->Get('DatabaseType');
380 my $db_name = RT->Config->Get('DatabaseName');
381
382 if ( $db_type eq 'Oracle' ) {
383 my $db_user = RT->Config->Get('DatabaseUser');
384 my $status = $dbh->do( "DROP USER $db_user CASCADE" );
385 unless ( $status ) {
386 return 0, "Couldn't drop user $db_user."
387 ."\nError: ". $dbh->errstr;
388 }
389 return (1, "Successfully dropped user '$db_user' with his schema.");
390 }
391 elsif ( $db_type eq 'SQLite' ) {
392 my $path = $db_name;
393 $path = "$RT::VarPath/$path" unless substr($path, 0, 1) eq '/';
394 unlink $path or return (0, "Couldn't remove '$path': $!");
395 return (1);
396 } else {
397 $dbh->do("DROP DATABASE ". $db_name)
398 or return (0, $DBI::errstr);
399 }
400 return (1);
401}
402
403=head2 InsertACL
404
405=cut
406
407sub InsertACL {
408 my $self = shift;
409 my $dbh = shift;
410 my $base_path = shift || $RT::EtcPath;
411
412 my $db_type = RT->Config->Get('DatabaseType');
413 return (1) if $db_type eq 'SQLite';
414
415 $dbh = $self->dbh if !$dbh && ref $self;
416 return (0, "No DBI handle provided") unless $dbh;
417
418 return (0, "'$base_path' doesn't exist") unless -e $base_path;
419
420 my $path;
421 if ( -d $base_path ) {
422 $path = File::Spec->catfile( $base_path, "acl.$db_type");
423 $path = $self->GetVersionFile($dbh, $path);
424
425 $path = File::Spec->catfile( $base_path, "acl")
426 unless $path && -e $path;
427 return (0, "Couldn't find ACLs for $db_type")
428 unless -e $path;
429 } else {
430 $path = $base_path;
431 }
432
433 local *acl;
434 do $path || return (0, "Couldn't load ACLs: " . $@);
435 my @acl = acl($dbh);
436 foreach my $statement (@acl) {
437 my $sth = $dbh->prepare($statement)
438 or return (0, "Couldn't prepare SQL query:\n $statement\n\nERROR: ". $dbh->errstr);
439 unless ( $sth->execute ) {
440 return (0, "Couldn't run SQL query:\n $statement\n\nERROR: ". $sth->errstr);
441 }
442 }
443 return (1);
444}
445
446=head2 InsertSchema
447
448=cut
449
450sub InsertSchema {
451 my $self = shift;
452 my $dbh = shift;
453 my $base_path = (shift || $RT::EtcPath);
454
455 $dbh = $self->dbh if !$dbh && ref $self;
456 return (0, "No DBI handle provided") unless $dbh;
457
458 my $db_type = RT->Config->Get('DatabaseType');
459
460 my $file;
461 if ( -d $base_path ) {
462 $file = $base_path . "/schema." . $db_type;
463 } else {
464 $file = $base_path;
465 }
466
467 $file = $self->GetVersionFile( $dbh, $file );
468 unless ( $file ) {
469 return (0, "Couldn't find schema file(s) '$file*'");
470 }
471 unless ( -f $file && -r $file ) {
472 return (0, "File '$file' doesn't exist or couldn't be read");
473 }
474
475 my (@schema);
476
477 open( my $fh_schema, '<', $file ) or die $!;
478
479 my $has_local = 0;
480 open( my $fh_schema_local, "<" . $self->GetVersionFile( $dbh, $RT::LocalEtcPath . "/schema." . $db_type ))
481 and $has_local = 1;
482
483 my $statement = "";
484 foreach my $line ( <$fh_schema>, ($_ = ';;'), $has_local? <$fh_schema_local>: () ) {
485 $line =~ s/\#.*//g;
486 $line =~ s/--.*//g;
487 $statement .= $line;
488 if ( $line =~ /;(\s*)$/ ) {
489 $statement =~ s/;(\s*)$//g;
490 push @schema, $statement;
491 $statement = "";
492 }
493 }
494 close $fh_schema; close $fh_schema_local;
495
496 if ( $db_type eq 'Oracle' ) {
497 my $db_user = RT->Config->Get('DatabaseUser');
498 my $status = $dbh->do( "ALTER SESSION SET CURRENT_SCHEMA=$db_user" );
499 unless ( $status ) {
500 return $status, "Couldn't set current schema to $db_user."
501 ."\nError: ". $dbh->errstr;
502 }
503 }
504
505 local $SIG{__WARN__} = sub {};
506 my $is_local = 0;
507 $dbh->begin_work or return (0, "Couldn't begin transaction: ". $dbh->errstr);
508 foreach my $statement (@schema) {
509 if ( $statement =~ /^\s*;$/ ) {
510 $is_local = 1; next;
511 }
512
513 my $sth = $dbh->prepare($statement)
514 or return (0, "Couldn't prepare SQL query:\n$statement\n\nERROR: ". $dbh->errstr);
515 unless ( $sth->execute or $is_local ) {
516 return (0, "Couldn't run SQL query:\n$statement\n\nERROR: ". $sth->errstr);
517 }
518 }
519 $dbh->commit or return (0, "Couldn't commit transaction: ". $dbh->errstr);
520 return (1);
521}
522
523=head1 GetVersionFile
524
525Takes base name of the file as argument, scans for <base name>-<version> named
526files and returns file name with closest version to the version of the RT DB.
527
528=cut
529
530sub GetVersionFile {
531 my $self = shift;
532 my $dbh = shift;
533 my $base_name = shift;
534
535 my $db_version = ref $self
536 ? $self->DatabaseVersion
537 : do {
538 my $tmp = RT::Handle->new;
539 $tmp->dbh($dbh);
540 $tmp->DatabaseVersion;
541 };
542
543 require File::Glob;
544 my @files = File::Glob::bsd_glob("$base_name*");
545 return '' unless @files;
546
547 my %version = map { $_ =~ /\.\w+-([-\w\.]+)$/; ($1||0) => $_ } @files;
548 my $version;
549 foreach ( reverse sort cmp_version keys %version ) {
550 if ( cmp_version( $db_version, $_ ) >= 0 ) {
551 $version = $_;
552 last;
553 }
554 }
555
556 return defined $version? $version{ $version } : undef;
557}
558
559{ my %word = (
560 a => -4,
561 alpha => -4,
562 b => -3,
563 beta => -3,
564 pre => -2,
565 rc => -1,
566 head => 9999,
567);
568sub cmp_version($$) {
569 my ($a, $b) = (@_);
570 my @a = grep defined, map { /^[0-9]+$/? $_ : /^[a-zA-Z]+$/? $word{$_}|| -10 : undef }
571 split /([^0-9]+)/, $a;
572 my @b = grep defined, map { /^[0-9]+$/? $_ : /^[a-zA-Z]+$/? $word{$_}|| -10 : undef }
573 split /([^0-9]+)/, $b;
574 @a > @b
575 ? push @b, (0) x (@a-@b)
576 : push @a, (0) x (@b-@a);
577 for ( my $i = 0; $i < @a; $i++ ) {
578 return $a[$i] <=> $b[$i] if $a[$i] <=> $b[$i];
579 }
580 return 0;
581}}
582
583
584=head2 InsertInitialData
585
586Inserts system objects into RT's DB, like system user or 'nobody',
587internal groups and other records required. However, this method
588doesn't insert any real users like 'root' and you have to use
589InsertData or another way to do that.
590
591Takes no arguments. Returns status and message tuple.
592
593It's safe to call this method even if those objects already exist.
594
595=cut
596
597sub InsertInitialData {
598 my $self = shift;
599
600 my @warns;
601
602 # create RT_System user and grant him rights
603 {
604 require RT::CurrentUser;
605
606 my $test_user = RT::User->new( RT::CurrentUser->new() );
607 $test_user->Load('RT_System');
608 if ( $test_user->id ) {
609 push @warns, "Found system user in the DB.";
610 }
611 else {
612 my $user = RT::User->new( RT::CurrentUser->new() );
613 my ( $val, $msg ) = $user->_BootstrapCreate(
614 Name => 'RT_System',
615 RealName => 'The RT System itself',
616 Comments => 'Do not delete or modify this user. '
617 . 'It is integral to RT\'s internal database structures',
618 Creator => '1',
619 LastUpdatedBy => '1',
620 );
621 return ($val, $msg) unless $val;
622 }
623 DBIx::SearchBuilder::Record::Cachable->FlushCache;
624 }
625
626 # init RT::SystemUser and RT::System objects
627 RT::InitSystemObjects();
628 unless ( RT->SystemUser->id ) {
629 return (0, "Couldn't load system user");
630 }
631
632 # grant SuperUser right to system user
633 {
634 my $test_ace = RT::ACE->new( RT->SystemUser );
635 $test_ace->LoadByCols(
636 PrincipalId => ACLEquivGroupId( RT->SystemUser->Id ),
637 PrincipalType => 'Group',
638 RightName => 'SuperUser',
639 ObjectType => 'RT::System',
640 ObjectId => 1,
641 );
642 if ( $test_ace->id ) {
643 push @warns, "System user has global SuperUser right.";
644 } else {
645 my $ace = RT::ACE->new( RT->SystemUser );
646 my ( $val, $msg ) = $ace->_BootstrapCreate(
647 PrincipalId => ACLEquivGroupId( RT->SystemUser->Id ),
648 PrincipalType => 'Group',
649 RightName => 'SuperUser',
650 ObjectType => 'RT::System',
651 ObjectId => 1,
652 );
653 return ($val, $msg) unless $val;
654 }
655 DBIx::SearchBuilder::Record::Cachable->FlushCache;
656 }
657
658 # system groups
659 # $self->loc('Everyone'); # For the string extractor to get a string to localize
660 # $self->loc('Privileged'); # For the string extractor to get a string to localize
661 # $self->loc('Unprivileged'); # For the string extractor to get a string to localize
662 foreach my $name (qw(Everyone Privileged Unprivileged)) {
663 my $group = RT::Group->new( RT->SystemUser );
664 $group->LoadSystemInternalGroup( $name );
665 if ( $group->id ) {
666 push @warns, "System group '$name' already exists.";
667 next;
668 }
669
670 $group = RT::Group->new( RT->SystemUser );
671 my ( $val, $msg ) = $group->_Create(
672 Type => $name,
673 Domain => 'SystemInternal',
674 Description => 'Pseudogroup for internal use', # loc
675 Name => '',
676 Instance => '',
677 );
678 return ($val, $msg) unless $val;
679 }
680
681 # nobody
682 {
683 my $user = RT::User->new( RT->SystemUser );
684 $user->Load('Nobody');
685 if ( $user->id ) {
686 push @warns, "Found 'Nobody' user in the DB.";
687 }
688 else {
689 my ( $val, $msg ) = $user->Create(
690 Name => 'Nobody',
691 RealName => 'Nobody in particular',
692 Comments => 'Do not delete or modify this user. It is integral '
693 .'to RT\'s internal data structures',
694 Privileged => 0,
695 );
696 return ($val, $msg) unless $val;
697 }
698
699 if ( $user->HasRight( Right => 'OwnTicket', Object => $RT::System ) ) {
700 push @warns, "User 'Nobody' has global OwnTicket right.";
701 } else {
702 my ( $val, $msg ) = $user->PrincipalObj->GrantRight(
703 Right => 'OwnTicket',
704 Object => $RT::System,
705 );
706 return ($val, $msg) unless $val;
707 }
708 }
709
710 # rerun to get init Nobody as well
711 RT::InitSystemObjects();
712
713 # system role groups
714 foreach my $name (qw(Owner Requestor Cc AdminCc)) {
715 my $group = RT::Group->new( RT->SystemUser );
716 $group->LoadSystemRoleGroup( $name );
717 if ( $group->id ) {
718 push @warns, "System role '$name' already exists.";
719 next;
720 }
721
722 $group = RT::Group->new( RT->SystemUser );
723 my ( $val, $msg ) = $group->_Create(
724 Type => $name,
725 Domain => 'RT::System-Role',
726 Description => 'SystemRolegroup for internal use', # loc
727 Name => '',
728 Instance => '',
729 );
730 return ($val, $msg) unless $val;
731 }
732
733 push @warns, "You appear to have a functional RT database."
734 if @warns;
735
736 return (1, join "\n", @warns);
737}
738
739=head2 InsertData
740
741Load some sort of data into the database, takes path to a file.
742
743=cut
744
745sub InsertData {
746 my $self = shift;
747 my $datafile = shift;
748 my $root_password = shift;
749
750 # Slurp in stuff to insert from the datafile. Possible things to go in here:-
751 our (@Groups, @Users, @ACL, @Queues, @ScripActions, @ScripConditions,
752 @Templates, @CustomFields, @Scrips, @Attributes, @Initial, @Final);
753 local (@Groups, @Users, @ACL, @Queues, @ScripActions, @ScripConditions,
754 @Templates, @CustomFields, @Scrips, @Attributes, @Initial, @Final);
755
756 local $@;
757 $RT::Logger->debug("Going to load '$datafile' data file");
758 eval { require $datafile }
759 or return (0, "Couldn't load data from '$datafile' for import:\n\nERROR:". $@);
760
761 if ( @Initial ) {
762 $RT::Logger->debug("Running initial actions...");
763 foreach ( @Initial ) {
764 local $@;
765 eval { $_->(); 1 } or return (0, "One of initial functions failed: $@");
766 }
767 $RT::Logger->debug("Done.");
768 }
769 if ( @Groups ) {
770 $RT::Logger->debug("Creating groups...");
771 foreach my $item (@Groups) {
772 my $new_entry = RT::Group->new( RT->SystemUser );
773 my $member_of = delete $item->{'MemberOf'};
774 my ( $return, $msg ) = $new_entry->_Create(%$item);
775 unless ( $return ) {
776 $RT::Logger->error( $msg );
777 next;
778 } else {
779 $RT::Logger->debug($return .".");
780 }
781 if ( $member_of ) {
782 $member_of = [ $member_of ] unless ref $member_of eq 'ARRAY';
783 foreach( @$member_of ) {
784 my $parent = RT::Group->new(RT->SystemUser);
785 if ( ref $_ eq 'HASH' ) {
786 $parent->LoadByCols( %$_ );
787 }
788 elsif ( !ref $_ ) {
789 $parent->LoadUserDefinedGroup( $_ );
790 }
791 else {
792 $RT::Logger->error(
793 "(Error: wrong format of MemberOf field."
794 ." Should be name of user defined group or"
795 ." hash reference with 'column => value' pairs."
796 ." Use array reference to add to multiple groups)"
797 );
798 next;
799 }
800 unless ( $parent->Id ) {
801 $RT::Logger->error("(Error: couldn't load group to add member)");
802 next;
803 }
804 my ( $return, $msg ) = $parent->AddMember( $new_entry->Id );
805 unless ( $return ) {
806 $RT::Logger->error( $msg );
807 } else {
808 $RT::Logger->debug( $return ."." );
809 }
810 }
811 }
812 }
813 $RT::Logger->debug("done.");
814 }
815 if ( @Users ) {
816 $RT::Logger->debug("Creating users...");
817 foreach my $item (@Users) {
818 if ( $item->{'Name'} eq 'root' && $root_password ) {
819 $item->{'Password'} = $root_password;
820 }
821 my $new_entry = RT::User->new( RT->SystemUser );
822 my ( $return, $msg ) = $new_entry->Create(%$item);
823 unless ( $return ) {
824 $RT::Logger->error( $msg );
825 } else {
826 $RT::Logger->debug( $return ."." );
827 }
828 }
829 $RT::Logger->debug("done.");
830 }
831 if ( @Queues ) {
832 $RT::Logger->debug("Creating queues...");
833 for my $item (@Queues) {
834 my $new_entry = RT::Queue->new(RT->SystemUser);
835 my ( $return, $msg ) = $new_entry->Create(%$item);
836 unless ( $return ) {
837 $RT::Logger->error( $msg );
838 } else {
839 $RT::Logger->debug( $return ."." );
840 }
841 }
842 $RT::Logger->debug("done.");
843 }
844 if ( @CustomFields ) {
845 $RT::Logger->debug("Creating custom fields...");
846 for my $item ( @CustomFields ) {
847 my $new_entry = RT::CustomField->new( RT->SystemUser );
848 my $values = delete $item->{'Values'};
849
850 my @queues;
851 # if ref then it's list of queues, so we do things ourself
852 if ( exists $item->{'Queue'} && ref $item->{'Queue'} ) {
853 $item->{'LookupType'} ||= 'RT::Queue-RT::Ticket';
854 @queues = @{ delete $item->{'Queue'} };
855 }
856
857 my ( $return, $msg ) = $new_entry->Create(%$item);
858 unless( $return ) {
859 $RT::Logger->error( $msg );
860 next;
861 }
862
863 if ( $item->{'BasedOn'} ) {
864 my $basedon = RT::CustomField->new($RT::SystemUser);
865 my ($ok, $msg ) = $basedon->LoadByCols( Name => $item->{'BasedOn'},
866 LookupType => $new_entry->LookupType );
867 if ($ok) {
868 ($ok, $msg) = $new_entry->SetBasedOn( $basedon );
869 if ($ok) {
870 $RT::Logger->debug("Added BasedOn $item->{BasedOn}: $msg");
871 } else {
872 $RT::Logger->error("Failed to add basedOn $item->{BasedOn}: $msg");
873 }
874 } else {
875 $RT::Logger->error("Unable to load $item->{BasedOn} as a $item->{LookupType} CF. Skipping BasedOn");
876 }
877 }
878
879 foreach my $value ( @{$values} ) {
880 my ( $return, $msg ) = $new_entry->AddValue(%$value);
881 $RT::Logger->error( $msg ) unless $return;
882 }
883
884 # apply by default
885 if ( !@queues && !exists $item->{'Queue'} && $item->{LookupType} ) {
886 my $ocf = RT::ObjectCustomField->new(RT->SystemUser);
887 $ocf->Create( CustomField => $new_entry->Id );
888 }
889
890 for my $q (@queues) {
891 my $q_obj = RT::Queue->new(RT->SystemUser);
892 $q_obj->Load($q);
893 unless ( $q_obj->Id ) {
894 $RT::Logger->error("Could not find queue ". $q );
895 next;
896 }
897 my $OCF = RT::ObjectCustomField->new(RT->SystemUser);
898 ( $return, $msg ) = $OCF->Create(
899 CustomField => $new_entry->Id,
900 ObjectId => $q_obj->Id,
901 );
902 $RT::Logger->error( $msg ) unless $return and $OCF->Id;
903 }
904 }
905
906 $RT::Logger->debug("done.");
907 }
908 if ( @ACL ) {
909 $RT::Logger->debug("Creating ACL...");
910 for my $item (@ACL) {
911
912 my ($princ, $object);
913
914 # Global rights or Queue rights?
915 if ( $item->{'CF'} ) {
916 $object = RT::CustomField->new( RT->SystemUser );
917 my @columns = ( Name => $item->{'CF'} );
918 push @columns, Queue => $item->{'Queue'} if $item->{'Queue'} and not ref $item->{'Queue'};
919 $object->LoadByName( @columns );
920 } elsif ( $item->{'Queue'} ) {
921 $object = RT::Queue->new(RT->SystemUser);
922 $object->Load( $item->{'Queue'} );
923 } else {
924 $object = $RT::System;
925 }
926
927 $RT::Logger->error("Couldn't load object") and next unless $object and $object->Id;
928
929 # Group rights or user rights?
930 if ( $item->{'GroupDomain'} ) {
931 $princ = RT::Group->new(RT->SystemUser);
932 if ( $item->{'GroupDomain'} eq 'UserDefined' ) {
933 $princ->LoadUserDefinedGroup( $item->{'GroupId'} );
934 } elsif ( $item->{'GroupDomain'} eq 'SystemInternal' ) {
935 $princ->LoadSystemInternalGroup( $item->{'GroupType'} );
936 } elsif ( $item->{'GroupDomain'} eq 'RT::System-Role' ) {
937 $princ->LoadSystemRoleGroup( $item->{'GroupType'} );
938 } elsif ( $item->{'GroupDomain'} eq 'RT::Queue-Role' &&
939 $item->{'Queue'} )
940 {
941 $princ->LoadQueueRoleGroup( Type => $item->{'GroupType'},
942 Queue => $object->id);
943 } else {
944 $princ->Load( $item->{'GroupId'} );
945 }
946 unless ( $princ->Id ) {
947 RT->Logger->error("Unable to load Group: GroupDomain => $item->{GroupDomain}, GroupId => $item->{GroupId}, Queue => $item->{Queue}");
948 next;
949 }
950 } else {
951 $princ = RT::User->new(RT->SystemUser);
952 my ($ok, $msg) = $princ->Load( $item->{'UserId'} );
953 unless ( $ok ) {
954 RT->Logger->error("Unable to load user: $item->{UserId} : $msg");
955 next;
956 }
957 }
958
959 # Grant it
960 my ( $return, $msg ) = $princ->PrincipalObj->GrantRight(
961 Right => $item->{'Right'},
962 Object => $object
963 );
964 unless ( $return ) {
965 $RT::Logger->error( $msg );
966 }
967 else {
968 $RT::Logger->debug( $return ."." );
969 }
970 }
971 $RT::Logger->debug("done.");
972 }
973
974 if ( @ScripActions ) {
975 $RT::Logger->debug("Creating ScripActions...");
976
977 for my $item (@ScripActions) {
978 my $new_entry = RT::ScripAction->new(RT->SystemUser);
979 my ( $return, $msg ) = $new_entry->Create(%$item);
980 unless ( $return ) {
981 $RT::Logger->error( $msg );
982 }
983 else {
984 $RT::Logger->debug( $return ."." );
985 }
986 }
987
988 $RT::Logger->debug("done.");
989 }
990
991 if ( @ScripConditions ) {
992 $RT::Logger->debug("Creating ScripConditions...");
993
994 for my $item (@ScripConditions) {
995 my $new_entry = RT::ScripCondition->new(RT->SystemUser);
996 my ( $return, $msg ) = $new_entry->Create(%$item);
997 unless ( $return ) {
998 $RT::Logger->error( $msg );
999 }
1000 else {
1001 $RT::Logger->debug( $return ."." );
1002 }
1003 }
1004
1005 $RT::Logger->debug("done.");
1006 }
1007
1008 if ( @Templates ) {
1009 $RT::Logger->debug("Creating templates...");
1010
1011 for my $item (@Templates) {
1012 my $new_entry = RT::Template->new(RT->SystemUser);
1013 my ( $return, $msg ) = $new_entry->Create(%$item);
1014 unless ( $return ) {
1015 $RT::Logger->error( $msg );
1016 }
1017 else {
1018 $RT::Logger->debug( $return ."." );
1019 }
1020 }
1021 $RT::Logger->debug("done.");
1022 }
1023 if ( @Scrips ) {
1024 $RT::Logger->debug("Creating scrips...");
1025
1026 for my $item (@Scrips) {
1027 my $new_entry = RT::Scrip->new(RT->SystemUser);
1028
1029 my @queues = ref $item->{'Queue'} eq 'ARRAY'? @{ $item->{'Queue'} }: $item->{'Queue'} || 0;
1030 push @queues, 0 unless @queues; # add global queue at least
1031
1032 foreach my $q ( @queues ) {
1033 my ( $return, $msg ) = $new_entry->Create( %$item, Queue => $q );
1034 unless ( $return ) {
1035 $RT::Logger->error( $msg );
1036 }
1037 else {
1038 $RT::Logger->debug( $return ."." );
1039 }
1040 }
1041 }
1042 $RT::Logger->debug("done.");
1043 }
1044 if ( @Attributes ) {
1045 $RT::Logger->debug("Creating attributes...");
1046 my $sys = RT::System->new(RT->SystemUser);
1047
1048 for my $item (@Attributes) {
1049 my $obj = delete $item->{Object}; # XXX: make this something loadable
1050 $obj ||= $sys;
1051 my ( $return, $msg ) = $obj->AddAttribute (%$item);
1052 unless ( $return ) {
1053 $RT::Logger->error( $msg );
1054 }
1055 else {
1056 $RT::Logger->debug( $return ."." );
1057 }
1058 }
1059 $RT::Logger->debug("done.");
1060 }
1061 if ( @Final ) {
1062 $RT::Logger->debug("Running final actions...");
1063 for ( @Final ) {
1064 local $@;
1065 eval { $_->(); };
1066 $RT::Logger->error( "Failed to run one of final actions: $@" )
1067 if $@;
1068 }
1069 $RT::Logger->debug("done.");
1070 }
1071
1072 my $db_type = RT->Config->Get('DatabaseType');
1073 $RT::Handle->Disconnect() unless $db_type eq 'SQLite';
1074
1075 $RT::Logger->debug("Done setting up database content.");
1076
1077# TODO is it ok to return 1 here? If so, the previous codes in this sub
1078# should return (0, $msg) if error happens instead of just warning.
1079# anyway, we need to return something here to tell if everything is ok
1080 return( 1, 'Done inserting data' );
1081}
1082
1083=head2 ACLEquivGroupId
1084
1085Given a userid, return that user's acl equivalence group
1086
1087=cut
1088
1089sub ACLEquivGroupId {
1090 my $id = shift;
1091
1092 my $cu = RT->SystemUser;
1093 unless ( $cu ) {
1094 require RT::CurrentUser;
1095 $cu = RT::CurrentUser->new;
1096 $cu->LoadByName('RT_System');
1097 warn "Couldn't load RT_System user" unless $cu->id;
1098 }
1099
1100 my $equiv_group = RT::Group->new( $cu );
1101 $equiv_group->LoadACLEquivalenceGroup( $id );
1102 return $equiv_group->Id;
1103}
1104
1105=head2 QueryHistory
1106
1107Returns the SQL query history associated with this handle. The top level array
1108represents a lists of request. Each request is a hash with metadata about the
1109request (such as the URL) and a list of queries. You'll probably not be using this.
1110
1111=cut
1112
1113sub QueryHistory {
1114 my $self = shift;
1115
1116 return $self->{QueryHistory};
1117}
1118
1119=head2 AddRequestToHistory
1120
1121Adds a web request to the query history. It must be a hash with keys Path (a
1122string) and Queries (an array reference of arrays, where elements are time,
1123sql, bind parameters, and duration).
1124
1125=cut
1126
1127sub AddRequestToHistory {
1128 my $self = shift;
1129 my $request = shift;
1130
1131 push @{ $self->{QueryHistory} }, $request;
1132}
1133
1134=head2 Quote
1135
1136Returns the parameter quoted by DBI. B<You almost certainly do not need this.>
1137Use bind parameters (C<?>) instead. This is used only outside the scope of interacting
1138with the database.
1139
1140=cut
1141
1142sub Quote {
1143 my $self = shift;
1144 my $value = shift;
1145
1146 return $self->dbh->quote($value);
1147}
1148
1149=head2 FillIn
1150
1151Takes a SQL query and an array reference of bind parameters and fills in the
1152query's C<?> parameters.
1153
1154=cut
1155
1156sub FillIn {
1157 my $self = shift;
1158 my $sql = shift;
1159 my $bind = shift;
1160
1161 my $b = 0;
1162
1163 # is this regex sufficient?
1164 $sql =~ s{\?}{$self->Quote($bind->[$b++])}eg;
1165
1166 return $sql;
1167}
1168
1169# log a mason stack trace instead of a Carp::longmess because it's less painful
1170# and uses mason component paths properly
1171sub _LogSQLStatement {
1172 my $self = shift;
1173 my $statement = shift;
1174 my $duration = shift;
1175 my @bind = @_;
1176
1177 require HTML::Mason::Exceptions;
1178 push @{$self->{'StatementLog'}} , ([Time::HiRes::time(), $statement, [@bind], $duration, HTML::Mason::Exception->new->as_string]);
1179}
1180
1181__PACKAGE__->FinalizeDatabaseType;
1182
1183RT::Base->_ImportOverlays();
1184
11851;