]> git.uio.no Git - usit-rt.git/blob - lib/RT/Config.pm
Upgrade to 4.0.10.
[usit-rt.git] / lib / RT / Config.pm
1 # BEGIN BPS TAGGED BLOCK {{{
2 #
3 # COPYRIGHT:
4 #
5 # This software is Copyright (c) 1996-2013 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::Config;
50
51 use strict;
52 use warnings;
53
54
55 use File::Spec ();
56
57 =head1 NAME
58
59     RT::Config - RT's config
60
61 =head1 SYNOPSYS
62
63     # get config object
64     use RT::Config;
65     my $config = RT::Config->new;
66     $config->LoadConfigs;
67
68     # get or set option
69     my $rt_web_path = $config->Get('WebPath');
70     $config->Set(EmailOutputEncoding => 'latin1');
71
72     # get config object from RT package
73     use RT;
74     RT->LoadConfig;
75     my $config = RT->Config;
76
77 =head1 DESCRIPTION
78
79 C<RT::Config> class provide access to RT's and RT extensions' config files.
80
81 RT uses two files for site configuring:
82
83 First file is F<RT_Config.pm> - core config file. This file is shipped
84 with RT distribution and contains default values for all available options.
85 B<You should never edit this file.>
86
87 Second file is F<RT_SiteConfig.pm> - site config file. You can use it
88 to customize your RT instance. In this file you can override any option
89 listed in core config file.
90
91 RT extensions could also provide thier config files. Extensions should
92 use F<< <NAME>_Config.pm >> and F<< <NAME>_SiteConfig.pm >> names for
93 config files, where <NAME> is extension name.
94
95 B<NOTE>: All options from RT's config and extensions' configs are saved
96 in one place and thus extension could override RT's options, but it is not
97 recommended.
98
99 =cut
100
101 =head2 %META
102
103 Hash of Config options that may be user overridable
104 or may require more logic than should live in RT_*Config.pm
105
106 Keyed by config name, there are several properties that
107 can be set for each config optin:
108
109  Section     - What header this option should be grouped
110                under on the user Settings page
111  Overridable - Can users change this option
112  SortOrder   - Within a Section, how should the options be sorted
113                for display to the user
114  Widget      - Mason component path to widget that should be used 
115                to display this config option
116  WidgetArguments - An argument hash passed to the WIdget
117     Description - Friendly description to show the user
118     Values      - Arrayref of options (for select Widget)
119     ValuesLabel - Hashref, key is the Value from the Values
120                   list, value is a user friendly description
121                   of the value
122     Callback    - subref that receives no arguments.  It returns
123                   a hashref of items that are added to the rest
124                   of the WidgetArguments
125  PostLoadCheck - subref passed the RT::Config object and the current
126                  setting of the config option.  Can make further checks
127                  (such as seeing if a library is installed) and then change
128                  the setting of this or other options in the Config using 
129                  the RT::Config option.
130    Obfuscate   - subref passed the RT::Config object, current setting of the config option
131                  and a user object, can return obfuscated value. it's called in
132                  RT->Config->GetObfuscated() 
133
134 =cut
135
136 our %META = (
137     # General user overridable options
138     DefaultQueue => {
139         Section         => 'General',
140         Overridable     => 1,
141         SortOrder       => 1,
142         Widget          => '/Widgets/Form/Select',
143         WidgetArguments => {
144             Description => 'Default queue',    #loc
145             Callback    => sub {
146                 my $ret = { Values => [], ValuesLabel => {}};
147                 my $q = RT::Queues->new($HTML::Mason::Commands::session{'CurrentUser'});
148                 $q->UnLimit;
149                 while (my $queue = $q->Next) {
150                     next unless $queue->CurrentUserHasRight("CreateTicket");
151                     push @{$ret->{Values}}, $queue->Id;
152                     $ret->{ValuesLabel}{$queue->Id} = $queue->Name;
153                 }
154                 return $ret;
155             },
156         }
157     },
158     RememberDefaultQueue => {
159         Section     => 'General',
160         Overridable => 1,
161         SortOrder   => 2,
162         Widget      => '/Widgets/Form/Boolean',
163         WidgetArguments => {
164             Description => 'Remember default queue' # loc
165         }
166     },
167     UsernameFormat => {
168         Section         => 'General',
169         Overridable     => 1,
170         SortOrder       => 3,
171         Widget          => '/Widgets/Form/Select',
172         WidgetArguments => {
173             Description => 'Username format', # loc
174             Values      => [qw(concise verbose)],
175             ValuesLabel => {
176                 concise => 'Short usernames', # loc
177                 verbose => 'Name and email address', # loc
178             },
179         },
180     },
181     AutocompleteOwners => {
182         Section     => 'General',
183         Overridable => 1,
184         SortOrder   => 3.1,
185         Widget      => '/Widgets/Form/Boolean',
186         WidgetArguments => {
187             Description => 'Use autocomplete to find owners?', # loc
188             Hints       => 'Replaces the owner dropdowns with textboxes' #loc
189         }
190     },
191     WebDefaultStylesheet => {
192         Section         => 'General',                #loc
193         Overridable     => 1,
194         SortOrder       => 4,
195         Widget          => '/Widgets/Form/Select',
196         WidgetArguments => {
197             Description => 'Theme',                  #loc
198             # XXX: we need support for 'get values callback'
199             Values => [qw(web2 aileron ballard)],
200         },
201         PostLoadCheck => sub {
202             my $self = shift;
203             my $value = $self->Get('WebDefaultStylesheet');
204
205             my @comp_roots = RT::Interface::Web->ComponentRoots;
206             for my $comp_root (@comp_roots) {
207                 return if -d $comp_root.'/NoAuth/css/'.$value;
208             }
209
210             $RT::Logger->warning(
211                 "The default stylesheet ($value) does not exist in this instance of RT. "
212               . "Defaulting to aileron."
213             );
214
215             $self->Set('WebDefaultStylesheet', 'aileron');
216         },
217     },
218     UseSideBySideLayout => {
219         Section => 'Ticket composition',
220         Overridable => 1,
221         SortOrder => 5,
222         Widget => '/Widgets/Form/Boolean',
223         WidgetArguments => {
224             Description => 'Use a two column layout for create and update forms?' # loc
225         }
226     },
227     MessageBoxRichText => {
228         Section => 'Ticket composition',
229         Overridable => 1,
230         SortOrder => 5.1,
231         Widget => '/Widgets/Form/Boolean',
232         WidgetArguments => {
233             Description => 'WYSIWYG message composer' # loc
234         }
235     },
236     MessageBoxRichTextHeight => {
237         Section => 'Ticket composition',
238         Overridable => 1,
239         SortOrder => 6,
240         Widget => '/Widgets/Form/Integer',
241         WidgetArguments => {
242             Description => 'WYSIWYG composer height', # loc
243         }
244     },
245     MessageBoxWidth => {
246         Section         => 'Ticket composition',
247         Overridable     => 1,
248         SortOrder       => 7,
249         Widget          => '/Widgets/Form/Integer',
250         WidgetArguments => {
251             Description => 'Message box width',           #loc
252         },
253     },
254     MessageBoxHeight => {
255         Section         => 'Ticket composition',
256         Overridable     => 1,
257         SortOrder       => 8,
258         Widget          => '/Widgets/Form/Integer',
259         WidgetArguments => {
260             Description => 'Message box height',          #loc
261         },
262     },
263     MessageBoxWrap => {
264         Section         => 'Ticket composition',                #loc
265         Overridable     => 1,
266         SortOrder       => 8.1,
267         Widget          => '/Widgets/Form/Select',
268         WidgetArguments => {
269             Description => 'Message box wrapping',   #loc
270             Values => [qw(SOFT HARD)],
271             Hints => "When the WYSIWYG editor is not enabled, this setting determines whether automatic line wraps in the ticket message box are sent to RT or not.",              # loc
272         },
273     },
274     DefaultTimeUnitsToHours => {
275         Section         => 'Ticket composition', #loc
276         Overridable     => 1,
277         SortOrder       => 9,
278         Widget          => '/Widgets/Form/Boolean',
279         WidgetArguments => {
280             Description => 'Enter time in hours by default', #loc
281             Hints       => 'Only for entry, not display', #loc
282         },
283     },
284     SearchResultsRefreshInterval => {
285         Section         => 'General',                       #loc
286         Overridable     => 1,
287         SortOrder       => 9,
288         Widget          => '/Widgets/Form/Select',
289         WidgetArguments => {
290             Description => 'Search results refresh interval',                            #loc
291             Values      => [qw(0 120 300 600 1200 3600 7200)],
292             ValuesLabel => {
293                 0 => "Don't refresh search results.",                      #loc
294                 120 => "Refresh search results every 2 minutes.",          #loc
295                 300 => "Refresh search results every 5 minutes.",          #loc
296                 600 => "Refresh search results every 10 minutes.",         #loc
297                 1200 => "Refresh search results every 20 minutes.",        #loc
298                 3600 => "Refresh search results every 60 minutes.",        #loc
299                 7200 => "Refresh search results every 120 minutes.",       #loc
300             },  
301         },  
302     },
303
304     # User overridable options for RT at a glance
305     DefaultSummaryRows => {
306         Section         => 'RT at a glance',    #loc
307         Overridable     => 1,
308         SortOrder       => 1,
309         Widget          => '/Widgets/Form/Integer',
310         WidgetArguments => {
311             Description => 'Number of search results',    #loc
312         },
313     },
314     HomePageRefreshInterval => {
315         Section         => 'RT at a glance',                       #loc
316         Overridable     => 1,
317         SortOrder       => 2,
318         Widget          => '/Widgets/Form/Select',
319         WidgetArguments => {
320             Description => 'Home page refresh interval',                #loc
321             Values      => [qw(0 120 300 600 1200 3600 7200)],
322             ValuesLabel => {
323                 0 => "Don't refresh home page.",                  #loc
324                 120 => "Refresh home page every 2 minutes.",      #loc
325                 300 => "Refresh home page every 5 minutes.",      #loc
326                 600 => "Refresh home page every 10 minutes.",     #loc
327                 1200 => "Refresh home page every 20 minutes.",    #loc
328                 3600 => "Refresh home page every 60 minutes.",    #loc
329                 7200 => "Refresh home page every 120 minutes.",   #loc
330             },  
331         },  
332     },
333
334     # User overridable options for Ticket displays
335     MaxInlineBody => {
336         Section         => 'Ticket display',              #loc
337         Overridable     => 1,
338         SortOrder       => 1,
339         Widget          => '/Widgets/Form/Integer',
340         WidgetArguments => {
341             Description => 'Maximum inline message length',    #loc
342             Hints =>
343             "Length in characters; Use '0' to show all messages inline, regardless of length" #loc
344         },
345     },
346     OldestTransactionsFirst => {
347         Section         => 'Ticket display',
348         Overridable     => 1,
349         SortOrder       => 2,
350         Widget          => '/Widgets/Form/Boolean',
351         WidgetArguments => {
352             Description => 'Show oldest history first',    #loc
353         },
354     },
355     DeferTransactionLoading => {
356         Section         => 'Ticket display',
357         Overridable     => 1,
358         SortOrder       => 3,
359         Widget          => '/Widgets/Form/Boolean',
360         WidgetArguments => {
361             Description => 'Hide ticket history by default',    #loc
362         },
363     },
364     ShowUnreadMessageNotifications => { 
365         Section         => 'Ticket display',
366         Overridable     => 1,
367         SortOrder       => 4,
368         Widget          => '/Widgets/Form/Boolean',
369         WidgetArguments => {
370             Description => 'Notify me of unread messages',    #loc
371         },
372
373     },
374     PlainTextPre => {
375         Section         => 'Ticket display',
376         Overridable     => 1,
377         SortOrder       => 5,
378         Widget          => '/Widgets/Form/Boolean',
379         WidgetArguments => {
380             Description => 'add <pre> tag around plain text attachments', #loc
381             Hints       => "Use this to protect the format of plain text" #loc
382         },
383     },
384     PlainTextMono => {
385         Section         => 'Ticket display',
386         Overridable     => 1,
387         SortOrder       => 5,
388         Widget          => '/Widgets/Form/Boolean',
389         WidgetArguments => {
390             Description => 'display wrapped and formatted plain text attachments', #loc
391             Hints => 'Use css rules to display text monospaced and with formatting preserved, but wrap as needed.  This does not work well with IE6 and you should use the previous option', #loc
392         },
393     },
394     MoreAboutRequestorTicketList => {
395         Section         => 'Ticket display',                       #loc
396         Overridable     => 1,
397         SortOrder       => 6,
398         Widget          => '/Widgets/Form/Select',
399         WidgetArguments => {
400             Description => q|What tickets to display in the 'More about requestor' box|,                #loc
401             Values      => [qw(Active Inactive All None)],
402             ValuesLabel => {
403                 Active   => "Show the Requestor's 10 highest priority active tickets",                  #loc
404                 Inactive => "Show the Requestor's 10 highest priority inactive tickets",      #loc
405                 All      => "Show the Requestor's 10 highest priority tickets",      #loc
406                 None     => "Show no tickets for the Requestor", #loc
407             },
408         },
409     },
410     SimplifiedRecipients => {
411         Section         => 'Ticket display',                       #loc
412         Overridable     => 1,
413         SortOrder       => 7,
414         Widget          => '/Widgets/Form/Boolean',
415         WidgetArguments => {
416             Description => q|Show simplified recipient list on ticket update|,                #loc
417         },
418     },
419     DisplayTicketAfterQuickCreate => {
420         Section         => 'Ticket display',
421         Overridable     => 1,
422         SortOrder       => 8,
423         Widget          => '/Widgets/Form/Boolean',
424         WidgetArguments => {
425             Description => q{Display ticket after "Quick Create"}, #loc
426         },
427     },
428
429     # User overridable locale options
430     DateTimeFormat => {
431         Section         => 'Locale',                       #loc
432         Overridable     => 1,
433         Widget          => '/Widgets/Form/Select',
434         WidgetArguments => {
435             Description => 'Date format',                            #loc
436             Callback => sub { my $ret = { Values => [], ValuesLabel => {}};
437                               my $date = RT::Date->new($HTML::Mason::Commands::session{'CurrentUser'});
438                               $date->SetToNow;
439                               foreach my $value ($date->Formatters) {
440                                  push @{$ret->{Values}}, $value;
441                                  $ret->{ValuesLabel}{$value} = $date->Get(
442                                      Format     => $value,
443                                      Timezone   => 'user',
444                                  );
445                               }
446                               return $ret;
447             },
448         },
449     },
450
451     RTAddressRegexp => {
452         Type    => 'SCALAR',
453         PostLoadCheck => sub {
454             my $self = shift;
455             my $value = $self->Get('RTAddressRegexp');
456             if (not $value) {
457                 $RT::Logger->debug(
458                     'The RTAddressRegexp option is not set in the config.'
459                     .' Not setting this option results in additional SQL queries to'
460                     .' check whether each address belongs to RT or not.'
461                     .' It is especially important to set this option if RT recieves'
462                     .' emails on addresses that are not in the database or config.'
463                 );
464             } elsif (ref $value and ref $value eq "Regexp") {
465                 # Ensure that the regex is case-insensitive; while the
466                 # local part of email addresses is _technically_
467                 # case-sensitive, most MTAs don't treat it as such.
468                 $RT::Logger->warning(
469                     'RTAddressRegexp is set to a case-sensitive regular expression.'
470                     .' This may lead to mail loops with MTAs which treat the'
471                     .' local part as case-insensitive -- which is most of them.'
472                 ) if "$value" =~ /^\(\?[a-z]*-([a-z]*):/ and "$1" =~ /i/;
473             }
474         },
475     },
476     # User overridable mail options
477     EmailFrequency => {
478         Section         => 'Mail',                                     #loc
479         Overridable     => 1,
480         Default     => 'Individual messages',
481         Widget          => '/Widgets/Form/Select',
482         WidgetArguments => {
483             Description => 'Email delivery',    #loc
484             Values      => [
485             'Individual messages',    #loc
486             'Daily digest',           #loc
487             'Weekly digest',          #loc
488             'Suspended'               #loc
489             ]
490         }
491     },
492     NotifyActor => {
493         Section         => 'Mail',                                     #loc
494         Overridable     => 1,
495         SortOrder       => 2,
496         Widget          => '/Widgets/Form/Boolean',
497         WidgetArguments => {
498             Description => 'Outgoing mail', #loc
499             Hints => 'Should RT send you mail for ticket updates you make?', #loc
500         }
501     },
502
503     # this tends to break extensions that stash links in ticket update pages
504     Organization => {
505         Type            => 'SCALAR',
506         PostLoadCheck   => sub {
507             my ($self,$value) = @_;
508             $RT::Logger->error("your \$Organization setting ($value) appears to contain whitespace.  Please fix this.")
509                 if $value =~ /\s/;;
510         },
511     },
512
513     # Internal config options
514     FullTextSearch => {
515         Type => 'HASH',
516         PostLoadCheck => sub {
517             my $self = shift;
518             my $v = $self->Get('FullTextSearch');
519             return unless $v->{Enable} and $v->{Indexed};
520             my $dbtype = $self->Get('DatabaseType');
521             if ($dbtype eq 'Oracle') {
522                 if (not $v->{IndexName}) {
523                     $RT::Logger->error("No IndexName set for full-text index; disabling");
524                     $v->{Enable} = $v->{Indexed} = 0;
525                 }
526             } elsif ($dbtype eq 'Pg') {
527                 my $bad = 0;
528                 if (not $v->{'Column'}) {
529                     $RT::Logger->error("No Column set for full-text index; disabling");
530                     $v->{Enable} = $v->{Indexed} = 0;
531                 } elsif ($v->{'Column'} eq "Content"
532                              and (not $v->{'Table'} or $v->{'Table'} eq "Attachments")) {
533                     $RT::Logger->error("Column for full-text index is set to Content, not tsvector column; disabling");
534                     $v->{Enable} = $v->{Indexed} = 0;
535                 }
536             } elsif ($dbtype eq 'mysql') {
537                 if (not $v->{'Table'}) {
538                     $RT::Logger->error("No Table set for full-text index; disabling");
539                     $v->{Enable} = $v->{Indexed} = 0;
540                 } elsif ($v->{'Table'} eq "Attachments") {
541                     $RT::Logger->error("Table for full-text index is set to Attachments, not SphinxSE table; disabling");
542                     $v->{Enable} = $v->{Indexed} = 0;
543                 } elsif (not $v->{'MaxMatches'}) {
544                     $RT::Logger->warn("No MaxMatches set for full-text index; defaulting to 10000");
545                     $v->{MaxMatches} = 10_000;
546                 }
547             } else {
548                 $RT::Logger->error("Indexed full-text-search not supported for $dbtype");
549                 $v->{Indexed} = 0;
550             }
551         },
552     },
553     DisableGraphViz => {
554         Type            => 'SCALAR',
555         PostLoadCheck   => sub {
556             my $self  = shift;
557             my $value = shift;
558             return if $value;
559             return if $INC{'GraphViz.pm'};
560             local $@;
561             return if eval {require GraphViz; 1};
562             $RT::Logger->debug("You've enabled GraphViz, but we couldn't load the module: $@");
563             $self->Set( DisableGraphViz => 1 );
564         },
565     },
566     DisableGD => {
567         Type            => 'SCALAR',
568         PostLoadCheck   => sub {
569             my $self  = shift;
570             my $value = shift;
571             return if $value;
572             return if $INC{'GD.pm'};
573             local $@;
574             return if eval {require GD; 1};
575             $RT::Logger->debug("You've enabled GD, but we couldn't load the module: $@");
576             $self->Set( DisableGD => 1 );
577         },
578     },
579     MailPlugins  => { Type => 'ARRAY' },
580     Plugins      => {
581         Type => 'ARRAY',
582         PostLoadCheck => sub {
583             my $self = shift;
584             my $value = $self->Get('Plugins');
585             # XXX Remove in RT 4.2
586             return unless $value and grep {$_ eq "RT::FM"} @{$value};
587             warn 'RTFM has been integrated into core RT, and must be removed from your @Plugins';
588         },
589     },
590     GnuPG        => { Type => 'HASH' },
591     GnuPGOptions => { Type => 'HASH',
592         PostLoadCheck => sub {
593             my $self = shift;
594             my $gpg = $self->Get('GnuPG');
595             return unless $gpg->{'Enable'};
596             my $gpgopts = $self->Get('GnuPGOptions');
597             unless (-d $gpgopts->{homedir}  && -r _ ) { # no homedir, no gpg
598                 $RT::Logger->debug(
599                     "RT's GnuPG libraries couldn't successfully read your".
600                     " configured GnuPG home directory (".$gpgopts->{homedir}
601                     ."). PGP support has been disabled");
602                 $gpg->{'Enable'} = 0;
603                 return;
604             }
605
606
607             require RT::Crypt::GnuPG;
608             unless (RT::Crypt::GnuPG->Probe()) {
609                 $RT::Logger->debug(
610                     "RT's GnuPG libraries couldn't successfully execute gpg.".
611                     " PGP support has been disabled");
612                 $gpg->{'Enable'} = 0;
613             }
614         }
615     },
616     ReferrerWhitelist => { Type => 'ARRAY' },
617     ResolveDefaultUpdateType => {
618         PostLoadCheck => sub {
619             my $self  = shift;
620             my $value = shift;
621             return unless $value;
622             $RT::Logger->info('The ResolveDefaultUpdateType config option has been deprecated.  '.
623                               'You can change the site default in your %Lifecycles config.');
624         }
625     },
626     WebPath => {
627         PostLoadCheck => sub {
628             my $self  = shift;
629             my $value = shift;
630
631             # "In most cases, you should leave $WebPath set to '' (an empty value)."
632             return unless $value;
633
634             # try to catch someone who assumes that you shouldn't leave this empty
635             if ($value eq '/') {
636                 $RT::Logger->error("For the WebPath config option, use the empty string instead of /");
637                 return;
638             }
639
640             # $WebPath requires a leading / but no trailing /, or it can be blank.
641             return if $value =~ m{^/.+[^/]$};
642
643             if ($value =~ m{/$}) {
644                 $RT::Logger->error("The WebPath config option requires no trailing slash");
645             }
646
647             if ($value !~ m{^/}) {
648                 $RT::Logger->error("The WebPath config option requires a leading slash");
649             }
650         },
651     },
652     WebDomain => {
653         PostLoadCheck => sub {
654             my $self  = shift;
655             my $value = shift;
656
657             if (!$value) {
658                 $RT::Logger->error("You must set the WebDomain config option");
659                 return;
660             }
661
662             if ($value =~ m{^(\w+://)}) {
663                 $RT::Logger->error("The WebDomain config option must not contain a scheme ($1)");
664                 return;
665             }
666
667             if ($value =~ m{(/.*)}) {
668                 $RT::Logger->error("The WebDomain config option must not contain a path ($1)");
669                 return;
670             }
671
672             if ($value =~ m{:(\d*)}) {
673                 $RT::Logger->error("The WebDomain config option must not contain a port ($1)");
674                 return;
675             }
676         },
677     },
678     WebPort => {
679         PostLoadCheck => sub {
680             my $self  = shift;
681             my $value = shift;
682
683             if (!$value) {
684                 $RT::Logger->error("You must set the WebPort config option");
685                 return;
686             }
687
688             if ($value !~ m{^\d+$}) {
689                 $RT::Logger->error("The WebPort config option must be an integer");
690             }
691         },
692     },
693     WebBaseURL => {
694         PostLoadCheck => sub {
695             my $self  = shift;
696             my $value = shift;
697
698             if (!$value) {
699                 $RT::Logger->error("You must set the WebBaseURL config option");
700                 return;
701             }
702
703             if ($value !~ m{^https?://}i) {
704                 $RT::Logger->error("The WebBaseURL config option must contain a scheme (http or https)");
705             }
706
707             if ($value =~ m{/$}) {
708                 $RT::Logger->error("The WebBaseURL config option requires no trailing slash");
709             }
710
711             if ($value =~ m{^https?://.+?(/[^/].*)}i) {
712                 $RT::Logger->error("The WebBaseURL config option must not contain a path ($1)");
713             }
714         },
715     },
716     WebURL => {
717         PostLoadCheck => sub {
718             my $self  = shift;
719             my $value = shift;
720
721             if (!$value) {
722                 $RT::Logger->error("You must set the WebURL config option");
723                 return;
724             }
725
726             if ($value !~ m{^https?://}i) {
727                 $RT::Logger->error("The WebURL config option must contain a scheme (http or https)");
728             }
729
730             if ($value !~ m{/$}) {
731                 $RT::Logger->error("The WebURL config option requires a trailing slash");
732             }
733         },
734     },
735     EmailInputEncodings => {
736         Type => 'ARRAY',
737         PostLoadCheck => sub {
738             my $self  = shift;
739             my $value = $self->Get('EmailInputEncodings');
740             return unless $value && @$value;
741
742             my %seen;
743             foreach my $encoding ( grep defined && length, splice @$value ) {
744                 next if $seen{ $encoding };
745                 if ( $encoding eq '*' ) {
746                     unshift @$value, '*';
747                     next;
748                 }
749
750                 my $canonic = Encode::resolve_alias( $encoding );
751                 unless ( $canonic ) {
752                     warn "Unknown encoding '$encoding' in \@EmailInputEncodings option";
753                 }
754                 elsif ( $seen{ $canonic }++ ) {
755                     next;
756                 }
757                 else {
758                     push @$value, $canonic;
759                 }
760             }
761         },
762     },
763
764     ActiveStatus => {
765         Type => 'ARRAY',
766         PostLoadCheck => sub {
767             my $self  = shift;
768             return unless shift;
769             # XXX Remove in RT 4.2
770             warn <<EOT;
771 The ActiveStatus configuration has been replaced by the new Lifecycles
772 functionality. You should set the 'active' property of the 'default'
773 lifecycle and add transition rules; see RT_Config.pm for documentation.
774 EOT
775         },
776     },
777     InactiveStatus => {
778         Type => 'ARRAY',
779         PostLoadCheck => sub {
780             my $self  = shift;
781             return unless shift;
782             # XXX Remove in RT 4.2
783             warn <<EOT;
784 The InactiveStatus configuration has been replaced by the new Lifecycles
785 functionality. You should set the 'inactive' property of the 'default'
786 lifecycle and add transition rules; see RT_Config.pm for documentation.
787 EOT
788         },
789     },
790 );
791 my %OPTIONS = ();
792
793 =head1 METHODS
794
795 =head2 new
796
797 Object constructor returns new object. Takes no arguments.
798
799 =cut
800
801 sub new {
802     my $proto = shift;
803     my $class = ref($proto) ? ref($proto) : $proto;
804     my $self  = bless {}, $class;
805     $self->_Init(@_);
806     return $self;
807 }
808
809 sub _Init {
810     return;
811 }
812
813 =head2 InitConfig
814
815 Do nothin right now.
816
817 =cut
818
819 sub InitConfig {
820     my $self = shift;
821     my %args = ( File => '', @_ );
822     $args{'File'} =~ s/(?<=Config)(?=\.pm$)/Meta/;
823     return 1;
824 }
825
826 =head2 LoadConfigs
827
828 Load all configs. First of all load RT's config then load
829 extensions' config files in alphabetical order.
830 Takes no arguments.
831
832 =cut
833
834 sub LoadConfigs {
835     my $self    = shift;
836
837     $self->InitConfig( File => 'RT_Config.pm' );
838     $self->LoadConfig( File => 'RT_Config.pm' );
839
840     my @configs = $self->Configs;
841     $self->InitConfig( File => $_ ) foreach @configs;
842     $self->LoadConfig( File => $_ ) foreach @configs;
843     return;
844 }
845
846 =head1 LoadConfig
847
848 Takes param hash with C<File> field.
849 First, the site configuration file is loaded, in order to establish
850 overall site settings like hostname and name of RT instance.
851 Then, the core configuration file is loaded to set fallback values
852 for all settings; it bases some values on settings from the site
853 configuration file.
854
855 B<Note> that core config file don't change options if site config
856 has set them so to add value to some option instead of
857 overriding you have to copy original value from core config file.
858
859 =cut
860
861 sub LoadConfig {
862     my $self = shift;
863     my %args = ( File => '', @_ );
864     $args{'File'} =~ s/(?<!Site)(?=Config\.pm$)/Site/;
865     if ( $args{'File'} eq 'RT_SiteConfig.pm'
866         and my $site_config = $ENV{RT_SITE_CONFIG} )
867     {
868         $self->_LoadConfig( %args, File => $site_config );
869     } else {
870         $self->_LoadConfig(%args);
871     }
872     $args{'File'} =~ s/Site(?=Config\.pm$)//;
873     $self->_LoadConfig(%args);
874     return 1;
875 }
876
877 sub _LoadConfig {
878     my $self = shift;
879     my %args = ( File => '', @_ );
880
881     my ($is_ext, $is_site);
882     if ( $args{'File'} eq ($ENV{RT_SITE_CONFIG}||'') ) {
883         ($is_ext, $is_site) = ('', 1);
884     } else {
885         $is_ext = $args{'File'} =~ /^(?!RT_)(?:(.*)_)(?:Site)?Config/ ? $1 : '';
886         $is_site = $args{'File'} =~ /SiteConfig/ ? 1 : 0;
887     }
888
889     eval {
890         package RT;
891         local *Set = sub(\[$@%]@) {
892             my ( $opt_ref, @args ) = @_;
893             my ( $pack, $file, $line ) = caller;
894             return $self->SetFromConfig(
895                 Option     => $opt_ref,
896                 Value      => [@args],
897                 Package    => $pack,
898                 File       => $file,
899                 Line       => $line,
900                 SiteConfig => $is_site,
901                 Extension  => $is_ext,
902             );
903         };
904         my @etc_dirs = ($RT::LocalEtcPath);
905         push @etc_dirs, RT->PluginDirs('etc') if $is_ext;
906         push @etc_dirs, $RT::EtcPath, @INC;
907         local @INC = @etc_dirs;
908         require $args{'File'};
909     };
910     if ($@) {
911         return 1 if $is_site && $@ =~ /^Can't locate \Q$args{File}/;
912         if ( $is_site || $@ !~ /^Can't locate \Q$args{File}/ ) {
913             die qq{Couldn't load RT config file $args{'File'}:\n\n$@};
914         }
915
916         my $username = getpwuid($>);
917         my $group    = getgrgid($();
918
919         my ( $file_path, $fileuid, $filegid );
920         foreach ( $RT::LocalEtcPath, $RT::EtcPath, @INC ) {
921             my $tmp = File::Spec->catfile( $_, $args{File} );
922             ( $fileuid, $filegid ) = ( stat($tmp) )[ 4, 5 ];
923             if ( defined $fileuid ) {
924                 $file_path = $tmp;
925                 last;
926             }
927         }
928         unless ($file_path) {
929             die
930                 qq{Couldn't load RT config file $args{'File'} as user $username / group $group.\n}
931                 . qq{The file couldn't be found in $RT::LocalEtcPath and $RT::EtcPath.\n$@};
932         }
933
934         my $message = <<EOF;
935
936 RT couldn't load RT config file %s as:
937     user: $username 
938     group: $group
939
940 The file is owned by user %s and group %s.  
941
942 This usually means that the user/group your webserver is running
943 as cannot read the file.  Be careful not to make the permissions
944 on this file too liberal, because it contains database passwords.
945 You may need to put the webserver user in the appropriate group
946 (%s) or change permissions be able to run succesfully.
947 EOF
948
949         my $fileusername = getpwuid($fileuid);
950         my $filegroup    = getgrgid($filegid);
951         my $errormessage = sprintf( $message,
952             $file_path, $fileusername, $filegroup, $filegroup );
953         die "$errormessage\n$@";
954     }
955     return 1;
956 }
957
958 sub PostLoadCheck {
959     my $self = shift;
960     foreach my $o ( grep $META{$_}{'PostLoadCheck'}, $self->Options( Overridable => undef ) ) {
961         $META{$o}->{'PostLoadCheck'}->( $self, $self->Get($o) );
962     }
963 }
964
965 =head2 Configs
966
967 Returns list of config files found in local etc, plugins' etc
968 and main etc directories.
969
970 =cut
971
972 sub Configs {
973     my $self    = shift;
974
975     my @configs = ();
976     foreach my $path ( $RT::LocalEtcPath, RT->PluginDirs('etc'), $RT::EtcPath ) {
977         my $mask = File::Spec->catfile( $path, "*_Config.pm" );
978         my @files = glob $mask;
979         @files = grep !/^RT_Config\.pm$/,
980             grep $_ && /^\w+_Config\.pm$/,
981             map { s/^.*[\\\/]//; $_ } @files;
982         push @configs, sort @files;
983     }
984
985     my %seen;
986     @configs = grep !$seen{$_}++, @configs;
987     return @configs;
988 }
989
990 =head2 Get
991
992 Takes name of the option as argument and returns its current value.
993
994 In the case of a user-overridable option, first checks the user's
995 preferences before looking for site-wide configuration.
996
997 Returns values from RT_SiteConfig, RT_Config and then the %META hash
998 of configuration variables's "Default" for this config variable,
999 in that order.
1000
1001 Returns different things in scalar and array contexts. For scalar
1002 options it's not that important, however for arrays and hash it's.
1003 In scalar context returns references to arrays and hashes.
1004
1005 Use C<scalar> perl's op to force context, especially when you use
1006 C<(..., Argument => RT->Config->Get('ArrayOpt'), ...)>
1007 as perl's '=>' op doesn't change context of the right hand argument to
1008 scalar. Instead use C<(..., Argument => scalar RT->Config->Get('ArrayOpt'), ...)>.
1009
1010 It's also important for options that have no default value(no default
1011 in F<etc/RT_Config.pm>). If you don't force scalar context then you'll
1012 get empty list and all your named args will be messed up. For example
1013 C<(arg1 => 1, arg2 => RT->Config->Get('OptionDoesNotExist'), arg3 => 3)>
1014 will result in C<(arg1 => 1, arg2 => 'arg3', 3)> what is most probably
1015 unexpected, or C<(arg1 => 1, arg2 => RT->Config->Get('ArrayOption'), arg3 => 3)>
1016 will result in C<(arg1 => 1, arg2 => 'element of option', 'another_one' => ..., 'arg3', 3)>.
1017
1018 =cut
1019
1020 sub Get {
1021     my ( $self, $name, $user ) = @_;
1022
1023     my $res;
1024     if ( $user && $user->id && $META{$name}->{'Overridable'} ) {
1025         $user = $user->UserObj if $user->isa('RT::CurrentUser');
1026         my $prefs = $user->Preferences($RT::System);
1027         $res = $prefs->{$name} if $prefs;
1028     }
1029     $res = $OPTIONS{$name}           unless defined $res;
1030     $res = $META{$name}->{'Default'} unless defined $res;
1031     return $self->_ReturnValue( $res, $META{$name}->{'Type'} || 'SCALAR' );
1032 }
1033
1034 =head2 GetObfuscated
1035
1036 the same as Get, except it returns Obfuscated value via Obfuscate sub
1037
1038 =cut
1039
1040 sub GetObfuscated {
1041     my $self = shift;
1042     my ( $name, $user ) = @_;
1043     my $obfuscate = $META{$name}->{Obfuscate};
1044
1045     # we use two Get here is to simplify the logic of the return value
1046     # configs need obfuscation are supposed to be less, so won't be too heavy
1047
1048     return $self->Get(@_) unless $obfuscate;
1049
1050     my $res = $self->Get(@_);
1051     $res = $obfuscate->( $self, $res, $user );
1052     return $self->_ReturnValue( $res, $META{$name}->{'Type'} || 'SCALAR' );
1053 }
1054
1055 =head2 Set
1056
1057 Set option's value to new value. Takes name of the option and new value.
1058 Returns old value.
1059
1060 The new value should be scalar, array or hash depending on type of the option.
1061 If the option is not defined in meta or the default RT config then it is of
1062 scalar type.
1063
1064 =cut
1065
1066 sub Set {
1067     my ( $self, $name ) = ( shift, shift );
1068
1069     my $old = $OPTIONS{$name};
1070     my $type = $META{$name}->{'Type'} || 'SCALAR';
1071     if ( $type eq 'ARRAY' ) {
1072         $OPTIONS{$name} = [@_];
1073         { no warnings 'once'; no strict 'refs'; @{"RT::$name"} = (@_); }
1074     } elsif ( $type eq 'HASH' ) {
1075         $OPTIONS{$name} = {@_};
1076         { no warnings 'once'; no strict 'refs'; %{"RT::$name"} = (@_); }
1077     } else {
1078         $OPTIONS{$name} = shift;
1079         {no warnings 'once'; no strict 'refs'; ${"RT::$name"} = $OPTIONS{$name}; }
1080     }
1081     $META{$name}->{'Type'} = $type;
1082     return $self->_ReturnValue( $old, $type );
1083 }
1084
1085 sub _ReturnValue {
1086     my ( $self, $res, $type ) = @_;
1087     return $res unless wantarray;
1088
1089     if ( $type eq 'ARRAY' ) {
1090         return @{ $res || [] };
1091     } elsif ( $type eq 'HASH' ) {
1092         return %{ $res || {} };
1093     }
1094     return $res;
1095 }
1096
1097 sub SetFromConfig {
1098     my $self = shift;
1099     my %args = (
1100         Option     => undef,
1101         Value      => [],
1102         Package    => 'RT',
1103         File       => '',
1104         Line       => 0,
1105         SiteConfig => 1,
1106         Extension  => 0,
1107         @_
1108     );
1109
1110     unless ( $args{'File'} ) {
1111         ( $args{'Package'}, $args{'File'}, $args{'Line'} ) = caller(1);
1112     }
1113
1114     my $opt = $args{'Option'};
1115
1116     my $type;
1117     my $name = $self->__GetNameByRef($opt);
1118     if ($name) {
1119         $type = ref $opt;
1120         $name =~ s/.*:://;
1121     } else {
1122         $name = $$opt;
1123         $type = $META{$name}->{'Type'} || 'SCALAR';
1124     }
1125
1126     # if option is already set we have to check where
1127     # it comes from and may be ignore it
1128     if ( exists $OPTIONS{$name} ) {
1129         if ( $type eq 'HASH' ) {
1130             $args{'Value'} = [
1131                 @{ $args{'Value'} },
1132                 @{ $args{'Value'} }%2? (undef) : (),
1133                 $self->Get( $name ),
1134             ];
1135         } elsif ( $args{'SiteConfig'} && $args{'Extension'} ) {
1136             # if it's site config of an extension then it can only
1137             # override options that came from its main config
1138             if ( $args{'Extension'} ne $META{$name}->{'Source'}{'Extension'} ) {
1139                 my %source = %{ $META{$name}->{'Source'} };
1140                 warn
1141                     "Change of config option '$name' at $args{'File'} line $args{'Line'} has been ignored."
1142                     ." This option earlier has been set in $source{'File'} line $source{'Line'}."
1143                     ." To overide this option use ". ($source{'Extension'}||'RT')
1144                     ." site config."
1145                 ;
1146                 return 1;
1147             }
1148         } elsif ( !$args{'SiteConfig'} && $META{$name}->{'Source'}{'SiteConfig'} ) {
1149             # if it's core config then we can override any option that came from another
1150             # core config, but not site config
1151
1152             my %source = %{ $META{$name}->{'Source'} };
1153             if ( $source{'Extension'} ne $args{'Extension'} ) {
1154                 # as a site config is loaded earlier then its base config
1155                 # then we warn only on different extensions, for example
1156                 # RTIR's options is set in main site config
1157                 warn
1158                     "Change of config option '$name' at $args{'File'} line $args{'Line'} has been ignored."
1159                     ." It may be ok, but we want you to be aware."
1160                     ." This option has been set earlier in $source{'File'} line $source{'Line'}."
1161                 ;
1162             }
1163
1164             return 1;
1165         }
1166     }
1167
1168     $META{$name}->{'Type'} = $type;
1169     foreach (qw(Package File Line SiteConfig Extension)) {
1170         $META{$name}->{'Source'}->{$_} = $args{$_};
1171     }
1172     $self->Set( $name, @{ $args{'Value'} } );
1173
1174     return 1;
1175 }
1176
1177     our %REF_SYMBOLS = (
1178             SCALAR => '$',
1179             ARRAY  => '@',
1180             HASH   => '%',
1181             CODE   => '&',
1182         );
1183
1184 {
1185     my $last_pack = '';
1186
1187     sub __GetNameByRef {
1188         my $self = shift;
1189         my $ref  = shift;
1190         my $pack = shift;
1191         if ( !$pack && $last_pack ) {
1192             my $tmp = $self->__GetNameByRef( $ref, $last_pack );
1193             return $tmp if $tmp;
1194         }
1195         $pack ||= 'main::';
1196         $pack .= '::' unless substr( $pack, -2 ) eq '::';
1197
1198         no strict 'refs';
1199         my $name = undef;
1200
1201         # scan $pack's nametable(hash)
1202         foreach my $k ( keys %{$pack} ) {
1203
1204             # The hash for main:: has a reference to itself
1205             next if $k eq 'main::';
1206
1207             # if the entry has a trailing '::' then
1208             # it is a link to another name space
1209             if ( substr( $k, -2 ) eq '::') {
1210                 $name = $self->__GetNameByRef( $ref, $k );
1211                 return $name if $name;
1212             }
1213
1214             # entry of the table with references to
1215             # SCALAR, ARRAY... and other types with
1216             # the same name
1217             my $entry = ${$pack}{$k};
1218             next unless $entry;
1219
1220             # get entry for type we are looking for
1221             # XXX skip references to scalars or other references.
1222             # Otherwie 5.10 goes boom. maybe we should skip any
1223             # reference
1224             next if ref($entry) eq 'SCALAR' || ref($entry) eq 'REF';
1225
1226             my $ref_type = ref($ref);
1227
1228             # regex/arrayref/hashref/coderef are stored in SCALAR glob
1229             $ref_type = 'SCALAR' if $ref_type eq 'REF';
1230
1231             my $entry_ref = *{$entry}{ $ref_type };
1232             next unless $entry_ref;
1233
1234             # if references are equal then we've found
1235             if ( $entry_ref == $ref ) {
1236                 $last_pack = $pack;
1237                 return ( $REF_SYMBOLS{ $ref_type } || '*' ) . $pack . $k;
1238             }
1239         }
1240         return '';
1241     }
1242 }
1243
1244 =head2 Metadata
1245
1246
1247 =head2 Meta
1248
1249 =cut
1250
1251 sub Meta {
1252     return $META{ $_[1] };
1253 }
1254
1255 sub Sections {
1256     my $self = shift;
1257     my %seen;
1258     my @sections = sort
1259         grep !$seen{$_}++,
1260         map $_->{'Section'} || 'General',
1261         values %META;
1262     return @sections;
1263 }
1264
1265 sub Options {
1266     my $self = shift;
1267     my %args = ( Section => undef, Overridable => 1, Sorted => 1, @_ );
1268     my @res  = keys %META;
1269     
1270     @res = grep( ( $META{$_}->{'Section'} || 'General' ) eq $args{'Section'},
1271         @res 
1272     ) if defined $args{'Section'};
1273
1274     if ( defined $args{'Overridable'} ) {
1275         @res
1276             = grep( ( $META{$_}->{'Overridable'} || 0 ) == $args{'Overridable'},
1277             @res );
1278     }
1279
1280     if ( $args{'Sorted'} ) {
1281         @res = sort {
1282             ($META{$a}->{SortOrder}||9999) <=> ($META{$b}->{SortOrder}||9999)
1283             || $a cmp $b 
1284         } @res;
1285     } else {
1286         @res = sort { $a cmp $b } @res;
1287     }
1288     return @res;
1289 }
1290
1291 =head2 AddOption( Name => '', Section => '', ... )
1292
1293 =cut
1294
1295 sub AddOption {
1296     my $self = shift;
1297     my %args = (
1298         Name            => undef,
1299         Section         => undef,
1300         Overridable     => 0,
1301         SortOrder       => undef,
1302         Widget          => '/Widgets/Form/String',
1303         WidgetArguments => {},
1304         @_
1305     );
1306
1307     unless ( $args{Name} ) {
1308         $RT::Logger->error("Need Name to add a new config");
1309         return;
1310     }
1311
1312     unless ( $args{Section} ) {
1313         $RT::Logger->error("Need Section to add a new config option");
1314         return;
1315     }
1316
1317     $META{ delete $args{Name} } = \%args;
1318 }
1319
1320 =head2 DeleteOption( Name => '' )
1321
1322 =cut
1323
1324 sub DeleteOption {
1325     my $self = shift;
1326     my %args = (
1327         Name            => undef,
1328         @_
1329         );
1330     if ( $args{Name} ) {
1331         delete $META{$args{Name}};
1332     }
1333     else {
1334         $RT::Logger->error("Need Name to remove a config option");
1335         return;
1336     }
1337 }
1338
1339 =head2 UpdateOption( Name => '' ), Section => '', ... )
1340
1341 =cut
1342
1343 sub UpdateOption {
1344     my $self = shift;
1345     my %args = (
1346         Name            => undef,
1347         Section         => undef,
1348         Overridable     => undef,
1349         SortOrder       => undef,
1350         Widget          => undef,
1351         WidgetArguments => undef,
1352         @_
1353     );
1354
1355     my $name = delete $args{Name};
1356
1357     unless ( $name ) {
1358         $RT::Logger->error("Need Name to update a new config");
1359         return;
1360     }
1361
1362     unless ( exists $META{$name} ) {
1363         $RT::Logger->error("Config $name doesn't exist");
1364         return;
1365     }
1366
1367     for my $type ( keys %args ) {
1368         next unless defined $args{$type};
1369         $META{$name}{$type} = $args{$type};
1370     }
1371     return 1;
1372 }
1373
1374 RT::Base->_ImportOverlays();
1375
1376 1;