1 # BEGIN BPS TAGGED BLOCK {{{
5 # This software is Copyright (c) 1996-2012 Best Practical Solutions, LLC
6 # <sales@bestpractical.com>
8 # (Except where explicitly superseded by other copyright notices)
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
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.
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.
30 # CONTRIBUTION SUBMISSION POLICY:
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.)
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.
47 # END BPS TAGGED BLOCK }}}
58 use vars qw($Config $System $SystemUser $Nobody $Handle $Logger $_Privileged $_Unprivileged $_INSTALL_MODE);
73 $MasonLocalComponentRoot
78 RT->LoadGeneratedData();
86 A fully featured request tracker package
94 Load RT's config file. First, the site configuration file
95 (F<RT_SiteConfig.pm>) is loaded, in order to establish overall site
96 settings like hostname and name of RT instance. Then, the core
97 configuration file (F<RT_Config.pm>) is loaded to set fallback values
98 for all settings; it bases some values on settings from the site
101 In order for the core configuration to not override the site's
102 settings, the function C<Set> is used; it only sets values if they
103 have not been set already.
109 $Config = RT::Config->new;
110 $Config->LoadConfigs;
113 # RT::Essentials mistakenly recommends that WebPath be set to '/'.
114 # If the user does that, do what they mean.
115 $RT::WebPath = '' if ($RT::WebPath eq '/');
117 # fix relative LogDir and GnuPG homedir
118 unless ( File::Spec->file_name_is_absolute( $Config->Get('LogDir') ) ) {
119 $Config->Set( LogDir =>
120 File::Spec->catfile( $BasePath, $Config->Get('LogDir') ) );
123 my $gpgopts = $Config->Get('GnuPGOptions');
124 unless ( File::Spec->file_name_is_absolute( $gpgopts->{homedir} ) ) {
125 $gpgopts->{homedir} = File::Spec->catfile( $BasePath, $gpgopts->{homedir} );
133 L<Connects to the database|/ConnectToDatabase>, L<initilizes system
134 objects|/InitSystemObjects>, L<preloads classes|/InitClasses>, L<sets
135 up logging|/InitLogging>, and L<loads plugins|/InitPlugins>.
141 CheckPerlRequirements();
145 #Get a database connection
152 RT->Config->PostLoadCheck;
156 =head2 ConnectToDatabase
158 Get a database connection. See also L</Handle>.
162 sub ConnectToDatabase {
164 $Handle = RT::Handle->new unless $Handle;
171 Create the Logger object and set up signal handlers.
179 # We have to set the record separator ($, man perlvar)
180 # or Log::Dispatch starts getting
181 # really pissy, as some other module we use unsets it.
183 use Log::Dispatch 1.6;
186 map( { $_ => } 0..7 ),
191 error => 4, 'err' => 4,
192 critical => 5, crit => 5,
194 emergency => 7, emerg => 7,
197 unless ( $RT::Logger ) {
199 $RT::Logger = Log::Dispatch->new;
201 my $stack_from_level;
202 if ( $stack_from_level = RT->Config->Get('LogStackTraces') ) {
203 # if option has old style '\d'(true) value
204 $stack_from_level = 0 if $stack_from_level =~ /^\d+$/;
205 $stack_from_level = $level_to_num{ $stack_from_level } || 0;
207 $stack_from_level = 99; # don't log
210 my $simple_cb = sub {
211 # if this code throw any warning we can get segfault
215 # skip Log::* stack frames
217 $frame++ while caller($frame) && caller($frame) =~ /^Log::/;
218 my ($package, $filename, $line) = caller($frame);
220 $p{'message'} =~ s/(?:\r*\n)+$//;
221 return "[". gmtime(time) ."] [". $p{'level'} ."]: "
222 . $p{'message'} ." ($filename:$line)\n";
225 my $syslog_cb = sub {
226 # if this code throw any warning we can get segfault
230 my $frame = 0; # stack frame index
231 # skip Log::* stack frames
232 $frame++ while caller($frame) && caller($frame) =~ /^Log::/;
233 my ($package, $filename, $line) = caller($frame);
235 # syswrite() cannot take utf8; turn it off here.
236 Encode::_utf8_off($p{message});
238 $p{message} =~ s/(?:\r*\n)+$//;
239 if ($p{level} eq 'debug') {
240 return "$p{message}\n";
242 return "$p{message} ($filename:$line)\n";
249 return $p{'message'} unless $level_to_num{ $p{'level'} } >= $stack_from_level;
251 require Devel::StackTrace;
252 my $trace = Devel::StackTrace->new( ignore_class => [ 'Log::Dispatch', 'Log::Dispatch::Base' ] );
253 return $p{'message'} . $trace->as_string;
255 # skip calling of the Log::* subroutins
257 $frame++ while caller($frame) && caller($frame) =~ /^Log::/;
258 $frame++ while caller($frame) && (caller($frame))[3] =~ /^Log::/;
260 $p{'message'} .= "\nStack trace:\n";
261 while( my ($package, $filename, $line, $sub) = caller($frame++) ) {
262 $p{'message'} .= "\t$sub(...) called at $filename:$line\n";
264 return $p{'message'};
267 if ( $Config->Get('LogToFile') ) {
268 my ($filename, $logdir) = (
269 $Config->Get('LogToFileNamed') || 'rt.log',
270 $Config->Get('LogDir') || File::Spec->catdir( $VarPath, 'log' ),
272 if ( $filename =~ m![/\\]! ) { # looks like an absolute path.
273 ($logdir) = $filename =~ m{^(.*[/\\])};
276 $filename = File::Spec->catfile( $logdir, $filename );
279 unless ( -d $logdir && ( ( -f $filename && -w $filename ) || -w $logdir ) ) {
280 # localizing here would be hard when we don't have a current user yet
281 die "Log file '$filename' couldn't be written or created.\n RT can't run.";
284 require Log::Dispatch::File;
285 $RT::Logger->add( Log::Dispatch::File->new
287 min_level=> $Config->Get('LogToFile'),
288 filename=> $filename,
290 callbacks => [ $simple_cb, $stack_cb ],
293 if ( $Config->Get('LogToScreen') ) {
294 require Log::Dispatch::Screen;
295 $RT::Logger->add( Log::Dispatch::Screen->new
297 min_level => $Config->Get('LogToScreen'),
298 callbacks => [ $simple_cb, $stack_cb ],
302 if ( $Config->Get('LogToSyslog') ) {
303 require Log::Dispatch::Syslog;
304 $RT::Logger->add(Log::Dispatch::Syslog->new
307 min_level => $Config->Get('LogToSyslog'),
308 callbacks => [ $syslog_cb, $stack_cb ],
310 $Config->Get('LogToSyslogConf'),
314 InitSignalHandlers(%arg);
317 sub InitSignalHandlers {
320 return if $arg{'NoSignalHandlers'};
323 ## This is the default handling of warnings and die'ings in the code
324 ## (including other used modules - maybe except for errors catched by
325 ## Mason). It will log all problems through the standard logging
326 ## mechanism (see above).
328 $SIG{__WARN__} = sub {
329 # The 'wide character' warnings has to be silenced for now, at least
330 # until HTML::Mason offers a sane way to process both raw output and
332 # use 'goto &foo' syntax to hide ANON sub from stack
333 if( index($_[0], 'Wide character in ') != 0 ) {
334 unshift @_, $RT::Logger, qw(level warning message);
335 goto &Log::Dispatch::log;
339 #When we call die, trap it and log->crit with the value of the die.
341 $SIG{__DIE__} = sub {
342 # if we are not in eval and perl is not parsing code
343 # then rollback transactions and log RT error
344 unless ($^S || !defined $^S ) {
345 $RT::Handle->Rollback(1) if $RT::Handle;
346 $RT::Logger->crit("$_[0]") if $RT::Logger;
353 sub CheckPerlRequirements {
354 if ($^V < 5.008003) {
355 die sprintf "RT requires Perl v5.8.3 or newer. Your current Perl is v%vd\n", $^V;
358 # use $error here so the following "die" can still affect the global $@
365 require Scalar::Util;
366 Scalar::Util::weaken($y);
374 RT requires the Scalar::Util module be built with support for the 'weaken'
377 It is sometimes the case that operating system upgrades will replace
378 a working Scalar::Util with a non-working one. If your system was working
379 correctly up until now, this is likely the cause of the problem.
381 Please reinstall Scalar::Util, being careful to let it build with your C
382 compiler. Usually this is as simple as running the following command as
385 perl -MCPAN -e'install Scalar::Util'
394 Load all modules that define base classes.
399 shift if @_%2; # so we can call it as a function or method
402 require RT::Transactions;
403 require RT::Attachments;
405 require RT::Principals;
406 require RT::CurrentUser;
407 require RT::Templates;
409 require RT::ScripActions;
410 require RT::ScripConditions;
413 require RT::GroupMembers;
414 require RT::CustomFields;
415 require RT::CustomFieldValues;
416 require RT::ObjectCustomFields;
417 require RT::ObjectCustomFieldValues;
418 require RT::Attributes;
419 require RT::Dashboard;
420 require RT::Approval;
421 require RT::Lifecycle;
425 require RT::Articles;
428 require RT::ObjectClass;
429 require RT::ObjectClasses;
430 require RT::ObjectTopic;
431 require RT::ObjectTopics;
435 # on a cold server (just after restart) people could have an object
436 # in the session, as we deserialize it so we never call constructor
437 # of the class, so the list of accessible fields is empty and we die
438 # with "Method xxx is not implemented in RT::SomeClass"
440 # without this, we also can never call _ClassAccessible, because we
441 # won't have filled RT::Record::_TABLE_ATTR
442 $_->_BuildTableAttributes foreach qw(
457 RT::ObjectCustomField
458 RT::ObjectCustomFieldValue
469 if ( $args{'Heavy'} ) {
470 # load scrips' modules
471 my $scrips = RT::Scrips->new(RT->SystemUser);
472 $scrips->Limit( FIELD => 'Stage', OPERATOR => '!=', VALUE => 'Disabled' );
473 while ( my $scrip = $scrips->Next ) {
475 eval { $scrip->LoadModules } or
476 $RT::Logger->error("Invalid Scrip ".$scrip->Id.". Unable to load the Action or Condition. ".
477 "You should delete or repair this Scrip in the admin UI.\n$@\n");
480 foreach my $class ( grep $_, RT->Config->Get('CustomFieldValuesSources') ) {
482 eval "require $class; 1" or $RT::Logger->error(
483 "Class '$class' is listed in CustomFieldValuesSources option"
484 ." in the config, but we failed to load it:\n$@\n"
491 =head2 InitSystemObjects
493 Initializes system objects: C<$RT::System>, C<< RT->SystemUser >>
494 and C<< RT->Nobody >>.
498 sub InitSystemObjects {
500 #RT's system user is a genuine database user. its id lives here
501 require RT::CurrentUser;
502 $SystemUser = RT::CurrentUser->new;
503 $SystemUser->LoadByName('RT_System');
505 #RT's "nobody user" is a genuine database user. its ID lives here.
506 $Nobody = RT::CurrentUser->new;
507 $Nobody->LoadByName('Nobody');
510 $System = RT::System->new( $SystemUser );
517 Returns the current L<config object|RT::Config>, but note that
518 you must L<load config|/LoadConfig> first otherwise this method
521 Method can be called as class method.
525 sub Config { return $Config || shift->LoadConfig(); }
527 =head2 DatabaseHandle
529 Returns the current L<database handle object|RT::Handle>.
531 See also L</ConnectToDatabase>.
535 sub DatabaseHandle { return $Handle }
539 Returns the logger. See also L</InitLogging>.
543 sub Logger { return $Logger }
547 Returns the current L<system object|RT::System>. See also
548 L</InitSystemObjects>.
552 sub System { return $System }
556 Returns the system user's object, it's object of
557 L<RT::CurrentUser> class that represents the system. See also
558 L</InitSystemObjects>.
562 sub SystemUser { return $SystemUser }
566 Returns object of Nobody. It's object of L<RT::CurrentUser> class
567 that represents a user who can own ticket and nothing else. See
568 also L</InitSystemObjects>.
572 sub Nobody { return $Nobody }
574 sub PrivilegedUsers {
576 $_Privileged = RT::Group->new(RT->SystemUser);
577 $_Privileged->LoadSystemInternalGroup('Privileged');
582 sub UnprivilegedUsers {
583 if (!$_Unprivileged) {
584 $_Unprivileged = RT::Group->new(RT->SystemUser);
585 $_Unprivileged->LoadSystemInternalGroup('Unprivileged');
587 return $_Unprivileged;
593 Returns a listref of all Plugins currently configured for this RT instance.
594 You can define plugins by adding them to the @Plugins list in your RT_SiteConfig
602 $self->InitPluginPaths;
603 @PLUGINS = $self->InitPlugins;
610 Takes an optional subdir (e.g. po, lib, etc.) and returns a list of
611 directories from plugins where that subdirectory exists.
613 This code does not check plugin names, plugin validitity, or load
614 plugins (see L</InitPlugins>) in any way, and requires that RT's
615 configuration have been already loaded.
626 foreach my $plugin (grep $_, RT->Config->Get('Plugins')) {
627 my $path = RT::Plugin->new( name => $plugin )->Path( $subdir );
628 next unless -d $path;
634 =head2 InitPluginPaths
636 Push plugins' lib paths into @INC right after F<local/lib>.
637 In case F<local/lib> isn't in @INC, append them to @INC
641 sub InitPluginPaths {
642 my $self = shift || __PACKAGE__;
644 my @lib_dirs = $self->PluginDirs('lib');
649 if ( Cwd::realpath($_) eq $RT::LocalLibPath) {
650 push @tmp_inc, $_, @lib_dirs;
657 # append @lib_dirs in case $RT::LocalLibPath isn't in @INC
658 push @tmp_inc, @lib_dirs unless $added;
661 @INC = grep !$seen{$_}++, @tmp_inc;
666 Initialize all Plugins found in the RT configuration file, setting up
667 their lib and L<HTML::Mason> component roots.
675 foreach my $plugin (grep $_, RT->Config->Get('Plugins')) {
677 die $UNIVERSAL::require::ERROR if ($UNIVERSAL::require::ERROR);
678 push @plugins, RT::Plugin->new(name =>$plugin);
687 my ($integrity, $state, $msg) = RT::Handle->CheckIntegrity;
688 if ($_[0] and $integrity) {
689 # Trying to turn install mode on but we have a good DB!
692 Carp::longmess("Something tried to turn on InstallMode but we have DB integrity!")
696 $_INSTALL_MODE = shift;
698 require RT::CurrentUser;
699 $SystemUser = RT::CurrentUser->new();
703 return $_INSTALL_MODE;
706 sub LoadGeneratedData {
708 my $pm_path = ( File::Spec->splitpath( $INC{'RT.pm'} ) )[1];
710 require "$pm_path/RT/Generated.pm" || die "Couldn't load RT::Generated: $@";
711 $class->CanonicalizeGeneratedPaths();
714 sub CanonicalizeGeneratedPaths {
716 unless ( File::Spec->file_name_is_absolute($EtcPath) ) {
718 # if BasePath exists and is absolute, we won't infer it from $INC{'RT.pm'}.
719 # otherwise RT.pm will make the source dir(where we configure RT) be the
720 # BasePath instead of the one specified by --prefix
721 unless ( -d $BasePath
722 && File::Spec->file_name_is_absolute($BasePath) )
724 my $pm_path = ( File::Spec->splitpath( $INC{'RT.pm'} ) )[1];
726 # need rel2abs here is to make sure path is absolute, since $INC{'RT.pm'}
727 # is not always absolute
728 $BasePath = File::Spec->rel2abs(
729 File::Spec->catdir( $pm_path, File::Spec->updir ) );
732 $BasePath = Cwd::realpath($BasePath);
735 qw/EtcPath BinPath SbinPath VarPath LocalPath LocalEtcPath
736 LocalLibPath LexiconPath LocalLexiconPath PluginPath
737 LocalPluginPath MasonComponentRoot MasonLocalComponentRoot
738 MasonDataDir MasonSessionDir/
743 # just change relative ones
744 $$path = File::Spec->catfile( $BasePath, $$path )
745 unless File::Spec->file_name_is_absolute($$path);
753 helper method to add js files to C<JSFiles> config.
754 to add extra js files, you can add the following line
755 in the plugin's main file:
757 RT->AddJavaScript( 'foo.js', 'bar.js' );
764 my @old = RT->Config->Get('JSFiles');
765 RT->Config->Set( 'JSFiles', @old, @_ );
766 return RT->Config->Get('JSFiles');
769 =head2 AddStyleSheets
771 helper method to add css files to C<CSSFiles> config
773 to add extra css files, you can add the following line
774 in the plugin's main file:
776 RT->AddStyleSheets( 'foo.css', 'bar.css' );
782 my @old = RT->Config->Get('CSSFiles');
783 RT->Config->Set( 'CSSFiles', @old, @_ );
784 return RT->Config->Get('CSSFiles');
789 helper method of RT->Config->Get('JSFiles')
794 return RT->Config->Get('JSFiles');
799 helper method of RT->Config->Get('CSSFiles')
804 return RT->Config->Get('CSSFiles');
809 Please report them to rt-bugs@bestpractical.com, if you know what's
810 broken and have at least some idea of what needs to be fixed.
812 If you're not sure what's going on, report them rt-devel@lists.bestpractical.com.
817 L<DBIx::SearchBuilder>
822 RT::Base->_ImportOverlays();