script/NewsClipper.pl untested

filter: Statementstmt 0.0% 0 / 548 Branchbran 0.0% 0 / 240 Conditioncond 0.0% 0 / 142 MC/DCmcdc 0.0% 0 / 86 Subroutinesub 0.0% 0 / 56 Podpod 0.0% 0 / 35 totaltotal 0.0% 0 / 1107 CC 113 SCAR 43.2
CC
113
Cov
0%
ProcessFiles
210.0
ValidateSetup
210.0
SetupConfig
110.0
CRAP 75.2
1 #!/usr/local/bin/perl -w
2  
3 # For bare-bones documentation, do "perldoc NewsClipper.pl". A user's manual
4 # is included with the purchase of one of the commercial versions.
5 # To subscribe to the News Clipper mailing list, visit
6 # http://www.NewsClipper.com/techsup.htm#MailingList
7 # Send bug reports or enhancements to bugs@newsclipper.com. Send in a
8 # significant enhancement and you'll get a free license for News Clipper.
9  
10 # Visit the News Clipper homepage at http://www.newsclipper.com/ for more
11 # information.
12  
13 #------------------------------------------------------------------------------
14  
15 # Written by: David Coppit http://coppit.org/ <david@coppit.org>
16  
17 # This code is distributed under the GNU General Public License (GPL). See
18 # http://www.opensource.org/gpl-license.html and http://www.opensource.org/.
19  
20 # ------------------------------------------------------------------------------
21  
22 require 5.005;
23 use strict;
24  
25 use Getopt::Long;
26 use FileHandle;
27 use File::Cache;
28  
29 use vars qw( %config %opts $VERSION $COMPATIBLE_CONFIG_VERSION $lock_manager );
30  
31 # These need to be predeclared so that this code can be parsed and run until
32 # we load the NewsClipper::Globals module. WARNING! Be careful to not use
33 # these until NewsClipper::Globals has been imported!
34 sub DEBUG();
35 sub dprint(@);
36 sub lprint(@);
37 sub reformat(@);
38 sub dequote($;$);
39  
40 # To suppress warnings
41 use vars qw(&dprint &reformat &dequote);
42  
43 # The version of the script
44 $VERSION = do {my @r=(q$ 1.3.2 $=~/\d+/g);sprintf"%d."."%1d"x$#r,@r};
45  
46 # The version of configuration file that this version of News Clipper can use.
47 $COMPATIBLE_CONFIG_VERSION = 1.30;
48  
49 # ------------------------------ MAIN PROGRAM ---------------------------------
50  
51 sub SetupConfig();
52 sub print_usage();
53 sub HandleProxyPassword();
54 sub HandleClearCache();
55 sub ProcessFlagCommand();
56 sub ProcessFiles();
57 sub PrintDebugSummary(\@);
58  
59 {
60 # Store a copy of @INC for later debugging messages
61 my @startingINC = @INC;
62  
63 SetupConfig();
64  
65 PrintDebugSummary(@startingINC);
66  
67 $config{start_time} = scalar localtime time;
68  
69 lprint "--------------------------------------------------------------------";
70 lprint "News Clipper $VERSION started: $config{start_time}";
71 }
72  
73 # Print the usage if the -h flag was used
74 print_usage() && exit if $opts{h};
75  
76 # Set up the lockfile. SetupConfig() above created .NewsClipper, so we can
77 # lock on that. This feature can not be used in Windows because it doesn't
78 # have fork()
79 unless (($^O eq 'MSWin32') || ($^O eq 'dos'))
80 {
81 require LockFile::Simple;
82 $lock_manager = LockFile::Simple->make('-autoclean' => 1, '-nfs' => 1,
83 '-stale' => 1, '-warn' => 0, '-wfunc' => undef, '-efunc' => undef,
84 '-hold' => $config{script_timeout} + 10,
85 '-max' => 2 * ($config{script_timeout} + 10),
86 '-format' => "$NewsClipper::Globals::home/.NewsClipper/lock");
87 $lock_manager->lock("$NewsClipper::Globals::home/.NewsClipper")
88 or die reformat dequote<<" EOF";
89 There is already another copy of News Clipper running. This copy of News
90 Clipper waited 60 seconds for the other copy to finish. Aborting. (You
91 should delete $NewsClipper::Globals::home/.NewsClipper/lock if you are
92 sure that no other News Clipper is running.)
93 EOF
94 }
95  
96 HandleProxyPassword();
97 HandleClearCache();
98  
99 my $exit_value = 0;
100  
101 # Do timers unless we are in debug mode or on the broken Windows platform
102 if (DEBUG || ($^O eq 'MSWin32') || ($^O eq 'dos'))
103 {
104 if ($opts{e})
105 {
106 ProcessFlagCommand();
107 }
108 else
109 {
110 ProcessFiles();
111 }
112 }
113 else
114 {
115 $SIG{ALRM} = sub { die "newsclipper timeout" };
116  
117 eval
118 {
119 alarm($config{script_timeout});
120 if ($opts{e})
121 {
122 ProcessFlagCommand();
123 }
124 else
125 {
126 ProcessFiles();
127 }
128 alarm(0);
129 };
130  
131 if ($@)
132 {
133 # See if it was our timeout
134 if ($@ =~ /newsclipper timeout/)
135 {
136 die "News Clipper script timeout has expired. News Clipper killed.\n";
137 }
138 else
139 {
140 # The eval got aborted, so we need to stop the alarm
141 alarm (0);
142 # and print the error. (I'm not simply die'ing here because I don't like
143 # the annoying ...propagated message. I don't know if this is the right
144 # way to do this, but it works.)
145 warn $@;
146 lprint $@;
147 $exit_value = 1;
148 }
149 }
150 }
151  
152 $lock_manager->unlock("$NewsClipper::Globals::home/.NewsClipper")
153 if defined $lock_manager;
154  
155 exit($exit_value);
156  
157 #------------------------------------------------------------------------------
158  
159 # This is the real meat of the main program. For each file, we parse it,
160 # executing and News Clipper commands. We also do some work to redirect STDOUT
161 # to the output file.
162  
163 sub ProcessFiles()
164 {
165 # Make unbuffered for easier debugging.
166 $| = 1 if DEBUG;
167  
168 for (my $i=0;$i <= $#{$config{input_files}};$i++)
169 {
170 dprint "Now processing $config{input_files}[$i] => $config{output_files}[$i]";
171 lprint "Processing $config{input_files}[$i] => $config{output_files}[$i]";
172  
173 # Print a warning and skip if the file doesn't exist and isn't a text file.
174 # However, don't do the checks if the file is STDIN.
175 unless ($config{input_files}[$i] eq 'STDIN')
176 {
177 warn reformat "Input file $config{input_files}[$i] can't be found.\n"
178 and next unless -e $config{input_files}[$i];
179 warn reformat "Input file $config{input_files}[$i] is a directory.\n"
180 and next if -d $config{input_files}[$i];
181 warn reformat "Input file $config{input_files}[$i] is empty.\n"
182 and next if -z $config{input_files}[$i];
183 }
184  
185 # We'll write to the file unless we're in DEBUG mode.
186 my $writeToFile = 1;
187 $writeToFile = 0
188 if DEBUG || $config{output_files}[$i] eq 'STDOUT';
189  
190 $config{input_files}[$i] = *STDIN if $config{input_files}[$i] eq 'STDIN';
191  
192 my $oldSTDOUT = new FileHandle;
193  
194 # Redirect STDOUT to a temp file.
195 if ($writeToFile)
196 {
197 # Store the old STDOUT so we can replace it later.
198 $oldSTDOUT->open(">&STDOUT") or die "Couldn't save STDOUT: $!\n";
199  
200 # If the user wants to see a copy of the output... (Doesn't work in
201 # Windows or DOS)
202 if ($opts{v} && ($^O ne 'MSWin32') && ($^O ne 'dos'))
203 {
204 # Make unbuffered
205 $| = 2;
206 open (STDOUT,"| tee $config{output_files}[$i].temp")
207 or die reformat dequote<<" EOF";
208 Couldn't create temporary output file
209 $config{output_files}[$i].temp using "tee": $!
210 EOF
211 }
212 else
213 {
214 open (STDOUT,">$config{output_files}[$i].temp")
215 or die reformat dequote<<" EOF";
216 Couldn't create temporary output file
217 $config{output_files}[$i].temp: $!
218 EOF
219 }
220 }
221  
222 require NewsClipper::Parser;
223  
224 # Okay, now do the magic. Parse the input file, calling the handlers
225 # whenever a special tag is seen.
226  
227 my $p = new NewsClipper::Parser;
228 $p->parse_file($config{input_files}[$i]);
229  
230 # Restore STDOUT to the way it was
231 if ($writeToFile)
232 {
233 close (STDOUT);
234 open(STDOUT, ">&" . $oldSTDOUT->fileno())
235 or die "Can't restore STDOUT: $!.\n";
236  
237 # Replace the output file with the temp file. Move it to .del for OSes
238 # that have delayed deletes.
239 unlink ("$config{output_files}[$i].del");
240 rename ($config{output_files}[$i], "$config{output_files}[$i].del");
241 rename ("$config{output_files}[$i].temp",$config{output_files}[$i])
242 or die "Could not rename $config{output_files}[$i].temp " .
243 "to $config{output_files}[$i]: $!";
244 unlink ("$config{output_files}[$i].del");
245  
246 if ($config{make_output_files_executable} =~ /^y/i)
247 {
248 chmod 0755, $config{output_files}[$i];
249 }
250 else
251 {
252 chmod 0644, $config{output_files}[$i];
253 }
254  
255 FTP_File($config{output_files}[$i],$config{ftp_files}[$i])
256 if defined $config{ftp_files}[$i] &&
257 exists $config{ftp_files}[$i]{server};
258  
259 Email_File($config{output_files}[$i],$config{email_files}[$i])
260 if defined $config{email_files}[$i];
261 }
262 }
263 }
264  
265 #------------------------------------------------------------------------------
266  
267 # This is a special handler which does parse any files. Instead it creates a
268 # simple News Clipper command for the handler specified with -e and executes
269 # that.
270  
271 sub ProcessFlagCommand()
272 {
273 # Make unbuffered for easier debugging.
274 $| = 1 if DEBUG;
275  
276 dprint "Now processing handler \"$opts{e}\" => STDOUT";
277 lprint "Processing handler \"$opts{e}\" => STDOUT";
278  
279 my $oldSTDOUT = new FileHandle;
280  
281 require NewsClipper::Parser;
282  
283 my $inputCommand;
284 # Construct the input command
285 if ($opts{e} =~ /<.*>/s)
286 {
287 $inputCommand = dequote<<" EOF";
288 <!-- newsclipper
289 $opts{e}
290 -->
291 EOF
292 }
293 else
294 {
295 $inputCommand .= "<!-- newsclipper\n";
296  
297 # Each News Clipper command is separated by a comma
298 my @handlers = split /,/,$opts{e};
299 for (my $i=0 ; $i <= $#handlers ; $i++)
300 {
301 if ($i == 0)
302 {
303 $inputCommand .= " <input name=$handlers[$i]>\n";
304 }
305 elsif ($i != $#handlers)
306 {
307 $inputCommand .= " <filter name=$handlers[$i]>\n";
308 }
309 else
310 {
311 $inputCommand .= " <output name=$handlers[$i]>\n";
312 }
313 }
314  
315 $inputCommand .= "-->\n";
316 }
317  
318 my $p = new NewsClipper::Parser;
319 $p->parse($inputCommand);
320 }
321  
322 # ------------------------------------------------------------------------------
323  
324 # Send the file to the server. Prints and error to STDERR and returns 0 if
325 # something goes wrong. Returns 1 otherwise.
326  
327 sub FTP_File()
328 {
329 my $filename = shift;
330 my %ftp_info = %{shift @_};
331  
332 dprint "FTP'ing file $filename to server $ftp_info{server}";
333 lprint "FTP'ing file $filename to server $ftp_info{server}";
334  
335 use Net::FTP;
336  
337 my $numTriesLeft = $config{socket_tries};
338  
339 my $ftp;
340  
341 do
342 {
343 $ftp = Net::FTP->new($ftp_info{server},Timeout => $config{socket_timeout});
344 } until ($numTriesLeft == 0 || $ftp);
345  
346 unless ($ftp)
347 {
348 warn "FTP connection failed: $@";
349 return 0;
350 }
351  
352 unless ($ftp->login($ftp_info{username},$ftp_info{password}))
353 {
354 warn "FTP login failed for user $ftp_info{username} on host " .
355 "$ftp_info{server}: $@";
356 $ftp->quit;
357 return 0;
358 }
359  
360 unless ($ftp->cwd($ftp_info{dir}))
361 {
362 warn "Couldn't change to directory $ftp_info{dir} during FTP: $@";
363 $ftp->quit;
364 return 0;
365 }
366  
367 unless ($ftp->put($filename))
368 {
369 warn "Couldn't FTP file $filename: $@";
370 $ftp->quit;
371 return 0;
372 }
373  
374 $ftp->quit;
375 }
376  
377 # ------------------------------------------------------------------------------
378  
379 # Send the file to an email address. Prints and error to STDERR and returns 0
380 # if something goes wrong. Returns 1 otherwise.
381  
382 sub Email_File()
383 {
384 my $filename = shift;
385 my %email_info = %{ shift @_ };
386  
387 dprint "Emailing file $filename to $email_info{To}";
388 lprint "Emailing file $filename to $email_info{To}";
389  
390 open HTML,$filename;
391 my $message = join '', <HTML>;
392 close HTML;
393  
394 $email_info{'content-type'} = 'text/html; charset="iso-8859-1"'
395 unless defined $email_info{'content-type'};
396  
397 $email_info{'body'} = $message;
398  
399 require Mail::Sendmail;
400  
401 unless (Mail::Sendmail::sendmail(%email_info))
402 {
403 warn "Could not send email: $Mail::Sendmail::error";
404  
405 # To shut up the warning
406 { my $dummy = $Mail::Sendmail::error; }
407  
408 return 0;
409 }
410  
411 return 1;
412 }
413  
414 # ------------------------------------------------------------------------------
415  
416 sub get_exe_name
417 {
418 my $exe_name = $0;
419 # Fix the $exe_name if it's the compiled version.
420 ($exe_name) = $ENV{sourceExe} =~ /([^\/\\]*)$/ if defined $ENV{sourceExe};
421  
422 return $exe_name;
423 }
424  
425 # ------------------------------------------------------------------------------
426  
427 # Prints the usage information
428  
429 sub print_usage()
430 {
431 my $exeName = get_exe_name();
432  
433 my $version = "$VERSION, $config{product}";
434  
435 if ($config{product} eq "Personal")
436 {
437 $version .= " ($config{number_pages} page";
438 $version .= "s" if $config{number_pages} > 1;
439 $version .= ", $config{number_handlers} handlers)";
440 }
441  
442 print dequote<<" EOF";
443 This is News Clipper version $version
444  
445 usage: $exeName [-adnrvPC] [-i inputfile] [-o outputfile]
446 [-c configfile] [-H homepath]
447 [-e command,command,...] [command,command,...]
448  
449 -i The template file to use as input (overrides value in configuration file)
450 -o The output file (overrides value in configuration file)
451 -e Run the specified handler and output the results. (Overrides -i and -o.)
452 -c The configuration file to use
453 -a Automatically download handlers as needed
454 -n Check for new versions of the handlers
455 -r Forces caching proxies to reload data
456 -d Enable debug mode
457 -P Pause after completion
458 -v Output to STDOUT in addition to the file. (Unix only.)
459 -C Clear the cache, handler state, or News Clipper state
460 -H Set the user's home directory
461 EOF
462 }
463  
464 # ------------------------------------------------------------------------------
465  
466 use File::Spec::Functions qw(splitdir catdir);
467  
468 # Find the parent directory of a directory. Returns undef if there is no
469 # parent
470  
471 sub _Get_Parent_Directory
472 {
473 my ($directory) = @_;
474  
475 defined($directory) or
476 die("directory required");
477  
478 my @directories = splitdir($directory);
479 pop @directories;
480  
481 return undef unless @directories;
482  
483 return catdir(@directories);
484 }
485  
486 # ------------------------------------------------------------------------------
487  
488 # Calls LoadSysConfig and LoadUserConfig to load the system-wide and user
489 # configuration information. It then tweaks a few of the configuration
490 # parameters and loads the News Clipper global functions and constants. Then
491 # it prints a summary if we're running in DEBUG mode. Finally, it validates
492 # the parameters to make sure they are valid.
493  
494 sub SetupConfig()
495 {
496 SetupSSI();
497  
498 ProcessFlags();
499  
500 # We load the configuration, being careful not to use any of the stuff in
501 # NewsClipper::Globals. (Like dprint, for example.)
502 LoadConfigFiles();
503  
504 ValidateConfigFiles();
505  
506 # Translate the cache size into bytes from megabytes
507 $config{max_cache_size} *= 1048576 if defined $config{max_cache_size};
508  
509 # Put the handler locations on the include search path
510 foreach my $dir (@{$config{handler_locations}})
511 {
512 unshift @INC,@{$config{handler_locations}} if -d $dir;
513 }
514  
515 # Override the config values if the user specified -i or -o.
516 $config{input_files} = [$opts{i}] if defined $opts{i};
517 $config{output_files} = [$opts{o}] if defined $opts{o};
518  
519 # This should be in ValidateSetup, but we need to check it before slurping
520 # in the NewsClipper::Globals. (We don't need module_path in the compiled
521 # version.)
522 foreach my $directory (split /\s+/,$config{module_path})
523 {
524 die "\"$directory\" in module_path setting of NewsClipper.cfg must be a directory.\n"
525 unless -d $directory;
526 }
527  
528 # Put the News Clipper module file location on @INC
529 unshift @INC,split(/\s+/,$config{module_path})
530 if defined $config{module_path} && $config{module_path} ne '';
531  
532 # Now we slurp in the global functions and constants.
533 require NewsClipper::Globals;
534 NewsClipper::Globals->import;
535  
536 $NewsClipper::Globals::home = GetHomeDirectory();
537  
538 # Make the .NewsClipper directory if it doesn't exist already.
539 mkdir "$NewsClipper::Globals::home/.NewsClipper", 0700
540 unless -e "$NewsClipper::Globals::home/.NewsClipper";
541  
542 # Make the logfile directories if they don't exist already.
543 {
544 use File::Path;
545 my $debug_log_directory = _Get_Parent_Directory($config{'debug_log_file'});
546 my $run_log_directory = _Get_Parent_Directory($config{'run_log_file'});
547 mkpath $debug_log_directory unless -e $debug_log_directory;
548 mkpath $run_log_directory unless -e $run_log_directory;
549 }
550  
551 # Initialize the HTML cache, News Clipper state, and handler factory
552 require NewsClipper::Cache;
553 $NewsClipper::Globals::cache = new NewsClipper::Cache;
554 # To shut up the warning
555 { my $dummy = $NewsClipper::Globals::cache; }
556  
557 # Be sure to do a require here to load our own version of File::Cache.
558 # (Remove later when File::Cache supports persistence mechanism choice.)
559 $NewsClipper::Globals::state = new File::Cache (
560 { cache_key => "$NewsClipper::Globals::home/.NewsClipper/state",
561 namespace => 'NewsClipper',
562 username => '',
563 filemode => 0666,
564 auto_remove_stale => 0,
565 persistence_mechanism => 'Data::Dumper',
566 } );
567 # To shut up the warning
568 { my $dummy = $NewsClipper::Globals::state; }
569  
570 require NewsClipper::HandlerFactory;
571 $NewsClipper::Globals::handlerFactory = new NewsClipper::HandlerFactory;
572 # To shut up the warning
573 { my $dummy = $NewsClipper::Globals::handlerFactory; }
574  
575 ValidateSetup();
576 }
577  
578 # ------------------------------------------------------------------------------
579  
580 # This function sets up few things for the case when News Clipper is run as
581 # a server-side include. (We don't support running News Clipper as a CGI
582 # program.)
583  
584 sub SetupSSI()
585 {
586 return unless exists $ENV{SCRIPT_NAME};
587  
588 # First, we redirect STDERR to STDOUT so errors go to the browser.
589 open(STDERR,">&STDOUT");
590 }
591  
592 # ------------------------------------------------------------------------------
593  
594 sub ProcessFlags
595 {
596 # Get the command line flags. Localize @ARGV since getopt destroys it. We
597 # do this before loading the configuration in order to get the -c flag.
598 local @ARGV = @ARGV;
599 Getopt::Long::Configure(
600 qw(bundling noignore_case auto_abbrev prefix_pattern=-));
601 GetOptions(\%opts, qw(i:s o:s c:s e:s a h d n r v P C H:s));
602  
603 # Treat left-over arguments as -e arguments.
604 if (@ARGV)
605 {
606 my $joined_args = join ",",@ARGV;
607 @ARGV = ('-e',$joined_args);
608 }
609  
610 my %extra_opts;
611 GetOptions(\%extra_opts, qw(i:s o:s c:s e:s a h d n r v P C H:s));
612  
613 if (defined $opts{e})
614 {
615 $opts{e} .= ",$extra_opts{e}" if defined $extra_opts{e};
616 }
617 else
618 {
619 $opts{e} = $extra_opts{e} if defined $extra_opts{e};
620 }
621 }
622  
623 # ------------------------------------------------------------------------------
624  
625 # This function loads the system-wide config and the user's config. It dies
626 # with an error if a configuration file could not be loaded. If the user's
627 # configuration file can't be found or loaded in Unix, this is okay. But on
628 # Windows, it is an error.
629  
630 sub LoadConfigFiles()
631 {
632 my ($sysStatus,$sysConfigMessage) = LoadSysConfig();
633 my ($userStatus,$userConfigMessage) = LoadUserConfig();
634  
635 # Okay situations
636 return if $sysStatus eq 'okay' && $userStatus eq 'okay';
637 return if $sysStatus eq 'okay' && ($userStatus eq 'open error' && !$opts{c});
638 return if $sysStatus eq 'no env variable' && $userStatus eq 'okay';
639 return if $sysStatus eq 'windows' && $userStatus eq 'okay';
640  
641 warn $sysConfigMessage if $sysStatus ne 'okay';
642 warn "\n" if $sysStatus ne 'okay' && $userStatus ne 'okay';
643 warn $userConfigMessage if $userStatus ne 'okay';
644 die "\n";
645 }
646  
647 # ------------------------------------------------------------------------------
648  
649 # Loads the system-wide configuration file, storing the location of that file
650 # in $config{sys_config_file}. The location is specified by the NEWSCLIPPER
651 # environment variable.
652  
653 sub LoadSysConfig()
654 {
655 my $warnings;
656  
657 $config{sys_config_file} = 'Not specified';
658  
659 unless (exists $ENV{NEWSCLIPPER})
660 {
661 $warnings = <<" EOF";
662 News Clipper could not open your system-wide configuration file
663 because your NEWSCLIPPER environment variable is not set.
664 EOF
665 return ('no env variable',$warnings);
666 }
667  
668 return ('windows','') if $^O eq 'MSWin32' || $^O eq 'dos';
669  
670 my $configFile = "$ENV{NEWSCLIPPER}/NewsClipper.cfg";
671  
672 my ($evalWarnings,$evalResult) = ('',0);
673  
674 # Hide any warnings that occur from parsing the config file.
675 local $SIG{__WARN__} = sub { $evalWarnings .= $_[0] };
676 my $home = GetHomeDirectory();
677  
678 # We do an eval instead of doing a "do $configFile" because we want to
679 # slurp in $home from the enclosing block. "do $configFile" doesn't slurp
680 # $home.
681 my $openResult = open CONFIGFILE, $configFile;
682 if ($openResult)
683 {
684 my $code = join '', <CONFIGFILE>;
685 close CONFIGFILE;
686 $evalResult = eval $code;
687 }
688 else
689 {
690 $warnings = <<" EOF";
691 News Clipper could not open your system-wide configuration file
692 "$configFile". Make sure your NEWSCLIPPER environment
693 variable is set correctly. The error is:
694 $!
695 EOF
696 return ('open error',$warnings);
697 }
698  
699 # Check that the config file wasn't a directory or something.
700 if (!-f $configFile)
701 {
702 $warnings = <<" EOF";
703 News Clipper could not open your system-wide configuration file
704 because "$configFile" is not a plain file.
705 EOF
706  
707 return ('open error',$warnings);
708 }
709  
710 # Check if there were any syntax errors while eval'ing the configuration
711 # file.
712 if ($@)
713 {
714 $warnings = <<" EOF";
715 News Clipper found your system-wide configuration file
716 "$configFile", but it could not be processed
717 because of the following error:
718 $@
719 EOF
720 return ('compile error',$warnings);
721 }
722  
723 if ($warnings)
724 {
725 $warnings = <<" EOF";
726 News Clipper found your system-wide configuration file
727 "$configFile", but encountered some warnings
728 while processing it:
729 $evalWarnings
730 EOF
731 return ('compile error',$warnings);
732 }
733  
734 # No error message means we found it
735 if ($evalResult)
736 {
737 $config{sys_config_file} = $configFile;
738 return ('okay','');
739 }
740 else
741 {
742 # Can't get here, since there would have been errors or warnings above.
743 die "Whoa! You shouldn't be here! Send email describing what you ".
744 "were doing";
745 }
746 }
747  
748 # ------------------------------------------------------------------------------
749  
750 # Loads the user's configuration file, storing the location of that file in
751 # $config{user_config_file}. The location of this file is
752 # $home/.NewsClipper/NewsClipper.cfg.
753  
754 sub LoadUserConfig()
755 {
756 $config{user_config_file} = 'Not found';
757  
758 my $home = GetHomeDirectory();
759 my $configFile = $opts{c} || "$home/.NewsClipper/NewsClipper.cfg";
760  
761 my ($evalWarnings,$evalResult,$warnings) = ('',0,'');
762  
763 # Hide any warnings that occur from parsing the config file.
764 local $SIG{__WARN__} = sub { $evalWarnings .= $_[0] };
765  
766 # We do an eval instead of doing a "do $configFile" because we want to
767 # slurp in $home from the enclosing block. "do $configFile" doesn't slurp
768 # $home.
769 my $openResult = open CONFIGFILE, $configFile;
770 if ($openResult)
771 {
772 my $code = join '', <CONFIGFILE>;
773 close CONFIGFILE;
774  
775 # This is kinda tricky. We don't want the %config in $configFile to
776 # totally redefine %main::config, so we wrap the "eval" in a package
777 # declaration, which will put the config file's %config in the
778 # NewsClipper::config package for later use.
779 my $outerPackage = __PACKAGE__;
780 package NewsClipper::config;
781 use vars qw(%config);
782  
783 $evalResult = eval $code;
784  
785 # Restore outer package, being careful that the eval doesn't overwrite the
786 # $@ result of the previous eval
787 {
788 local $@;
789 eval "package $outerPackage";
790 }
791 }
792 else
793 {
794 if ($^O eq 'MSWin32' || $^O eq 'dos')
795 {
796 $warnings = <<" EOF";
797 News Clipper could not open your personal configuration file
798 "$configFile".
799 Your registry value for "InstallDir" in
800 "HKEY_LOCAL_MACHINE\\SOFTWARE\\Spinnaker Software\\News
801 Clipper\\$VERSION" (or your HOME environment variable) may not be
802 correct.
803 EOF
804 }
805 else
806 {
807 $warnings = <<" EOF";
808 News Clipper could not open your personal configuration file
809 "$configFile". The error is:
810 $!
811 EOF
812 }
813  
814 return ('open error',$warnings);
815 }
816  
817 # Check that the config file wasn't a directory or something.
818 if (!-f $configFile)
819 {
820 if ($^O eq 'MSWin32' || $^O eq 'dos')
821 {
822 $warnings = <<" EOF";
823 News Clipper could not open your personal configuration file
824 because "$configFile" is not a plain file. Your registry
825 value for "InstallDir" in
826 "HKEY_LOCAL_MACHINE\\SOFTWARE\\Spinnaker Software\\News
827 Clipper\\$VERSION" (or your HOME environment variable) may not be
828 correct.
829 EOF
830 }
831 else
832 {
833 $warnings = <<" EOF";
834 News Clipper could not open your personal configuration file
835 because "$configFile" is not a plain file. Make sure the file
836 NewsClipper.cfg is in your <HOME>/.NewsClipper directory.
837 EOF
838 }
839  
840 return ('open error',$warnings);
841 }
842  
843 # Check if there were any syntax errors while eval'ing the configuration
844 # file.
845 if ($@)
846 {
847 $warnings = <<" EOF";
848 News Clipper found your personal configuration file
849 "$configFile", but it could not be processed
850 because of the following error:
851 $@
852 EOF
853 return ('compile error',$warnings);
854 }
855  
856 if ($evalWarnings)
857 {
858 $warnings = <<" EOF";
859 News Clipper found your personal configuration file
860 "$configFile", but encountered some warnings
861 while processing it:
862 $evalWarnings
863 EOF
864 return ('compile error',$warnings);
865 }
866  
867 # No error message means we found it
868 if ($evalResult)
869 {
870 $config{user_config_file} = $configFile;
871  
872 # Now override main's %config
873 while (my ($key,$value) = each %NewsClipper::config::config)
874 {
875 $main::config{$key} = $value;
876 }
877  
878 undef %NewsClipper::config::config;
879 return ('okay','');
880 }
881 else
882 {
883 # Can't get here, since there would have been errors or warnings above.
884 die "Whoa! You shouldn't be here! Send email describing what you ".
885 "were doing";
886 }
887 }
888  
889 # ------------------------------------------------------------------------------
890  
891 # Simply gets the home directory. First it tries to get it from the password
892 # file, then from the Windows registry, and finally from the HOME environment
893 # variable.
894  
895 sub GetHomeDirectory()
896 {
897 # Get the user's home directory. First try the password info, then the
898 # registry (if it's a Windows machine), then any HOME environment variable.
899 my $home = $opts{H} || eval { (getpwuid($>))[7] } ||
900 GetWinInstallDir() || $ENV{HOME};
901  
902 # "s cause problems in Windows. Sometimes people set their home variable as
903 # "c:\Program Files\NewsClipper", which causes when the path is therefore
904 # "c:\Program Files\NewsClipper"\.NewsClipper\Handler\Acquisition
905 $home =~ s/"//g if defined $home;
906  
907 die <<" EOF"
908 News Clipper could not determine your home directory. On non-Windows
909 machines, News Clipper attempts to get your home directory using getpwuid,
910 then the HOME environment variable. On Windows machines, it attempts to
911 read the registry entry "HKEY_LOCAL_MACHINE\\SOFTWARE\\Spinnaker
912 Software\\News Clipper\\$VERSION" then tries the HOME environment
913 variable.
914 EOF
915 unless defined $home;
916  
917 return $home;
918 }
919  
920 # ------------------------------------------------------------------------------
921  
922 sub ValidateConfigFiles
923 {
924 die <<" EOF"
925 Could not find either a system-wide configuration file or a personal
926 configuration file.
927 EOF
928 if $config{sys_config_file} eq 'Not specified' &&
929 $config{user_config_file} eq 'Not found';
930  
931 if (!defined $config{for_news_clipper_version} ||
932 ($config{for_news_clipper_version} < $COMPATIBLE_CONFIG_VERSION))
933 {
934 my $version_string = $config{for_news_clipper_version};
935 $version_string = 'pre-1.21' unless defined $version_string;
936  
937 die <<" EOF";
938 Your NewsClipper.cfg configuration file is incompatible with this
939 version of News Clipper (need $COMPATIBLE_CONFIG_VERSION, have $version_string).
940 Please run "ConvertConfig /path/NewsClipper.cfg" using the ConvertConfig that
941 came with this distribution of News Clipper.
942 EOF
943 }
944 }
945  
946 # ------------------------------------------------------------------------------
947  
948 # Checks the setup (system-wide modified by user's) to make sure everything is
949 # okay.
950  
951 sub ValidateSetup()
952 {
953 die "\"handler_locations\" in NewsClipper.cfg must be non-empty.\n"
954 if $#{$config{handler_locations}} == -1;
955  
956 foreach my $dir (@{$config{handler_locations}})
957 {
958 die "\"$dir\" from handler_locations in NewsClipper.cfg is not ".
959 "a directory.\n" unless -d $dir;
960 }
961  
962 CheckRegistration();
963  
964 # Check that the user isn't trying to use the -i and -o flags for the Trial
965 # and Personal versions
966 if (($config{product} eq "Trial" ||
967 $config{product} eq "Personal") &&
968 (defined $opts{i} || defined $opts{o}))
969 {
970 die reformat dequote<<" EOF";
971 The -i and -o flags are disabled in the Trial and Personal versions of
972 News Clipper. Please specify your input and output files in the
973 NewsClipper.cfg file.
974 EOF
975 }
976  
977 # Check that the input files and output files match
978 if ($#{$config{input_files}} != $#{$config{output_files}})
979 {
980 die reformat dequote <<" EOF";
981 Your input and output files are not correctly specified. Check your
982 configuration file NewsClipper.cfg.
983 EOF
984 }
985  
986 # Check that if the user is using ftp_files, the number matches
987 if ($#{$config{ftp_files}} != -1 &&
988 $#{$config{ftp_files}} != $#{$config{output_files}})
989 {
990 die reformat dequote <<" EOF";
991 Your ftp information is not correctly specified. If you do not want to
992 ftp any files, there should be nothing specified. If you want to ftp any
993 files, you must specify the information for each file, or use "{}" to
994 indicate that a file should not be sent.
995 EOF
996 }
997  
998 # Check that if the user is using email_files, the number matches
999 if ($#{$config{email_files}} != -1 &&
1000 $#{$config{email_files}} != $#{$config{output_files}})
1001 {
1002 die reformat dequote <<" EOF";
1003 Your email information is not correctly specified. If you do not want to
1004 email any files, there should be nothing specified. If you want to email
1005 any files, you must specify the information for each file, or use "{}"
1006 to indicate that a file should not be emailed.
1007 EOF
1008 }
1009  
1010 # Check that the user isn't trying to process more than one input file for
1011 # the Trial version
1012 if ($#{$config{input_files}} > 0 && $config{product} eq "Trial")
1013 {
1014 die reformat dequote <<" EOF";
1015 Sorry, but the Trial version of News Clipper can only process one input
1016 file.
1017 EOF
1018 }
1019  
1020 # Check that the user isn't trying to process more than the registered
1021 # number of files for the Personal version
1022 if ($config{product} eq "Personal" &&
1023 $#{$config{input_files}}+1 > $config{number_pages} )
1024 {
1025 die reformat dequote<<" EOF";
1026 Sorry, but this Personal version of News Clipper is only registered to
1027 process $config{number_pages} input files.
1028 EOF
1029 }
1030  
1031 die "No input files specified.\n" if $#{$config{input_files}} == -1;
1032  
1033 # Check that they specified cache_location and max_cache_size
1034 die "cache_location not specified in NewsClipper.cfg\n"
1035 unless defined $config{cache_location} &&
1036 $config{cache_location} ne '';
1037 die "max_cache_size not specified in NewsClipper.cfg\n"
1038 unless defined $config{max_cache_size} &&
1039 $config{max_cache_size} != 0;
1040  
1041 # Check socket_tries, and set it if necessary
1042 $config{socket_tries} = 1 unless defined $config{socket_tries};
1043 die "socket_tries must be 1 or more\n" unless $config{socket_tries} > 0;
1044 }
1045  
1046 # ------------------------------------------------------------------------------
1047  
1048 # Prints some useful information when running in DEBUG mode.
1049  
1050 sub PrintDebugSummary(\@)
1051 {
1052 my @startingINC = @{shift @_};
1053  
1054 return unless DEBUG;
1055  
1056 my $exe_name = get_exe_name();
1057  
1058 dprint "Operating system:\n $^O";
1059 dprint "Version:\n $VERSION, $config{product}";
1060 dprint "Command line was:\n $exe_name @ARGV";
1061 dprint "Options are:";
1062  
1063 foreach my $key (sort keys %opts)
1064 {
1065 dprint " $key: $opts{$key}";
1066 }
1067  
1068 dprint "\$ENV{NEWSCLIPPER}:\n";
1069 if (defined $ENV{NEWSCLIPPER})
1070 {
1071 dprint " $ENV{NEWSCLIPPER}";
1072 }
1073 else
1074 {
1075 dprint " <NOT SPECIFIED>";
1076 }
1077  
1078 dprint "Home directory:\n " . GetHomeDirectory();
1079
1080 require Cwd;
1081 dprint "Current directory:\n ",Cwd::cwd(),"\n";
1082  
1083 dprint "System-wide configuration file found as:\n $config{sys_config_file}\n";
1084 dprint "Personal configuration file found as:\n $config{user_config_file}\n";
1085  
1086 dprint "\@INC before loading configuration:";
1087 dprint " $_" foreach @startingINC;
1088  
1089 dprint "\@INC after loading configuration:";
1090 foreach my $i (@INC)
1091 {
1092 dprint " $i";
1093 }
1094  
1095 dprint "Configuration is:";
1096  
1097 DumpData(\%config,' ');
1098 }
1099  
1100 # ------------------------------------------------------------------------------
1101  
1102 # Recursively outputs a data structure, with indentation. First argument is
1103 # a ref to the data, and the second argument is the prefix to append to the
1104 # output.
1105  
1106 sub DumpData
1107 {
1108 my $data = shift;
1109 my $prefix = shift;
1110  
1111 if (!defined $data)
1112 {
1113 dprint "$prefix<NOT SPECIFIED>\n";
1114 }
1115 elsif (!ref $data)
1116 {
1117 if (defined $data && $data ne '')
1118 {
1119 dprint "$prefix$data\n";
1120 }
1121 else
1122 {
1123 dprint "$prefix<NOT SPECIFIED>\n";
1124 }
1125 }
1126 elsif (UNIVERSAL::isa($data,'SCALAR'))
1127 {
1128 if (defined $$data && $$data ne '')
1129 {
1130 dprint "$prefix$$data\n";
1131 }
1132 else
1133 {
1134 dprint "$prefix<NOT SPECIFIED>\n";
1135 }
1136 }
1137 elsif (UNIVERSAL::isa($data,'ARRAY'))
1138 {
1139 foreach my $temp (@$data)
1140 {
1141 DumpData($temp,$prefix);
1142 }
1143 }
1144 elsif (UNIVERSAL::isa($data,'HASH'))
1145 {
1146 foreach my $temp (keys %$data)
1147 {
1148 dprint "$prefix$temp:";
1149 DumpData($$data{$temp},"$prefix ");
1150 }
1151 }
1152 else
1153 {
1154 print STDERR "6\n";
1155 dprint "$prefix<UNKNOWN TYPE>\n";
1156 }
1157 }
1158  
1159 # ------------------------------------------------------------------------------
1160  
1161 # Checks the registration key to make sure it's a valid one.
1162  
1163 sub CheckRegistration()
1164 {
1165 # Set the default product type
1166 $config{product} = "Trial";
1167 $config{number_pages} = 1;
1168 $config{number_handlers} = 1;
1169  
1170 # Override the product type in the Open Source version.
1171 $config{product} = "Open Source", return;
1172  
1173 # Extract the date, license type, and crypt'd code from the key
1174 my ($date,$license,$numPages,$numHandlers,$code) =
1175 $config{registration_key} =~ /^(.*?)#(.*?)#(.*?)#(.*)#(.*)$/;
1176  
1177 # In case the registration_key isn't valid
1178 $date = '' unless defined $date;
1179 $license = '' unless defined $license;
1180 $numPages = '' unless defined $numPages;
1181 $numHandlers = '' unless defined $numHandlers;
1182 $code = '' unless defined $code;
1183  
1184 # We will try two strings--one with the operating system (pre-1.32) and one
1185 # without the operating system (after-1.32).
1186 my $licensestring1 =
1187 "$date#$license#$^O#$config{email}#$numPages#$numHandlers";
1188 my $licensestring2 =
1189 "$date#$license#$config{email}#$numPages#$numHandlers";
1190  
1191 # Mash groups of eight together to help hash the string for crypt, which can
1192 # only use up to eight characters
1193 my $hashed1 = "";
1194 my $hashed2 = "";
1195  
1196 foreach ($licensestring1 =~ /(.{1,8})/gs) { $hashed1 ^= $_ }
1197 foreach ($licensestring2 =~ /(.{1,8})/gs) { $hashed2 ^= $_ }
1198  
1199 # Now check the key.
1200 if ((crypt($hashed1,$code) eq $code) || (crypt($hashed2,$code) eq $code))
1201 {
1202 if ($license eq 'p')
1203 {
1204 $config{product} = "Personal";
1205 $config{number_pages} = $numPages;
1206 $config{number_handlers} = $numHandlers;
1207 }
1208  
1209 if ($license eq 'c')
1210 {
1211 $config{product} = "Corporate";
1212 }
1213 }
1214 elsif ($config{registration_key} ne 'YOUR_REG_KEY_HERE')
1215 {
1216 warn reformat dequote<<" EOF";
1217 ERROR: Your registration key appears to be incorrect. Here is the
1218 information News Clipper was able to determine:
1219 EOF
1220 die dequote ' ',<<" EOF";
1221 System-wide configuration file: $config{sys_config_file}
1222 Personal configuration file: $config{user_config_file}
1223 Email: $config{email}
1224 Key: $config{registration_key}
1225 Date Issued: $date
1226 License Type: $license
1227 Number of pages: $numPages
1228 Number of Handlers: $numHandlers
1229 EOF
1230 }
1231 else
1232 {
1233 # Stays the trial version
1234 }
1235 }
1236  
1237 # ------------------------------------------------------------------------------
1238  
1239 # Clear the cache, prompting the user if necessary.
1240 #
1241 # DO NOT REMOVE THE PROMPT! We don't want hordes of websites calling us
1242 # because someone is clearing their cache and hitting the servers every 5
1243 # minutes of the day.
1244  
1245 sub HandleClearCache()
1246 {
1247 use File::Path;
1248  
1249 if ($opts{C})
1250 {
1251 my $response;
1252  
1253 # Clear HTML cache
1254 print "Do you want to clear the HTML cache? ";
1255 $response = <STDIN>;
1256  
1257 while ($response !~ /^[yn]/i)
1258 {
1259 print "Yes or no? ";
1260 $response = <STDIN>;
1261 }
1262  
1263 if ($response =~ /^y/i)
1264 {
1265 rmtree (["$config{cache_location}/html"]);
1266 }
1267  
1268 # Clear handler state
1269 print "Do you want to clear the handler-specific data storage? ";
1270 $response = <STDIN>;
1271  
1272 while ($response !~ /^[yn]/i)
1273 {
1274 print "Yes or no? ";
1275 $response = <STDIN>;
1276 }
1277  
1278 if ($response =~ /^y/i)
1279 {
1280 rmtree (["$NewsClipper::Globals::home/.NewsClipper/state/Acquisition"]);
1281 rmtree (["$NewsClipper::Globals::home/.NewsClipper/state/Filter"]);
1282 rmtree (["$NewsClipper::Globals::home/.NewsClipper/state/Output"]);
1283 }
1284  
1285 # Clear News Clipper state
1286 print reformat "Do you want to clear News Clipper's data storage " .
1287 "(which includes the times that handlers were last checked for updates)? ";
1288 $response = <STDIN>;
1289  
1290 while ($response !~ /^[yn]/i)
1291 {
1292 print "Yes or no? ";
1293 $response = <STDIN>;
1294 }
1295  
1296 if ($response =~ /^y/i)
1297 {
1298 rmtree (["$NewsClipper::Globals::home/.NewsClipper/state/NewsClipper"]);
1299 }
1300  
1301 # Clear debug log
1302 print reformat "Do you want to clear the debug log? ";
1303 $response = <STDIN>;
1304  
1305 while ($response !~ /^[yn]/i)
1306 {
1307 print "Yes or no? ";
1308 $response = <STDIN>;
1309 }
1310  
1311 if ($response =~ /^y/i)
1312 {
1313 open DEBUG_LOG, ">$config{'debug_log_file'}";
1314 close DEBUG_LOG;
1315 }
1316  
1317 # Clear run log
1318 print reformat "Do you want to clear the run log? ";
1319 $response = <STDIN>;
1320  
1321 while ($response !~ /^[yn]/i)
1322 {
1323 print "Yes or no? ";
1324 $response = <STDIN>;
1325 }
1326  
1327 if ($response =~ /^y/i)
1328 {
1329 open DEBUG_LOG, ">$config{'run_log_file'}";
1330 close DEBUG_LOG;
1331 }
1332  
1333 exit(0);
1334 }
1335 }
1336  
1337 # ------------------------------------------------------------------------------
1338  
1339 # This routine allows the user to enter a username and password for a proxy.
1340  
1341 sub HandleProxyPassword()
1342 {
1343 # Handle the proxy password, if a username was given but not a password, and
1344 # a tty is available.
1345 if (($config{proxy_username} ne '') &&
1346 (($config{proxy_password} eq '') && (-t STDIN)))
1347 {
1348 unless (eval "require Term::ReadKey")
1349 {
1350 die reformat dequote<<" EOF";
1351 You need Term::ReadKey for password authorization.\nGet it from
1352 CPAN.\n";
1353 EOF
1354 }
1355  
1356 # Make unbuffered
1357 my $oldBuffer = $|;
1358 $|=1;
1359  
1360 print "Please enter your proxy password: ";
1361  
1362 # Turn off echo to read in password
1363 Term::ReadKey::ReadMode('noecho');
1364  
1365 $config{proxy_password} = <STDIN>;
1366 chomp($config{proxy_password});
1367  
1368 # Turn echo back on
1369 Term::ReadKey::ReadMode ('restore');
1370  
1371 # Give the user a visual cue that their password has been entered
1372 print "\n";
1373  
1374 $| = $oldBuffer;
1375 }
1376 }
1377  
1378 # ------------------------------------------------------------------------------
1379  
1380 # Attempts to grab the installation from the registry for Windows machines. It
1381 # returns nothing if anything goes wrong, otherwise the installation path.
1382  
1383 sub GetWinInstallDir()
1384 {
1385 return if ($^O ne 'MSWin32') && ($^O ne 'dos');
1386  
1387 require Win32::Registry;
1388  
1389 # To get rid of "main::HKEY_LOCAL_MACHINE" used only once warning.
1390 $main::HKEY_LOCAL_MACHINE = $main::HKEY_LOCAL_MACHINE;
1391  
1392 my $key = "SOFTWARE\\Spinnaker Software\\News Clipper\\$VERSION";
1393 my $TempKey;
1394  
1395 # Return if we can't find the key in the registry.
1396 $main::HKEY_LOCAL_MACHINE->Open($key, $TempKey) || return;
1397  
1398 my ($class, $nSubKey, $nVals);
1399 $TempKey->QueryKey($class, $nSubKey, $nVals);
1400  
1401 # Return if there are no values for the key.
1402 return if $nVals <= 0;
1403  
1404 my ($value,$type);
1405  
1406 # Return if we can't find the value.
1407 $TempKey->QueryValueEx('InstallDir',$type,$value) || return;
1408  
1409 # Return if the value is there, but is the wrong type.
1410 return unless $type == 1;
1411  
1412 return $value;
1413 }
1414  
1415 #-------------------------------------------------------------------------------
1416  
1417 # If we're in DEBUG mode, output the modules we used during this run. Be
1418 # careful not to try to do this if something bad happened before we loaded
1419 # NewsClipper::Globals, which set the DEBUG constant.
1420  
1421 END
1422 {
1423 # Only do this if we got far enough to define dprint and lprint;
1424 if (defined &DEBUG)
1425 {
1426 # Print the modules used to the debug log
1427 dprint "Here are all the modules used during this run, and their locations:";
1428 foreach my $key (sort keys %INC)
1429 {
1430 dprint " $key =>\n $INC{$key}";
1431 }
1432  
1433 # Print process completion status to the status and run logs
1434 my $end_time = scalar localtime time;
1435  
1436 if ($? == 0)
1437 {
1438 lprint "News Clipper completed normally: $end_time";
1439 }
1440 else
1441 {
1442 lprint "News Clipper completed but had an error: $end_time";
1443 }
1444 }
1445  
1446 if ($opts{P})
1447 {
1448 $| = 1;
1449 print "News Clipper has finished processing the input files.\n" .
1450 "Press enter to continue...";
1451 <STDIN>;
1452 }
1453 }
1454  
1455 # ------------------------------------------------------------------------------
1456  
1457 # Needed by compiler
1458  
1459 #perl2exe_include constant
1460 #perl2exe_include NewsClipper/AcquisitionFunctions
1461 #perl2exe_include NewsClipper/Cache
1462 #perl2exe_include NewsClipper/HTMLTools
1463 #perl2exe_include NewsClipper/Handler
1464 #perl2exe_include NewsClipper/HandlerFactory
1465 #perl2exe_include NewsClipper/Interpreter
1466 #perl2exe_include NewsClipper/Parser
1467 #perl2exe_include NewsClipper/Types
1468 #perl2exe_include Time/CTime
1469 #perl2exe_include Date/Format
1470 #perl2exe_include Net/NNTP
1471 #perl2exe_include File/Spec/Win32.pm
1472  
1473 #-------------------------------------------------------------------------------
1474  
1475 __END__