3 # Library functions for the NewsStats package.
5 # Copyright (c) 2010 Thomas Hochstein <thh@inter.net>
7 # This module can be redistributed and/or modified under the same terms under
8 # which Perl itself is published.
14 our ($VERSION, @ISA, @EXPORT, @EXPORT_OK, %EXPORT_TAGS);
41 %EXPORT_TAGS = ( TimePeriods => [qw(GetTimePeriod LastMonth CheckMonth SplitPeriod ListMonth)],
42 Output => [qw(OutputData FormatOutput)],
43 SQLHelper => [qw(SQLHierarchies SQLGroupList GetMaxLenght)]);
45 our $PackageVersion = '0.01';
54 #####-------------------------------- Vars --------------------------------#####
56 our $MySelf = fileparse($0, '.pl');
57 our $MyVersion = "$MySelf $::VERSION (NewsStats.pm $VERSION)";
59 #####------------------------------- Basics -------------------------------#####
61 ################################################################################
63 ################################################################################
64 ### read commandline options and act on standard options -h and -V
65 ### IN : $Params: list of legal commandline paramaters (without -h and -V)
66 ### OUT: a hash containing the commandline options
67 $Getopt::Std::STANDARD_HELP_VERSION = 1;
72 getopts('Vh'.$Params, \%Options);
75 &ShowVersion if ($Options{'V'});
77 # -h: feed myself to perldoc
78 &ShowPOD if ($Options{'h'});
82 ################################################################################
84 ################################################################################
86 ################################################################################
87 ### display version and exit
88 print "NewsStats v$PackageVersion\n$MyVersion\nCopyright (c) 2010 Thomas Hochstein <thh\@inter.net>\n";
89 print "This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.\n";
92 ################################################################################
94 ################################################################################
96 ################################################################################
97 ### feed myself to perldoc and exit
101 ################################################################################
103 ################################################################################
105 ################################################################################
106 ### read config via Config::Auto
107 ### IN : $ConfFile: config filename
108 ### OUT: reference to a hash containing the configuration
110 return Config::Auto::parse($ConfFile, format => 'equal');
112 ################################################################################
114 ################################################################################
116 ################################################################################
117 ### override configuration values
118 ### IN : $ConfigR : reference to configuration hash
119 ### $OverrideR: reference to a hash containing overrides
120 my ($ConfigR,$OverrideR) = @_;
121 my %Override = %$OverrideR;
123 warn "$MySelf W: Empty configuration hash passed to OverrideConfig().\n" if ( keys %$ConfigR < 1);
124 # return if no overrides
125 return if (keys %Override < 1 or keys %$ConfigR < 1);
126 foreach my $Key (keys %Override) {
127 $$ConfigR{$Key} = $Override{$Key};
130 ################################################################################
132 ################################################################################
134 ################################################################################
135 ### initialise database connection
136 ### IN : $ConfigR: reference to configuration hash
137 ### $Die : if TRUE, die if connection fails
139 my ($ConfigR,$Die) = @_;
140 my %Conf = %$ConfigR;
141 my $DBHandle = DBI->connect(sprintf('DBI:%s:database=%s;host=%s',$Conf{'DBDriver'},$Conf{'DBDatabase'},$Conf{'DBHost'}), $Conf{'DBUser'}, $Conf{'DBPw'}, { PrintError => 0 });
143 die ("$MySelf: E: $DBI::errstr\n") if (defined($Die) and $Die);
144 warn("$MySelf: W: $DBI::errstr\n");
148 ################################################################################
150 #####------------------------------ GetStats ------------------------------#####
152 ################################################################################
154 ################################################################################
155 ### explode a (scalar) list of newsgroup names to a list of newsgroup and
156 ### hierarchy names where every newsgroup and hierarchy appears only once:
157 ### de.alt.test,de.alt.admin -> de.ALL, de.alt.ALL, de.alt.test, de.alt.admin
158 ### IN : $Newsgroups : a list of newsgroups (content of Newsgroups: header)
159 ### $ValidGroupsR: reference to a hash containing all valid newsgroups
161 ### OUT: %Newsgroups : hash containing all newsgroup and hierarchy names as keys
162 my ($Newsgroups,$ValidGroupsR) = @_;
163 my %ValidGroups = %{$ValidGroupsR} if $ValidGroupsR;
166 # remove whitespace from contents of Newsgroups:
167 $Newsgroups =~ s/\s//;
168 # call &HierarchyCount for each newsgroup in $Newsgroups:
169 for (split /,/, $Newsgroups) {
170 # don't count invalid newsgroups
171 if(%ValidGroups and !defined($ValidGroups{$_})) {
172 warn (sprintf("DROPPED: %s\n",$_));
175 # add original newsgroup to %Newsgroups
177 # add all hierarchy elements to %Newsgroups, amended by '.ALL',
178 # i.e. de.alt.ALL and de.ALL
179 foreach (ParseHierarchies($_)) {
180 $Newsgroups{$_.'.ALL'} = 1;
186 ################################################################################
187 sub ParseHierarchies {
188 ################################################################################
189 ### return a list of all hierarchy levels a newsgroup belongs to
190 ### (for de.alt.test.moderated that would be de/de.alt/de.alt.test)
191 ### IN : $Newsgroup : a newsgroup name
192 ### OUT: @Hierarchies: array containing all hierarchies the newsgroup belongs to
193 my ($Newsgroup) = @_;
195 # strip trailing dots
196 $Newsgroup =~ s/(.+)\.+$/$1/;
197 # butcher newsgroup name by "." and add each hierarchy to @Hierarchies
198 # i.e. de.alt.test: "de.alt" and "de"
199 while ($Newsgroup =~ /\./) {
200 $Newsgroup =~ s/^((?:\.?[^.]+)*)\.[^.]+$/$1/;
201 push @Hierarchies, $Newsgroup;
206 ################################################################################
208 ################################################################################
209 ### read a list of valid newsgroups from file (each group on one line,
210 ### ignoring everything after the first whitespace and so accepting files
211 ### in checkgroups format as well as (parts of) an INN active file)
212 ### IN : $Filename : file to read
213 ### OUT: \%ValidGroups: hash containing all valid newsgroups
216 open (my $LIST,"<$Filename") or die "$MySelf: E: Cannot read $Filename: $!\n";
220 $ValidGroups{$_} = '1';
223 return \%ValidGroups;
226 ################################################################################
228 #####----------------------------- TimePeriods ----------------------------#####
230 ################################################################################
232 ################################################################################
233 ### get a time period to act on, in order of preference: by default the
234 ### last month; or a month submitted by -m YYYY-MM; or a time period submitted
235 ### by -p YYYY-MM:YYYY-MM
236 ### IN : $Month,$Period: contents of -m and -p
237 ### OUT: $StartMonth, $EndMonth (identical if period is just one month)
238 my ($Month,$Period) = @_;
239 # exit if -m is set and not like YYYY-MM
240 die "$MySelf: E: Wrong date format - use '$MySelf -m YYYY-MM'!\n" if not &CheckMonth($Month);
241 # warn if -m and -p is set
242 warn "$MySelf: W: Time period assigned by '-p' takes precendece over month assigned by '-m'.\n" if ($Month && $Period);
243 # default: set -m to last month
244 $Month = &LastMonth if (!defined($Month) and !defined($Period));
245 # set $StartMonth, $EndMonth
246 my ($StartMonth, $EndMonth);
249 ($StartMonth, $EndMonth) = &SplitPeriod($Period);
250 die "$MySelf: E: Wrong format for time period - use '$MySelf -p YYYY-MM:YYYY-MM'!\n" if !defined($StartMonth);
252 # set $StartMonth = $EndMonth = $Month if -p is not set
253 $StartMonth = $EndMonth = $Month;
255 return ($StartMonth, $EndMonth);
258 ################################################################################
260 ################################################################################
261 ### get last month from todays date in YYYY-MM format
262 ### OUT: last month as YYYY-MM
264 my (undef,undef,undef,undef,$Month,$Year,undef,undef,undef) = localtime(time);
265 # $Month is already defined from 0 to 11, so no need to decrease it by 1
272 return sprintf('%4d-%02d',$Year,$Month);
275 ################################################################################
277 ################################################################################
278 ### check if input is a valid month in YYYY-MM form
279 ### IN : $Month: month
280 ### OUT: TRUE / FALSE
282 return 0 if (defined($Month) and $Month !~ /^\d{4}-\d{2}$/);
286 ################################################################################
288 ################################################################################
289 ### split a time period denoted by YYYY-MM:YYYY-MM into start and end month
290 ### IN : $Period: time period
291 ### OUT: $StartMonth, Â$EndMonth
293 return (undef,undef) if $Period !~ /^\d{4}-\d{2}:\d{4}-\d{2}$/;
294 my ($StartMonth, $EndMonth) = split /:/, $Period;
295 # switch parameters as necessary
296 if ($EndMonth gt $StartMonth) {
297 return ($StartMonth, $EndMonth);
299 return ($EndMonth, $StartMonth);
303 ################################################################################
305 ################################################################################
306 ### return a list of months (YYYY-MM) between start and end month
307 ### IN : $StartMonth, $EndMonth
308 ### OUT: @Months: array containing all months from $StartMonth to $EndMonth
309 my ($StartMonth, $EndMonth) = @_;
310 return (undef,undef) if ($StartMonth !~ /^\d{4}-\d{2}$/ or $EndMonth !~ /^\d{4}-\d{2}$/);
311 # return if $StartMonth = $EndMonth
312 return ($StartMonth) if ($StartMonth eq $EndMonth);
313 # set $Year, $Month from $StartMonth
314 my ($Year, $Month) = split /-/, $StartMonth;
317 until ("$Year-$Month" gt $EndMonth) {
318 push @Months, "$Year-$Month";
319 $Month = "$Month"; # force string context
329 #####---------------------------- OutputFormats ---------------------------#####
331 ################################################################################
333 ################################################################################
334 ### read database query results from DBHandle and print results with formatting
335 ### IN : $Format : format specifier
336 ### $FileName: file name template (-f): filename-YYYY-MM
337 ### $DBQuery : database query handle with executed query,
338 ### containing $Month, $Key, $Value
339 ### $PadGroup: padding length for newsgroups field (optional) for 'pretty'
340 my ($Format, $FileName, $DBQuery, $PadGroup) = @_;
343 while (my ($Month, $Key, $Value) = $DBQuery->fetchrow_array) {
344 # set output file handle
346 $Handle = *STDOUT{IO}; # set $Handle to a reference to STDOUT
347 } elsif (!defined($LastIteration) or $LastIteration ne $Month) {
348 close $OUT if ($LastIteration);
349 open ($OUT,sprintf('>%s-%s',$FileName,$Month)) or die sprintf("$MySelf: E: Cannot open output file '%s-%s': $!\n",$FileName,$Month);
352 print $Handle &FormatOutput($Format, $Month, $Key, $Value, $PadGroup);
353 $LastIteration = $Month;
355 close $OUT if ($FileName);
358 ################################################################################
360 ################################################################################
361 ### format information for output according to format specifier
362 ### IN : $Format : format specifier
363 ### $Month : month (as YYYY-MM)
364 ### $Key : newsgroup, client, ...
365 ### $Value : number of postings with that attribute
366 ### $PadGroup: padding length for key field (optional) for 'pretty'
367 ### OUT: $Output: formatted output
368 my ($Format, $Month, $Key, $Value, $PadGroup) = @_;
370 # define output types
372 @LegalOutput{('dump','dumpgroup','list','pretty')} = ();
373 # bail out if format is unknown
374 die "$MySelf: E: Unknown output type '$Format'!\n" if !exists($LegalOutput{$Format});
377 # keep last month in mind
378 our ($LastIteration);
379 if ($Format eq 'dump') {
380 # output as dump (ng nnnnn)
381 $Output = sprintf ("%s %u\n",$Key,$Value);
382 } elsif ($Format eq 'dumpgroup') {
383 # output as dump (YYYY-NN: nnnnn)
384 $Output = sprintf ("%s: %5u\n",$Month,$Value);
385 } elsif ($Format eq 'list') {
386 # output as list (YYYY-NN: ng nnnnn)
387 $Output = sprintf ("%s: %s %u\n",$Month,$Key,$Value);
388 } elsif ($Format eq 'pretty') {
390 $Output = sprintf ("----- %s:\n",$Month) if (!defined($LastIteration) or $Month ne $LastIteration);
391 $LastIteration = $Month;
392 $Output .= sprintf ($PadGroup ? sprintf("%%-%us %%5u\n",$PadGroup) : "%s %u\n",$Key,$Value);
397 #####------------------------- QueryModifications -------------------------#####
399 ################################################################################
401 ################################################################################
402 ### add exclusion of hierarchy levels (de.alt.ALL) from SQL query by
403 ### amending the WHERE clause if $ShowHierarchies is false (or don't, if it is
404 ### true, accordingly)
405 ### IN : $ShowHierarchies: boolean value
407 my ($ShowHierarchies) = @_;
408 return $ShowHierarchies ? '' : "AND newsgroup NOT LIKE '%.ALL'";
411 ################################################################################
413 ################################################################################
414 ### get length of longest field in future query result
415 ### IN : $DBHandle : database handel
416 ### $Table : table to query
417 ### $Field : field to check
418 ### $WhereClause: WHERE clause
419 ### @BindVars : bind variables for WHERE clause
420 ### OUT: $Length: length of longest instnace of $Field
421 my ($DBHandle,$Table,$Field,$WhereClause,@BindVars) = @_;
422 my $DBQuery = $DBHandle->prepare(sprintf("SELECT MAX(LENGTH(%s)) FROM %s WHERE %s",$Field,$Table,$WhereClause));
423 $DBQuery->execute(@BindVars) or warn sprintf("$MySelf: W: Can't get field length for %s from table %s: $DBI::errstr\n",$Field,$Table);
424 my ($Length) = $DBQuery->fetchrow_array;
428 ################################################################################
430 ################################################################################
431 ### explode list of newsgroups separated by : (with wildcards) to a SQL WHERE
433 ### IN : $Newsgroups: list of newsgroups (group.one.*:group.two:group.three.*)
434 ### OUT: SQL code, list of newsgroups
435 my ($Newsgroups) = @_;
436 $Newsgroups =~ s/\*/%/g;
437 return ('newsgroup LIKE ?', $Newsgroups) if $Newsgroups !~ /:/;
439 my @GroupList = split /:/, $Newsgroups;
440 foreach (@GroupList) {
441 $SQL .= ' OR ' if $SQL gt '(';
442 $SQL .= 'newsgroup LIKE ?';
445 return ($SQL,@GroupList);
448 #####------------------------------- done ---------------------------------#####