OMatic/install.pm untested

filter: Statementstmt 0.0% 0 / 769 Branchbran 0.0% 0 / 260 Conditioncond 0.0% 0 / 186 MC/DCmcdc 0.0% 0 / 106 Subroutinesub 0.0% 0 / 55 Podpod 0.0% 0 / 39 totaltotal 0.0% 0 / 1415 CC 131 SCAR 45.2
CC
131
Cov
0%
checkConfig
306.0
askConfigStep
272.0
isDone
210.0
CRAP 92.3
1 ##############################################################################
2 # The Faq-O-Matic is Copyright 1997 by Jon Howell, all rights reserved. #
3 # #
4 # This program is free software; you can redistribute it and/or #
5 # modify it under the terms of the GNU General Public License #
6 # as published by the Free Software Foundation; either version 2 #
7 # of the License, or (at your option) any later version. #
8 # #
9 # This program is distributed in the hope that it will be useful, #
10 # but WITHOUT ANY WARRANTY; without even the implied warranty of #
11 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
12 # GNU General Public License for more details. #
13 # #
14 # You should have received a copy of the GNU General Public License #
15 # along with this program; if not, write to the Free Software #
16 # Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.#
17 # #
18 # Jon Howell can be contacted at: #
19 # 6211 Sudikoff Lab, Dartmouth College #
20 # Hanover, NH 03755-3510 #
21 # jonh@cs.dartmouth.edu #
22 # #
23 # An electronic copy of the GPL is available at: #
24 # http://www.gnu.org/copyleft/gpl.html #
25 # #
26 ##############################################################################
27  
28 use strict;
29  
30 ###
31 ### install.pm
32 ###
33 ### This module allows the administrator to install and configure a
34 ### Faq-O-Matic.
35 ###
36  
37 my $VERSION = undef; # mod_perl really won't care about this file-scoped 'my'
38 # This is NOT really the version number. See FAQ/OMatic.pm.
39 # THANKS: "Andreas J. Koenig" <andreas.koenig@anima.de> says that I need
40 # THANKS: a dummy VERSION string to fix a weird interaction among MakeMaker,
41 # THANKS: CPAN, and FAQ-O-Matic encountered by
42 # THANKS: "Larry W. Virden" <lvirden@cas.org>.
43  
44 package FAQ::OMatic::install;
45  
46 use Config;
47 use CGI;
48 use Digest::MD5 qw(md5_hex);
49 use FAQ::OMatic;
50 use FAQ::OMatic::Item;
51 use FAQ::OMatic::Part;
52 use FAQ::OMatic::Versions;
53 use FAQ::OMatic::I18N;
54 use FAQ::OMatic::ColorPicker;
55 use FAQ::OMatic::maintenance;
56  
57 use vars qw($params $configInfo); # file-scoped, mod_perl-safe
58  
59 sub main {
60 $params = {};
61  
62 if ($FAQ::OMatic::Config::secureInstall) {
63 require FAQ::OMatic::Auth;
64 # make params available to FAQ::OMatic::Auth::getId
65 $params = FAQ::OMatic::getParams(cgi(), 'dontlog');
66 my ($id,$aq) = FAQ::OMatic::Auth::getID();
67 # THANKS to Joerg Schneider <joergs@mail.deuba.com> for
68 # sending in this patch that lets the admin set the permissions
69 # for who (else) can get to the install page.
70 if (($id ne $FAQ::OMatic::Config::adminAuth) or ($aq<5)) {
71 FAQ::OMatic::Auth::ensurePerm('-item'=>'',
72 '-operation'=>'PermInstall',
73 '-restart'=>FAQ::OMatic::commandName(),
74 '-cgi'=>cgi(),
75 '-failexit'=>1);
76 }
77 } elsif (defined($main::temporaryCryptedPassword)) {
78 # secureInstall isn't set -- the temporary password must be
79 # present.
80 my $tcp = $main::temporaryCryptedPassword;
81 my $temppass = cgi()->param('temppass') || '';
82 my $crtemppass = md5_hex($temppass);
83 if ($crtemppass ne $tcp) {
84 tempPassPage();
85 FAQ::OMatic::myExit(0);
86 }
87 # else temp pass matched -- accept it.
88 }
89  
90 if ((cgi()->param('step')||'') eq 'makeSecure') {
91 makeSecureStep(); # don't print text/html header
92 } else {
93 print FAQ::OMatic::header(cgi(), '-type'=>"text/html");
94 print cgi()->start_html('-title'=>gettext("Faq-O-Matic Installer"),
95 '-bgcolor'=>"#ffffff");
96
97 doStep(cgi()->param('step'));
98  
99 print cgi()->end_html();
100 }
101 }
102  
103 sub doStep {
104 my $step = shift || '';
105  
106 my %knownSteps = map {$_=>$_} qw(
107 default askMeta configMeta initConfig
108 mainMenu
109 configItem askConfig
110 firstItem initMetaFiles setConfig
111 maintenance makeSecure
112 colorSampler askColor setColor
113 copyItems configVersion
114 );
115  
116 if ($knownSteps{$step}) {
117 # look up subroutine dynamically.
118 $step = $knownSteps{$step}; # untaint input
119 my $expr = $step."Step()";
120 eval($expr);
121 if ($@) {
122 displayMessage(gettexta("%0 failed: ", $step).$@
123 .FAQ::OMatic::stackTrace('html'), 'default');
124 }
125 } elsif ($step eq '') {
126 doStep('default');
127 } else {
128 displayMessage(gettexta("Unknown step: \"%0\".", $step), 'default');
129 }
130 }
131  
132 sub defaultStep {
133 if ((-f FAQ::OMatic::dispatch::meta()."/config")
134 and (FAQ::OMatic::dispatch::meta()
135 ne ($FAQ::OMatic::Config::metaDir||''))) {
136 # CGI stub points at a valid config file, but config hasn't
137 # been updated. This happens if admin moves meta dir and
138 # fixes the stub.
139 displayMessage(gettexta("Updating config to reflect new meta location <b>%0</b>.",
140 FAQ::OMatic::dispatch::meta()));
141 my $map = readConfig();
142 $map->{'$metaDir'} = "'".FAQ::OMatic::dispatch::meta()."'";
143 writeConfig($map);
144 rereadConfig();
145 doStep('mainMenu');
146 FAQ::OMatic::myExit(0);
147 }
148  
149 my $meta = $FAQ::OMatic::Config::metaDir || './';
150 if (-f "$meta/config") {
151 # There's a config file in the directory pointed to by the
152 # CGI stub. We're can run the main menu and do everything else
153 # from there now.
154 doStep('mainMenu');
155 } else {
156 # Can't see a config file. Offer to create it for admin.
157 displayMessage(gettexta("(Can't find <b>config</b> in '%0' -- assuming this is a new installation.)", $meta));
158 doStep('askMeta');
159 }
160 }
161  
162 sub askMetaStep {
163 my $rt = '';
164 use Cwd;
165  
166 # THANKS Jason R <jasonr@austin.rr.com>. On his platform (HPUX?),
167 # the Cwd module depends on an untainted $PATH.
168 my $pathSave = $ENV{'PATH'};
169 $ENV{'PATH'} = '/bin';
170 my $stubMeta = cwd();
171 $ENV{'PATH'} = $pathSave;
172  
173 if (FAQ::OMatic::dispatch::meta() =~ m#^/#) {
174 $stubMeta = ""; # stub meta is an absolute path
175 } else {
176 $stubMeta =~s#/$##; # stub meta is relative to cwd
177 $stubMeta .= "/";
178 }
179 $stubMeta.="<b>".FAQ::OMatic::dispatch::meta()."</b>";
180  
181 $rt.="<a href=\"".installUrl('configMeta')."\">".gettexta("Click here</a> to create %0.", $stubMeta)."<p>\n";
182  
183 $rt.=gettext("If you want to change the CGI stub to point to another directory, edit the script and then");
184 $rt.="\n<a href=\""
185 .installUrl('default')
186 ."\">".gettext("click here to use the new location")."</a>.<p>\n";
187  
188 $rt.=gettexta("FAQ-O-Matic stores files in two main directories.<p>The <b>meta/</b> directory path is encoded in your CGI stub (%0). It contains:", $0);
189 $rt.=gettext("<ul><li>the <b>config</b> file that tells FAQ-O-Matic where everything else lives. That's why the CGI stub needs to know where meta/ is, so it can figure out the rest of its configuration. <li>the <b>idfile</b> file that lists user identities. Therefore, meta/ should not be accessible via the web server. <li>the <b>RCS/</b> subdirectory that tracks revisions to FAQ items. <li>various hint files that are used as FAQ-O-Matic runs. These can be regenerated automatically.</ul>");
190 $rt.=gettext("<p>The <b>serve/</b> directory contains three subdirectories <b>item/</b>, <b>cache/</b>, and <b>bags/</b>. These directories are created and populated by the FAQ-O-Matic CGI, but should be directly accessible via the web server (without invoking the CGI).");
191 $rt.=gettext("<ul><li>serve/item/ contains only FAQ-O-Matic formatted source files, which encode both user-entered text and the hierarchical structure of the answers and categories in the FAQ. These files are only accessed through the web server (rather than the CGI) when another FAQ-O-Matic is mirroring this one. <li>serve/cache/ contains a cache of automatically-generated HTML versions of FAQ answers and categories. When possible, the CGI directs users to the cache to reduce load on the server. (CGI hits are far more expensive than regular file loads.) <li>serve/bags/ contains image files and other ``bags of bits.'' Bit-bags can be linked to or inlined into FAQ items (in the case of images). </ul>");
192  
193 displayMessage($rt);
194 }
195  
196 sub configMetaStep {
197 my $rt.='';
198  
199 my $meta = FAQ::OMatic::dispatch::meta();
200 if (not -d "$meta/.") {
201 # try mkdir
202 if (not mkdir(stripSlash($meta), 0700)) {
203 displayMessage(gettexta("I couldn't create <b>%0</b>: %1" , $meta, $!));
204 doStep('askMeta');
205 return;
206 }
207 displayMessage(gettexta("Created <b>%0</b>.", $meta));
208 }
209 if (not -w "$meta/.") {
210 displayMessage(gettexta("I don't have write permission to <b>%0</b>.", $meta));
211 doStep('askMeta');
212 return;
213 }
214 my $rcsDir = FAQ::OMatic::concatDir($meta, "/RCS/");
215 if (not -d $rcsDir) {
216 # try mkdir
217 if (not mkdir(stripSlash($rcsDir), 0700)) {
218 displayMessage(gettexta("I couldn't create <b>%0</b>: %1", $rcsDir, $!));
219 doStep('askMeta');
220 return;
221 }
222 displayMessage(gettexta("Created <b>%0</b>.", $rcsDir));
223 }
224 if (not -w "$rcsDir.") {
225 displayMessage(gettexta("I don't have write permission to <b>%0</b>.", $rcsDir));
226 doStep('askMeta');
227 return;
228 }
229  
230 doStep('initConfig');
231 }
232  
233 sub initConfigStep {
234 if (not -f FAQ::OMatic::dispatch::meta()."/config") {
235 my $metaDfl = FAQ::OMatic::dispatch::meta();
236 $metaDfl .= "/" if (not $metaDfl =~ m#/$#);
237 my $mailDfl = which("sendmail") || which("mailx");
238
239 if ($mailDfl=~m/mailx/) {
240 # `` changed to mySystem() call to avoid -T error on some
241 # machines.
242 # THANKS Thomas Hiller <hiller@tu-harburg.de>
243 my @lrc = FAQ::OMatic::mySystem('/bin/uname -s', 'always');
244 if ((defined $lrc[3]) and ($lrc[3] =~ m/Linux/i)) {
245 # linux mailx doesn't work like we'd hope. Let's go for
246 # /bin/mail (which takes -s on linux), and if that fails,
247 # leave it blank and hold out hope that the admin will supply
248 # a path to sendmail.
249 $mailDfl = which("mail");
250 }
251 }
252
253 my $map = getPotentialConfig();
254  
255 # THANKS: to Jim Adler <jima@sr.hp.com> for this fix that
256 # keeps HP-UX's RCS happy. (I'd recommend just installing
257 # GNU RCS, but this will be convenient for some.)
258 my $ciDfl = $map->{'$RCSci'};
259 if ($Config{osname} eq 'hpux' and
260 ($ciDfl eq '/usr/bin/ci' or $ciDfl eq '/bin/ci')) {
261 #TODO don't know if this handles '-k' correctly.
262 $map->{'$RCSciArgs'} = "'-l -mnull'";
263 }
264  
265 $map->{'$metaDir'} = "'".$metaDfl."'";
266 $map->{'$mailCommand'} = "'".$mailDfl."'";
267
268 writeConfig($map);
269 displayMessage(gettext("Created new config file."));
270 }
271  
272 doStep('initMetaFiles');
273 }
274  
275 sub initMetaFilesStep {
276 if (not open(IDFILE, ">>".FAQ::OMatic::dispatch::meta()."/idfile")) {
277 displayMessage(gettexta("I couldn't create <b>%0</b>: %1",
278 FAQ::OMatic::dispatch::meta()."/idfile", $!),
279 'askMeta');
280 return;
281 }
282 close IDFILE;
283 displayMessage(gettext("The idfile exists."));
284  
285 doStep('default');
286 }
287  
288 sub which {
289 my $prog = shift;
290 foreach my $path (split(':', $ENV{'PATH'})) {
291 if (-x "$path/$prog") {
292 return "$path/$prog";
293 }
294 }
295 return '';
296 }
297  
298 sub rereadConfig {
299 # reread config if available, so that we immediately reflect
300 # any changes.
301 if (-f FAQ::OMatic::dispatch::meta()."/config") {
302 open IN, FAQ::OMatic::dispatch::meta()."/config";
303 my @cfg = <IN>;
304 close IN;
305 my $cfg = join('', @cfg);
306  
307 $cfg =~ m/^(.*)$/s; # untaint (since data is from a file)
308 $cfg = $1;
309  
310 {
311 no strict 'vars';
312 # config file is not written in 'strict' form (vars are
313 # not declared/imported).
314 local $SIG{'__WARN__'} = sub { die $_[0] };
315 # ensure we can see any warnings that come from the eval
316 eval($cfg);
317 die $@ if ($@);
318 }
319 }
320 }
321  
322 sub mainMenuStep {
323 my $rt='';
324  
325 rereadConfig();
326  
327 my $maintenanceSecret = $FAQ::OMatic::Config::maintenanceSecret || '';
328 my $mirror = ($FAQ::OMatic::Config::mirrorURL||'') ne '';
329  
330 my $par = ""; # "<p>" for more space between items
331  
332 $rt.="<h3>".gettext("Configuration Main Menu (install module)")."</h3>\n";
333 $rt.=gettexta("Perform these tasks in order to prepare your FAQ-O-Matic version %0:",
334 $FAQ::OMatic::VERSION)
335 ."\n<ol>";
336 $rt.="$par<li><a href=\"".installUrl('askConfig')."\">"
337 .checkBoxFor('askConfig')
338 .gettext("Define configuration parameters")."</a>\n";
339 if (not $FAQ::OMatic::Config::secureInstall) {
340 if ($FAQ::OMatic::Config::mailCommand and $FAQ::OMatic::Config::adminAuth) {
341 $rt.="$par<li><a href=\"".installUrl('makeSecure')."\">"
342 .checkBoxFor('makeSecure')
343 .gettext("Set your password and turn on installer security")
344 ."</a>\n";
345 } else {
346 $rt.="$par<li>"
347 .checkBoxFor('makeSecure')
348 .gettext("Set your password and turn on installer security")
349 .gettext("(Need to configure \$mailCommand and \$adminAuth)")
350 ."\n";
351 }
352 } else {
353 $rt.="$par<li>"
354 .checkBoxFor('makeSecure')
355 .gettext("(Installer security is on)")
356 ."\n";
357 }
358 $rt.="$par<li><a href=\"".installUrl('configItem')."\">"
359 .checkBoxFor('configItem')
360 .gettext("Create item, cache, and bags directories in serve dir")
361 ."</a>\n";
362  
363 if (not $mirror) {
364 if (defined($FAQ::OMatic::Config::itemDir_Old)) {
365 $rt.="$par<li>"
366 ."<a href=\"".installUrl('copyItems')."\">"
367 .checkBoxFor('copyItems')
368 .gettexta("Copy old items</a> from <tt>%0</tt> to <tt>%1</tt>.",
369 $FAQ::OMatic::Config::itemDir_Old,
370 $FAQ::OMatic::Config::itemDir)
371 ."\n";
372 $rt.="$par<li>"
373 ."<a href=\"".installUrl('firstItem')."\">"
374 .checkBoxFor('firstItem')
375 .gettext("Install any new items that come with the system")
376 ."</a>\n"
377 } else {
378 $rt.="$par<li><a href=\"".installUrl('firstItem')."\">"
379 .checkBoxFor('firstItem')
380 .gettext("Create system default items")
381 ."</a>\n";
382 }
383  
384 $rt.="$par<li>"
385 .checkBoxFor('rebuildCache')
386 ."<a href=\"".installUrl('', 'url', 'maintenance')
387 ."&secret=$maintenanceSecret&tasks=rebuildCache\">"
388 .gettext("Rebuild the cache and dependency files")
389 ."</a>\n";
390
391 $rt.="$par<li>"
392 .checkBoxFor('systemBags')
393 ."<a href=\"".installUrl('', 'url', 'maintenance')
394 ."&secret=$maintenanceSecret&tasks=bagAllImages\">"
395 .gettext("Install system images and icons")
396 ."</a>\n";
397 } else {
398 # mirror sites should update now
399 $rt.="$par<li>"
400 .checkBoxFor('nothing')
401 ."<a href=\"".installUrl('', 'url', 'maintenance')
402 ."&secret=$maintenanceSecret&tasks=mirrorClient\">"
403 .gettext("Update mirror from master now. (this can be slow!)")
404 ."</a>\n";
405 }
406  
407 $rt.="$par<li><a href=\"".installUrl('maintenance')."\">"
408 .checkBoxFor('maintenance')
409 .gettext("Set up the maintenance cron job")
410 ."</a>\n";
411 if ($maintenanceSecret) {
412 $rt.="$par<li><a href=\"".installUrl('', 'url', 'maintenance')
413 ."&secret=$maintenanceSecret\">"
414 .checkBoxFor('manualMaintenance')
415 .gettext("Run maintenance script manually now")
416 .".</a>\n";
417 } else {
418 $rt.="$par<li>"
419 .checkBoxFor('manualMaintenance')
420 .gettext("Run maintenance script manually now")
421 ." "
422 .gettext("(Need to set up the maintenance cron job first)")
423 .".\n";
424 }
425 my $lm = FAQ::OMatic::maintenance::readMaintenanceHint();
426 my $lmstr = $lm
427 ? FAQ::OMatic::Item::compactDate($lm)
428 : "never";
429 $rt.="<br>".checkBoxFor('nothing')
430 .gettext("Maintenance last run at:")
431 ." $lmstr\n";
432  
433 $rt.="$par<li><a href=\"".installUrl('configVersion')."\">"
434 .checkBoxFor('configVersion')
435 .gettexta("Mark the config file as upgraded to Version %0",
436 $FAQ::OMatic::VERSION)
437 ."</a>\n";
438  
439 $rt.="$par<li><a href=\"".installUrl('colorSampler')."\">"
440 .checkBoxFor('customColors')
441 .gettext("Select custom colors for your Faq-O-Matic</a> (optional)")
442 .".\n";
443 $rt.="$par<li><a href=\"".installUrl('', 'url', 'editGroups')."\">"
444 .checkBoxFor('customGroups')
445 .gettext("Define groups</a> (optional)")
446 .".\n";
447  
448 # THANKS: to John Goerzen for discovering the CGI.pm/bags bug
449 $rt.="$par<li>"
450 .checkBoxFor('CGIversion')
451 .gettext("Upgrade to CGI.pm version 2.49 or newer.")
452 .($CGI::VERSION >= 2.49
453 ? ''
454 : " ".gettext("(optional; older versions have bugs that affect bags)")."\n"
455 )
456 ." "
457 .gettexta("You are using version %0 now.", $CGI::VERSION)
458 ."\n";
459  
460 $rt.="$par<li>".checkBoxFor('nothing')
461 ."<a href=\"".installUrl('mainMenu')."\">"
462 .gettext("Bookmark this link to be able to return to this menu.")
463 ."</a>\n";
464 if ($FAQ::OMatic::Config::secureInstall) {
465 $rt.="$par<li>".checkBoxFor('nothing')
466 ."<a href=\"".installUrl('', 'url', 'faq')."\">"
467 .gettext("Go to the Faq-O-Matic")
468 ."</a>\n";
469 } else {
470 $rt.="$par<li>".checkBoxFor('nothing')
471 .gettext("Go to the Faq-O-Matic")
472 ." "
473 .gettext("(need to turn on installer security)");
474 }
475 $rt.="</ol>\n";
476 $rt.="<ul><u>".gettext("Other available tasks:")."</u>\n";
477 $rt.="$par<li>"
478 .checkBoxFor('nothing')
479 ."<a href=\"".installUrl('','url','stats')."\">"
480 .gettext("See access statistics")
481 ."</a>\n";
482 $rt.="$par<li>"
483 .checkBoxFor('nothing')
484 ."<a href=\"".installUrl('','url','selectBag')."\">"
485 .gettext("Examine all bags")
486 ."</a>\n";
487 $rt.="$par<li>"
488 .checkBoxFor('nothing')
489 ."<a href=\"".installUrl('', 'url', 'maintenance')
490 ."&secret=$maintenanceSecret&tasks=expireBags\">"
491 .gettext("Check for unreferenced bags (not linked by any FAQ item)")
492 ."</a>\n";
493 $rt.="$par<li>"
494 .checkBoxFor('nothing')
495 ."<a href=\"".installUrl('', 'url', 'maintenance')
496 ."&secret=$maintenanceSecret&tasks=emptyTrash\">"
497 .gettext("Empty old trash now")
498 ."</a>\n";
499 $rt.="$par<li>"
500 .checkBoxFor('nothing')
501 ."<a href=\"".installUrl('', 'url', 'maintenance')
502 ."&secret=$maintenanceSecret&tasks=fsck\">"
503 .gettext("fsck (check and repair tree structure) now")
504 ."</a>\n";
505 $rt.="$par<li>"
506 .checkBoxFor('nothing')
507 ."<a href=\"".installUrl('', 'url', 'maintenance')
508 ."&secret=$maintenanceSecret&tasks=buildSearchDB&force=true\">"
509 .gettext("rebuild search database now")
510 ."</a>\n";
511 # rebuildCache shows up again at the end, because it doesn't show
512 # up in the numbered list if this is a mirror site.
513 $rt.="$par<li>"
514 .checkBoxFor('nothing')
515 ."<a href=\"".installUrl('', 'url', 'maintenance')
516 ."&secret=$maintenanceSecret&tasks=rebuildCache\">"
517 .gettext("Rebuild the cache and dependency files now")
518 ."</a>\n";
519
520 $rt.="</ul>\n";
521  
522 $rt.=gettexta("The Faq-O-Matic modules are version %0.", $FAQ::OMatic::VERSION)
523 ."\n";
524  
525 displayMessage($rt);
526 }
527  
528 sub isDone {
529 my $thing = shift;
530  
531 return 1 if (($thing eq 'askConfig')
532 && (($FAQ::OMatic::Config::adminAuth||'') ne '')
533 && not undefinedConfigsExist());
534 return 1 if (($thing eq 'configItem')
535 && (($FAQ::OMatic::Config::itemDir||'') ne '')
536 && (-d "$FAQ::OMatic::Config::itemDir/.")
537 && (($FAQ::OMatic::Config::cacheDir||'') ne '')
538 && (-d "$FAQ::OMatic::Config::cacheDir/.")
539 && (($FAQ::OMatic::Config::bagsDir||'') ne '')
540 && (-d "$FAQ::OMatic::Config::bagsDir/."));
541 return 1 if (($thing eq 'firstItem')
542 && FAQ::OMatic::Versions::getVersion('Items') eq $FAQ::OMatic::VERSION);
543 # The above test ensures that the "create initial items" routine
544 # has been run once by this version of the faq. That way as new
545 # default initial items are supplied, upgraders don't get a checkbox
546 # until they're installed.
547 return 1
548 if (($thing eq 'maintenance')
549 && ($FAQ::OMatic::Config::maintenanceSecret));
550 return 1 if (($thing eq 'makeSecure') && ($FAQ::OMatic::Config::secureInstall));
551 return 1 if (($thing eq 'manualMaintenance')
552 && (-f "$FAQ::OMatic::Config::metaDir/lastMaintenance")
553 && (FAQ::OMatic::Versions::getVersion('MaintenanceInvoked')
554 eq $FAQ::OMatic::VERSION));
555 return 1 if (($thing eq 'customColors')
556 && FAQ::OMatic::Versions::getVersion('CustomColors'));
557 return 1 if (($thing eq 'rebuildCache')
558 && (FAQ::OMatic::Versions::getVersion('CacheRebuild')
559 eq $FAQ::OMatic::VERSION));
560 return 1 if (($thing eq 'customGroups')
561 && FAQ::OMatic::Versions::getVersion('CustomGroups'));
562 return 1 if (($thing eq 'systemBags')
563 && (FAQ::OMatic::Versions::getVersion('SystemBags')
564 eq $FAQ::OMatic::VERSION));
565 return 1 if (($thing eq 'CGIversion')
566 && ($CGI::VERSION >= 2.49));
567 return 1 if (($thing eq 'copyItems')
568 && (-f "$FAQ::OMatic::Config::itemDir/1"));
569 return 1 if (($thing eq 'configVersion')
570 && ($FAQ::OMatic::Config::version
571 eq $FAQ::OMatic::VERSION));
572  
573 return 0;
574 }
575  
576 sub checkBoxFor {
577 my $thing = shift;
578 my $done = isDone($thing);
579  
580 my $rt = "<img border=0 src=\"";
581 if ($thing eq 'nothing') {
582 $rt.=installUrl('', 'url', 'img', 'space');
583 } elsif ($done) {
584 $rt.=installUrl('', 'url', 'img', 'checked');
585 } else {
586 $rt.=installUrl('', 'url', 'img', 'unchecked');
587 }
588 $rt.="\"> ";
589 return $rt;
590 }
591  
592 # sub askItemStep {
593 # my $rt = '';
594 #
595 # my $dflItem = stripQuotes(readConfig()->{'$itemDir'});
596 #
597 # $rt.="Faq-O-Matic needs a writable directory in which to store\n";
598 # $rt.="FAQ item data. Frequently, this is just a subdirectory of\n";
599 # $rt.="the <b>meta/</b> directory. If you have an existing Faq-O-Matic 2\n";
600 # $rt.="installation, you can enter the path to its <b>item/</b> here,\n";
601 # $rt.="and this installation will use those existing items.\n";
602 # $rt.=installUrl('configItem', 'GET');
603 # $rt.="<input type=text size=60 name=item value=\"$dflItem\">\n";
604 # $rt.="<input type=submit name=junk value=\"Define\">\n";
605 # $rt.="</form>\n";
606 # displayMessage($rt);
607 # }
608  
609 sub configItemStep {
610 my $rt.='';
611  
612 # create item, cache, and bags directories.
613 createDir('$item', '/item/');
614 createDir('$cache', '/cache/');
615 createDir('$bags', '/bags/');
616  
617 doStep('mainMenu');
618 }
619  
620 sub createDir {
621 my $dirSymbol = shift;
622 my $dirSuffix = shift;
623  
624 my $dirPath =
625 FAQ::OMatic::concatDir($FAQ::OMatic::Config::serveDir, $dirSuffix);
626 my $dirUrl =
627 FAQ::OMatic::concatDir($FAQ::OMatic::Config::serveURL, $dirSuffix);
628  
629 if (not -d $dirPath) {
630 if (not mkdir(stripSlash($dirPath), 0700)) {
631 dirFail(gettexta("I couldn't create <b>%0</b>: %1", $dirPath, $!));
632 return;
633 }
634 displayMessage(gettexta("Created <b>%0</b>.", $dirPath));
635 }
636 if (not -w "$dirPath/.") {
637 dirFail(gettexta("I don't have write permission to <b>%0</b>.", $dirPath));
638 return;
639 }
640 if (not chmod 0755, $dirPath) {
641 dirFail(gettexta("I wasn't able to change the permissions on <b>%0</b> to 755 (readable/searchable by all).",
642 $dirPath));
643 return;
644 }
645  
646 my $map = readConfig();
647 if (defined $map->{$dirSymbol."Dir"}
648 and ($map->{$dirSymbol."Dir"} ne "''")) {
649 # copy the prior definition. Used so we know where the old
650 # $itemDir was after we've created the new one.
651 $map->{$dirSymbol."Dir_Old"} = $map->{$dirSymbol."Dir"};
652 }
653 $map->{$dirSymbol."Dir"} = "'".$dirPath."'";
654 $map->{$dirSymbol."URL"} = "'".$dirUrl."'";
655 writeConfig($map);
656 displayMessage(gettext("updated config file:")." $dirSymbol"."Dir = <b>$dirPath</b>"
657 ."<br>".gettext("updated config file:")." $dirSymbol"."URL = <b>$dirUrl</b>");
658 }
659  
660 sub dirFail {
661 my $message = shift;
662  
663 displayMessage($message
664 ."<p>".gettexta("Redefine configuration parameters to ensure that <b>%0</b> is valid.", $FAQ::OMatic::Config::serveDir));
665 doStep('mainMenu');
666 }
667  
668 # lets me succinctly define configInfo entries
669 sub ci {
670 my $key = shift;
671 my $mymap = {};
672 my $property;
673 while (defined($property = shift(@_))) {
674 if (not $property=~m/^-/) {
675 FAQ::OMatic::gripe('error',
676 gettexta("Jon made a mistake here; key=%0, property=%1.", $key, $property))
677 }
678 my $val = 1;
679 if (scalar(@_) and not $_[0]=~m/^-/) {
680 $val = shift(@_); # shift an argument on, if possible
681 }
682 $mymap->{$property} = $val;
683 }
684 return ($key,$mymap);
685 }
686  
687 $configInfo = undef;
688 sub configInfo {
689 # init the array inside a sub so that it doesn't get initted unless
690 # needed -- some of the defaults call things like which(), which goes
691 # out and frobs the filesystem, which is pretty heavyweight.
692 if (not defined $configInfo) {
693 $configInfo = {
694 # config var => [ 'sortOrder|hide', 'description',
695 # ['unquoted values'], free-input-okay, is-a-command ]
696 # -desc=>'...' -- description of variable
697 # -choices=>[] -- list of potential choices
698 # -free -- provide a free-form input field
699 # -hide -- hide variable from define page
700 # -sort=key -- variable sorts in this order on define page
701 # -cmd -- variable is a Unix command string
702 # -mirror -- variable should be mirrored from server
703  
704 ci('sep_a', '-sort'=>'a--sep', '-separator', '-desc'=>
705 gettext("<b>Mandatory:</b> System information")),
706 ci('adminAuth', '-sort'=>'a-a1', '-free',
707 '-default'=>"''", '-desc'=>
708 gettext("Identity of local FAQ-O-Matic administrator (an email address)")),
709 ci('mailCommand', '-sort'=>'a-m1', '-free', '-cmd', '-desc' =>
710 gettext("A command FAQ-O-Matic can use to send mail. It must either be sendmail, or it must understand the -s (Subject) switch.")),
711 ci('crontabCommand','-sort'=>'a-m4', '-free', '-cmd', '-desc' =>
712 gettext("The command FAQ-O-Matic can use to install a cron job."),
713 '-default'=>"'".which('crontab')."'"),
714 ci('RCSci', '-sort'=>'a-r1', '-free', '-cmd',
715 '-default'=>"'".which('ci')."'", '-desc'=>
716 gettext("Path to the <b>ci</b> command from the RCS package.")),
717 ci('RCSco', '-sort'=>'a-r2', '-free', '-cmd',
718 '-default'=>"'".which('co')."'", '-desc'=>
719 gettext("Path to the <b>co</b> command from the RCS package.")),
720  
721 ci('sep_c', '-sort'=>'c--sep', '-separator', '-desc'=>
722 gettext("<b>Mandatory:</b> Server directory configuration")),
723 ci('serverBase', '-sort'=>'c-a1', '-free', '-desc'=>
724 gettext("Protocol, host, and port parts of the URL to your site. This will be used to construct link URLs. Omit the trailing '/'; for example: <tt>http://www.dartmouth.edu</tt>"),
725 '-default'=>"'".FAQ::OMatic::serverBase()."'" ),
726 ci('cgiURL', '-sort'=>'c-a2', '-free', '-desc'=>
727 gettext("The path part of the URL used to access this CGI script, beginning with '/' and omitting any parameters after the '?'. For example: <tt>/cgi-bin/cgiwrap/jonh/faq.pl</tt>"),
728 '-default'=>"'".FAQ::OMatic::cgiURL()."'" ),
729 ci('serveDir', '-sort'=>'c-c1', '-free', '-desc'=>
730 gettext("Filesystem directory where FAQ-O-Matic will keep item files, image and other bit-bag files, and a cache of generated HTML files. This directory must be accessible directly via the http server. It might be something like /home/faqomatic/public_html/fom-serve/"),'-default'=>"''"),
731 ci('serveURL', '-sort'=>'c-c2', '-free', '-desc'=>
732 gettext("The path prefix of the URL needed to access files in <b>\$serveDir</b>. It should be relative to the root of the server (omit http://hostname:port, but include a leading '/'). It should also end with a '/'.") , '-default'=>"''" ),
733  
734 ci('sep_e', '-sort'=>'e--sep', '-separator', '-desc'=>
735 gettext("<i>Optional:</i> Miscellaneous configurations")),
736 ci('language', '-sort'=>'k-m00',
737 '-choices'=>[ "'en'", "'de_iso8859_1'", "'fr'", "'ru'",
738 "'uk'", "'fi'", "'ja_JP.EUC'" , "'hu'"],
739 '-desc'=>
740 gettext("Select the display language."),
741 '-default'=>gettext("'en'")),
742 ci('dateFormat', '-sort'=>'k-m01',
743 '-choices'=>[ "''", "'24'"],
744 '-desc'=>
745 gettext("Show dates in 24-hour time or am/pm format."),
746 '-default'=>"''"),
747 ci('mirrorURL', '-sort'=>'k-m1', '-free', '-choices'=>[ "''"],
748 '-default'=>"''", '-desc'=>
749 gettext("If this parameter is set, this FAQ will become a mirror of the one at the given URL. The URL should be the base name of the CGI script of the master FAQ-O-Matic.")),
750 ci('pageHeader', '-sort'=>'m-p1', '-free', '-mirror', '-desc'=>
751 gettext("An HTML fragment inserted at the top of each page. You might use this to place a corporate logo.")
752 ." "
753 .gettext("If this field begins with <tt>file=</tt>, the text will come from the named file in the meta directory; otherwise, this field is included verbatim.")),
754 # THANKS to Vicki Brown <vlb@cfcl.com> for demanding a configurable
755 # tableWidth tag. It's a workaround for Netscape's buggy page layout;
756 # it doesn't even help with align=right images.
757 ci('tableWidth', '-sort'=>'m-p15',
758 '-choices'=>[ "'width=\"100%\"'" ],
759 '-default'=>"'width=\"100%\"'",
760 '-free', '-mirror', '-desc'=>
761 gettext("The <tt>width=</tt> tag in a table. If your <b>\$pageHeader</b> has <tt>align=left</tt>, you will want to make this empty.")),
762 ci('pageFooter', '-sort'=>'m-p2', '-free', '-mirror',
763 '-default' => "'This FAQ administered by ...'", '-desc'=>
764 gettext("An HTML fragment appended to the bottom of each page. You might use this to identify the webmaster for this site.")
765 ." "
766 .gettext("If this field begins with <tt>file=</tt>, the text will come from the named file in the meta directory; otherwise, this field is included verbatim.")),
767 ci('adminEmail','-sort'=>'n-e2', '-free', '-choices'=>[ '$adminAuth' ],
768 '-default' => "\$adminAuth",
769 '-desc'=> gettext("Where FAQ-O-Matic should send email when it wants to alert the administrator (usually same as \$adminAuth)")),
770 ci('maintSendErrors', '-sort'=>'n-m2', '-choices'=>[ "'true'", "''" ],
771 '-desc'=> gettext("If true, FAQ-O-Matic will mail the log file to the administrator whenever it is truncated."),
772 '-default'=>"'true'"),
773 ci('RCSuser', '-sort'=>'r-r3', '-free', '-choices'=>['getpwuid($>)'],
774 '-desc'=> gettext("User to use for RCS ci command (default is process UID)"),
775 '-default'=>'getpwuid($>)'),
776 ci('useServerRelativeRefs', '-sort'=>'r-s1',
777 '-choices'=>[ "'true'", "''" ], '-default'=>"''", '-desc'=>
778 gettext("Links from cache to CGI are relative to the server root, rather than absolute URLs including hostname:")),
779 ci('antiSpam', '-sort'=>'r-s7', '-mirror',
780 '-choices'=>[ "'off'", "'cheesy'", "'nameonly'", "'hide'" ],
781 '-default'=>"'off'", '-desc'=>
782 gettext("mailto: links can be rewritten such as jonhATdartmouthDOTedu (cheesy), jonh (nameonly), or e-mail addresses suppressed entirely (hide).")),
783 ci('cookieLife', '-sort'=>'r-s8', '-free',
784 '-choices'=>[ "'3600'" ],
785 '-default'=>"'3600'",
786 '-desc'=> gettext("Number of seconds that authentication cookies remain valid. These cookies are stored in URLs, and so can be retrieved from a browser history file. Hence they should usually time-out fairly quickly.")),
787 ci('trashTime', '-sort'=>'r-s9', '-free',
788 '-choices'=>[ "'14'" ],
789 '-default'=>"'14'",
790 '-desc'=> gettext("Number of days that trash sits in the trash category before maintenance cleans it up. '0' lets it stay forever.")),
791  
792 ci('sep_t', '-sort'=>'t--sep', '-separator', '-desc'=>
793 gettext("<i>Optional:</i> These options set the default [Appearance] modes.")),
794  
795 ci('renderDefault', '-sort'=>'t-t1', '-mirror',
796 '-choices'=>[ "'tables'", "'simple'", "'text'" ],
797 '-default'=> "'tables'", '-desc'=>
798 gettext("Page rendering scheme. Do not choose 'text' as the default.")),
799  
800 ci('editCmdsDefault', '-sort'=>'t-t2', '-mirror',
801 '-choices'=>[ "'show'", "'compact'", "'hide'" ],
802 '-default'=>"'hide'", '-desc'=>
803 gettext("expert editing commands")),
804  
805 ci('showModeratorDefault', '-sort'=>'t-t3', '-mirror',
806 '-choices'=>[ "'show'", "'hide'" ],
807 '-default'=>"'hide'", '-desc'=>
808 gettext("name of moderator who organizes current category")),
809  
810 ci('showLastModifiedDefault', '-sort'=>'t-t4', '-mirror',
811 '-choices'=>[ "'show'", "'hide'" ],
812 '-default'=>"'hide'", '-desc'=>
813 gettext("last modified date")),
814  
815 ci('showAttributionsDefault', '-sort'=>'t-t5', '-mirror',
816 '-choices'=>[ "'all'", "'default'", "'hide'" ],
817 '-default'=>"'default'", '-desc'=>
818 gettext("attributions")),
819  
820 ci('textCmdsDefault', '-sort'=>'t-t6', '-mirror',
821 '-choices'=>[ "'show'", "'hide'" ],
822 '-default'=>"'hide'", '-desc'=>
823 gettext("commands for generating text output")),
824  
825 ci('sep_u', '-sort'=>'v--sep', '-separator', '-desc'=>
826 gettext("<i>Optional:</i> These options fine-tune the appearance of editing features.")),
827 ci('showEditOnFaq', '-sort'=>'v-s3', '-mirror',
828 '-choices'=>[ "'show'", "'compact'", "''" ], '-default'=>"''", '-desc'=>
829 gettext("The old [Show Edit Commands] button appears in the navigation bar.")),
830  
831 ci('navigationBlockAtTop', '-sort'=>'v-s35', '-mirror',
832 '-choices'=>[ "'true'", "''" ], '-default'=>"''", '-desc'=>
833 gettext("Navigation links appear at top of page as well as at the bottom.")),
834  
835 ci('hideEasyEdits', '-sort'=>'v-s4', '-mirror',
836 '-choices'=>[ "'true'", "''" ], '-default'=>"''", '-desc'=>
837 gettext("Hide [Append to This Answer] and [Add New Answer in ...] buttons.")),
838  
839 ci('showEditIcons', '-sort'=>'v-s6', '-mirror',
840 '-choices'=>[ "'icons-and-label'", "'icons-only'", "''" ],
841 '-default'=>"''", '-desc'=>
842 gettext("Editing commands appear with neat-o icons rather than [In Brackets].")),
843  
844 ci('sep_z', '-sort'=>'z--sep', '-separator', '-desc'=>
845 gettext("<i>Optional:</i> Other configurations that you should probably ignore if present.")),
846  
847 ci('nolanTitles', '-mirror', '-choices'=>[ "'true'", "''" ],
848 '-default'=>"''", '-desc'=>
849 gettext("Draw Item titles John Nolan's way.")),
850  
851 ci('hideSiblings', '-mirror', '-choices'=>[ "'true'", "''" ],
852 '-default'=>"''", '-desc'=>
853 gettext("Hide sibling (Previous, Next) links")),
854  
855 ci('useDBMSearch', '-choices'=>[ "'true'", "''" ],
856 '-default'=>"''", '-desc'=>
857 gettext("Use DBM-based search databases. Faster on machines with non-broken DBM.")),
858 ci('disableSearchHighlight', '-choices'=>[ "'true'", "''" ],
859 '-default'=>"''", '-desc'=>
860 gettext("Links from search results page point into cache (do not highlight search terms)")),
861 # THANKS anti-feature suggested by
862 # THANKS "Dameon D. Welch-Abernathy" <dwelch@phoneboy.com>
863  
864 ci('RCSciArgs', '-sort'=>'a-r1-args', '-free', '-desc'=>
865 gettext("Arguments to make ci quietly log changes and not mash RCS tags (use default with GNU RCS)"),
866 '-default'=>"'-mnull -t-null'"),
867 ci('RCScoArgs', '-sort'=>'a-r2-args', '-free', '-desc'=>
868 gettext("Arguments to make co not mash RCS tags (use default with GNU RCS)"),
869 '-default'=>"'-ko -l'"),
870 ci('RCSargs', '-hide', '-free', '-desc'=>
871 gettext('deprecated; subsumed by RCSciArgs and RCScoArgs.')),
872 ci('authorEmail', '-hide', '-default'=>"''"),
873 ci('backgroundColor', '-hide', '-mirror', '-default'=>"'#ffffff'"),
874 ci('bagsDir', '-hide'),
875 ci('bagsURL', '-hide'),
876 ci('cacheDir', '-hide'),
877 ci('cacheURL', '-hide'),
878 ci('directoryPartColor', '-hide', '-mirror', '-default'=>"'#80d080'"),
879 ci('highlightColor', '-hide', '-mirror', '-default'=>"'#d00050'"),
880 ci('itemBarColor', '-hide', '-mirror', '-default'=>"'#606060'"),
881 ci('itemDir', '-hide'),
882 ci('itemURL', '-hide'),
883 ci('linkColor', '-hide', '-mirror', '-default'=>"'#3030c0'"),
884 ci('maintenanceSecret', '-hide'),
885 ci('metaDir', '-hide',),
886 ci('regularPartColor', '-hide', '-mirror', '-default'=>"'#d0d0d0'"),
887 ci('secureInstall', '-hide'),
888 ci('statUniqueHosts', '-hide',
889 '-default'=>"''"),
890 ci('textColor', '-hide', '-mirror', '-default'=>"'#000000'"),
891 ci('version', '-hide', '-default'=>"'$FAQ::OMatic::VERSION'"),
892 ci('vlinkColor', '-hide', '-mirror', '-default'=>"'#3030c0'"),
893  
894 ci('bagsDir_Old', '-hide', '-desc'=>'(internal use)'),
895 ci('cacheDir_Old', '-hide', '-desc'=>'(internal use)'),
896 ci('compactEditCmds', '-hide', '-desc'=>'(obsolete)'),
897 ci('showLastModifiedAlways', '-hide',
898 '-choices'=>[ ], '-desc'=>
899 '(obsolete) Items always display their last-modified dates.')
900 }
901 }
902 return $configInfo;
903 }
904 # THANKS: John Goerzen and someone else (sorry I forgot who since I
905 # THANKS: fixed it!) pointed out that the serveURL (then the cacheURL) needs
906 # THANKS: a leading slash to avoid picking up a prefix like cgi-bin/.
907  
908 sub getPotentialConfig {
909 # gets the current config, plus empty strings for any expected but
910 # nonexistant keys (probably because the modules have been upgraded to
911 # a new version)
912 my $map = readConfig('ignoreErrors');
913  
914 # Provide defaults for any new options not present in config file
915 my $ckey;
916 foreach $ckey (sort keys %{configInfo()}) {
917 next if defined($map->{'$'.$ckey});
918 next if configInfo()->{$ckey}->{'-separator'};
919 $map->{'$'.$ckey} =
920 configInfo()->{$ckey}->{'-default'} || "''";
921 }
922  
923 return $map;
924 }
925  
926 sub undefinedConfigsExist {
927 my $map = readConfig();
928 my $ckey;
929 foreach $ckey (sort keys %{configInfo()}) {
930 if (not defined($map->{'$'.$ckey})
931 and not configInfo()->{$ckey}->{'-separator'}) {
932 FAQ::OMatic::gripe('debug', "not defined: $ckey");
933 return 1;
934 }
935 }
936 return 0;
937 }
938  
939 sub askConfigStep {
940 my $rt = '';
941 my ($left, $right);
942  
943 $rt.="<table>\n";
944 $rt.=installUrl('setConfig', 'POST'); # long pageHeader can exceed limit of web server
945  
946 # Read current configuration
947 my $map = getPotentialConfig();
948  
949 my $widgets = {}; # collect widgets here for sorting later
950 # want to list any widget that either in the existing $map, or
951 # in the list of possible configs (configInfo()); but of course
952 # any given widget should appear only once (hence the hash).
953 my %keylist = map {$_=>$_}
954 ((keys %{$map}),
955 (map {'$'.$_} keys %{configInfo()}));
956 foreach $left (sort keys %keylist) {
957 $right = $map->{$left} || '';
958 my $aleft = $left;
959 $aleft =~ s/^\$//;
960 my $isLegacy = not $right=~m/^'/; # if value isn't a free input
961 my $aright = stripQuotes($right);
962 my ($sort,$desc,$choices,$free,$cmd,$separator,$mirror,$default);
963 my $ch = configInfo()->{$aleft} || {'-free'=>1};
964 if (defined $ch) {
965 $sort = $ch->{'-sort'} || 'zzzz';
966 $desc = $ch->{'-desc'} || '(no description)';
967 $choices = $ch->{'-choices'} || [];
968 $free = $ch->{'-free'} || 0;
969 $cmd = $ch->{'-cmd'} || 0;
970 $separator = $ch->{'-separator'} || 0;
971 $mirror = $ch->{'-mirror'} || 0;
972 $default = $ch->{'-default'} || '';
973 $sort = 'hide' if ($ch->{'-hide'});
974 $desc.="<br>".gettext("This is a command, so only letters, hyphens, and slashes are allowed.") if ($cmd);
975 }
976 if ($separator) {
977 $widgets->{$sort} =
978 "<tr><td colspan=2>\n<hr>$desc<hr>\n</td></tr>\n";
979 } elsif ($sort eq 'hide') {
980 # don't show hidden widgets
981 } elsif ((($FAQ::OMatic::Config::mirrorURL||'') ne '') and $mirror) {
982 # don't show mirrorable widgets if this is a mirror site --
983 # they'll get automatically defined at mirroring time.
984 } else {
985 my $wd = '';
986 $wd.="<tr><td align=right valign=top><b>$left</b></td>"
987 ."<td align=left valign=top>\n";
988 $wd.="$desc<br>\n";
989 my $selected = 0; # don't show $right in free field if
990 # it was available by a select button
991 if (scalar(@{$choices})) {
992 foreach my $choice (@{$choices}) {
993 my $defaultText = ($choice eq $default)
994 ? ' <i>(default)</i>'
995 : '';
996 my $echoice = FAQ::OMatic::entify($choice);
997 $wd.="<input type=radio name=\"$left-select\" "
998 .($right eq $choice ? ' checked' : '')
999 ." value=\"$echoice\"> $choice$defaultText<br>\n";
1000 $selected = 1 if ($right eq $choice);
1001 }
1002 if ($selected == 0 and $isLegacy) {
1003 # there is an unquoted value that's no longer
1004 # a given choice, but can't go in the free field
1005 # (because otherwise it'll pick up quotes.)
1006 $wd.="<input type=radio name=\"$left-select\" "
1007 ."checked value=\""
1008 .FAQ::OMatic::entify($right)
1009 ."\"> $right "
1010 ."<i><font color=red>This is no longer a "
1011 ."recommended selection.</font></i><br>\n";
1012 $selected = 1;
1013 }
1014 if ($free) {
1015 $wd.="<input type=radio name=\"$left-select\" "
1016 .($selected ? '' : ' checked')
1017 ." value=\"free\">\n";
1018 }
1019 } else {
1020 $wd.="<input type=hidden name=$left-select value=\"free\">\n";
1021 }
1022 if ($free) {
1023 $wd.="<input type=text size=40 name=\"$left-free\" "
1024 ."value=\""
1025 .($selected ? '' : FAQ::OMatic::entify($aright))
1026 ."\">\n";
1027 }
1028 $wd.="</td></tr>\n";
1029 $widgets->{$sort} .= $wd;
1030 }
1031 }
1032  
1033 $rt.=gettext("If this is your first time installing a FAQ-O-Matic, I recommend only filling in the sections marked <b>Mandatory</b>.");
1034 # now display the widgets in sorted order
1035 $rt.= join('', map {$widgets->{$_}} sort(keys %{$widgets}));
1036 $rt.="<tr><td></td><td>"
1037 ."<input type=submit name=junk value=\"".gettext("Define")."\"></td></tr>\n";
1038 $rt.="</form>\n";
1039 $rt.="</table>\n";
1040  
1041 displayMessage($rt);
1042 }
1043  
1044 sub setConfigStep {
1045 my $warnings = '';
1046 my $notices = ''; #nonproblems
1047 my ($left, $right);
1048 my $map = getPotentialConfig();
1049  
1050 foreach $left (sort keys %{$map}) {
1051 $right = $map->{$left};
1052 my $selected = cgi()->param($left."-select") || '';
1053 if ($selected eq 'free') {
1054 $map->{$left} = "'".cgi()->param($left."-free")."'";
1055 } elsif ($selected ne '') {
1056 $map->{$left} = $selected;
1057 }
1058 $map->{$left} =~ s/\n//gs; # don't let weirdo newlines through
1059 my $aleft = $left;
1060 $aleft =~ s/^\$//;
1061 if (configInfo()->{$aleft}->{'-cmd'}) { # it represents a command...
1062 $map->{$left} =~ s#[^\w/'-]##gs; # be very restrictive
1063 }
1064 my ($warn,$howbad) = checkConfig($left, \$map->{$left});
1065 if ($howbad eq 'ok') {
1066 $notices .= "<li>$warn";
1067 } elsif ($warn) {
1068 $warnings .= "<li>$warn";
1069 }
1070 }
1071 writeConfig($map);
1072 FAQ::OMatic::I18N::reload(); # future displays should be in new language
1073 # TODO except in practice the next configuration screen
1074 # stays in the old language.
1075 if ($notices) {
1076 $notices = "<ul>$notices</ul>\n";
1077 }
1078 if ($warnings) {
1079 $warnings = "<p><b>".gettext("Warnings:")." <ul>$warnings</ul>"
1080 .gettexta("You should <a href=\"%0\">go back</a> and fix these configurations.", installUrl('askConfig'))
1081 ."</b>";
1082 }
1083 displayMessage(gettext("Rewrote configuration file.")
1084 ."\n$notices\n$warnings");
1085 doStep('mainMenu');
1086 }
1087  
1088 sub checkConfig {
1089 my $left = shift;
1090 my $rightref = shift;
1091 my $right = ${$rightref};
1092 my $eright = FAQ::OMatic::entify($right);
1093 my $aright = stripQuotes($right);
1094  
1095 if ($aright =~ m/'/) {
1096 $$rightref = configInfo()->{$left}->{'-default'} || "''";
1097 return (gettexta("%0 (%1) has an internal apostrophe, which will certainly make Perl choke on the config file.", $left, $eright), 'fix');
1098 }
1099 if ($left eq '$adminAuth') {
1100 if (not FAQ::OMatic::validEmail($aright)) {
1101 return (gettexta("%0 (%1) doesn't look like a fully-qualified email address.", $left, $eright),
1102 'fix');
1103 }
1104 }
1105 if ($left eq '$adminEmail' and $right ne '$adminAuth') {
1106 if (not FAQ::OMatic::validEmail($aright)) {
1107 return (gettexta("%0 (%1) doesn't look like a fully-qualified email address.", $left, $eright),
1108 'fix');
1109 }
1110 }
1111 if ($left eq '$mailCommand') {
1112 if (not -x $aright) {
1113 return (gettexta("%0 (%1) isn't executable.", $left, $eright), 'fix');
1114 }
1115 }
1116 if ($left eq '$RCSci') {
1117 if (not -x $aright) {
1118 return (gettexta("%0 (%1) isn't executable.", $left, $eright), 'fix');
1119 }
1120 }
1121 if ($left eq '$serveDir') {
1122 if ($aright eq '') {
1123 return ("$left undefined. You must define a directory readable "
1124 ."by the web server from which to serve data. If you are "
1125 ."upgrading, I recommend creating a new directory in the "
1126 ."appropriate place in your filesystem, and copying in "
1127 ."your old items later. The installer checklist will tell you "
1128 ."when to do the copy.",
1129 'fix');
1130 }
1131 $aright = FAQ::OMatic::canonDir($aright);
1132 if (not -d $aright) {
1133 my $dirname = stripSlash($aright);
1134 if (scalar($dirname =~ m#^([/\w\.\-_]+)$#)==0) {
1135 FAQ::OMatic::gripe('error', gettexta("%0 has funny characters.", $dirname));
1136 }
1137 $dirname = $1;
1138 if (not mkdir($dirname, 0755)) {
1139 return ("$left ($eright) can't be created.", 'fix');
1140 } else {
1141 chmod(0755,$dirname);
1142 return ("$left: Created directory $eright.", 'ok');
1143 }
1144 }
1145 }
1146 if ($left eq '$cookieLife') {
1147 if ($aright < 1) {
1148 $$rightref = "'3600'";
1149 return ("$left was nonpositive; I set it to '3600' (one hour).",
1150 'ok');
1151 # simply disallow unreasonable numbers. I can't imagine a
1152 # scenario where someone would want a 0 cookieLife (uttering
1153 # those words, of course, will cause such a scenario to
1154 # spring into existence), and this will save a lot of grief
1155 # for most people upgrading.
1156 }
1157 }
1158 return ('','');
1159 }
1160  
1161 sub firstItemStep {
1162 if (not -f "$FAQ::OMatic::Config::itemDir/1") {
1163 my $item = new FAQ::OMatic::Item();
1164 $item->setProperty('Title', gettext("Untitled Faq-O-Matic"));
1165 $item->setProperty('Parent', '1');
1166 $item->setProperty('Moderator', $FAQ::OMatic::Config::adminAuth);
1167  
1168 # tell the user how to name his FAQ
1169 my $helpPart = new FAQ::OMatic::Part();
1170 $helpPart->{'Text'} = gettext("To name your FAQ-O-Matic, use the [Appearance] page to show the expert editing commands, then click [Edit Category Title and Options].");
1171 push @{$item->{'Parts'}}, $helpPart;
1172  
1173 # prevent user from feeling dumb because he can't find
1174 # the [New Answer] button by making the initial item as a
1175 # category (giving it a directory).
1176 $item->makeDirectory()->
1177 setText(gettext("Subcategories:")."\n\n\n".gettext("Answers in this category:")."\n");
1178  
1179 $item->saveToFile('1');
1180 displayMessage(gettexta("Created category \"%0\".", 'Top (file=1)'));
1181 } else {
1182 displayMessage(gettexta("<b>%0</b> already contains a file '%1'.",
1183 $FAQ::OMatic::Config::itemDir, '1'));
1184 }
1185 if (not -f "$FAQ::OMatic::Config::itemDir/trash") {
1186 my $item = new FAQ::OMatic::Item();
1187 $item->setProperty('Title', 'Trash');
1188 $item->setProperty('Parent', 'trash');
1189 $item->setProperty('Moderator', $FAQ::OMatic::Config::adminAuth);
1190 $item->makeDirectory();
1191 $item->saveToFile('trash');
1192 displayMessage(gettexta("Created category \"%0\".", 'trash'));
1193 } else {
1194 displayMessage(gettexta("<b>%0</b> already contains a file '%1'.",
1195 $FAQ::OMatic::Config::itemDir, 'trash'));
1196 }
1197 if (not -f "$FAQ::OMatic::Config::itemDir/help000") {
1198 my $item = new FAQ::OMatic::Item();
1199 $item->setProperty('Title', 'Help');
1200 $item->setProperty('Parent', 'help000');
1201 $item->setProperty('Moderator', $FAQ::OMatic::Config::adminAuth);
1202 $item->makeDirectory();
1203 $item->saveToFile('help000');
1204 displayMessage(gettexta("Created category \"%0\".", 'help'));
1205 } else {
1206 displayMessage(gettexta("<b>%0</b> already contains a file '%1'.",
1207 $FAQ::OMatic::Config::itemDir, 'help000'));
1208 }
1209  
1210 # The reason for an Items version field is to ensure that
1211 # all of the items that come with a default FOM of a given
1212 # version are now installed. Old items are not replaced...
1213 FAQ::OMatic::Versions::setVersion('Items');
1214  
1215 # set itemDir_Old to current itemDir, since that's now the
1216 # working directory. That way if it ever moves again (oh man
1217 # I hope not), we'll know where to copy from. Ugh.
1218 my $map = readConfig();
1219 delete $map->{'$itemDir_Old'};
1220 writeConfig($map);
1221  
1222 doStep('mainMenu');
1223 }
1224  
1225 sub copyItemsStep {
1226 my $oldDir = $FAQ::OMatic::Config::itemDir_Old;
1227 my $newDir = $FAQ::OMatic::Config::itemDir;
1228
1229 my @oldList = FAQ::OMatic::getAllItemNames($oldDir);
1230 my $file;
1231 foreach $file (@oldList) {
1232 my $item = new FAQ::OMatic::Item($file, $oldDir);
1233 $item->saveToFile('', $newDir, 'noChange');
1234 }
1235 my @newList = FAQ::OMatic::getAllItemNames($newDir);
1236  
1237 if (scalar(@oldList) ne scalar(@newList)) {
1238 displayMessage("I'm vaguely concerned that $oldDir contained "
1239 .scalar(@oldList)." items, but (after copying) $newDir has "
1240 .scalar(@newList)." items. I don't plan on doing anything "
1241 ."about this, though. How about you check? :v)");
1242 } else {
1243 displayMessage(
1244 gettexta("Copied %0 items from <tt>%1</tt> to <tt>%2</tt>.",
1245 scalar(@newList), $oldDir, $newDir));
1246 }
1247 doStep('mainMenu');
1248 }
1249  
1250 sub maintenanceStep {
1251 require FAQ::OMatic::Entropy;
1252 my $rt = '';
1253 my $secret = FAQ::OMatic::Entropy::gatherRandomString();
1254  
1255 # The parameters we'll be passing to the maintenance module
1256 # via the CGI dispatch mechanism:
1257 my $host = cgi()->virtual_host();
1258 my $port = cgi()->server_port();
1259 my $path = cgi()->script_name();
1260 my $req = $path."?cmd=maintenance&secret=$secret";
1261  
1262 # Figure out a suitable -I include path in case we're picking up FAQ-O-Matic
1263 # modules relative to . (current working dir)
1264 my $idir;
1265 my $incBase='';
1266 my $incOption='';
1267 foreach $idir (@INC) {
1268 if (-d "$idir/FAQ/OMatic") {
1269 $incBase = $idir;
1270 last;
1271 }
1272 }
1273  
1274 if (not $incBase) {
1275 displayMessage("I can't figure out where the Faq-O-Matic modules live, "
1276 ."so the cron job may not work.");
1277 }
1278  
1279 # No way to know if path is a Perl default or if it was supplied
1280 # with the #! (shebang) line of the CGI, so we always include it just
1281 # to be sure the cron job will work.
1282 if (not $incBase =~ m#^/#) { # convert relative INC to absolute
1283 my $cwd = getcwd();
1284 $cwd =~ s#/$##;
1285 $incOption = "use lib \"$cwd/$incBase\"";
1286 } else {
1287 $incOption = "use lib \"$incBase\"";
1288 }
1289  
1290 # THANKS: John Goerzen pointed out that I wasn't putting a full path
1291 # THANKS: to perl in the cron job, which on some systems picks up the
1292 # THANKS: wrong Perl. (Perl 4, for example.)
1293 my $perlbin = $Config{'perlpath'};
1294 my $cronCmd = "$perlbin -e '$incOption; use FAQ::OMatic::maintenance; "
1295 ."FAQ::OMatic::maintenance::cronInvoke(\"$host\", "
1296 ."$port, \"$req\");'";
1297 my $cronLine = sprintf("%d * * * * %s\n", (rand(1<<16)%60), $cronCmd);
1298  
1299 # display what we're planning to do, so that resourceful admins
1300 # can still install even if our heuristics fail and we have to abort.
1301 displayMessage(gettext("Attempting to install cron job:")
1302 ."\n<pre><font size=\"-1\">$cronLine</font></pre>\n");
1303  
1304 # Set up new maintenance secret immediately, in case the install fails
1305 # but a resourceful admin manually installs the displayed crontab line.
1306 # THANKS: "Riesland, Dan (MN10)" <Dan.Riesland@HBC.Honeywell.com> for
1307 # THANKS: helping to figure this problem out.
1308 my $map = readConfig();
1309 $map->{'$maintenanceSecret'} = "'$secret'";
1310 writeConfig($map);
1311  
1312 # 1999-04-04 hal@dtor.com: we have to be sure to test on triple
1313 # of host, port, path to make sure we have correct entry
1314 # (allow for some hand editing to have happenend, too...)
1315 # THANKS to hal for supplying this in patch form instead of bug report form
1316 my $pattern = "\Qnvoke(\"$host\",\E\\s*$port,\\s*\Q\"$path?\E";
1317 #displayMessage( "pattern is:<pre>$pattern</pre>" );
1318  
1319 my @oldTab = getCurrentCrontab();
1320 my @oldUnrelated = grep {not m/$pattern/} @oldTab;
1321 my @oldReplacing = grep {m/$pattern/} @oldTab;
1322  
1323 if (scalar(@oldReplacing)>1) {
1324 displayMessage("Wait: more than one old crontab entry looks like\n"
1325 ."mine (matches <b>$pattern</b>). "
1326 ."I'm not going to touch them. You'd better add\n"
1327 ."the above line\n"
1328 ."to some crontab yourself with <b><tt>crontab -e</tt></b>.\n",
1329 'default', 'abort');
1330 }
1331  
1332 open(CRONTAB, ">$FAQ::OMatic::Config::metaDir/cronfile") ||
1333 displayMessage("Can't write to $FAQ::OMatic::Config::metaDir/cronfile."
1334 ." No crontab entry added.", 'default', 'abort');
1335 # preserve existing entries
1336 print CRONTAB join('', @oldUnrelated);
1337 # and add our new one.
1338 print CRONTAB $cronLine;
1339 close CRONTAB;
1340
1341 my $crontabbin = $FAQ::OMatic::Config::crontabCommand || '/bin/false';
1342 my $cmd = "$crontabbin $FAQ::OMatic::Config::metaDir/cronfile";
1343 my @msrc = FAQ::OMatic::mySystem($cmd);
1344 if (scalar(@msrc)) {
1345 $rt.="'$cmd' failed: ".join('', @msrc)."\n";
1346 }
1347  
1348 if (@oldReplacing) {
1349 $rt.=gettext("I replaced this old crontab line, which appears to be an older one for this same FAQ:")."\n<tt><p><font size=\"-1\">\n"
1350 .$oldReplacing[0]
1351 ."</font></tt>\n";
1352 }
1353  
1354 # perform a simple test to verify our cron line got installed
1355 my @newTab = getCurrentCrontab();
1356 if (scalar(grep {m/$pattern/} @newTab) != 1
1357 or scalar(grep {m/$secret/} @newTab) != 1) {
1358 displayMessage(gettext("I thought I installed a new cron job, but it didn't appear to take.")."\n"
1359 ."tab".join("<br>\n",@newTab)
1360 .gettexta("You better add %0 to some crontab yourself with <b><tt>crontab -e</tt></b>",
1361 "\n<pre><font size=\"-1\">$cronLine</font></pre>\n")."\n",
1362 'default', 'abort');
1363 }
1364  
1365 FAQ::OMatic::Versions::setVersion('MaintenanceCronJob');
1366 $rt.="<p>".gettext("Cron job installed. The maintenance script should run hourly.")."\n";
1367 displayMessage($rt);
1368 doStep('default');
1369 }
1370  
1371 sub getCurrentCrontab {
1372 my $crontabbin = $FAQ::OMatic::Config::crontabCommand || '/bin/false';
1373  
1374 my $cmd = "$crontabbin -l";
1375 my @systemrc = FAQ::OMatic::mySystem($cmd, 'alwaysWantReply');
1376 my @oldTab;
1377 if ($systemrc[0]==1) {
1378 if ($systemrc[3]=~m/open.*crontab/i
1379 or $systemrc[3]=~m/no crontab for /i) {
1380 # looks like the "error" you get if you don't have a crontab.
1381 # THANKS: to Hal Wine <hal@dtor.com> for supplying the
1382 # second pattern to match vixie-cron's error message
1383 @oldTab = ();
1384 $systemrc[0] = 0;
1385 }
1386 }
1387 if ($systemrc[0] != 0) {
1388 displayMessage("crontab -l failed: "
1389 .join(',', @systemrc),
1390 'default', 'abort');
1391 } else {
1392 @oldTab = @{$systemrc[4]};
1393 }
1394  
1395 if ((scalar(@oldTab)==1) and (not $oldTab[0] =~ m/^\s*[0-9*#]/)) {
1396 # crontab returned one line, and it doesn't look like a
1397 # cron comment or command line. It's probably the error
1398 # message you get if you don't already have a crontab.
1399 # (Unfortunately, the text of the message varies across versions.)
1400 @oldTab = ();
1401 }
1402  
1403 return @oldTab;
1404 }
1405  
1406 sub makeSecureStep {
1407 my $map = readConfig();
1408 $map->{'$secureInstall'} = "'true'";
1409 writeConfig($map);
1410  
1411 # send admin straight through to changePass, since he can't
1412 # have a password yet
1413 my $url = FAQ::OMatic::makeAref('changePass',
1414 {'_restart'=>'install', '_admin'=>1}, 'url');
1415 FAQ::OMatic::redirect(cgi(), $url);
1416 }
1417  
1418 sub colorSamplerStep {
1419 my $rt = '';
1420 my $button = "*";
1421  
1422 $rt.=gettexta("Use the <u>%0</u> links to change the color of a feature.", $button);
1423  
1424 # an outer table provides the background (page) color
1425 $rt.="\n<table bgcolor=$FAQ::OMatic::Config::backgroundColor width=\"100%\">\n";
1426 $rt.="<tr><td>\n";
1427  
1428 $rt.="<table width=\"100%\">\n";
1429 $rt.="<tr><td rowspan=5 bgcolor=".$FAQ::OMatic::Config::itemBarColor
1430 ." width=20 valign=bottom>\n";
1431 $rt.="<a href=\""
1432 .installUrl('askColor', 'url')."&whichColor=\$itemBarColor\">"
1433 ."$button</a>\n";
1434 $rt.="</td>\n";
1435 $rt.="<td bgcolor=$FAQ::OMatic::Config::backgroundColor>\n";
1436 $rt.="<b><font color=$FAQ::OMatic::Config::textColor>".gettext("An Item Title")."</font></b>\n";
1437 $rt.="</td></tr>\n";
1438  
1439 $rt.="<tr><td bgcolor=$FAQ::OMatic::Config::regularPartColor>\n";
1440 $rt.="<a href=\""
1441 .installUrl('askColor', 'url')."&whichColor=\$regularPartColor\">"
1442 ."$button</a><p>\n";
1443 $rt.="<font color=$FAQ::OMatic::Config::textColor>"
1444 .gettext("A regular part is how most of your content will appear. The text colors should be most pleasantly readable on this background.")
1445 ."</font>\n";
1446 $rt.="<br><font color=$FAQ::OMatic::Config::linkColor>".gettext("A new link")."</font>\n";
1447 $rt.="<br><font color=$FAQ::OMatic::Config::vlinkColor>".gettext("A visited link")."</font>\n";
1448 $rt.="<br><font color=$FAQ::OMatic::Config::highlightColor><b>"
1449 .gettext("A search hit")."</b></font>\n";
1450 $rt.="</td></tr>\n";
1451  
1452 $rt.="<tr><td bgcolor=$FAQ::OMatic::Config::directoryPartColor>\n";
1453 $rt.="<a href=\""
1454 .installUrl('askColor', 'url')."&whichColor=\$directoryPartColor\">"
1455 ."$button</a><p>\n";
1456 $rt.="<font color=$FAQ::OMatic::Config::textColor>"
1457 .gettext("A directory part should stand out")."</font>\n";
1458 $rt.="<br><font color=$FAQ::OMatic::Config::linkColor>".gettext("A new link")."</font>\n";
1459 $rt.="<br><font color=$FAQ::OMatic::Config::vlinkColor>".gettext("A visited link")."</font>\n";
1460 $rt.="<br><font color=$FAQ::OMatic::Config::highlightColor><b>"
1461 .gettext("A search hit")."</b></font>\n";
1462 $rt.="</td></tr>\n";
1463  
1464 $rt.="<tr><td bgcolor=$FAQ::OMatic::Config::regularPartColor>\n";
1465 $rt.="&nbsp;<p>\n";
1466 $rt.="</td></tr>\n";
1467  
1468 $rt.="<tr><td bgcolor=$FAQ::OMatic::Config::regularPartColor>\n";
1469 $rt.="&nbsp;<p>\n";
1470 $rt.="</td></tr>\n";
1471  
1472 $rt.="<tr><td colspan=2 bgcolor=$FAQ::OMatic::Config::backgroundColor>\n";
1473 $rt.="<a href=\""
1474 .installUrl('askColor', 'url')."&whichColor=\$backgroundColor\">"
1475 ."$button</a>\n";
1476 #$rt.="<font color=$FAQ::OMatic::Config::textColor>Page background color</font>";
1477 $rt.="<p>\n";
1478 $rt.="<a href=\""
1479 .installUrl('askColor', 'url')."&whichColor=\$textColor\">"
1480 ."$button</a>\n";
1481 $rt.="<font color=$FAQ::OMatic::Config::textColor>".gettext("Regular text")."</font><br>\n";
1482 $rt.="<a href=\""
1483 .installUrl('askColor', 'url')."&whichColor=\$linkColor\">"
1484 ."$button</a>\n";
1485 $rt.="<font color=$FAQ::OMatic::Config::linkColor>".gettext("A new link")."</font><br>\n";
1486 $rt.="<a href=\""
1487 .installUrl('askColor', 'url')."&whichColor=\$vlinkColor\">"
1488 ."$button</a>\n";
1489 $rt.="<font color=$FAQ::OMatic::Config::vlinkColor>".gettext("A visited link")."</font><br>\n";
1490 $rt.="<a href=\""
1491 .installUrl('askColor', 'url')."&whichColor=\$highlightColor\">"
1492 ."$button</a>\n";
1493 $rt.="<font color=$FAQ::OMatic::Config::highlightColor><b>"
1494 .gettext("A search hit")."</b></font>\n";
1495 $rt.="</td></tr>\n";
1496  
1497 $rt.="</table>\n";
1498  
1499 $rt.="</td></tr></table>\n";
1500 displayMessage($rt, 'mainMenu');
1501 }
1502  
1503 sub askColorStep {
1504 my $rt = '';
1505 my $which = $params->{'whichColor'};
1506 $rt.=gettexta("Select a color for %0:", $which)
1507 ."<p>\n";
1508 $rt.="<a href=\""
1509 .installUrl('setColor', 'url')
1510 ."&whichColor=$which&color=\"><img src=\""
1511 .installUrl('', 'url', 'img', 'picker')
1512 ."\" border=1 ismap width=256 height=128></a>\n";
1513  
1514 my $map = readConfig();
1515 my $oldval = stripQuotes($map->{$which});
1516 $rt.="<p>".installUrl('setColor', 'GET');
1517 $rt.=gettext("Or enter an HTML color specification manually:")."<br>\n";
1518 $rt.="<input type=hidden name=\"whichColor\" value=\"$which\">\n"
1519 ."<input type=text name=\"color\" value=\"$oldval\">\n"
1520 ."<input type=submit name=\"_junk\" value=\"".gettext("Select")."\">\n"
1521 ."</form>\n";
1522  
1523 displayMessage($rt);
1524 }
1525  
1526 sub setColorStep {
1527 my $which = $params->{'whichColor'};
1528 if (not $which =~ m/Color$/) {
1529 displayMessage(gettext("Unrecognized config parameter")." ($which).", 'default');
1530 return;
1531 }
1532 my $color = $params->{'color'}||'';
1533 my $colorSpec;
1534 if ($color =~ m/,/) {
1535 my ($c,$r) = ($color =~ m/\?(\d+),(\d+)/);
1536 if (not defined $c or not defined $r) {
1537 displayMessage("color parameter ($color) not received", 'default');
1538 return;
1539 }
1540 my ($red,$green,$blue) = FAQ::OMatic::ColorPicker::findRGB($c/255, $r/127);
1541 $colorSpec = sprintf("'#%02x%02x%02x'",
1542 $red*255, $green*255, $blue*255);
1543 } else {
1544 $colorSpec = "'$color'";
1545 }
1546  
1547 # update config file
1548 my $map = readConfig();
1549 $map->{$which} = $colorSpec;
1550 writeConfig($map);
1551  
1552 FAQ::OMatic::Versions::setVersion('CustomColors');
1553  
1554 rereadConfig();
1555  
1556 doStep('colorSampler');
1557 }
1558  
1559 sub configVersionStep {
1560 my $map = readConfig();
1561 $map->{'$version'} = "'$FAQ::OMatic::VERSION'";
1562 writeConfig($map);
1563
1564 doStep('mainMenu');
1565 }
1566  
1567 sub displayMessage {
1568 my $msg = shift;
1569 my $whereNext = shift;
1570 my $abort = shift;
1571  
1572 my $rt = '';
1573 $rt .= "\n$msg<p>\n";
1574  
1575 if ($whereNext) {
1576 my $url = installUrl($whereNext);
1577 $rt .= "[<a href=\"$url\">".gettexta("Proceed to step '%0'", $whereNext)."</a>]\n";
1578 }
1579 print $rt;
1580  
1581 if ($abort) {
1582 FAQ::OMatic::myExit(0);
1583 }
1584 }
1585  
1586 sub cgi {
1587 # file-scoped $cgi was a bad idea -- if this file gets called
1588 # from another, install::cgi may never get initialized.
1589 # So here we provide a shortcut to $cgi that is reliable.
1590 return $FAQ::OMatic::dispatch::cgi;
1591 }
1592  
1593 sub installUrl {
1594 # can't necessarily use makeAref yet, because we're not configured.
1595 my $step = shift;
1596 my $reftype = shift || 'url'; # 'url', 'GET' and 'POST' supported
1597 my $cmd = shift || 'install'; # for images, need to specify cmd
1598 my $name = shift || ''; # for images, need to specify name
1599 my $temppass = shift;
1600  
1601 if (not defined $temppass) {
1602 $temppass = cgi()->param('temppass') || '';
1603 }
1604  
1605 my $imarg = ($name) ? ("&name=$name") : '';
1606  
1607 if ($FAQ::OMatic::Config::secureInstall) {
1608 # What a hack. When coming from an invocation of install.pm,
1609 # this saves the cookie; when called in from outside (such
1610 # as from maintenance::mirrorClient), we can't figure
1611 # out where to get ahold of $params, so we just discard
1612 # the auth cookie. Not like they were going to use it anyway.
1613 my $authCookie = defined($params) ? $params->{'auth'} : '';
1614 return FAQ::OMatic::makeAref($cmd,
1615 {'step'=>$step,
1616 'name'=>$name,
1617 'auth'=>$authCookie # preserve only the cookie
1618 },
1619 $reftype, 0, 'blastAll');
1620 }
1621  
1622 my $url = FAQ::OMatic::serverBase().FAQ::OMatic::cgiURL();
1623 if ($reftype eq 'GET' || $reftype eq 'POST') {
1624 my $rt = '';
1625 $rt .= "<form action=\"$url\" method=\"${reftype}\">\n"
1626 ."<input type=hidden name=cmd value=install>\n"
1627 ."<input type=hidden name=step value=$step>\n";
1628 if ($temppass ne '') {
1629 $rt .= "<input type=hidden name=temppass value=\"$temppass\">\n";
1630 }
1631 return $rt;
1632 } else {
1633 my $tpa = ($temppass ne '') ? "&temppass=$temppass" : '';
1634 return "$url?cmd=${cmd}${tpa}&step=${step}${imarg}";
1635 }
1636 }
1637  
1638 sub readConfig {
1639 my $ignoreErrors = shift || '';
1640  
1641 if (not open(CONFIG, "<".FAQ::OMatic::dispatch::meta()."/config")) {
1642 if ($ignoreErrors) {
1643 return {};
1644 }
1645 displayMessage("Can't read config file \""
1646 .FAQ::OMatic::dispatch::meta()
1647 ."/config\" because: $!", 'default');
1648 return;
1649 }
1650  
1651 my $map = {};
1652 while (defined($_=<CONFIG>)) {
1653 chomp;
1654 next if (not m/=/);
1655 my ($left,$right) = m/(\S+)\s*=\s*(\S+.*);$/;
1656 if (defined $left and defined $right) {
1657 $map->{$left} = $right;
1658 }
1659 }
1660 close CONFIG;
1661  
1662 return $map;
1663 }
1664  
1665 sub writeConfig {
1666 my $map = shift;
1667  
1668 if (not open(CONFIG, ">".FAQ::OMatic::dispatch::meta()."/config")) {
1669 displayMessage("Can't write config file \""
1670 .FAQ::OMatic::dispatch::meta()
1671 ."/config\" because: $!", 'default', 'abort');
1672 }
1673  
1674 print CONFIG "package FAQ::OMatic::Config;\n";
1675 my ($left, $right);
1676 foreach $left (sort keys %{$map}) {
1677 $right = $map->{$left};
1678 print CONFIG $left." = ".$right.";\n";
1679 }
1680 print CONFIG "1;\n"; # modules have to return true
1681 close CONFIG;
1682  
1683 return;
1684 }
1685  
1686 sub stripQuotes {
1687 my $arg = shift;
1688 $arg =~ s/^'//;
1689 $arg =~ s/'$//;
1690 return $arg;
1691 }
1692  
1693 # some mkdir()s don't like to create a dir if the argument path has a
1694 # trailing slash. (John Goerzen says this is true of BSDI.) So although
1695 # canonically store directories with trailing slashes (to prevent
1696 # concatenating together a path and forgetting an intervening slash),
1697 # we need to strip the slash before calling mkdir().
1698 # THANKS: John Goerzen
1699 sub stripSlash {
1700 my $arg = shift;
1701  
1702 $arg =~ s#/+$##;
1703 return $arg;
1704 }
1705  
1706 sub tempPassPage {
1707 my $rt;
1708 $rt = gettext("You must enter the correct temporary password to install this FAQ-O-Matic. If you don't know it, remake the CGI stub to have a new one assigned.");
1709 $rt .= installUrl('', 'GET', 'install', '', '');
1710 # last '' prevents an old, incorrect temppass from sticking around
1711 $rt .= gettext("Temporary password: ")."<input type=password size=36 name=temppass>\n";
1712 # Null submit button is a workaround for a bug in Lynx that
1713 # prevents you from submitting a page with only a password field.
1714 # THANKS Boyd Lynn Gerber <gerberb@zenez.com> for complaining about this
1715 $rt .= "<input type=submit name=Submit value=Submit>\n";
1716 $rt .= "</form>\n";
1717  
1718 print FAQ::OMatic::header(cgi(), '-type'=>"text/html");
1719 print $rt;
1720 FAQ::OMatic::myExit(0);
1721 }
1722  
1723 1;
1724  
1725  
1726  
1727  
1728  
1729