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);
40 %EXPORT_TAGS = ( TimePeriods => [qw(GetTimePeriod LastMonth CheckMonth SplitPeriod ListMonth)],
41 Output => [qw(OutputData FormatOutput)],
42 SQLHelper => [qw(SQLHierarchies SQLGroupList GetMaxLenght)]);
44 our $PackageVersion = '0.01';
53 #####-------------------------------- Vars --------------------------------#####
55 our $MySelf = fileparse($0, '.pl');
56 our $MyVersion = "$MySelf $::VERSION (NewsStats.pm $VERSION)";
58 #####------------------------------- Basics -------------------------------#####
60 ################################################################################
62 ################################################################################
63 ### read commandline options and act on standard options -h and -V
64 ### IN : $Params: list of legal commandline paramaters (without -h and -V)
65 ### OUT: a hash containing the commandline options
66 $Getopt::Std::STANDARD_HELP_VERSION = 1;
71 getopts('Vh'.$Params, \%Options);
74 &ShowVersion if ($Options{'V'});
76 # -h: feed myself to perldoc
77 &ShowPOD if ($Options{'h'});
81 ################################################################################
83 ################################################################################
85 ################################################################################
86 ### display version and exit
87 print "NewsStats v$PackageVersion\n$MyVersion\nCopyright (c) 2010 Thomas Hochstein <thh\@inter.net>\n";
88 print "This program is free software; you may redistribute it and/or modify it under the same terms as Perl itself.\n";
91 ################################################################################
93 ################################################################################
95 ################################################################################
96 ### feed myself to perldoc and exit
100 ################################################################################
102 ################################################################################
104 ################################################################################
105 ### read config via Config::Auto
106 ### IN : $ConfFile: config filename
107 ### OUT: reference to a hash containing the configuration
109 return Config::Auto::parse($ConfFile, format => 'equal');
111 ################################################################################
113 ################################################################################
115 ################################################################################
116 ### override configuration values
117 ### IN : $ConfigR : reference to configuration hash
118 ### $OverrideR: reference to a hash containing overrides
119 my ($ConfigR,$OverrideR) = @_;
120 my %Override = %$OverrideR;
122 warn "$MySelf W: Empty configuration hash passed to OverrideConfig().\n" if ( keys %$ConfigR < 1);
123 # return if no overrides
124 return if (keys %Override < 1 or keys %$ConfigR < 1);
125 foreach my $Key (keys %Override) {
126 $$ConfigR{$Key} = $Override{$Key};
129 ################################################################################
131 ################################################################################
133 ################################################################################
134 ### initialise database connection
135 ### IN : $ConfigR: reference to configuration hash
136 ### $Die : if TRUE, die if connection fails
138 my ($ConfigR,$Die) = @_;
139 my %Conf = %$ConfigR;
140 my $DBHandle = DBI->connect(sprintf('DBI:%s:database=%s;host=%s',$Conf{'DBDriver'},$Conf{'DBDatabase'},$Conf{'DBHost'}), $Conf{'DBUser'}, $Conf{'DBPw'}, { PrintError => 0 });
142 die ("$MySelf: E: $DBI::errstr\n") if (defined($Die) and $Die);
143 warn("$MySelf: W: $DBI::errstr\n");
147 ################################################################################
149 #####------------------------------ GetStats ------------------------------#####
151 ################################################################################
153 ################################################################################
154 ### explode a (scalar) list of newsgroup names to a list of newsgroup and
155 ### hierarchy names where every newsgroup and hierarchy appears only once:
156 ### de.alt.test,de.alt.admin -> de.ALL, de.alt.ALL, de.alt.test, de.alt.admin
157 ### IN : $Newsgroups: a list of newsgroups (content of Newsgroups: header)
158 ### OUT: %Newsgroups: hash containing all newsgroup and hierarchy names as keys
159 my ($Newsgroups) = @_;
162 # remove whitespace from contents of Newsgroups:
163 $Newsgroups =~ s/\s//;
164 # call &HierarchyCount for each newsgroup in $Newsgroups:
165 for (split /,/, $Newsgroups) {
166 # add original newsgroup to %Newsgroups
168 # add all hierarchy elements to %Newsgroups, amended by '.ALL',
169 # i.e. de.alt.ALL and de.ALL
170 foreach (ParseHierarchies($_)) {
171 $Newsgroups{$_.'.ALL'} = 1;
177 ################################################################################
178 sub ParseHierarchies {
179 ################################################################################
180 ### return a list of all hierarchy levels a newsgroup belongs to
181 ### (for de.alt.test.moderated that would be de/de.alt/de.alt.test)
182 ### IN : $Newsgroup : a newsgroup name
183 ### OUT: @Hierarchies: array containing all hierarchies the newsgroup belongs to
184 my ($Newsgroup) = @_;
186 # strip trailing dots
187 $Newsgroup =~ s/(.+)\.+$/$1/;
188 # butcher newsgroup name by "." and add each hierarchy to @Hierarchies
189 # i.e. de.alt.test: "de.alt" and "de"
190 while ($Newsgroup =~ /\./) {
191 $Newsgroup =~ s/^((?:\.?[^.]+)*)\.[^.]+$/$1/;
192 push @Hierarchies, $Newsgroup;
197 ################################################################################
199 #####----------------------------- TimePeriods ----------------------------#####
201 ################################################################################
203 ################################################################################
204 ### get a time period to act on, in order of preference: by default the
205 ### last month; or a month submitted by -m YYYY-MM; or a time period submitted
206 ### by -p YYYY-MM:YYYY-MM
207 ### IN : $Month,$Period: contents of -m and -p
208 ### OUT: $StartMonth, $EndMonth (identical if period is just one month)
209 my ($Month,$Period) = @_;
210 # exit if -m is set and not like YYYY-MM
211 die "$MySelf: E: Wrong date format - use '$MySelf -m YYYY-MM'!\n" if not &CheckMonth($Month);
212 # warn if -m and -p is set
213 warn "$MySelf: W: Time period assigned by '-p' takes precendece over month assigned by '-m'.\n" if ($Month && $Period);
214 # default: set -m to last month
215 $Month = &LastMonth if (!defined($Month) and !defined($Period));
216 # set $StartMonth, $EndMonth
217 my ($StartMonth, $EndMonth);
220 ($StartMonth, $EndMonth) = &SplitPeriod($Period);
221 die "$MySelf: E: Wrong format for time period - use '$MySelf -p YYYY-MM:YYYY-MM'!\n" if !defined($StartMonth);
223 # set $StartMonth = $EndMonth = $Month if -p is not set
224 $StartMonth = $EndMonth = $Month;
226 return ($StartMonth, $EndMonth);
229 ################################################################################
231 ################################################################################
232 ### get last month from todays date in YYYY-MM format
233 ### OUT: last month as YYYY-MM
235 my (undef,undef,undef,undef,$Month,$Year,undef,undef,undef) = localtime(time);
236 # $Month is already defined from 0 to 11, so no need to decrease it by 1
243 return sprintf('%4d-%02d',$Year,$Month);
246 ################################################################################
248 ################################################################################
249 ### check if input is a valid month in YYYY-MM form
250 ### IN : $Month: month
251 ### OUT: TRUE / FALSE
253 return 0 if (defined($Month) and $Month !~ /^\d{4}-\d{2}$/);
257 ################################################################################
259 ################################################################################
260 ### split a time period denoted by YYYY-MM:YYYY-MM into start and end month
261 ### IN : $Period: time period
262 ### OUT: $StartMonth, Â$EndMonth
264 return (undef,undef) if $Period !~ /^\d{4}-\d{2}:\d{4}-\d{2}$/;
265 my ($StartMonth, $EndMonth) = split /:/, $Period;
266 # switch parameters as necessary
267 if ($EndMonth gt $StartMonth) {
268 return ($StartMonth, $EndMonth);
270 return ($EndMonth, $StartMonth);
274 ################################################################################
276 ################################################################################
277 ### return a list of months (YYYY-MM) between start and end month
278 ### IN : $StartMonth, $EndMonth
279 ### OUT: @Months: array containing all months from $StartMonth to $EndMonth
280 my ($StartMonth, $EndMonth) = @_;
281 return (undef,undef) if ($StartMonth !~ /^\d{4}-\d{2}$/ or $EndMonth !~ /^\d{4}-\d{2}$/);
282 # return if $StartMonth = $EndMonth
283 return ($StartMonth) if ($StartMonth eq $EndMonth);
284 # set $Year, $Month from $StartMonth
285 my ($Year, $Month) = split /-/, $StartMonth;
288 until ("$Year-$Month" gt $EndMonth) {
289 push @Months, "$Year-$Month";
290 $Month = "$Month"; # force string context
300 #####---------------------------- OutputFormats ---------------------------#####
302 ################################################################################
304 ################################################################################
305 ### read database query results from DBHandle and print results with formatting
306 ### IN : $Format : format specifier
307 ### $DBQuery: database query handle with executed query,
308 ### containing $Month, $Key, $Value
309 ### $PadGroup: padding length for newsgroups field (optional) for 'pretty'
310 my ($Format, $DBQuery,$PadGroup) = @_;
311 while (my ($Month, $Key, $Value) = $DBQuery->fetchrow_array) {
312 print &FormatOutput($Format, $Month, $Key, $Value, $PadGroup);
316 ################################################################################
318 ################################################################################
319 ### format information for output according to format specifier
320 ### IN : $Format : format specifier
321 ### $Month : month (as YYYY-MM)
322 ### $Key : newsgroup, client, ...
323 ### $Value : number of postings with that attribute
324 ### $PadGroup: padding length for key field (optional) for 'pretty'
325 ### OUT: $Output: formatted output
326 my ($Format, $Month, $Key, $Value, $PadGroup) = @_;
328 # define output types
330 @LegalOutput{('dump','dumpgroup','list','pretty')} = ();
331 # bail out if format is unknown
332 die "$MySelf: E: Unknown output type '$Format'!\n" if !exists($LegalOutput{$Format});
335 # keep last month in mind
336 our ($LastIteration);
337 if ($Format eq 'dump') {
338 # output as dump (ng nnnnn)
339 $Output = sprintf ("%s %u\n",$Key,$Value);
340 } elsif ($Format eq 'dumpgroup') {
341 # output as dump (YYYY-NN: nnnnn)
342 $Output = sprintf ("%s: %5u\n",$Month,$Value);
343 } elsif ($Format eq 'list') {
344 # output as list (YYYY-NN: ng nnnnn)
345 $Output = sprintf ("%s: %s %u\n",$Month,$Key,$Value);
346 } elsif ($Format eq 'pretty') {
348 $Output = sprintf ("----- %s:\n",$Month) if (!defined($LastIteration) or $Month ne $LastIteration);
349 $LastIteration = $Month;
350 $Output .= sprintf ($PadGroup ? sprintf("%%-%us %%5u\n",$PadGroup) : "%s %u\n",$Key,$Value);
355 #####------------------------- QueryModifications -------------------------#####
357 ################################################################################
359 ################################################################################
360 ### add exclusion of hierarchy levels (de.alt.ALL) from SQL query by
361 ### amending the WHERE clause if $ShowHierarchies is false (or don't, if it is
362 ### true, accordingly)
363 ### IN : $ShowHierarchies: boolean value
365 my ($ShowHierarchies) = @_;
366 return $ShowHierarchies ? '' : "AND newsgroup NOT LIKE '%.ALL'";
369 ################################################################################
371 ################################################################################
372 ### get length of longest field in future query result
373 ### IN : $DBHandle : database handel
374 ### $Table : table to query
375 ### $Field : field to check
376 ### $WhereClause: WHERE clause
377 ### @BindVars : bind variables for WHERE clause
378 ### OUT: $Length: length of longest instnace of $Field
379 my ($DBHandle,$Table,$Field,$WhereClause,@BindVars) = @_;
380 my $DBQuery = $DBHandle->prepare(sprintf("SELECT MAX(LENGTH(%s)) FROM %s WHERE %s",$Field,$Table,$WhereClause));
381 $DBQuery->execute(@BindVars) or warn sprintf("$MySelf: W: Can't get field length for %s from table %s: $DBI::errstr\n",$Field,$Table);
382 my ($Length) = $DBQuery->fetchrow_array;
386 ################################################################################
388 ################################################################################
389 ### explode list of newsgroups separated by : (with wildcards) to a SQL WHERE
391 ### IN : $Newsgroups: list of newsgroups (group.one.*:group.two:group.three.*)
392 ### OUT: SQL code, list of newsgroups
393 my ($Newsgroups) = @_;
394 $Newsgroups =~ s/\*/%/g;
395 return ('newsgroup LIKE ?', $Newsgroups) if $Newsgroups !~ /:/;
397 my @GroupList = split /:/, $Newsgroups;
398 foreach (@GroupList) {
399 $SQL .= ' OR ' if $SQL gt '(';
400 $SQL .= 'newsgroup LIKE ?';
403 return ($SQL,@GroupList);
406 #####------------------------------- done ---------------------------------#####