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